Actual source code: matrix.c

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

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

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

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

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

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

 55:   Logically Collective

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

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

 69:   Level: intermediate

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

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

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

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

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

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

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

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

111:   Logically Collective

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

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

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

125:   Level: advanced

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

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

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

143:   Logically Collective

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

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

153:   Level: advanced

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

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

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

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

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

180:   Logically Collective

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

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

188:   Level: advanced

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

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

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

208:   Logically Collective

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

213:   Level: developer

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

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

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

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

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

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

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

296:   Level: intermediate

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

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

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

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

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

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

329:   Level: intermediate

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

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

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

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

362:   Not Collective

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

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

370:   Level: advanced

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

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

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

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

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

400:   Not Collective

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

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

408:   Level: advanced

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

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

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

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

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

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

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

447:   Collective

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

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

455:   Level: advanced

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

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

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

476:   Logically Collective

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

481:   Level: advanced

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

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

500:   Collective

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

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

509:   Level: advanced

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

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

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

534:   Logically Collective

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

539:   Level: advanced

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

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

561:   Not Collective

563:   Input Parameters:
564: + mat - the matrix
565: - row - the row to get

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

572:   Level: advanced

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

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

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

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

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

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

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

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

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

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

626: /*@
627:   MatConjugate - replaces the matrix values with their complex conjugates

629:   Logically Collective

631:   Input Parameter:
632: . mat - the matrix

634:   Level: advanced

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

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

653:   Not Collective

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

662:   Level: advanced

664:   Notes:
665:   This routine should be called after you have finished examining the entries.

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

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

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

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

696:   Not Collective

698:   Input Parameter:
699: . mat - the matrix

701:   Level: advanced

703:   Note:
704:   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.

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

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

723:   Not Collective

725:   Input Parameter:
726: . mat - the matrix

728:   Level: advanced

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

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

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

751:   Logically Collective

753:   Input Parameters:
754: + A      - the matrix
755: - prefix - the prefix to prepend to all option names

757:   Level: advanced

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

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

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

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

782:   Logically Collective

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

788:   Level: developer

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

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

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

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

818:   Logically Collective

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

824:   Level: developer

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

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

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

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

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

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

862:   Logically Collective

864:   Input Parameters:
865: + A      - the matrix
866: - prefix - the prefix to prepend to all option names

868:   Level: advanced

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

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

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

889:   Not Collective

891:   Input Parameter:
892: . A - the matrix

894:   Output Parameter:
895: . prefix - pointer to the prefix string used

897:   Level: advanced

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

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

913:   Not Collective

915:   Input Parameter:
916: . A - the matrix

918:   Output Parameter:
919: . state - the object state

921:   Level: advanced

923:   Note:
924:   Object state is an integer which gets increased every time
925:   the object is changed. By saving and later querying the object state
926:   one can determine whether information about the object is still current.

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

930: .seealso: [](ch_matrices), `Mat`, `MatCreate()`, `PetscObjectStateGet()`, `MatGetNonzeroState()`
931: @*/
932: PetscErrorCode MatGetState(Mat A, PetscObjectState *state)
933: {
934:   PetscFunctionBegin;
936:   PetscAssertPointer(state, 2);
937:   PetscCall(PetscObjectStateGet((PetscObject)A, state));
938:   PetscFunctionReturn(PETSC_SUCCESS);
939: }

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

944:   Collective

946:   Input Parameter:
947: . A - the matrix

949:   Level: beginner

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

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

958:   Currently only supported for  `MATAIJ` matrices.

960: .seealso: [](ch_matrices), `Mat`, `MatSeqAIJSetPreallocation()`, `MatMPIAIJSetPreallocation()`, `MatXAIJSetPreallocation()`
961: @*/
962: PetscErrorCode MatResetPreallocation(Mat A)
963: {
964:   PetscFunctionBegin;
967:   PetscUseMethod(A, "MatResetPreallocation_C", (Mat), (A));
968:   PetscFunctionReturn(PETSC_SUCCESS);
969: }

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

974:   Collective

976:   Input Parameter:
977: . A - the matrix

979:   Level: intermediate

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

984:   Currently only supported for `MATAIJ` matrices.

986: .seealso: [](ch_matrices), `Mat`, `MatResetPreallocation()`
987: @*/
988: PetscErrorCode MatResetHash(Mat A)
989: {
990:   PetscFunctionBegin;
993:   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()");
994:   if (A->num_ass == 0) PetscFunctionReturn(PETSC_SUCCESS);
995:   PetscUseMethod(A, "MatResetHash_C", (Mat), (A));
996:   /* These flags are used to determine whether certain setups occur */
997:   A->was_assembled = PETSC_FALSE;
998:   A->assembled     = PETSC_FALSE;
999:   /* Log that the state of this object has changed; this will help guarantee that preconditioners get re-setup */
1000:   PetscCall(PetscObjectStateIncrease((PetscObject)A));
1001:   PetscFunctionReturn(PETSC_SUCCESS);
1002: }

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

1007:   Collective

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

1012:   Level: advanced

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

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

1020: .seealso: [](ch_matrices), `Mat`, `MatMult()`, `MatCreate()`, `MatDestroy()`, `MatXAIJSetPreallocation()`
1021: @*/
1022: PetscErrorCode MatSetUp(Mat A)
1023: {
1024:   PetscFunctionBegin;
1026:   if (!((PetscObject)A)->type_name) {
1027:     PetscMPIInt size;

1029:     PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)A), &size));
1030:     PetscCall(MatSetType(A, size == 1 ? MATSEQAIJ : MATMPIAIJ));
1031:   }
1032:   if (!A->preallocated) PetscTryTypeMethod(A, setup);
1033:   PetscCall(PetscLayoutSetUp(A->rmap));
1034:   PetscCall(PetscLayoutSetUp(A->cmap));
1035:   A->preallocated = PETSC_TRUE;
1036:   PetscFunctionReturn(PETSC_SUCCESS);
1037: }

1039: #if PetscDefined(HAVE_SAWS)
1040: #include <petscviewersaws.h>
1041: #endif

1043: /*
1044:    If threadsafety is on extraneous matrices may be printed

1046:    This flag cannot be stored in the matrix because the original matrix in MatView() may assemble a new matrix which is passed into MatViewFromOptions()
1047: */
1048: #if !PetscDefined(HAVE_THREADSAFETY)
1049: static PetscInt insidematview = 0;
1050: #endif

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

1055:   Collective

1057:   Input Parameters:
1058: + A    - the matrix
1059: . obj  - optional additional object that provides the options prefix to use
1060: - name - command line option

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

1065:   Level: intermediate

1067: .seealso: [](ch_matrices), `Mat`, `MatView()`, `PetscObjectViewFromOptions()`, `MatCreate()`
1068: @*/
1069: PetscErrorCode MatViewFromOptions(Mat A, PetscObject obj, const char name[])
1070: {
1071:   PetscFunctionBegin;
1073: #if !PetscDefined(HAVE_THREADSAFETY)
1074:   if (insidematview) PetscFunctionReturn(PETSC_SUCCESS);
1075: #endif
1076:   PetscCall(PetscObjectViewFromOptions((PetscObject)A, obj, name));
1077:   PetscFunctionReturn(PETSC_SUCCESS);
1078: }

1080: /*@
1081:   MatView - display information about a matrix in a variety ways

1083:   Collective on viewer

1085:   Input Parameters:
1086: + mat    - the matrix
1087: - viewer - visualization context

1089:   Options Database Keys:
1090: + -mat_view ::ascii_info         - Prints info on matrix at conclusion of `MatAssemblyEnd()`
1091: . -mat_view ::ascii_info_detail  - Prints more detailed info
1092: . -mat_view                      - Prints matrix in ASCII format
1093: . -mat_view ::ascii_matlab       - Prints matrix in MATLAB format
1094: . -mat_view draw                 - PetscDraws nonzero structure of matrix, using `MatView()` and `PetscDrawOpenX()`.
1095: . -display name                  - Sets display name (default is host)
1096: . -draw_pause sec                - Sets number of seconds to pause after display
1097: . -mat_view socket               - Sends matrix to socket, can be accessed from MATLAB (see Users-Manual: ch_matlab for details)
1098: . -viewer_socket_machine machine - -
1099: . -viewer_socket_port port       - -
1100: . -mat_view binary               - save matrix to file in binary format
1101: - -viewer_binary_filename name   - -

1103:   Level: beginner

1105:   Notes:
1106:   The available visualization contexts include
1107: +    `PETSC_VIEWER_STDOUT_SELF`   - for sequential matrices
1108: .    `PETSC_VIEWER_STDOUT_WORLD`  - for parallel matrices created on `PETSC_COMM_WORLD`
1109: .    `PETSC_VIEWER_STDOUT_`(comm) - for matrices created on MPI communicator comm
1110: -     `PETSC_VIEWER_DRAW_WORLD`   - graphical display of nonzero structure

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

1118:   The user can call `PetscViewerPushFormat()` to specify the output
1119:   format of ASCII printed objects (when using `PETSC_VIEWER_STDOUT_SELF`,
1120:   `PETSC_VIEWER_STDOUT_WORLD` and `PetscViewerASCIIOpen()`).  Available formats include
1121: +    `PETSC_VIEWER_DEFAULT`           - default, prints matrix contents
1122: .    `PETSC_VIEWER_ASCII_MATLAB`      - prints matrix contents in MATLAB format
1123: .    `PETSC_VIEWER_ASCII_DENSE`       - prints entire matrix including zeros
1124: .    `PETSC_VIEWER_ASCII_COMMON`      - prints matrix contents, using a sparse  format common among all matrix types
1125: .    `PETSC_VIEWER_ASCII_IMPL`        - prints matrix contents, using an implementation-specific format (which is in many cases the same as the default)
1126: .    `PETSC_VIEWER_ASCII_INFO`        - prints basic information about the matrix size and structure (not the matrix entries)
1127: -    `PETSC_VIEWER_ASCII_INFO_DETAIL` - prints more detailed information about the matrix nonzero structure (still not vector or matrix entries)

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

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

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

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

1140:   One can use `-mat_view draw -draw_pause -1` to pause the graphical display of matrix nonzero structure,
1141:   and then use the following mouse functions.
1142: .vb
1143:   left mouse: zoom in
1144:   middle mouse: zoom out
1145:   right mouse: continue with the simulation
1146: .ve

1148: .seealso: [](ch_matrices), `Mat`, `PetscViewerPushFormat()`, `PetscViewerASCIIOpen()`, `PetscViewerDrawOpen()`, `PetscViewer`,
1149:           `PetscViewerSocketOpen()`, `PetscViewerBinaryOpen()`, `MatLoad()`, `MatViewFromOptions()`
1150: @*/
1151: PetscErrorCode MatView(Mat mat, PetscViewer viewer)
1152: {
1153:   PetscInt          rows, cols, rbs, cbs;
1154:   PetscBool         isascii, isstring, issaws;
1155:   PetscViewerFormat format;
1156:   PetscMPIInt       size;

1158:   PetscFunctionBegin;
1161:   if (!viewer) PetscCall(PetscViewerASCIIGetStdout(PetscObjectComm((PetscObject)mat), &viewer));

1164:   PetscCall(PetscViewerGetFormat(viewer, &format));
1165:   PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)viewer), &size));
1166:   if (size == 1 && format == PETSC_VIEWER_LOAD_BALANCE) PetscFunctionReturn(PETSC_SUCCESS);

1168: #if !PetscDefined(HAVE_THREADSAFETY)
1169:   insidematview++;
1170: #endif
1171:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERSTRING, &isstring));
1172:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERASCII, &isascii));
1173:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERSAWS, &issaws));
1174:   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");

1176:   PetscCall(PetscLogEventBegin(MAT_View, mat, viewer, 0, 0));
1177:   if (isascii) {
1178:     if (!mat->preallocated) {
1179:       PetscCall(PetscViewerASCIIPrintf(viewer, "Matrix has not been preallocated yet\n"));
1180: #if !PetscDefined(HAVE_THREADSAFETY)
1181:       insidematview--;
1182: #endif
1183:       PetscCall(PetscLogEventEnd(MAT_View, mat, viewer, 0, 0));
1184:       PetscFunctionReturn(PETSC_SUCCESS);
1185:     }
1186:     if (!mat->assembled) {
1187:       PetscCall(PetscViewerASCIIPrintf(viewer, "Matrix has not been assembled yet\n"));
1188: #if !PetscDefined(HAVE_THREADSAFETY)
1189:       insidematview--;
1190: #endif
1191:       PetscCall(PetscLogEventEnd(MAT_View, mat, viewer, 0, 0));
1192:       PetscFunctionReturn(PETSC_SUCCESS);
1193:     }
1194:     PetscCall(PetscObjectPrintClassNamePrefixType((PetscObject)mat, viewer));
1195:     if (format == PETSC_VIEWER_ASCII_INFO || format == PETSC_VIEWER_ASCII_INFO_DETAIL) {
1196:       MatNullSpace nullsp, transnullsp;
1197:       PetscBool    nz_factor = PETSC_TRUE;

1199:       PetscCall(PetscViewerASCIIPushTab(viewer));
1200:       PetscCall(MatGetSize(mat, &rows, &cols));
1201:       PetscCall(MatGetBlockSizes(mat, &rbs, &cbs));
1202:       if (rbs != 1 || cbs != 1) {
1203:         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" : ""));
1204:         else PetscCall(PetscViewerASCIIPrintf(viewer, "rows=%" PetscInt_FMT ", cols=%" PetscInt_FMT ", bs=%" PetscInt_FMT "%s\n", rows, cols, rbs, mat->bsizes ? " variable blocks set" : ""));
1205:       } else PetscCall(PetscViewerASCIIPrintf(viewer, "rows=%" PetscInt_FMT ", cols=%" PetscInt_FMT "\n", rows, cols));
1206:       if (mat->factortype) {
1207:         MatSolverType solver;

1209:         PetscCall(MatFactorGetSolverType(mat, &solver));
1210:         PetscCall(PetscViewerASCIIPrintf(viewer, "package used to perform factorization: %s\n", solver));
1211:         PetscCall(PetscStrcmpAny(solver, &nz_factor, MATSOLVERUMFPACK, MATSOLVERCHOLMOD, MATSOLVERSUPERLU, MATSOLVERSUPERLU_DIST, MATSOLVERSTRUMPACK, MATSOLVERHTOOL, ""));
1212:         nz_factor = !nz_factor;
1213:       }
1214:       if (mat->ops->getinfo) {
1215:         PetscBool is_constant_or_diagonal;

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

1222:           PetscCall(MatGetInfo(mat, MAT_GLOBAL_SUM, &info));
1223:           PetscCall(PetscViewerASCIIPrintf(viewer, "total: nonzeros=%.f, allocated nonzeros=%.f\n", info.nz_used, info.nz_allocated));
1224:           if (!mat->factortype) PetscCall(PetscViewerASCIIPrintf(viewer, "total number of mallocs used during MatSetValues calls=%" PetscInt_FMT "\n", (PetscInt)info.mallocs));
1225:         }
1226:       }
1227:       PetscCall(MatGetNullSpace(mat, &nullsp));
1228:       PetscCall(MatGetTransposeNullSpace(mat, &transnullsp));
1229:       if (nullsp) PetscCall(PetscViewerASCIIPrintf(viewer, "  has attached null space\n"));
1230:       if (transnullsp && transnullsp != nullsp) PetscCall(PetscViewerASCIIPrintf(viewer, "  has attached transposed null space\n"));
1231:       PetscCall(MatGetNearNullSpace(mat, &nullsp));
1232:       if (nullsp) PetscCall(PetscViewerASCIIPrintf(viewer, "  has attached near null space\n"));
1233:       PetscCall(PetscViewerASCIIPushTab(viewer));
1234:       PetscCall(MatProductView(mat, viewer));
1235:       PetscCall(PetscViewerASCIIPopTab(viewer));
1236:       if (mat->bsizes && format == PETSC_VIEWER_ASCII_INFO_DETAIL) {
1237:         IS tmp;

1239:         PetscCall(ISCreateGeneral(PetscObjectComm((PetscObject)viewer), mat->nblocks, mat->bsizes, PETSC_USE_POINTER, &tmp));
1240:         PetscCall(PetscObjectSetName((PetscObject)tmp, "Block Sizes"));
1241:         PetscCall(PetscViewerASCIIPushTab(viewer));
1242:         PetscCall(ISView(tmp, viewer));
1243:         PetscCall(PetscViewerASCIIPopTab(viewer));
1244:         PetscCall(ISDestroy(&tmp));
1245:       }
1246:     }
1247:   } else if (issaws) {
1248: #if PetscDefined(HAVE_SAWS)
1249:     PetscMPIInt rank;

1251:     PetscCall(PetscObjectName((PetscObject)mat));
1252:     PetscCallMPI(MPI_Comm_rank(PETSC_COMM_WORLD, &rank));
1253:     if (!((PetscObject)mat)->amsmem && rank == 0) PetscCall(PetscObjectViewSAWs((PetscObject)mat, viewer));
1254: #endif
1255:   } else if (isstring) {
1256:     const char *type;
1257:     PetscCall(MatGetType(mat, &type));
1258:     PetscCall(PetscViewerStringSPrintf(viewer, " MatType: %-7.7s", type));
1259:     PetscTryTypeMethod(mat, view, viewer);
1260:   }
1261:   if ((format == PETSC_VIEWER_NATIVE || format == PETSC_VIEWER_LOAD_BALANCE) && mat->ops->viewnative) {
1262:     PetscCall(PetscViewerASCIIPushTab(viewer));
1263:     PetscUseTypeMethod(mat, viewnative, viewer);
1264:     PetscCall(PetscViewerASCIIPopTab(viewer));
1265:   } else if (mat->ops->view) {
1266:     PetscCall(PetscViewerASCIIPushTab(viewer));
1267:     PetscUseTypeMethod(mat, view, viewer);
1268:     PetscCall(PetscViewerASCIIPopTab(viewer));
1269:   }
1270:   if (isascii) {
1271:     PetscCall(PetscViewerGetFormat(viewer, &format));
1272:     if (format == PETSC_VIEWER_ASCII_INFO || format == PETSC_VIEWER_ASCII_INFO_DETAIL) PetscCall(PetscViewerASCIIPopTab(viewer));
1273:   }
1274:   PetscCall(PetscLogEventEnd(MAT_View, mat, viewer, 0, 0));
1275: #if !PetscDefined(HAVE_THREADSAFETY)
1276:   insidematview--;
1277: #endif
1278:   PetscFunctionReturn(PETSC_SUCCESS);
1279: }

1281: #if PetscDefined(USE_DEBUG)
1282: #include <../src/sys/totalview/tv_data_display.h>
1283: PETSC_UNUSED static int TV_display_type(const struct _p_Mat *mat)
1284: {
1285:   TV_add_row("Local rows", "int", &mat->rmap->n);
1286:   TV_add_row("Local columns", "int", &mat->cmap->n);
1287:   TV_add_row("Global rows", "int", &mat->rmap->N);
1288:   TV_add_row("Global columns", "int", &mat->cmap->N);
1289:   TV_add_row("Typename", TV_ascii_string_type, ((PetscObject)mat)->type_name);
1290:   return TV_format_OK;
1291: }
1292: #endif

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

1300:   Collective

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

1307:   Options Database Key:
1308: . -matload_block_size bs - set block size

1310:   Level: beginner

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

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

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

1325:   In parallel, each processor can load a subset of rows (or the
1326:   entire matrix).  This routine is especially useful when a large
1327:   matrix is stored on disk and only part of it is desired on each
1328:   processor.  For example, a parallel solver may access only some of
1329:   the rows from each processor.  The algorithm used here reads
1330:   relatively small blocks of data rather than reading the entire
1331:   matrix and then subsetting it.

1333:   Viewer's `PetscViewerType` must be either `PETSCVIEWERBINARY` or `PETSCVIEWERHDF5`.
1334:   Such viewer can be created using `PetscViewerBinaryOpen()` or `PetscViewerHDF5Open()`,
1335:   or the sequence like
1336: .vb
1337:     PetscViewer v;
1338:     PetscViewerCreate(PETSC_COMM_WORLD, &v);
1339:     PetscViewerSetType(v, PETSCVIEWERBINARY);
1340:     PetscViewerSetFromOptions(v);
1341:     PetscViewerFileSetMode(v, FILE_MODE_READ);
1342:     PetscViewerFileSetName(v, "datafile");
1343: .ve
1344:   The optional `PetscViewerSetFromOptions()` call allows overriding `PetscViewerSetType()` using the option
1345: .vb
1346:   -viewer_type (binary|hdf5)
1347: .ve

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

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

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

1362: .vb
1363:     PetscInt    MAT_FILE_CLASSID
1364:     PetscInt    number of rows
1365:     PetscInt    number of columns
1366:     PetscInt    total number of nonzeros
1367:     PetscInt    *number nonzeros in each row
1368:     PetscInt    *column indices of all nonzeros (starting index is zero)
1369:     PetscScalar *values of all nonzeros
1370: .ve
1371:   If PETSc was not configured with `--with-64-bit-indices` then only `MATMPIAIJ` matrices with more than `PETSC_INT_MAX` non-zeros can be
1372:   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
1373:   case will not fit in a (32-bit) `PetscInt` the value `PETSC_INT_MAX` is used for the header entry `total number of nonzeros`.

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

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

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

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

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

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

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

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

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

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

1413: .seealso: [](ch_matrices), `Mat`, `PetscViewerBinaryOpen()`, `PetscViewerSetType()`, `MatView()`, `VecLoad()`
1414:  @*/
1415: PetscErrorCode MatLoad(Mat mat, PetscViewer viewer)
1416: {
1417:   PetscBool flg;

1419:   PetscFunctionBegin;

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

1425:   flg = PETSC_FALSE;
1426:   PetscCall(PetscOptionsGetBool(((PetscObject)mat)->options, ((PetscObject)mat)->prefix, "-matload_symmetric", &flg, NULL));
1427:   if (flg) {
1428:     PetscCall(MatSetOption(mat, MAT_SYMMETRIC, PETSC_TRUE));
1429:     PetscCall(MatSetOption(mat, MAT_SYMMETRY_ETERNAL, PETSC_TRUE));
1430:   }
1431:   flg = PETSC_FALSE;
1432:   PetscCall(PetscOptionsGetBool(((PetscObject)mat)->options, ((PetscObject)mat)->prefix, "-matload_spd", &flg, NULL));
1433:   if (flg) PetscCall(MatSetOption(mat, MAT_SPD, PETSC_TRUE));

1435:   PetscCall(PetscLogEventBegin(MAT_Load, mat, viewer, 0, 0));
1436:   PetscUseTypeMethod(mat, load, viewer);
1437:   PetscCall(PetscLogEventEnd(MAT_Load, mat, viewer, 0, 0));
1438:   PetscFunctionReturn(PETSC_SUCCESS);
1439: }

1441: static PetscErrorCode MatDestroy_Redundant(Mat_Redundant **redundant)
1442: {
1443:   Mat_Redundant *redund = *redundant;

1445:   PetscFunctionBegin;
1446:   if (redund) {
1447:     if (redund->matseq) { /* via MatCreateSubMatrices()  */
1448:       PetscCall(ISDestroy(&redund->isrow));
1449:       PetscCall(ISDestroy(&redund->iscol));
1450:       PetscCall(MatDestroySubMatrices(1, &redund->matseq));
1451:     } else {
1452:       PetscCall(PetscFree2(redund->send_rank, redund->recv_rank));
1453:       PetscCall(PetscFree(redund->sbuf_j));
1454:       PetscCall(PetscFree(redund->sbuf_a));
1455:       for (PetscInt i = 0; i < redund->nrecvs; i++) {
1456:         PetscCall(PetscFree(redund->rbuf_j[i]));
1457:         PetscCall(PetscFree(redund->rbuf_a[i]));
1458:       }
1459:       PetscCall(PetscFree4(redund->sbuf_nz, redund->rbuf_nz, redund->rbuf_j, redund->rbuf_a));
1460:     }

1462:     PetscCall(PetscCommDestroy(&redund->subcomm));
1463:     PetscCall(PetscFree(redund));
1464:   }
1465:   PetscFunctionReturn(PETSC_SUCCESS);
1466: }

1468: /*@
1469:   MatDestroy - Frees space taken by a matrix.

1471:   Collective

1473:   Input Parameter:
1474: . A - the matrix

1476:   Level: beginner

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

1484: .seealso: [](ch_matrices), `Mat`, `MatCreate()`
1485: @*/
1486: PetscErrorCode MatDestroy(Mat *A)
1487: {
1488:   PetscFunctionBegin;
1489:   if (!*A) PetscFunctionReturn(PETSC_SUCCESS);
1491:   if (--((PetscObject)*A)->refct > 0) {
1492:     *A = NULL;
1493:     PetscFunctionReturn(PETSC_SUCCESS);
1494:   }

1496:   /* if memory was published with SAWs then destroy it */
1497:   PetscCall(PetscObjectSAWsViewOff((PetscObject)*A));
1498:   PetscTryTypeMethod(*A, destroy);

1500:   PetscCall(PetscFree((*A)->factorprefix));
1501:   PetscCall(PetscFree((*A)->defaultvectype));
1502:   PetscCall(PetscFree((*A)->defaultrandtype));
1503:   PetscCall(PetscFree((*A)->bsizes));
1504:   PetscCall(PetscFree((*A)->solvertype));
1505:   for (PetscInt i = 0; i < MAT_FACTOR_NUM_TYPES; i++) PetscCall(PetscFree((*A)->preferredordering[i]));
1506:   if ((*A)->redundant && (*A)->redundant->matseq[0] == *A) (*A)->redundant->matseq[0] = NULL;
1507:   PetscCall(MatDestroy_Redundant(&(*A)->redundant));
1508:   PetscCall(MatProductClear(*A));
1509:   PetscCall(MatNullSpaceDestroy(&(*A)->nullsp));
1510:   PetscCall(MatNullSpaceDestroy(&(*A)->transnullsp));
1511:   PetscCall(MatNullSpaceDestroy(&(*A)->nearnullsp));
1512:   PetscCall(MatDestroy(&(*A)->schur));
1513:   PetscCall(VecDestroy(&(*A)->dot_vec));
1514:   PetscCall(PetscLayoutDestroy(&(*A)->rmap));
1515:   PetscCall(PetscLayoutDestroy(&(*A)->cmap));
1516:   PetscCall(PetscHeaderDestroy(A));
1517:   PetscFunctionReturn(PETSC_SUCCESS);
1518: }

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

1526:   Not Collective

1528:   Input Parameters:
1529: + mat  - the matrix
1530: . m    - the number of rows
1531: . idxm - the global indices of the rows
1532: . n    - the number of columns
1533: . idxn - the global indices of the columns
1534: . v    - a one-dimensional array that contains the values implicitly stored as a two-dimensional array, by default in row-major order.
1535:          See `MAT_ROW_ORIENTED` in `MatSetOption()` for how to use column-major order.
1536: - addv - either `ADD_VALUES` to add values to any existing entries, or `INSERT_VALUES` to replace existing entries with new values

1538:   Level: beginner

1540:   Notes:
1541:   Calls to `MatSetValues()` with the `INSERT_VALUES` and `ADD_VALUES`
1542:   options cannot be mixed without intervening calls to the assembly
1543:   routines.

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

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

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

1556:   Fortran Notes:
1557:   If any of `idxm`, `idxn`, and `v` are scalars pass them using, for example,
1558: .vb
1559:   call MatSetValues(mat, one, [idxm], one, [idxn], [v], INSERT_VALUES, ierr)
1560: .ve

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

1565: .seealso: [](ch_matrices), `Mat`, `MatSetOption()`, `MatAssemblyBegin()`, `MatAssemblyEnd()`, `MatSetValuesBlocked()`, `MatSetValuesLocal()`,
1566:           `InsertMode`, `INSERT_VALUES`, `ADD_VALUES`
1567: @*/
1568: PetscErrorCode MatSetValues(Mat mat, PetscInt m, const PetscInt idxm[], PetscInt n, const PetscInt idxn[], const PetscScalar v[], InsertMode addv)
1569: {
1570:   PetscFunctionBeginHot;
1573:   if (!m || !n) PetscFunctionReturn(PETSC_SUCCESS); /* no values to insert */
1574:   PetscAssertPointer(idxm, 3);
1575:   PetscAssertPointer(idxn, 5);
1576:   MatCheckPreallocated(mat, 1);

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

1581:   if (PetscDefined(USE_DEBUG)) {
1582:     PetscInt i, j;

1584:     PetscCheck(!mat->factortype, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
1585:     if (v) {
1586:       for (i = 0; i < m; i++) {
1587:         for (j = 0; j < n; j++) {
1588:           if (mat->erroriffailure && PetscIsInfOrNanScalar(v[i * n + j]))
1589: #if PetscDefined(USE_COMPLEX)
1590:             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]);
1591: #else
1592:             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]);
1593: #endif
1594:         }
1595:       }
1596:     }
1597:     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);
1598:     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);
1599:   }

1601:   if (mat->assembled) {
1602:     mat->was_assembled = PETSC_TRUE;
1603:     mat->assembled     = PETSC_FALSE;
1604:   }
1605:   PetscCall(PetscLogEventBegin(MAT_SetValues, mat, 0, 0, 0));
1606:   PetscUseTypeMethod(mat, setvalues, m, idxm, n, idxn, v, addv);
1607:   PetscCall(PetscLogEventEnd(MAT_SetValues, mat, 0, 0, 0));
1608:   PetscFunctionReturn(PETSC_SUCCESS);
1609: }

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

1617:   Not Collective

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

1627:   Level: beginner

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

1632:   Calls to `MatSetValues()` with the `INSERT_VALUES` and `ADD_VALUES`
1633:   options cannot be mixed without intervening calls to the assembly
1634:   routines.

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

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

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

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

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

1654: .seealso: [](ch_matrices), `Mat`, `MatSetOption()`, `MatSetValues()`, `MatAssemblyBegin()`, `MatAssemblyEnd()`, `MatSetValuesBlocked()`, `MatSetValuesLocal()`,
1655:           `InsertMode`, `INSERT_VALUES`, `ADD_VALUES`
1656: @*/
1657: PetscErrorCode MatSetValuesIS(Mat mat, IS ism, IS isn, const PetscScalar v[], InsertMode addv)
1658: {
1659:   PetscInt        m, n;
1660:   const PetscInt *rows, *cols;

1662:   PetscFunctionBeginHot;
1664:   PetscCall(ISGetIndices(ism, &rows));
1665:   PetscCall(ISGetIndices(isn, &cols));
1666:   PetscCall(ISGetLocalSize(ism, &m));
1667:   PetscCall(ISGetLocalSize(isn, &n));
1668:   PetscCall(MatSetValues(mat, m, rows, n, cols, v, addv));
1669:   PetscCall(ISRestoreIndices(ism, &rows));
1670:   PetscCall(ISRestoreIndices(isn, &cols));
1671:   PetscFunctionReturn(PETSC_SUCCESS);
1672: }

1674: /*@
1675:   MatSetValuesRowLocal - Inserts a row of nonzero values into a matrix

1677:   Not Collective

1679:   Input Parameters:
1680: + mat - the matrix
1681: . row - the row to set
1682: - v   - a one-dimensional array that contains the values

1684:   Level: intermediate

1686:   Notes:
1687:   Currently only supported for `MATAIJ`.

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

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

1693:   `row` must belong to this MPI process

1695: .seealso: [](ch_matrices), `Mat`, `MatSetOption()`, `MatAssemblyBegin()`, `MatAssemblyEnd()`, `MatSetValuesBlocked()`, `MatSetValuesLocal()`,
1696:           `InsertMode`, `INSERT_VALUES`, `ADD_VALUES`, `MatSetValues()`, `MatSetValuesRow()`, `MatSetLocalToGlobalMapping()`, `MATAIJ`
1697: @*/
1698: PetscErrorCode MatSetValuesRowLocal(Mat mat, PetscInt row, const PetscScalar v[])
1699: {
1700:   PetscInt globalrow;

1702:   PetscFunctionBegin;
1705:   PetscAssertPointer(v, 3);
1706:   PetscCall(ISLocalToGlobalMappingApply(mat->rmap->mapping, 1, &row, &globalrow));
1707:   PetscCall(MatSetValuesRow(mat, globalrow, v));
1708:   PetscFunctionReturn(PETSC_SUCCESS);
1709: }

1711: /*@
1712:   MatSetValuesRow - Inserts a row of nonzero values into a matrix

1714:   Not Collective

1716:   Input Parameters:
1717: + mat - the matrix
1718: . row - the row to set
1719: - v   - a one dimensional array of values

1721:   Level: advanced

1723:   Notes:
1724:   Currently only supported for `MATAIJ`.

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

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

1730:   `row` must belong to this process

1732: .seealso: [](ch_matrices), `Mat`, `MatSetValues()`, `MatSetOption()`, `MatAssemblyBegin()`, `MatAssemblyEnd()`, `MatSetValuesBlocked()`, `MatSetValuesLocal()`,
1733:           `InsertMode`, `INSERT_VALUES`, `ADD_VALUES`, `MATAIJ`
1734: @*/
1735: PetscErrorCode MatSetValuesRow(Mat mat, PetscInt row, const PetscScalar v[])
1736: {
1737:   PetscFunctionBeginHot;
1740:   MatCheckPreallocated(mat, 1);
1741:   PetscAssertPointer(v, 3);
1742:   PetscCheck(mat->insertmode != ADD_VALUES, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Cannot mix add and insert values");
1743:   PetscCheck(!mat->factortype, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
1744:   mat->insertmode = INSERT_VALUES;

1746:   if (mat->assembled) {
1747:     mat->was_assembled = PETSC_TRUE;
1748:     mat->assembled     = PETSC_FALSE;
1749:   }
1750:   PetscCall(PetscLogEventBegin(MAT_SetValues, mat, 0, 0, 0));
1751:   PetscUseTypeMethod(mat, setvaluesrow, row, v);
1752:   PetscCall(PetscLogEventEnd(MAT_SetValues, mat, 0, 0, 0));
1753:   PetscFunctionReturn(PETSC_SUCCESS);
1754: }

1756: // PetscClangLinter pragma disable: -fdoc-section-header-unknown
1757: /*@
1758:   MatSetValuesStencil - Inserts or adds a block of values into a matrix.
1759:   Using structured grid indexing

1761:   Not Collective

1763:   Input Parameters:
1764: + mat  - the matrix
1765: . m    - number of rows being entered
1766: . idxm - grid coordinates (and component number when dof > 1) for matrix rows being entered
1767: . n    - number of columns being entered
1768: . idxn - grid coordinates (and component number when dof > 1) for matrix columns being entered
1769: . v    - a one-dimensional array that contains the values implicitly stored as a two-dimensional array, by default in row-major order.
1770:          See `MAT_ROW_ORIENTED` in `MatSetOption()` for how to use column-major order.
1771: - addv - either `ADD_VALUES` to add to existing entries at that location or `INSERT_VALUES` to replace existing entries with new values

1773:   Level: beginner

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

1778:   Calls to `MatSetValuesStencil()` with the `INSERT_VALUES` and `ADD_VALUES`
1779:   options cannot be mixed without intervening calls to the assembly
1780:   routines.

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

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

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

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

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

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

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

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

1809:   Fortran Notes:
1810:   If any of `idxm`, `idxn`, and `v` are scalars pass them using, for example,
1811: .vb
1812:   call MatSetValuesStencil(mat, one, [idxm], one, [idxn], [v], INSERT_VALUES, ierr)
1813: .ve

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

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

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

1831:   PetscFunctionBegin;
1832:   if (!m || !n) PetscFunctionReturn(PETSC_SUCCESS); /* no values to insert */
1835:   PetscAssertPointer(idxm, 3);
1836:   PetscAssertPointer(idxn, 5);

1838:   if ((m + n) <= (PetscInt)PETSC_STATIC_ARRAY_LENGTH(buf)) {
1839:     jdxm = buf;
1840:     jdxn = buf + m;
1841:   } else {
1842:     PetscCall(PetscMalloc2(m, &bufm, n, &bufn));
1843:     jdxm = bufm;
1844:     jdxn = bufn;
1845:   }
1846:   for (i = 0; i < m; i++) {
1847:     for (j = 0; j < 3 - sdim; j++) dxm++;
1848:     tmp = *dxm++ - starts[0];
1849:     for (j = 0; j < dim - 1; j++) {
1850:       if ((*dxm++ - starts[j + 1]) < 0 || tmp < 0) tmp = -1;
1851:       else tmp = tmp * dims[j] + *(dxm - 1) - starts[j + 1];
1852:     }
1853:     if (mat->stencil.noc) dxm++;
1854:     jdxm[i] = tmp;
1855:   }
1856:   for (i = 0; i < n; i++) {
1857:     for (j = 0; j < 3 - sdim; j++) dxn++;
1858:     tmp = *dxn++ - starts[0];
1859:     for (j = 0; j < dim - 1; j++) {
1860:       if ((*dxn++ - starts[j + 1]) < 0 || tmp < 0) tmp = -1;
1861:       else tmp = tmp * dims[j] + *(dxn - 1) - starts[j + 1];
1862:     }
1863:     if (mat->stencil.noc) dxn++;
1864:     jdxn[i] = tmp;
1865:   }
1866:   PetscCall(MatSetValuesLocal(mat, m, jdxm, n, jdxn, v, addv));
1867:   PetscCall(PetscFree2(bufm, bufn));
1868:   PetscFunctionReturn(PETSC_SUCCESS);
1869: }

1871: /*@
1872:   MatSetValuesBlockedStencil - Inserts or adds a block of values into a matrix.
1873:   Using structured grid indexing

1875:   Not Collective

1877:   Input Parameters:
1878: + mat  - the matrix
1879: . m    - number of rows being entered
1880: . idxm - grid coordinates for matrix rows being entered
1881: . n    - number of columns being entered
1882: . idxn - grid coordinates for matrix columns being entered
1883: . v    - a one-dimensional array that contains the values implicitly stored as a two-dimensional array, by default in row-major order.
1884:          See `MAT_ROW_ORIENTED` in `MatSetOption()` for how to use column-major order.
1885: - addv - either `ADD_VALUES` to add to existing entries or `INSERT_VALUES` to replace existing entries with new values

1887:   Level: beginner

1889:   Notes:
1890:   By default the values, `v`, are row-oriented and unsorted.
1891:   See `MatSetOption()` for other options.

1893:   Calls to `MatSetValuesBlockedStencil()` with the `INSERT_VALUES` and `ADD_VALUES`
1894:   options cannot be mixed without intervening calls to the assembly
1895:   routines.

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

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

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

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

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

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

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

1921:   Fortran Notes:
1922:   If any of `idxm`, `idxn`, and `v` are scalars pass them using, for example,
1923: .vb
1924:   call MatSetValuesBlockedStencil(mat, one, [idxm], one, [idxn], [v], INSERT_VALUES, ierr)
1925: .ve

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

1930: .seealso: [](ch_matrices), `Mat`, `DMDA`, `MatSetOption()`, `MatAssemblyBegin()`, `MatAssemblyEnd()`, `MatSetValuesBlocked()`, `MatSetValuesLocal()`,
1931:           `MatSetValues()`, `MatSetValuesStencil()`, `MatSetStencil()`, `DMCreateMatrix()`, `DMDAVecGetArray()`, `MatStencil`,
1932:           `MatSetBlockSize()`, `MatSetLocalToGlobalMapping()`
1933: @*/
1934: PetscErrorCode MatSetValuesBlockedStencil(Mat mat, PetscInt m, const MatStencil idxm[], PetscInt n, const MatStencil idxn[], const PetscScalar v[], InsertMode addv)
1935: {
1936:   PetscInt  buf[8192], *bufm = NULL, *bufn = NULL, *jdxm, *jdxn;
1937:   PetscInt  j, i, dim = mat->stencil.dim, *dims = mat->stencil.dims + 1, tmp;
1938:   PetscInt *starts = mat->stencil.starts, *dxm = (PetscInt *)idxm, *dxn = (PetscInt *)idxn, sdim = dim - (1 - (PetscInt)mat->stencil.noc);

1940:   PetscFunctionBegin;
1941:   if (!m || !n) PetscFunctionReturn(PETSC_SUCCESS); /* no values to insert */
1944:   PetscAssertPointer(idxm, 3);
1945:   PetscAssertPointer(idxn, 5);
1946:   PetscAssertPointer(v, 6);

1948:   if ((m + n) <= (PetscInt)PETSC_STATIC_ARRAY_LENGTH(buf)) {
1949:     jdxm = buf;
1950:     jdxn = buf + m;
1951:   } else {
1952:     PetscCall(PetscMalloc2(m, &bufm, n, &bufn));
1953:     jdxm = bufm;
1954:     jdxn = bufn;
1955:   }
1956:   for (i = 0; i < m; i++) {
1957:     for (j = 0; j < 3 - sdim; j++) dxm++;
1958:     tmp = *dxm++ - starts[0];
1959:     for (j = 0; j < sdim - 1; j++) {
1960:       if ((*dxm++ - starts[j + 1]) < 0 || tmp < 0) tmp = -1;
1961:       else tmp = tmp * dims[j] + *(dxm - 1) - starts[j + 1];
1962:     }
1963:     dxm++;
1964:     jdxm[i] = tmp;
1965:   }
1966:   for (i = 0; i < n; i++) {
1967:     for (j = 0; j < 3 - sdim; j++) dxn++;
1968:     tmp = *dxn++ - starts[0];
1969:     for (j = 0; j < sdim - 1; j++) {
1970:       if ((*dxn++ - starts[j + 1]) < 0 || tmp < 0) tmp = -1;
1971:       else tmp = tmp * dims[j] + *(dxn - 1) - starts[j + 1];
1972:     }
1973:     dxn++;
1974:     jdxn[i] = tmp;
1975:   }
1976:   PetscCall(MatSetValuesBlockedLocal(mat, m, jdxm, n, jdxn, v, addv));
1977:   PetscCall(PetscFree2(bufm, bufn));
1978:   PetscFunctionReturn(PETSC_SUCCESS);
1979: }

1981: /*@
1982:   MatSetStencil - Sets the grid information for setting values into a matrix via
1983:   `MatSetValuesStencil()`

1985:   Not Collective

1987:   Input Parameters:
1988: + mat    - the matrix
1989: . dim    - dimension of the grid 1, 2, or 3
1990: . dims   - number of grid points in x, y, and z direction, including ghost points on your processor
1991: . starts - starting point of ghost nodes on your processor in x, y, and z direction
1992: - dof    - number of degrees of freedom per node

1994:   Level: beginner

1996:   Notes:
1997:   Inspired by the structured grid interface to the HYPRE package
1998:   (www.llnl.gov/CASC/hyper)

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

2003: .seealso: [](ch_matrices), `Mat`, `MatStencil`, `MatSetOption()`, `MatAssemblyBegin()`, `MatAssemblyEnd()`, `MatSetValuesBlocked()`, `MatSetValuesLocal()`,
2004:           `MatSetValues()`, `MatSetValuesBlockedStencil()`, `MatSetValuesStencil()`
2005: @*/
2006: PetscErrorCode MatSetStencil(Mat mat, PetscInt dim, const PetscInt dims[], const PetscInt starts[], PetscInt dof)
2007: {
2008:   PetscFunctionBegin;
2010:   PetscAssertPointer(dims, 3);
2011:   PetscAssertPointer(starts, 4);

2013:   mat->stencil.dim = dim + (dof > 1);
2014:   for (PetscInt i = 0; i < dim; i++) {
2015:     mat->stencil.dims[i]   = dims[dim - i - 1]; /* copy the values in backwards */
2016:     mat->stencil.starts[i] = starts[dim - i - 1];
2017:   }
2018:   mat->stencil.dims[dim]   = dof;
2019:   mat->stencil.starts[dim] = 0;
2020:   mat->stencil.noc         = (PetscBool)(dof == 1);
2021:   PetscFunctionReturn(PETSC_SUCCESS);
2022: }

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

2027:   Not Collective

2029:   Input Parameters:
2030: + mat  - the matrix
2031: . m    - the number of block rows
2032: . idxm - the global block indices
2033: . n    - the number of block columns
2034: . idxn - the global block indices
2035: . v    - a one-dimensional array that contains the values implicitly stored as a two-dimensional array, by default in row-major order.
2036:          See `MAT_ROW_ORIENTED` in `MatSetOption()` for how to use column-major order.
2037: - addv - either `ADD_VALUES` to add values to any existing entries, or `INSERT_VALUES` replaces existing entries with new values

2039:   Level: intermediate

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

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

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

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

2056:   Calls to `MatSetValuesBlocked()` with the `INSERT_VALUES` and `ADD_VALUES`
2057:   options cannot be mixed without intervening calls to the assembly
2058:   routines.

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

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

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

2074:   Example:
2075: .vb
2076:    Suppose m=n=2 and block size(bs) = 2 The array is

2078:    1  2  | 3  4
2079:    5  6  | 7  8
2080:    - - - | - - -
2081:    9  10 | 11 12
2082:    13 14 | 15 16

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

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

2091:   Fortran Notes:
2092:   If any of `idmx`, `idxn`, and `v` are scalars pass them using, for example,
2093: .vb
2094:   call MatSetValuesBlocked(mat, one, [idxm], one, [idxn], [v], INSERT_VALUES, ierr)
2095: .ve

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

2100: .seealso: [](ch_matrices), `Mat`, `MatSetBlockSize()`, `MatSetOption()`, `MatAssemblyBegin()`, `MatAssemblyEnd()`, `MatSetValues()`, `MatSetValuesBlockedLocal()`
2101: @*/
2102: PetscErrorCode MatSetValuesBlocked(Mat mat, PetscInt m, const PetscInt idxm[], PetscInt n, const PetscInt idxn[], const PetscScalar v[], InsertMode addv)
2103: {
2104:   PetscFunctionBeginHot;
2107:   if (!m || !n) PetscFunctionReturn(PETSC_SUCCESS); /* no values to insert */
2108:   PetscAssertPointer(idxm, 3);
2109:   PetscAssertPointer(idxn, 5);
2110:   MatCheckPreallocated(mat, 1);
2111:   if (mat->insertmode == NOT_SET_VALUES) mat->insertmode = addv;
2112:   else PetscCheck(mat->insertmode == addv, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Cannot mix add values and insert values");
2113:   if (PetscDefined(USE_DEBUG)) {
2114:     PetscCheck(!mat->factortype, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
2115:     PetscCheck(mat->ops->setvaluesblocked || mat->ops->setvalues, PETSC_COMM_SELF, PETSC_ERR_SUP, "Mat type %s", ((PetscObject)mat)->type_name);
2116:   }
2117:   if (PetscDefined(USE_DEBUG)) {
2118:     PetscInt rbs, cbs, M, N, i;
2119:     PetscCall(MatGetBlockSizes(mat, &rbs, &cbs));
2120:     PetscCall(MatGetSize(mat, &M, &N));
2121:     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);
2122:     for (i = 0; i < n; i++)
2123:       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);
2124:   }
2125:   if (mat->assembled) {
2126:     mat->was_assembled = PETSC_TRUE;
2127:     mat->assembled     = PETSC_FALSE;
2128:   }
2129:   PetscCall(PetscLogEventBegin(MAT_SetValues, mat, 0, 0, 0));
2130:   if (mat->ops->setvaluesblocked) PetscUseTypeMethod(mat, setvaluesblocked, m, idxm, n, idxn, v, addv);
2131:   else {
2132:     PetscInt buf[8192], *bufr = NULL, *bufc = NULL, *iidxm, *iidxn;
2133:     PetscInt i, j, bs, cbs;

2135:     PetscCall(MatGetBlockSizes(mat, &bs, &cbs));
2136:     if ((m * bs + n * cbs) <= (PetscInt)PETSC_STATIC_ARRAY_LENGTH(buf)) {
2137:       iidxm = buf;
2138:       iidxn = buf + m * bs;
2139:     } else {
2140:       PetscCall(PetscMalloc2(m * bs, &bufr, n * cbs, &bufc));
2141:       iidxm = bufr;
2142:       iidxn = bufc;
2143:     }
2144:     for (i = 0; i < m; i++) {
2145:       for (j = 0; j < bs; j++) iidxm[i * bs + j] = bs * idxm[i] + j;
2146:     }
2147:     if (m != n || bs != cbs || idxm != idxn) {
2148:       for (i = 0; i < n; i++) {
2149:         for (j = 0; j < cbs; j++) iidxn[i * cbs + j] = cbs * idxn[i] + j;
2150:       }
2151:     } else iidxn = iidxm;
2152:     PetscCall(MatSetValues(mat, m * bs, iidxm, n * cbs, iidxn, v, addv));
2153:     PetscCall(PetscFree2(bufr, bufc));
2154:   }
2155:   PetscCall(PetscLogEventEnd(MAT_SetValues, mat, 0, 0, 0));
2156:   PetscFunctionReturn(PETSC_SUCCESS);
2157: }

2159: /*@
2160:   MatGetValues - Gets a block of local values from a matrix.

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

2164:   Input Parameters:
2165: + mat  - the matrix
2166: . v    - a logically two-dimensional array for storing the values
2167: . m    - the number of rows
2168: . idxm - the  global indices of the rows
2169: . n    - the number of columns
2170: - idxn - the global indices of the columns

2172:   Level: advanced

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

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

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

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

2185:   `MatGetValues()` requires that the matrix has been assembled
2186:   with `MatAssemblyBegin()`/`MatAssemblyEnd()`.  Thus, calls to
2187:   `MatSetValues()` and `MatGetValues()` CANNOT be made in succession
2188:   without intermediate matrix assembly.

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

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

2197: .seealso: [](ch_matrices), `Mat`, `MatGetRow()`, `MatCreateSubMatrices()`, `MatSetValues()`, `MatGetOwnershipRange()`, `MatGetValuesLocal()`, `MatGetValue()`
2198: @*/
2199: PetscErrorCode MatGetValues(Mat mat, PetscInt m, const PetscInt idxm[], PetscInt n, const PetscInt idxn[], PetscScalar v[])
2200: {
2201:   PetscFunctionBegin;
2204:   if (!m || !n) PetscFunctionReturn(PETSC_SUCCESS);
2205:   PetscAssertPointer(idxm, 3);
2206:   PetscAssertPointer(idxn, 5);
2207:   PetscAssertPointer(v, 6);
2208:   PetscCheck(mat->assembled, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
2209:   PetscCheck(!mat->factortype, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
2210:   MatCheckPreallocated(mat, 1);

2212:   PetscCall(PetscLogEventBegin(MAT_GetValues, mat, 0, 0, 0));
2213:   PetscUseTypeMethod(mat, getvalues, m, idxm, n, idxn, v);
2214:   PetscCall(PetscLogEventEnd(MAT_GetValues, mat, 0, 0, 0));
2215:   PetscFunctionReturn(PETSC_SUCCESS);
2216: }

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

2222:   Not Collective

2224:   Input Parameters:
2225: + mat  - the matrix
2226: . nrow - number of rows
2227: . irow - the row local indices
2228: . ncol - number of columns
2229: - icol - the column local indices

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

2235:   Level: advanced

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

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

2245: .seealso: [](ch_matrices), `Mat`, `MatAssemblyBegin()`, `MatAssemblyEnd()`, `MatSetValues()`, `MatSetLocalToGlobalMapping()`,
2246:           `MatSetValuesLocal()`, `MatGetValues()`
2247: @*/
2248: PetscErrorCode MatGetValuesLocal(Mat mat, PetscInt nrow, const PetscInt irow[], PetscInt ncol, const PetscInt icol[], PetscScalar y[])
2249: {
2250:   PetscFunctionBeginHot;
2253:   MatCheckPreallocated(mat, 1);
2254:   if (!nrow || !ncol) PetscFunctionReturn(PETSC_SUCCESS); /* no values to retrieve */
2255:   PetscAssertPointer(irow, 3);
2256:   PetscAssertPointer(icol, 5);
2257:   if (PetscDefined(USE_DEBUG)) {
2258:     PetscCheck(!mat->factortype, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
2259:     PetscCheck(mat->ops->getvalueslocal || mat->ops->getvalues, PETSC_COMM_SELF, PETSC_ERR_SUP, "Mat type %s", ((PetscObject)mat)->type_name);
2260:   }
2261:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
2262:   PetscCall(PetscLogEventBegin(MAT_GetValues, mat, 0, 0, 0));
2263:   if (mat->ops->getvalueslocal) PetscUseTypeMethod(mat, getvalueslocal, nrow, irow, ncol, icol, y);
2264:   else {
2265:     PetscInt buf[8192], *bufr = NULL, *bufc = NULL, *irowm, *icolm;
2266:     if ((nrow + ncol) <= (PetscInt)PETSC_STATIC_ARRAY_LENGTH(buf)) {
2267:       irowm = buf;
2268:       icolm = buf + nrow;
2269:     } else {
2270:       PetscCall(PetscMalloc2(nrow, &bufr, ncol, &bufc));
2271:       irowm = bufr;
2272:       icolm = bufc;
2273:     }
2274:     PetscCheck(mat->rmap->mapping, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "MatGetValuesLocal() cannot proceed without local-to-global row mapping (See MatSetLocalToGlobalMapping()).");
2275:     PetscCheck(mat->cmap->mapping, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "MatGetValuesLocal() cannot proceed without local-to-global column mapping (See MatSetLocalToGlobalMapping()).");
2276:     PetscCall(ISLocalToGlobalMappingApply(mat->rmap->mapping, nrow, irow, irowm));
2277:     PetscCall(ISLocalToGlobalMappingApply(mat->cmap->mapping, ncol, icol, icolm));
2278:     PetscCall(MatGetValues(mat, nrow, irowm, ncol, icolm, y));
2279:     PetscCall(PetscFree2(bufr, bufc));
2280:   }
2281:   PetscCall(PetscLogEventEnd(MAT_GetValues, mat, 0, 0, 0));
2282:   PetscFunctionReturn(PETSC_SUCCESS);
2283: }

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

2289:   Not Collective

2291:   Input Parameters:
2292: + mat  - the matrix
2293: . nb   - the number of blocks
2294: . bs   - the number of rows (and columns) in each block
2295: . rows - a concatenation of the rows for each block
2296: - v    - a concatenation of logically two-dimensional arrays of values

2298:   Level: advanced

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

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

2305: .seealso: [](ch_matrices), `Mat`, `MatSetOption()`, `MatAssemblyBegin()`, `MatAssemblyEnd()`, `MatSetValuesBlocked()`, `MatSetValuesLocal()`,
2306:           `InsertMode`, `INSERT_VALUES`, `ADD_VALUES`, `MatSetValues()`, `MatSetPreallocationCOO()`, `MatSetValuesCOO()`
2307: @*/
2308: PetscErrorCode MatSetValuesBatch(Mat mat, PetscInt nb, PetscInt bs, PetscInt rows[], const PetscScalar v[])
2309: {
2310:   PetscFunctionBegin;
2313:   PetscAssertPointer(rows, 4);
2314:   PetscAssertPointer(v, 5);
2315:   PetscAssert(!mat->factortype, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");

2317:   PetscCall(PetscLogEventBegin(MAT_SetValuesBatch, mat, 0, 0, 0));
2318:   for (PetscInt b = 0; b < nb; ++b) PetscCall(MatSetValues(mat, bs, &rows[b * bs], bs, &rows[b * bs], &v[b * bs * bs], ADD_VALUES));
2319:   PetscCall(PetscLogEventEnd(MAT_SetValuesBatch, mat, 0, 0, 0));
2320:   PetscFunctionReturn(PETSC_SUCCESS);
2321: }

2323: /*@
2324:   MatSetLocalToGlobalMapping - Sets a local-to-global numbering for use by
2325:   the routine `MatSetValuesLocal()` to allow users to insert matrix entries
2326:   using a local (per-processor) numbering.

2328:   Not Collective

2330:   Input Parameters:
2331: + x        - the matrix
2332: . rmapping - row mapping created with `ISLocalToGlobalMappingCreate()` or `ISLocalToGlobalMappingCreateIS()`
2333: - cmapping - column mapping

2335:   Level: intermediate

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

2340: .seealso: [](ch_matrices), `Mat`, `DM`, `DMCreateMatrix()`, `MatGetLocalToGlobalMapping()`, `MatAssemblyBegin()`, `MatAssemblyEnd()`, `MatSetValues()`, `MatSetValuesLocal()`, `MatGetValuesLocal()`
2341: @*/
2342: PetscErrorCode MatSetLocalToGlobalMapping(Mat x, ISLocalToGlobalMapping rmapping, ISLocalToGlobalMapping cmapping)
2343: {
2344:   PetscFunctionBegin;
2349:   if (x->ops->setlocaltoglobalmapping) PetscUseTypeMethod(x, setlocaltoglobalmapping, rmapping, cmapping);
2350:   else {
2351:     PetscCall(PetscLayoutSetISLocalToGlobalMapping(x->rmap, rmapping));
2352:     PetscCall(PetscLayoutSetISLocalToGlobalMapping(x->cmap, cmapping));
2353:   }
2354:   PetscFunctionReturn(PETSC_SUCCESS);
2355: }

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

2360:   Not Collective

2362:   Input Parameter:
2363: . A - the matrix

2365:   Output Parameters:
2366: + rmapping - row mapping
2367: - cmapping - column mapping

2369:   Level: advanced

2371: .seealso: [](ch_matrices), `Mat`, `MatSetLocalToGlobalMapping()`, `MatSetValuesLocal()`
2372: @*/
2373: PetscErrorCode MatGetLocalToGlobalMapping(Mat A, ISLocalToGlobalMapping *rmapping, ISLocalToGlobalMapping *cmapping)
2374: {
2375:   PetscFunctionBegin;
2378:   if (rmapping) {
2379:     PetscAssertPointer(rmapping, 2);
2380:     *rmapping = A->rmap->mapping;
2381:   }
2382:   if (cmapping) {
2383:     PetscAssertPointer(cmapping, 3);
2384:     *cmapping = A->cmap->mapping;
2385:   }
2386:   PetscFunctionReturn(PETSC_SUCCESS);
2387: }

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

2392:   Logically Collective

2394:   Input Parameters:
2395: + A    - the matrix
2396: . rmap - row layout
2397: - cmap - column layout

2399:   Level: advanced

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

2404: .seealso: [](ch_matrices), `Mat`, `PetscLayout`, `MatCreateVecs()`, `MatGetLocalToGlobalMapping()`, `MatGetLayouts()`
2405: @*/
2406: PetscErrorCode MatSetLayouts(Mat A, PetscLayout rmap, PetscLayout cmap)
2407: {
2408:   PetscFunctionBegin;
2410:   PetscCall(PetscLayoutReference(rmap, &A->rmap));
2411:   PetscCall(PetscLayoutReference(cmap, &A->cmap));
2412:   PetscFunctionReturn(PETSC_SUCCESS);
2413: }

2415: /*@
2416:   MatGetLayouts - Gets the `PetscLayout` objects for rows and columns

2418:   Not Collective

2420:   Input Parameter:
2421: . A - the matrix

2423:   Output Parameters:
2424: + rmap - row layout
2425: - cmap - column layout

2427:   Level: advanced

2429: .seealso: [](ch_matrices), `Mat`, [Matrix Layouts](sec_matlayout), `PetscLayout`, `MatCreateVecs()`, `MatGetLocalToGlobalMapping()`, `MatSetLayouts()`
2430: @*/
2431: PetscErrorCode MatGetLayouts(Mat A, PetscLayout *rmap, PetscLayout *cmap)
2432: {
2433:   PetscFunctionBegin;
2436:   if (rmap) {
2437:     PetscAssertPointer(rmap, 2);
2438:     *rmap = A->rmap;
2439:   }
2440:   if (cmap) {
2441:     PetscAssertPointer(cmap, 3);
2442:     *cmap = A->cmap;
2443:   }
2444:   PetscFunctionReturn(PETSC_SUCCESS);
2445: }

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

2451:   Not Collective

2453:   Input Parameters:
2454: + mat  - the matrix
2455: . nrow - number of rows
2456: . irow - the row local indices
2457: . ncol - number of columns
2458: . icol - the column local indices
2459: . v    - a one-dimensional array that contains the values implicitly stored as a two-dimensional array, by default in row-major order.
2460:          See `MAT_ROW_ORIENTED` in `MatSetOption()` for how to use column-major order.
2461: - addv - either `ADD_VALUES` to add values to any existing entries, or `INSERT_VALUES` to replace existing entries with new values

2463:   Level: intermediate

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

2468:   Calls to `MatSetValuesLocal()` with the `INSERT_VALUES` and `ADD_VALUES`
2469:   options cannot be mixed without intervening calls to the assembly
2470:   routines.

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

2475:   Fortran Notes:
2476:   If any of `irow`, `icol`, and `v` are scalars pass them using, for example,
2477: .vb
2478:   call MatSetValuesLocal(mat, one, [irow], one, [icol], [v], INSERT_VALUES, ierr)
2479: .ve

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

2484: .seealso: [](ch_matrices), `Mat`, `MatAssemblyBegin()`, `MatAssemblyEnd()`, `MatSetValues()`, `MatSetLocalToGlobalMapping()`,
2485:           `MatGetValuesLocal()`
2486: @*/
2487: PetscErrorCode MatSetValuesLocal(Mat mat, PetscInt nrow, const PetscInt irow[], PetscInt ncol, const PetscInt icol[], const PetscScalar v[], InsertMode addv)
2488: {
2489:   PetscFunctionBeginHot;
2492:   MatCheckPreallocated(mat, 1);
2493:   if (!nrow || !ncol) PetscFunctionReturn(PETSC_SUCCESS); /* no values to insert */
2494:   PetscAssertPointer(irow, 3);
2495:   PetscAssertPointer(icol, 5);
2496:   if (mat->insertmode == NOT_SET_VALUES) mat->insertmode = addv;
2497:   else PetscCheck(mat->insertmode == addv, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Cannot mix add values and insert values");
2498:   if (PetscDefined(USE_DEBUG)) {
2499:     PetscCheck(!mat->factortype, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
2500:     PetscCheck(mat->ops->setvalueslocal || mat->ops->setvalues, PETSC_COMM_SELF, PETSC_ERR_SUP, "Mat type %s", ((PetscObject)mat)->type_name);
2501:   }

2503:   if (mat->assembled) {
2504:     mat->was_assembled = PETSC_TRUE;
2505:     mat->assembled     = PETSC_FALSE;
2506:   }
2507:   PetscCall(PetscLogEventBegin(MAT_SetValues, mat, 0, 0, 0));
2508:   if (mat->ops->setvalueslocal) PetscUseTypeMethod(mat, setvalueslocal, nrow, irow, ncol, icol, v, addv);
2509:   else {
2510:     PetscInt        buf[8192], *bufr = NULL, *bufc = NULL;
2511:     const PetscInt *irowm, *icolm;

2513:     if ((!mat->rmap->mapping && !mat->cmap->mapping) || (nrow + ncol) <= (PetscInt)PETSC_STATIC_ARRAY_LENGTH(buf)) {
2514:       bufr  = buf;
2515:       bufc  = buf + nrow;
2516:       irowm = bufr;
2517:       icolm = bufc;
2518:     } else {
2519:       PetscCall(PetscMalloc2(nrow, &bufr, ncol, &bufc));
2520:       irowm = bufr;
2521:       icolm = bufc;
2522:     }
2523:     if (mat->rmap->mapping) PetscCall(ISLocalToGlobalMappingApply(mat->rmap->mapping, nrow, irow, bufr));
2524:     else irowm = irow;
2525:     if (mat->cmap->mapping) {
2526:       if (mat->cmap->mapping != mat->rmap->mapping || ncol != nrow || icol != irow) PetscCall(ISLocalToGlobalMappingApply(mat->cmap->mapping, ncol, icol, bufc));
2527:       else icolm = irowm;
2528:     } else icolm = icol;
2529:     PetscCall(MatSetValues(mat, nrow, irowm, ncol, icolm, v, addv));
2530:     if (bufr != buf) PetscCall(PetscFree2(bufr, bufc));
2531:   }
2532:   PetscCall(PetscLogEventEnd(MAT_SetValues, mat, 0, 0, 0));
2533:   PetscFunctionReturn(PETSC_SUCCESS);
2534: }

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

2540:   Not Collective

2542:   Input Parameters:
2543: + mat  - the matrix
2544: . nrow - number of rows
2545: . irow - the row local indices
2546: . ncol - number of columns
2547: . icol - the column local indices
2548: . v    - a one-dimensional array that contains the values implicitly stored as a two-dimensional array, by default in row-major order.
2549:          See `MAT_ROW_ORIENTED` in `MatSetOption()` for how to use column-major order.
2550: - addv - either `ADD_VALUES` to add values to any existing entries, or `INSERT_VALUES` to replace existing entries with new values

2552:   Level: intermediate

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

2558:   Calls to `MatSetValuesBlockedLocal()` with the `INSERT_VALUES` and `ADD_VALUES`
2559:   options cannot be mixed without intervening calls to the assembly
2560:   routines.

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

2565:   Fortran Notes:
2566:   If any of `irow`, `icol`, and `v` are scalars pass them using, for example,
2567: .vb
2568:   call MatSetValuesBlockedLocal(mat, one, [irow], one, [icol], [v], INSERT_VALUES, ierr)
2569: .ve

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

2574: .seealso: [](ch_matrices), `Mat`, `MatSetBlockSize()`, `MatSetLocalToGlobalMapping()`, `MatAssemblyBegin()`, `MatAssemblyEnd()`,
2575:           `MatSetValuesLocal()`, `MatSetValuesBlocked()`
2576: @*/
2577: PetscErrorCode MatSetValuesBlockedLocal(Mat mat, PetscInt nrow, const PetscInt irow[], PetscInt ncol, const PetscInt icol[], const PetscScalar v[], InsertMode addv)
2578: {
2579:   PetscFunctionBeginHot;
2582:   MatCheckPreallocated(mat, 1);
2583:   if (!nrow || !ncol) PetscFunctionReturn(PETSC_SUCCESS); /* no values to insert */
2584:   PetscAssertPointer(irow, 3);
2585:   PetscAssertPointer(icol, 5);
2586:   if (mat->insertmode == NOT_SET_VALUES) mat->insertmode = addv;
2587:   else PetscCheck(mat->insertmode == addv, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Cannot mix add values and insert values");
2588:   if (PetscDefined(USE_DEBUG)) {
2589:     PetscCheck(!mat->factortype, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
2590:     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);
2591:   }

2593:   if (mat->assembled) {
2594:     mat->was_assembled = PETSC_TRUE;
2595:     mat->assembled     = PETSC_FALSE;
2596:   }
2597:   if (PetscUnlikelyDebug(mat->rmap->mapping)) { /* Condition on the mapping existing, because MatSetValuesBlockedLocal_IS does not require it to be set. */
2598:     PetscInt irbs, rbs;
2599:     PetscCall(MatGetBlockSizes(mat, &rbs, NULL));
2600:     PetscCall(ISLocalToGlobalMappingGetBlockSize(mat->rmap->mapping, &irbs));
2601:     PetscCheck(rbs == irbs, PetscObjectComm((PetscObject)mat), PETSC_ERR_SUP, "Different row block sizes! mat %" PetscInt_FMT ", row l2g map %" PetscInt_FMT, rbs, irbs);
2602:   }
2603:   if (PetscUnlikelyDebug(mat->cmap->mapping)) {
2604:     PetscInt icbs, cbs;
2605:     PetscCall(MatGetBlockSizes(mat, NULL, &cbs));
2606:     PetscCall(ISLocalToGlobalMappingGetBlockSize(mat->cmap->mapping, &icbs));
2607:     PetscCheck(cbs == icbs, PetscObjectComm((PetscObject)mat), PETSC_ERR_SUP, "Different col block sizes! mat %" PetscInt_FMT ", col l2g map %" PetscInt_FMT, cbs, icbs);
2608:   }
2609:   PetscCall(PetscLogEventBegin(MAT_SetValues, mat, 0, 0, 0));
2610:   if (mat->ops->setvaluesblockedlocal) PetscUseTypeMethod(mat, setvaluesblockedlocal, nrow, irow, ncol, icol, v, addv);
2611:   else {
2612:     PetscInt        buf[8192], *bufr = NULL, *bufc = NULL;
2613:     const PetscInt *irowm, *icolm;

2615:     if ((!mat->rmap->mapping && !mat->cmap->mapping) || (nrow + ncol) <= ((PetscInt)PETSC_STATIC_ARRAY_LENGTH(buf))) {
2616:       bufr  = buf;
2617:       bufc  = buf + nrow;
2618:       irowm = bufr;
2619:       icolm = bufc;
2620:     } else {
2621:       PetscCall(PetscMalloc2(nrow, &bufr, ncol, &bufc));
2622:       irowm = bufr;
2623:       icolm = bufc;
2624:     }
2625:     if (mat->rmap->mapping) PetscCall(ISLocalToGlobalMappingApplyBlock(mat->rmap->mapping, nrow, irow, bufr));
2626:     else irowm = irow;
2627:     if (mat->cmap->mapping) {
2628:       if (mat->cmap->mapping != mat->rmap->mapping || ncol != nrow || icol != irow) PetscCall(ISLocalToGlobalMappingApplyBlock(mat->cmap->mapping, ncol, icol, bufc));
2629:       else icolm = irowm;
2630:     } else icolm = icol;
2631:     PetscCall(MatSetValuesBlocked(mat, nrow, irowm, ncol, icolm, v, addv));
2632:     if (bufr != buf) PetscCall(PetscFree2(bufr, bufc));
2633:   }
2634:   PetscCall(PetscLogEventEnd(MAT_SetValues, mat, 0, 0, 0));
2635:   PetscFunctionReturn(PETSC_SUCCESS);
2636: }

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

2641:   Collective

2643:   Input Parameters:
2644: + mat - the matrix
2645: - x   - the vector to be multiplied

2647:   Output Parameter:
2648: . y - the result

2650:   Level: developer

2652:   Note:
2653:   The vectors `x` and `y` cannot be the same.  I.e., one cannot
2654:   call `MatMultDiagonalBlock`(A,y,y).

2656: .seealso: [](ch_matrices), `Mat`, `MatMult()`, `MatMultTranspose()`, `MatMultAdd()`, `MatMultTransposeAdd()`
2657: @*/
2658: PetscErrorCode MatMultDiagonalBlock(Mat mat, Vec x, Vec y)
2659: {
2660:   PetscFunctionBegin;

2666:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
2667:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
2668:   PetscCheck(x != y, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "x and y must be different vectors");
2669:   MatCheckPreallocated(mat, 1);

2671:   PetscUseTypeMethod(mat, multdiagonalblock, x, y);
2672:   PetscCall(PetscObjectStateIncrease((PetscObject)y));
2673:   PetscFunctionReturn(PETSC_SUCCESS);
2674: }

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

2679:   Neighbor-wise Collective

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

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

2688:   Level: beginner

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

2694: .seealso: [](ch_matrices), `Mat`, `MatMultTranspose()`, `MatMultAdd()`, `MatMultTransposeAdd()`
2695: @*/
2696: PetscErrorCode MatMult(Mat mat, Vec x, Vec y)
2697: {
2698:   PetscFunctionBegin;
2702:   VecCheckAssembled(x);
2704:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
2705:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
2706:   PetscCheck(x != y, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "x and y must be different vectors");
2707:   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);
2708:   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);
2709:   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);
2710:   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);
2711:   PetscCall(VecSetErrorIfLocked(y, 3));
2712:   if (mat->erroriffailure) PetscCall(VecValidValues_Internal(x, 2, PETSC_TRUE));
2713:   MatCheckPreallocated(mat, 1);

2715:   PetscCall(VecLockReadPush(x));
2716:   PetscCall(PetscLogEventBegin(MAT_Mult, mat, x, y, 0));
2717:   PetscUseTypeMethod(mat, mult, x, y);
2718:   PetscCall(PetscLogEventEnd(MAT_Mult, mat, x, y, 0));
2719:   if (mat->erroriffailure) PetscCall(VecValidValues_Internal(y, 3, PETSC_FALSE));
2720:   PetscCall(VecLockReadPop(x));
2721:   PetscFunctionReturn(PETSC_SUCCESS);
2722: }

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

2727:   Neighbor-wise Collective

2729:   Input Parameters:
2730: + mat - the matrix
2731: - x   - the vector to be multiplied

2733:   Output Parameter:
2734: . y - the result

2736:   Level: beginner

2738:   Notes:
2739:   The vectors `x` and `y` cannot be the same.  I.e., one cannot
2740:   call `MatMultTranspose`(A,y,y).

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

2745: .seealso: [](ch_matrices), `Mat`, `MatMult()`, `MatMultAdd()`, `MatMultTransposeAdd()`, `MatMultHermitianTranspose()`, `MatTranspose()`
2746: @*/
2747: PetscErrorCode MatMultTranspose(Mat mat, Vec x, Vec y)
2748: {
2749:   PetscErrorCode (*op)(Mat, Vec, Vec) = NULL;

2751:   PetscFunctionBegin;
2755:   VecCheckAssembled(x);

2758:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
2759:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
2760:   PetscCheck(x != y, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "x and y must be different vectors");
2761:   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);
2762:   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);
2763:   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);
2764:   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);
2765:   if (mat->erroriffailure) PetscCall(VecValidValues_Internal(x, 2, PETSC_TRUE));
2766:   MatCheckPreallocated(mat, 1);

2768:   if (!mat->ops->multtranspose) {
2769:     if (mat->symmetric == PETSC_BOOL3_TRUE && mat->ops->mult) op = mat->ops->mult;
2770:     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);
2771:   } else op = mat->ops->multtranspose;
2772:   PetscCall(PetscLogEventBegin(MAT_MultTranspose, mat, x, y, 0));
2773:   PetscCall(VecLockReadPush(x));
2774:   PetscCall((*op)(mat, x, y));
2775:   PetscCall(VecLockReadPop(x));
2776:   PetscCall(PetscLogEventEnd(MAT_MultTranspose, mat, x, y, 0));
2777:   PetscCall(PetscObjectStateIncrease((PetscObject)y));
2778:   if (mat->erroriffailure) PetscCall(VecValidValues_Internal(y, 3, PETSC_FALSE));
2779:   PetscFunctionReturn(PETSC_SUCCESS);
2780: }

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

2785:   Neighbor-wise Collective

2787:   Input Parameters:
2788: + mat - the matrix
2789: - x   - the vector to be multiplied

2791:   Output Parameter:
2792: . y - the result

2794:   Level: beginner

2796:   Notes:
2797:   The vectors `x` and `y` cannot be the same.  I.e., one cannot
2798:   call `MatMultHermitianTranspose`(A,y,y).

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

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

2804: .seealso: [](ch_matrices), `Mat`, `MatMult()`, `MatMultAdd()`, `MatMultHermitianTransposeAdd()`, `MatMultTranspose()`
2805: @*/
2806: PetscErrorCode MatMultHermitianTranspose(Mat mat, Vec x, Vec y)
2807: {
2808:   PetscFunctionBegin;

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

2823:   PetscCall(PetscLogEventBegin(MAT_MultHermitianTranspose, mat, x, y, 0));
2824:   if (PetscDefined(USE_COMPLEX)) {
2825:     if (mat->ops->multhermitiantranspose || (mat->hermitian == PETSC_BOOL3_TRUE && mat->ops->mult)) {
2826:       PetscCall(VecLockReadPush(x));
2827:       if (mat->ops->multhermitiantranspose) PetscUseTypeMethod(mat, multhermitiantranspose, x, y);
2828:       else PetscUseTypeMethod(mat, mult, x, y);
2829:       PetscCall(VecLockReadPop(x));
2830:     } else {
2831:       Vec w;
2832:       PetscCall(VecDuplicate(x, &w));
2833:       PetscCall(VecCopy(x, w));
2834:       PetscCall(VecConjugate(w));
2835:       PetscCall(MatMultTranspose(mat, w, y));
2836:       PetscCall(VecDestroy(&w));
2837:       PetscCall(VecConjugate(y));
2838:     }
2839:     PetscCall(PetscObjectStateIncrease((PetscObject)y));
2840:   } else PetscCall(MatMultTranspose(mat, x, y));
2841:   PetscCall(PetscLogEventEnd(MAT_MultHermitianTranspose, mat, x, y, 0));
2842:   PetscFunctionReturn(PETSC_SUCCESS);
2843: }

2845: /*@
2846:   MatMultAdd -  Computes $v3 = v2 + A * v1$.

2848:   Neighbor-wise Collective

2850:   Input Parameters:
2851: + mat - the matrix
2852: . v1  - the vector to be multiplied by `mat`
2853: - v2  - the vector to be added to the result

2855:   Output Parameter:
2856: . v3 - the result

2858:   Level: beginner

2860:   Note:
2861:   The vectors `v1` and `v3` cannot be the same.  I.e., one cannot
2862:   call `MatMultAdd`(A,v1,v2,v1).

2864: .seealso: [](ch_matrices), `Mat`, `MatMultTranspose()`, `MatMult()`, `MatMultTransposeAdd()`
2865: @*/
2866: PetscErrorCode MatMultAdd(Mat mat, Vec v1, Vec v2, Vec v3)
2867: {
2868:   PetscFunctionBegin;

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

2885:   PetscCall(PetscLogEventBegin(MAT_MultAdd, mat, v1, v2, v3));
2886:   PetscCall(VecLockReadPush(v1));
2887:   PetscUseTypeMethod(mat, multadd, v1, v2, v3);
2888:   PetscCall(VecLockReadPop(v1));
2889:   PetscCall(PetscLogEventEnd(MAT_MultAdd, mat, v1, v2, v3));
2890:   PetscCall(PetscObjectStateIncrease((PetscObject)v3));
2891:   PetscFunctionReturn(PETSC_SUCCESS);
2892: }

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

2897:   Neighbor-wise Collective

2899:   Input Parameters:
2900: + mat - the matrix
2901: . v1  - the vector to be multiplied by the transpose of the matrix
2902: - v2  - the vector to be added to the result

2904:   Output Parameter:
2905: . v3 - the result

2907:   Level: beginner

2909:   Note:
2910:   The vectors `v1` and `v3` cannot be the same.  I.e., one cannot
2911:   call `MatMultTransposeAdd`(A,v1,v2,v1).

2913: .seealso: [](ch_matrices), `Mat`, `MatMultTranspose()`, `MatMultAdd()`, `MatMult()`
2914: @*/
2915: PetscErrorCode MatMultTransposeAdd(Mat mat, Vec v1, Vec v2, Vec v3)
2916: {
2917:   PetscErrorCode (*op)(Mat, Vec, Vec, Vec) = (!mat->ops->multtransposeadd && mat->symmetric) ? mat->ops->multadd : mat->ops->multtransposeadd;

2919:   PetscFunctionBegin;

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

2935:   PetscCall(PetscLogEventBegin(MAT_MultTransposeAdd, mat, v1, v2, v3));
2936:   PetscCall(VecLockReadPush(v1));
2937:   PetscCall((*op)(mat, v1, v2, v3));
2938:   PetscCall(VecLockReadPop(v1));
2939:   PetscCall(PetscLogEventEnd(MAT_MultTransposeAdd, mat, v1, v2, v3));
2940:   PetscCall(PetscObjectStateIncrease((PetscObject)v3));
2941:   PetscFunctionReturn(PETSC_SUCCESS);
2942: }

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

2947:   Neighbor-wise Collective

2949:   Input Parameters:
2950: + mat - the matrix
2951: . v1  - the vector to be multiplied by the Hermitian transpose
2952: - v2  - the vector to be added to the result

2954:   Output Parameter:
2955: . v3 - the result

2957:   Level: beginner

2959:   Note:
2960:   The vectors `v1` and `v3` cannot be the same.  I.e., one cannot
2961:   call `MatMultHermitianTransposeAdd`(A,v1,v2,v1).

2963: .seealso: [](ch_matrices), `Mat`, `MatMultHermitianTranspose()`, `MatMultTranspose()`, `MatMultAdd()`, `MatMult()`
2964: @*/
2965: PetscErrorCode MatMultHermitianTransposeAdd(Mat mat, Vec v1, Vec v2, Vec v3)
2966: {
2967:   PetscFunctionBegin;

2974:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
2975:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
2976:   PetscCheck(v1 != v3, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_IDN, "v1 and v3 must be different vectors");
2977:   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);
2978:   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);
2979:   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);
2980:   MatCheckPreallocated(mat, 1);

2982:   PetscCall(PetscLogEventBegin(MAT_MultHermitianTransposeAdd, mat, v1, v2, v3));
2983:   PetscCall(VecLockReadPush(v1));
2984:   if (mat->ops->multhermitiantransposeadd) PetscUseTypeMethod(mat, multhermitiantransposeadd, v1, v2, v3);
2985:   else {
2986:     Vec w, z;
2987:     PetscCall(VecDuplicate(v1, &w));
2988:     PetscCall(VecCopy(v1, w));
2989:     PetscCall(VecConjugate(w));
2990:     PetscCall(VecDuplicate(v3, &z));
2991:     PetscCall(MatMultTranspose(mat, w, z));
2992:     PetscCall(VecDestroy(&w));
2993:     PetscCall(VecConjugate(z));
2994:     if (v2 != v3) PetscCall(VecWAXPY(v3, 1.0, v2, z));
2995:     else PetscCall(VecAXPY(v3, 1.0, z));
2996:     PetscCall(VecDestroy(&z));
2997:   }
2998:   PetscCall(VecLockReadPop(v1));
2999:   PetscCall(PetscLogEventEnd(MAT_MultHermitianTransposeAdd, mat, v1, v2, v3));
3000:   PetscCall(PetscObjectStateIncrease((PetscObject)v3));
3001:   PetscFunctionReturn(PETSC_SUCCESS);
3002: }

3004: PetscErrorCode MatADot_Default(Mat mat, Vec x, Vec y, PetscScalar *val)
3005: {
3006:   PetscFunctionBegin;
3007:   if (!mat->dot_vec) PetscCall(MatCreateVecs(mat, &mat->dot_vec, NULL));
3008:   PetscCall(MatMult(mat, x, mat->dot_vec));
3009:   PetscCall(VecDot(mat->dot_vec, y, val));
3010:   PetscFunctionReturn(PETSC_SUCCESS);
3011: }

3013: PetscErrorCode MatANorm_Default(Mat mat, Vec x, PetscReal *val)
3014: {
3015:   PetscScalar sval;

3017:   PetscFunctionBegin;
3018:   PetscCall(MatADot_Default(mat, x, x, &sval));
3019:   PetscCheck(PetscRealPart(sval) >= 0.0, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONG, "Matrix argument is not positive definite");
3020:   PetscCheck(PetscAbsReal(PetscImaginaryPart(sval)) < 100 * PETSC_MACHINE_EPSILON, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONG, "Matrix argument is not Hermitian");
3021:   *val = PetscSqrtReal(PetscRealPart(sval));
3022:   PetscFunctionReturn(PETSC_SUCCESS);
3023: }

3025: /*@
3026:   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)
3027:   positive definite.

3029:   Collective

3031:   Input Parameters:
3032: + mat - matrix used to define the inner product
3033: . x   - first vector
3034: - y   - second vector

3036:   Output Parameter:
3037: . val - the dot product with respect to `A`

3039:   Level: intermediate

3041:   Note:
3042:   For complex vectors, `MatADot()` computes
3043: $$
3044:   val = (x,y)_A = y^H A x,
3045: $$
3046:   where $y^H$ denotes the conjugate transpose of `y`. Note that this corresponds to the "mathematicians" complex
3047:   inner product where the SECOND argument gets the complex conjugate.

3049: .seealso: [](ch_matrices), `Mat`, `MatANorm()`, `VecDot()`, `VecNorm()`, `MatMult()`, `MatMultAdd()`, `MatMultTransposeAdd()`
3050: @*/
3051: PetscErrorCode MatADot(Mat mat, Vec x, Vec y, PetscScalar *val)
3052: {
3053:   PetscFunctionBegin;
3057:   VecCheckAssembled(x);
3059:   VecCheckAssembled(y);
3062:   PetscAssertPointer(val, 4);
3063:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
3064:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
3065:   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);
3066:   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);
3067:   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);
3068:   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);
3069:   if (mat->erroriffailure) PetscCall(VecValidValues_Internal(x, 2, PETSC_TRUE));
3070:   if (mat->erroriffailure) PetscCall(VecValidValues_Internal(y, 3, PETSC_TRUE));
3071:   MatCheckPreallocated(mat, 1);

3073:   PetscCall(VecLockReadPush(x));
3074:   PetscCall(VecLockReadPush(y));
3075:   PetscCall(PetscLogEventBegin(MAT_ADot, mat, x, y, 0));
3076:   PetscUseTypeMethod(mat, adot, x, y, val);
3077:   PetscCall(PetscLogEventEnd(MAT_ADot, mat, x, y, 0));
3078:   PetscCall(VecLockReadPop(y));
3079:   PetscCall(VecLockReadPop(x));
3080:   PetscFunctionReturn(PETSC_SUCCESS);
3081: }

3083: /*@
3084:   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)
3085:   positive definite.

3087:   Collective

3089:   Input Parameters:
3090: + mat - matrix used to define norm
3091: - x   - the vector to compute the norm of

3093:   Output Parameter:
3094: . val - the norm with respect to `A`

3096:   Level: intermediate

3098:   Note:
3099:   For complex vectors, `MatANorm()` computes
3100: $$
3101:   val = (x,x)_A^{1/2} = (x^H A x)^{1/2},
3102: $$
3103:   where $x^H$ denotes the conjugate transpose of `x`.

3105: .seealso: [](ch_matrices), `Mat`, `MatADot()`, `VecDot()`, `VecNorm()`, `MatMult()`, `MatMultAdd()`, `MatMultTransposeAdd()`
3106: @*/
3107: PetscErrorCode MatANorm(Mat mat, Vec x, PetscReal *val)
3108: {
3109:   PetscFunctionBegin;
3113:   VecCheckAssembled(x);
3115:   PetscAssertPointer(val, 3);
3116:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
3117:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
3118:   PetscCheck(mat->cmap->N == x->map->N, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_SIZ, "Mat mat,Vec x: global dim %" PetscInt_FMT " %" PetscInt_FMT, mat->cmap->N, x->map->N);
3119:   PetscCheck(mat->rmap->N == 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);
3120:   PetscCheck(mat->cmap->n == x->map->n, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Mat mat,Vec x: local dim %" PetscInt_FMT " %" PetscInt_FMT, mat->cmap->n, x->map->n);
3121:   PetscCheck(mat->rmap->n == 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);
3122:   if (mat->erroriffailure) PetscCall(VecValidValues_Internal(x, 2, PETSC_TRUE));
3123:   MatCheckPreallocated(mat, 1);

3125:   PetscCall(VecLockReadPush(x));
3126:   PetscCall(PetscLogEventBegin(MAT_ANorm, mat, x, 0, 0));
3127:   PetscUseTypeMethod(mat, anorm, x, val);
3128:   PetscCall(PetscLogEventEnd(MAT_ANorm, mat, x, 0, 0));
3129:   PetscCall(VecLockReadPop(x));
3130:   PetscFunctionReturn(PETSC_SUCCESS);
3131: }

3133: /*@
3134:   MatGetFactorType - gets the type of factorization a matrix is

3136:   Not Collective

3138:   Input Parameter:
3139: . mat - the matrix

3141:   Output Parameter:
3142: . 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`

3144:   Level: intermediate

3146: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatFactorType`, `MatGetFactor()`, `MatSetFactorType()`, `MAT_FACTOR_NONE`, `MAT_FACTOR_LU`, `MAT_FACTOR_CHOLESKY`, `MAT_FACTOR_ILU`,
3147:           `MAT_FACTOR_ICC`, `MAT_FACTOR_ILUDT`, `MAT_FACTOR_QR`
3148: @*/
3149: PetscErrorCode MatGetFactorType(Mat mat, MatFactorType *t)
3150: {
3151:   PetscFunctionBegin;
3154:   PetscAssertPointer(t, 2);
3155:   *t = mat->factortype;
3156:   PetscFunctionReturn(PETSC_SUCCESS);
3157: }

3159: /*@
3160:   MatSetFactorType - sets the type of factorization a matrix is

3162:   Logically Collective

3164:   Input Parameters:
3165: + mat - the matrix
3166: - 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`

3168:   Level: intermediate

3170: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatFactorType`, `MatGetFactor()`, `MatGetFactorType()`, `MAT_FACTOR_NONE`, `MAT_FACTOR_LU`, `MAT_FACTOR_CHOLESKY`, `MAT_FACTOR_ILU`,
3171:           `MAT_FACTOR_ICC`, `MAT_FACTOR_ILUDT`, `MAT_FACTOR_QR`
3172: @*/
3173: PetscErrorCode MatSetFactorType(Mat mat, MatFactorType t)
3174: {
3175:   PetscFunctionBegin;
3178:   mat->factortype = t;
3179:   PetscFunctionReturn(PETSC_SUCCESS);
3180: }

3182: /*@
3183:   MatGetInfo - Returns information about matrix storage (number of
3184:   nonzeros, memory, etc.).

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

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

3192:   Output Parameter:
3193: . info - matrix information context

3195:   Options Database Key:
3196: . -mat_view ::ascii_info - print matrix info to `PETSC_STDOUT`

3198:   Level: intermediate

3200:   Notes:
3201:   The `MatInfo` context contains a variety of matrix data, including
3202:   number of nonzeros allocated and used, number of mallocs during
3203:   matrix assembly, etc.  Additional information for factored matrices
3204:   is provided (such as the fill ratio, number of mallocs during
3205:   factorization, etc.).

3207:   Example:
3208:   See the file ${PETSC_DIR}/include/petscmat.h for a complete list of
3209:   data within the `MatInfo` context.  For example,
3210: .vb
3211:       MatInfo info;
3212:       Mat     A;
3213:       double  mal, nz_a, nz_u;

3215:       MatGetInfo(A, MAT_LOCAL, &info);
3216:       mal  = info.mallocs;
3217:       nz_a = info.nz_allocated;
3218: .ve

3220: .seealso: [](ch_matrices), `Mat`, `MatInfo`, `MatStashGetInfo()`
3221: @*/
3222: PetscErrorCode MatGetInfo(Mat mat, MatInfoType flag, MatInfo *info)
3223: {
3224:   PetscFunctionBegin;
3227:   PetscAssertPointer(info, 3);
3228:   MatCheckPreallocated(mat, 1);
3229:   PetscUseTypeMethod(mat, getinfo, flag, info);
3230:   PetscFunctionReturn(PETSC_SUCCESS);
3231: }

3233: /*
3234:    This is used by external packages where it is not easy to get the info from the actual
3235:    matrix factorization.
3236: */
3237: PetscErrorCode MatGetInfo_External(Mat A, MatInfoType flag, MatInfo *info)
3238: {
3239:   PetscFunctionBegin;
3240:   PetscCall(PetscMemzero(info, sizeof(MatInfo)));
3241:   PetscFunctionReturn(PETSC_SUCCESS);
3242: }

3244: /*@
3245:   MatLUFactor - Performs in-place LU factorization of matrix.

3247:   Collective

3249:   Input Parameters:
3250: + mat  - the matrix
3251: . row  - row permutation
3252: . col  - column permutation
3253: - info - options for factorization, includes
3254: .vb
3255:           fill - expected fill as ratio of original fill.
3256:           dtcol - pivot tolerance (0 no pivot, 1 full column pivoting)
3257:                    Run with the option -info to determine an optimal value to use
3258: .ve

3260:   Level: developer

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

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

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

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

3276: .seealso: [](ch_matrices), [Matrix Factorization](sec_matfactor), `Mat`, `MatFactorType`, `MatLUFactorSymbolic()`, `MatLUFactorNumeric()`, `MatCholeskyFactor()`,
3277:           `MatGetOrdering()`, `MatSetUnfactored()`, `MatFactorInfo`, `MatGetFactor()`
3278: @*/
3279: PetscErrorCode MatLUFactor(Mat mat, IS row, IS col, const MatFactorInfo *info)
3280: {
3281:   MatFactorInfo tinfo;

3283:   PetscFunctionBegin;
3287:   if (info) PetscAssertPointer(info, 4);
3289:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
3290:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
3291:   MatCheckPreallocated(mat, 1);
3292:   if (!info) {
3293:     PetscCall(MatFactorInfoInitialize(&tinfo));
3294:     info = &tinfo;
3295:   }

3297:   PetscCall(PetscLogEventBegin(MAT_LUFactor, mat, row, col, 0));
3298:   PetscUseTypeMethod(mat, lufactor, row, col, info);
3299:   PetscCall(PetscLogEventEnd(MAT_LUFactor, mat, row, col, 0));
3300:   PetscCall(PetscObjectStateIncrease((PetscObject)mat));
3301:   PetscFunctionReturn(PETSC_SUCCESS);
3302: }

3304: /*@
3305:   MatILUFactor - Performs in-place ILU factorization of matrix.

3307:   Collective

3309:   Input Parameters:
3310: + mat  - the matrix
3311: . row  - row permutation
3312: . col  - column permutation
3313: - info - structure containing
3314: .vb
3315:       levels - number of levels of fill.
3316:       expected fill - as ratio of original fill.
3317:       1 or 0 - indicating force fill on diagonal (improves robustness for matrices
3318:                 missing diagonal entries)
3319: .ve

3321:   Level: developer

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

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

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

3335: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatILUFactorSymbolic()`, `MatLUFactorNumeric()`, `MatCholeskyFactor()`, `MatFactorInfo`
3336: @*/
3337: PetscErrorCode MatILUFactor(Mat mat, IS row, IS col, const MatFactorInfo *info)
3338: {
3339:   PetscFunctionBegin;
3343:   PetscAssertPointer(info, 4);
3345:   PetscCheck(mat->rmap->N == mat->cmap->N, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONG, "matrix must be square");
3346:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
3347:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
3348:   MatCheckPreallocated(mat, 1);

3350:   PetscCall(PetscLogEventBegin(MAT_ILUFactor, mat, row, col, 0));
3351:   PetscUseTypeMethod(mat, ilufactor, row, col, info);
3352:   PetscCall(PetscLogEventEnd(MAT_ILUFactor, mat, row, col, 0));
3353:   PetscCall(PetscObjectStateIncrease((PetscObject)mat));
3354:   PetscFunctionReturn(PETSC_SUCCESS);
3355: }

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

3361:   Collective

3363:   Input Parameters:
3364: + fact - the factor matrix obtained with `MatGetFactor()`
3365: . mat  - the matrix
3366: . row  - the row permutation
3367: . col  - the column permutation
3368: - info - options for factorization, includes
3369: .vb
3370:           fill - expected fill as ratio of original fill. Run with the option -info to determine an optimal value to use
3371:           dtcol - pivot tolerance (0 no pivot, 1 full column pivoting)
3372: .ve

3374:   Level: developer

3376:   Notes:
3377:   See [Matrix Factorization](sec_matfactor) for additional information about factorizations

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

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

3386: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatGetFactor()`, `MatLUFactor()`, `MatLUFactorNumeric()`, `MatCholeskyFactor()`, `MatFactorInfo`, `MatFactorInfoInitialize()`
3387: @*/
3388: PetscErrorCode MatLUFactorSymbolic(Mat fact, Mat mat, IS row, IS col, const MatFactorInfo *info)
3389: {
3390:   MatFactorInfo tinfo;

3392:   PetscFunctionBegin;
3397:   if (info) PetscAssertPointer(info, 5);
3400:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
3401:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
3402:   MatCheckPreallocated(mat, 2);
3403:   if (!info) {
3404:     PetscCall(MatFactorInfoInitialize(&tinfo));
3405:     info = &tinfo;
3406:   }

3408:   if (!fact->trivialsymbolic) PetscCall(PetscLogEventBegin(MAT_LUFactorSymbolic, mat, row, col, 0));
3409:   PetscUseTypeMethod(fact, lufactorsymbolic, mat, row, col, info);
3410:   if (!fact->trivialsymbolic) PetscCall(PetscLogEventEnd(MAT_LUFactorSymbolic, mat, row, col, 0));
3411:   PetscCall(PetscObjectStateIncrease((PetscObject)fact));
3412:   PetscFunctionReturn(PETSC_SUCCESS);
3413: }

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

3419:   Collective

3421:   Input Parameters:
3422: + fact - the factor matrix obtained with `MatGetFactor()`
3423: . mat  - the matrix
3424: - info - options for factorization

3426:   Level: developer

3428:   Notes:
3429:   See `MatLUFactor()` for in-place factorization.  See
3430:   `MatCholeskyFactorNumeric()` for the symmetric, positive definite case.

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

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

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

3445:   PetscFunctionBegin;
3450:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
3451:   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,
3452:              mat->rmap->N, (fact)->rmap->N, mat->cmap->N, (fact)->cmap->N);

3454:   MatCheckPreallocated(mat, 2);
3455:   if (!info) {
3456:     PetscCall(MatFactorInfoInitialize(&tinfo));
3457:     info = &tinfo;
3458:   }

3460:   if (!fact->trivialsymbolic) PetscCall(PetscLogEventBegin(MAT_LUFactorNumeric, mat, fact, 0, 0));
3461:   else PetscCall(PetscLogEventBegin(MAT_LUFactor, mat, fact, 0, 0));
3462:   PetscUseTypeMethod(fact, lufactornumeric, mat, info);
3463:   if (!fact->trivialsymbolic) PetscCall(PetscLogEventEnd(MAT_LUFactorNumeric, mat, fact, 0, 0));
3464:   else PetscCall(PetscLogEventEnd(MAT_LUFactor, mat, fact, 0, 0));
3465:   PetscCall(MatViewFromOptions(fact, NULL, "-mat_factor_view"));
3466:   PetscCall(PetscObjectStateIncrease((PetscObject)fact));
3467:   PetscFunctionReturn(PETSC_SUCCESS);
3468: }

3470: /*@
3471:   MatCholeskyFactor - Performs in-place Cholesky factorization of a
3472:   symmetric matrix.

3474:   Collective

3476:   Input Parameters:
3477: + mat  - the matrix
3478: . perm - row and column permutations
3479: - info - expected fill as ratio of original fill

3481:   Level: developer

3483:   Notes:
3484:   See `MatLUFactor()` for the nonsymmetric case.  See also `MatGetFactor()`,
3485:   `MatCholeskyFactorSymbolic()`, and `MatCholeskyFactorNumeric()`.

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

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

3494: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatGetFactor()`, `MatFactorInfo`, `MatLUFactor()`, `MatCholeskyFactorSymbolic()`, `MatCholeskyFactorNumeric()`,
3495:           `MatGetOrdering()`
3496: @*/
3497: PetscErrorCode MatCholeskyFactor(Mat mat, IS perm, const MatFactorInfo *info)
3498: {
3499:   MatFactorInfo tinfo;

3501:   PetscFunctionBegin;
3504:   if (info) PetscAssertPointer(info, 3);
3506:   PetscCheck(mat->rmap->N == mat->cmap->N, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONG, "Matrix must be square");
3507:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
3508:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
3509:   MatCheckPreallocated(mat, 1);
3510:   if (!info) {
3511:     PetscCall(MatFactorInfoInitialize(&tinfo));
3512:     info = &tinfo;
3513:   }

3515:   PetscCall(PetscLogEventBegin(MAT_CholeskyFactor, mat, perm, 0, 0));
3516:   PetscUseTypeMethod(mat, choleskyfactor, perm, info);
3517:   PetscCall(PetscLogEventEnd(MAT_CholeskyFactor, mat, perm, 0, 0));
3518:   PetscCall(PetscObjectStateIncrease((PetscObject)mat));
3519:   PetscFunctionReturn(PETSC_SUCCESS);
3520: }

3522: /*@
3523:   MatCholeskyFactorSymbolic - Performs symbolic Cholesky factorization
3524:   of a symmetric matrix.

3526:   Collective

3528:   Input Parameters:
3529: + fact - the factor matrix obtained with `MatGetFactor()`
3530: . mat  - the matrix
3531: . perm - row and column permutations
3532: - info - options for factorization, includes
3533: .vb
3534:           fill - expected fill as ratio of original fill.
3535:           dtcol - pivot tolerance (0 no pivot, 1 full column pivoting)
3536:                    Run with the option -info to determine an optimal value to use
3537: .ve

3539:   Level: developer

3541:   Notes:
3542:   See `MatLUFactorSymbolic()` for the nonsymmetric case.  See also
3543:   `MatCholeskyFactor()` and `MatCholeskyFactorNumeric()`.

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

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

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

3559:   PetscFunctionBegin;
3563:   if (info) PetscAssertPointer(info, 4);
3566:   PetscCheck(mat->rmap->N == mat->cmap->N, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONG, "Matrix must be square");
3567:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
3568:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
3569:   MatCheckPreallocated(mat, 2);
3570:   if (!info) {
3571:     PetscCall(MatFactorInfoInitialize(&tinfo));
3572:     info = &tinfo;
3573:   }

3575:   if (!fact->trivialsymbolic) PetscCall(PetscLogEventBegin(MAT_CholeskyFactorSymbolic, mat, perm, 0, 0));
3576:   PetscUseTypeMethod(fact, choleskyfactorsymbolic, mat, perm, info);
3577:   if (!fact->trivialsymbolic) PetscCall(PetscLogEventEnd(MAT_CholeskyFactorSymbolic, mat, perm, 0, 0));
3578:   PetscCall(PetscObjectStateIncrease((PetscObject)fact));
3579:   PetscFunctionReturn(PETSC_SUCCESS);
3580: }

3582: /*@
3583:   MatCholeskyFactorNumeric - Performs numeric Cholesky factorization
3584:   of a symmetric matrix. Call this routine after first calling `MatGetFactor()` and
3585:   `MatCholeskyFactorSymbolic()`.

3587:   Collective

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

3594:   Level: developer

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

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

3604: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatFactorInfo`, `MatGetFactor()`, `MatCholeskyFactorSymbolic()`, `MatCholeskyFactor()`, `MatLUFactorNumeric()`
3605: @*/
3606: PetscErrorCode MatCholeskyFactorNumeric(Mat fact, Mat mat, const MatFactorInfo *info)
3607: {
3608:   MatFactorInfo tinfo;

3610:   PetscFunctionBegin;
3615:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
3616:   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,
3617:              mat->rmap->N, (fact)->rmap->N, mat->cmap->N, (fact)->cmap->N);
3618:   MatCheckPreallocated(mat, 2);
3619:   if (!info) {
3620:     PetscCall(MatFactorInfoInitialize(&tinfo));
3621:     info = &tinfo;
3622:   }

3624:   if (!fact->trivialsymbolic) PetscCall(PetscLogEventBegin(MAT_CholeskyFactorNumeric, mat, fact, 0, 0));
3625:   else PetscCall(PetscLogEventBegin(MAT_CholeskyFactor, mat, fact, 0, 0));
3626:   PetscUseTypeMethod(fact, choleskyfactornumeric, mat, info);
3627:   if (!fact->trivialsymbolic) PetscCall(PetscLogEventEnd(MAT_CholeskyFactorNumeric, mat, fact, 0, 0));
3628:   else PetscCall(PetscLogEventEnd(MAT_CholeskyFactor, mat, fact, 0, 0));
3629:   PetscCall(MatViewFromOptions(fact, NULL, "-mat_factor_view"));
3630:   PetscCall(PetscObjectStateIncrease((PetscObject)fact));
3631:   PetscFunctionReturn(PETSC_SUCCESS);
3632: }

3634: /*@
3635:   MatQRFactor - Performs in-place QR factorization of matrix.

3637:   Collective

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

3649:   Level: developer

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

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

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

3662: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatFactorInfo`, `MatGetFactor()`, `MatQRFactorSymbolic()`, `MatQRFactorNumeric()`, `MatLUFactor()`,
3663:           `MatSetUnfactored()`
3664: @*/
3665: PetscErrorCode MatQRFactor(Mat mat, IS col, const MatFactorInfo *info)
3666: {
3667:   PetscFunctionBegin;
3670:   if (info) PetscAssertPointer(info, 3);
3672:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
3673:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
3674:   MatCheckPreallocated(mat, 1);
3675:   PetscCall(PetscLogEventBegin(MAT_QRFactor, mat, col, 0, 0));
3676:   PetscUseMethod(mat, "MatQRFactor_C", (Mat, IS, const MatFactorInfo *), (mat, col, info));
3677:   PetscCall(PetscLogEventEnd(MAT_QRFactor, mat, col, 0, 0));
3678:   PetscCall(PetscObjectStateIncrease((PetscObject)mat));
3679:   PetscFunctionReturn(PETSC_SUCCESS);
3680: }

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

3686:   Collective

3688:   Input Parameters:
3689: + fact - the factor matrix obtained with `MatGetFactor()`
3690: . mat  - the matrix
3691: . col  - column permutation
3692: - info - options for factorization, includes
3693: .vb
3694:           fill - expected fill as ratio of original fill.
3695:           dtcol - pivot tolerance (0 no pivot, 1 full column pivoting)
3696:                    Run with the option -info to determine an optimal value to use
3697: .ve

3699:   Level: developer

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

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

3709: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatGetFactor()`, `MatFactorInfo`, `MatQRFactor()`, `MatQRFactorNumeric()`, `MatLUFactor()`, `MatFactorInfoInitialize()`
3710: @*/
3711: PetscErrorCode MatQRFactorSymbolic(Mat fact, Mat mat, IS col, const MatFactorInfo *info)
3712: {
3713:   MatFactorInfo tinfo;

3715:   PetscFunctionBegin;
3719:   if (info) PetscAssertPointer(info, 4);
3722:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
3723:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
3724:   MatCheckPreallocated(mat, 2);
3725:   if (!info) {
3726:     PetscCall(MatFactorInfoInitialize(&tinfo));
3727:     info = &tinfo;
3728:   }

3730:   if (!fact->trivialsymbolic) PetscCall(PetscLogEventBegin(MAT_QRFactorSymbolic, fact, mat, col, 0));
3731:   PetscUseMethod(fact, "MatQRFactorSymbolic_C", (Mat, Mat, IS, const MatFactorInfo *), (fact, mat, col, info));
3732:   if (!fact->trivialsymbolic) PetscCall(PetscLogEventEnd(MAT_QRFactorSymbolic, fact, mat, col, 0));
3733:   PetscCall(PetscObjectStateIncrease((PetscObject)fact));
3734:   PetscFunctionReturn(PETSC_SUCCESS);
3735: }

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

3741:   Collective

3743:   Input Parameters:
3744: + fact - the factor matrix obtained with `MatGetFactor()`
3745: . mat  - the matrix
3746: - info - options for factorization

3748:   Level: developer

3750:   Notes:
3751:   See `MatQRFactor()` for in-place factorization.

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

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

3760: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatFactorInfo`, `MatGetFactor()`, `MatQRFactor()`, `MatQRFactorSymbolic()`, `MatLUFactor()`
3761: @*/
3762: PetscErrorCode MatQRFactorNumeric(Mat fact, Mat mat, const MatFactorInfo *info)
3763: {
3764:   MatFactorInfo tinfo;

3766:   PetscFunctionBegin;
3771:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
3772:   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,
3773:              mat->rmap->N, (fact)->rmap->N, mat->cmap->N, (fact)->cmap->N);

3775:   MatCheckPreallocated(mat, 2);
3776:   if (!info) {
3777:     PetscCall(MatFactorInfoInitialize(&tinfo));
3778:     info = &tinfo;
3779:   }

3781:   if (!fact->trivialsymbolic) PetscCall(PetscLogEventBegin(MAT_QRFactorNumeric, mat, fact, 0, 0));
3782:   else PetscCall(PetscLogEventBegin(MAT_QRFactor, mat, fact, 0, 0));
3783:   PetscUseMethod(fact, "MatQRFactorNumeric_C", (Mat, Mat, const MatFactorInfo *), (fact, mat, info));
3784:   if (!fact->trivialsymbolic) PetscCall(PetscLogEventEnd(MAT_QRFactorNumeric, mat, fact, 0, 0));
3785:   else PetscCall(PetscLogEventEnd(MAT_QRFactor, mat, fact, 0, 0));
3786:   PetscCall(MatViewFromOptions(fact, NULL, "-mat_factor_view"));
3787:   PetscCall(PetscObjectStateIncrease((PetscObject)fact));
3788:   PetscFunctionReturn(PETSC_SUCCESS);
3789: }

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

3794:   Neighbor-wise Collective

3796:   Input Parameters:
3797: + mat - the factored matrix
3798: - b   - the right-hand-side vector

3800:   Output Parameter:
3801: . x - the result vector

3803:   Level: developer

3805:   Notes:
3806:   The vectors `b` and `x` cannot be the same.  I.e., one cannot
3807:   call `MatSolve`(A,x,x).

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

3813: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatGetFactor()`, `MatLUFactor()`, `MatSolveAdd()`, `MatSolveTranspose()`, `MatSolveTransposeAdd()`
3814: @*/
3815: PetscErrorCode MatSolve(Mat mat, Vec b, Vec x)
3816: {
3817:   PetscFunctionBegin;
3822:   PetscCheckSameComm(mat, 1, b, 2);
3823:   PetscCheckSameComm(mat, 1, x, 3);
3824:   PetscCheck(x != b, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_IDN, "x and b must be different vectors");
3825:   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);
3826:   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);
3827:   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);
3828:   if (!mat->rmap->N && !mat->cmap->N) PetscFunctionReturn(PETSC_SUCCESS);
3829:   MatCheckPreallocated(mat, 1);

3831:   PetscCall(PetscLogEventBegin(MAT_Solve, mat, b, x, 0));
3832:   PetscCall(VecFlag(x, mat->factorerrortype));
3833:   if (mat->factorerrortype) PetscCall(PetscInfo(mat, "MatFactorError %d\n", mat->factorerrortype));
3834:   else PetscUseTypeMethod(mat, solve, b, x);
3835:   PetscCall(PetscLogEventEnd(MAT_Solve, mat, b, x, 0));
3836:   PetscCall(PetscObjectStateIncrease((PetscObject)x));
3837:   PetscFunctionReturn(PETSC_SUCCESS);
3838: }

3840: static PetscErrorCode MatMatSolve_Basic(Mat A, Mat B, Mat X, PetscBool trans)
3841: {
3842:   Vec      b, x;
3843:   PetscInt N;
3844:   PetscErrorCode (*f)(Mat, Vec, Vec);
3845:   PetscBool Abound, Bneedconv = PETSC_FALSE, Xneedconv = PETSC_FALSE;

3847:   PetscFunctionBegin;
3848:   if (A->factorerrortype) {
3849:     PetscCall(PetscInfo(A, "MatFactorError %d\n", A->factorerrortype));
3850:     PetscCall(MatSetInf(X));
3851:     PetscFunctionReturn(PETSC_SUCCESS);
3852:   }
3853:   f = (!trans || (!A->ops->solvetranspose && A->symmetric)) ? A->ops->solve : A->ops->solvetranspose;
3854:   PetscCheck(f, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "Mat type %s", ((PetscObject)A)->type_name);
3855:   PetscCall(MatBoundToCPU(A, &Abound));
3856:   if (!Abound) {
3857:     PetscCall(PetscObjectTypeCompareAny((PetscObject)B, &Bneedconv, MATSEQDENSE, MATMPIDENSE, ""));
3858:     PetscCall(PetscObjectTypeCompareAny((PetscObject)X, &Xneedconv, MATSEQDENSE, MATMPIDENSE, ""));
3859:   }
3860: #if PetscDefined(HAVE_CUDA)
3861:   if (Bneedconv) PetscCall(MatConvert(B, MATDENSECUDA, MAT_INPLACE_MATRIX, &B));
3862:   if (Xneedconv) PetscCall(MatConvert(X, MATDENSECUDA, MAT_INPLACE_MATRIX, &X));
3863: #elif PetscDefined(HAVE_HIP)
3864:   if (Bneedconv) PetscCall(MatConvert(B, MATDENSEHIP, MAT_INPLACE_MATRIX, &B));
3865:   if (Xneedconv) PetscCall(MatConvert(X, MATDENSEHIP, MAT_INPLACE_MATRIX, &X));
3866: #endif
3867:   PetscCall(MatGetSize(B, NULL, &N));
3868:   for (PetscInt i = 0; i < N; i++) {
3869:     PetscCall(MatDenseGetColumnVecRead(B, i, &b));
3870:     PetscCall(MatDenseGetColumnVecWrite(X, i, &x));
3871:     PetscCall((*f)(A, b, x));
3872:     PetscCall(MatDenseRestoreColumnVecWrite(X, i, &x));
3873:     PetscCall(MatDenseRestoreColumnVecRead(B, i, &b));
3874:   }
3875:   if (Bneedconv) PetscCall(MatConvert(B, MATDENSE, MAT_INPLACE_MATRIX, &B));
3876:   if (Xneedconv) PetscCall(MatConvert(X, MATDENSE, MAT_INPLACE_MATRIX, &X));
3877:   PetscFunctionReturn(PETSC_SUCCESS);
3878: }

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

3883:   Neighbor-wise Collective

3885:   Input Parameters:
3886: + A - the factored matrix
3887: - B - the right-hand-side matrix `MATDENSE` (or sparse `MATAIJ`-- when using MUMPS)

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

3892:   Level: developer

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

3898: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatGetFactor()`, `MatSolve()`, `MatMatSolveTranspose()`, `MatLUFactor()`, `MatCholeskyFactor()`
3899: @*/
3900: PetscErrorCode MatMatSolve(Mat A, Mat B, Mat X)
3901: {
3902:   PetscFunctionBegin;
3907:   PetscCheckSameComm(A, 1, B, 2);
3908:   PetscCheckSameComm(A, 1, X, 3);
3909:   PetscCheck(A->cmap->N == X->rmap->N, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_SIZ, "Mat A,Mat X: global dim %" PetscInt_FMT " %" PetscInt_FMT, A->cmap->N, X->rmap->N);
3910:   PetscCheck(A->rmap->N == B->rmap->N, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_SIZ, "Mat A,Mat B: global dim %" PetscInt_FMT " %" PetscInt_FMT, A->rmap->N, B->rmap->N);
3911:   PetscCheck(X->cmap->N == B->cmap->N, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_SIZ, "Solution matrix must have same number of columns as rhs matrix");
3912:   if (!A->rmap->N && !A->cmap->N) PetscFunctionReturn(PETSC_SUCCESS);
3913:   MatCheckPreallocated(A, 1);

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

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

3928:   Neighbor-wise Collective

3930:   Input Parameters:
3931: + A - the factored matrix
3932: - B - the right-hand-side matrix  (`MATDENSE` matrix)

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

3937:   Level: developer

3939:   Note:
3940:   The matrices `B` and `X` cannot be the same.  I.e., one cannot
3941:   call `MatMatSolveTranspose`(A,X,X).

3943: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatGetFactor()`, `MatSolveTranspose()`, `MatMatSolve()`, `MatLUFactor()`, `MatCholeskyFactor()`
3944: @*/
3945: PetscErrorCode MatMatSolveTranspose(Mat A, Mat B, Mat X)
3946: {
3947:   PetscFunctionBegin;
3952:   PetscCheckSameComm(A, 1, B, 2);
3953:   PetscCheckSameComm(A, 1, X, 3);
3954:   PetscCheck(X != B, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_IDN, "X and B must be different matrices");
3955:   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);
3956:   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);
3957:   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);
3958:   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");
3959:   if (!A->rmap->N && !A->cmap->N) PetscFunctionReturn(PETSC_SUCCESS);
3960:   MatCheckPreallocated(A, 1);

3962:   PetscCall(PetscLogEventBegin(MAT_MatSolve, A, B, X, 0));
3963:   if (!A->ops->matsolvetranspose) {
3964:     PetscCall(PetscInfo(A, "Mat type %s using basic MatMatSolveTranspose\n", ((PetscObject)A)->type_name));
3965:     PetscCall(MatMatSolve_Basic(A, B, X, PETSC_TRUE));
3966:   } else PetscUseTypeMethod(A, matsolvetranspose, B, X);
3967:   PetscCall(PetscLogEventEnd(MAT_MatSolve, A, B, X, 0));
3968:   PetscCall(PetscObjectStateIncrease((PetscObject)X));
3969:   PetscFunctionReturn(PETSC_SUCCESS);
3970: }

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

3975:   Neighbor-wise Collective

3977:   Input Parameters:
3978: + A  - the factored matrix
3979: - Bt - the transpose of right-hand-side matrix as a `MATDENSE`

3981:   Output Parameter:
3982: . X - the result matrix (dense matrix)

3984:   Level: developer

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

3990: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatMatSolve()`, `MatMatSolveTranspose()`, `MatLUFactor()`, `MatCholeskyFactor()`
3991: @*/
3992: PetscErrorCode MatMatTransposeSolve(Mat A, Mat Bt, Mat X)
3993: {
3994:   PetscFunctionBegin;
3999:   PetscCheckSameComm(A, 1, Bt, 2);
4000:   PetscCheckSameComm(A, 1, X, 3);

4002:   PetscCheck(X != Bt, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_IDN, "X and B must be different matrices");
4003:   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);
4004:   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);
4005:   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");
4006:   if (!A->rmap->N && !A->cmap->N) PetscFunctionReturn(PETSC_SUCCESS);
4007:   PetscCheck(A->factortype, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_WRONGSTATE, "Unfactored matrix");
4008:   MatCheckPreallocated(A, 1);

4010:   PetscCall(PetscLogEventBegin(MAT_MatTrSolve, A, Bt, X, 0));
4011:   PetscUseTypeMethod(A, mattransposesolve, Bt, X);
4012:   PetscCall(PetscLogEventEnd(MAT_MatTrSolve, A, Bt, X, 0));
4013:   PetscCall(PetscObjectStateIncrease((PetscObject)X));
4014:   PetscFunctionReturn(PETSC_SUCCESS);
4015: }

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

4021:   Neighbor-wise Collective

4023:   Input Parameters:
4024: + mat - the factored matrix
4025: - b   - the right-hand-side vector

4027:   Output Parameter:
4028: . x - the result vector

4030:   Level: developer

4032:   Notes:
4033:   `MatSolve()` should be used for most applications, as it performs
4034:   a forward solve followed by a backward solve.

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

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

4045: .seealso: [](ch_matrices), `Mat`, `MatBackwardSolve()`, `MatGetFactor()`, `MatSolve()`
4046: @*/
4047: PetscErrorCode MatForwardSolve(Mat mat, Vec b, Vec x)
4048: {
4049:   PetscFunctionBegin;
4054:   PetscCheckSameComm(mat, 1, b, 2);
4055:   PetscCheckSameComm(mat, 1, x, 3);
4056:   PetscCheck(x != b, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_IDN, "x and b must be different vectors");
4057:   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);
4058:   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);
4059:   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);
4060:   if (!mat->rmap->N && !mat->cmap->N) PetscFunctionReturn(PETSC_SUCCESS);
4061:   MatCheckPreallocated(mat, 1);

4063:   PetscCall(PetscLogEventBegin(MAT_ForwardSolve, mat, b, x, 0));
4064:   PetscUseTypeMethod(mat, forwardsolve, b, x);
4065:   PetscCall(PetscLogEventEnd(MAT_ForwardSolve, mat, b, x, 0));
4066:   PetscCall(PetscObjectStateIncrease((PetscObject)x));
4067:   PetscFunctionReturn(PETSC_SUCCESS);
4068: }

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

4074:   Neighbor-wise Collective

4076:   Input Parameters:
4077: + mat - the factored matrix
4078: - b   - the right-hand-side vector

4080:   Output Parameter:
4081: . x - the result vector

4083:   Level: developer

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

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

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

4098: .seealso: [](ch_matrices), `Mat`, `MatForwardSolve()`, `MatGetFactor()`, `MatSolve()`
4099: @*/
4100: PetscErrorCode MatBackwardSolve(Mat mat, Vec b, Vec x)
4101: {
4102:   PetscFunctionBegin;
4107:   PetscCheckSameComm(mat, 1, b, 2);
4108:   PetscCheckSameComm(mat, 1, x, 3);
4109:   PetscCheck(x != b, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_IDN, "x and b must be different vectors");
4110:   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);
4111:   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);
4112:   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);
4113:   if (!mat->rmap->N && !mat->cmap->N) PetscFunctionReturn(PETSC_SUCCESS);
4114:   MatCheckPreallocated(mat, 1);

4116:   PetscCall(PetscLogEventBegin(MAT_BackwardSolve, mat, b, x, 0));
4117:   PetscUseTypeMethod(mat, backwardsolve, b, x);
4118:   PetscCall(PetscLogEventEnd(MAT_BackwardSolve, mat, b, x, 0));
4119:   PetscCall(PetscObjectStateIncrease((PetscObject)x));
4120:   PetscFunctionReturn(PETSC_SUCCESS);
4121: }

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

4126:   Neighbor-wise Collective

4128:   Input Parameters:
4129: + mat - the factored matrix
4130: . b   - the right-hand-side vector
4131: - y   - the vector to be added to

4133:   Output Parameter:
4134: . x - the result vector

4136:   Level: developer

4138:   Note:
4139:   The vectors `b` and `x` cannot be the same.  I.e., one cannot
4140:   call `MatSolveAdd`(A,x,y,x).

4142: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatSolve()`, `MatGetFactor()`, `MatSolveTranspose()`, `MatSolveTransposeAdd()`
4143: @*/
4144: PetscErrorCode MatSolveAdd(Mat mat, Vec b, Vec y, Vec x)
4145: {
4146:   PetscScalar one = 1.0;
4147:   Vec         tmp;

4149:   PetscFunctionBegin;
4155:   PetscCheckSameComm(mat, 1, b, 2);
4156:   PetscCheckSameComm(mat, 1, y, 3);
4157:   PetscCheckSameComm(mat, 1, x, 4);
4158:   PetscCheck(x != b, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_IDN, "x and b must be different vectors");
4159:   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);
4160:   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);
4161:   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);
4162:   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);
4163:   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);
4164:   if (!mat->rmap->N && !mat->cmap->N) PetscFunctionReturn(PETSC_SUCCESS);
4165:   MatCheckPreallocated(mat, 1);

4167:   PetscCall(PetscLogEventBegin(MAT_SolveAdd, mat, b, x, y));
4168:   PetscCall(VecFlag(x, mat->factorerrortype));
4169:   if (mat->factorerrortype) {
4170:     PetscCall(PetscInfo(mat, "MatFactorError %d\n", mat->factorerrortype));
4171:   } else if (mat->ops->solveadd) {
4172:     PetscUseTypeMethod(mat, solveadd, b, y, x);
4173:   } else {
4174:     /* do the solve then the add manually */
4175:     if (x != y) {
4176:       PetscCall(MatSolve(mat, b, x));
4177:       PetscCall(VecAXPY(x, one, y));
4178:     } else {
4179:       PetscCall(VecDuplicate(x, &tmp));
4180:       PetscCall(VecCopy(x, tmp));
4181:       PetscCall(MatSolve(mat, b, x));
4182:       PetscCall(VecAXPY(x, one, tmp));
4183:       PetscCall(VecDestroy(&tmp));
4184:     }
4185:   }
4186:   PetscCall(PetscLogEventEnd(MAT_SolveAdd, mat, b, x, y));
4187:   PetscCall(PetscObjectStateIncrease((PetscObject)x));
4188:   PetscFunctionReturn(PETSC_SUCCESS);
4189: }

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

4194:   Neighbor-wise Collective

4196:   Input Parameters:
4197: + mat - the factored matrix
4198: - b   - the right-hand-side vector

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

4203:   Level: developer

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

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

4213: .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `KSP`, `MatSolve()`, `MatSolveAdd()`, `MatSolveTransposeAdd()`
4214: @*/
4215: PetscErrorCode MatSolveTranspose(Mat mat, Vec b, Vec x)
4216: {
4217:   PetscErrorCode (*f)(Mat, Vec, Vec) = (!mat->ops->solvetranspose && mat->symmetric) ? mat->ops->solve : mat->ops->solvetranspose;

4219:   PetscFunctionBegin;
4224:   PetscCheckSameComm(mat, 1, b, 2);
4225:   PetscCheckSameComm(mat, 1, x, 3);
4226:   PetscCheck(x != b, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_IDN, "x and b must be different vectors");
4227:   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);
4228:   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);
4229:   if (!mat->rmap->N && !mat->cmap->N) PetscFunctionReturn(PETSC_SUCCESS);
4230:   MatCheckPreallocated(mat, 1);
4231:   PetscCall(PetscLogEventBegin(MAT_SolveTranspose, mat, b, x, 0));
4232:   PetscCall(VecFlag(x, mat->factorerrortype));
4233:   if (mat->factorerrortype) {
4234:     PetscCall(PetscInfo(mat, "MatFactorError %d\n", mat->factorerrortype));
4235:   } else {
4236:     PetscCheck(f, PetscObjectComm((PetscObject)mat), PETSC_ERR_SUP, "Matrix type %s", ((PetscObject)mat)->type_name);
4237:     PetscCall((*f)(mat, b, x));
4238:   }
4239:   PetscCall(PetscLogEventEnd(MAT_SolveTranspose, mat, b, x, 0));
4240:   PetscCall(PetscObjectStateIncrease((PetscObject)x));
4241:   PetscFunctionReturn(PETSC_SUCCESS);
4242: }

4244: /*@
4245:   MatSolveTransposeAdd - Computes $x = y + A^{-T} b$
4246:   factored matrix.

4248:   Neighbor-wise Collective

4250:   Input Parameters:
4251: + mat - the factored matrix
4252: . b   - the right-hand-side vector
4253: - y   - the vector to be added to

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

4258:   Level: developer

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

4264: .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatSolve()`, `MatSolveAdd()`, `MatSolveTranspose()`
4265: @*/
4266: PetscErrorCode MatSolveTransposeAdd(Mat mat, Vec b, Vec y, Vec x)
4267: {
4268:   PetscScalar one = 1.0;
4269:   Vec         tmp;
4270:   PetscErrorCode (*f)(Mat, Vec, Vec, Vec) = (!mat->ops->solvetransposeadd && mat->symmetric) ? mat->ops->solveadd : mat->ops->solvetransposeadd;

4272:   PetscFunctionBegin;
4278:   PetscCheckSameComm(mat, 1, b, 2);
4279:   PetscCheckSameComm(mat, 1, y, 3);
4280:   PetscCheckSameComm(mat, 1, x, 4);
4281:   PetscCheck(x != b, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_IDN, "x and b must be different vectors");
4282:   PetscCheck(mat->rmap->N == x->map->N, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_SIZ, "Mat mat,Vec x: global dim %" PetscInt_FMT " %" PetscInt_FMT, mat->rmap->N, x->map->N);
4283:   PetscCheck(mat->cmap->N == b->map->N, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_SIZ, "Mat mat,Vec b: global dim %" PetscInt_FMT " %" PetscInt_FMT, mat->cmap->N, b->map->N);
4284:   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);
4285:   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);
4286:   if (!mat->rmap->N && !mat->cmap->N) PetscFunctionReturn(PETSC_SUCCESS);
4287:   MatCheckPreallocated(mat, 1);

4289:   PetscCall(PetscLogEventBegin(MAT_SolveTransposeAdd, mat, b, x, y));
4290:   PetscCall(VecFlag(x, mat->factorerrortype));
4291:   if (mat->factorerrortype) {
4292:     PetscCall(PetscInfo(mat, "MatFactorError %d\n", mat->factorerrortype));
4293:   } else if (f) {
4294:     PetscCall((*f)(mat, b, y, x));
4295:   } else {
4296:     /* do the solve then the add manually */
4297:     if (x != y) {
4298:       PetscCall(MatSolveTranspose(mat, b, x));
4299:       PetscCall(VecAXPY(x, one, y));
4300:     } else {
4301:       PetscCall(VecDuplicate(x, &tmp));
4302:       PetscCall(VecCopy(x, tmp));
4303:       PetscCall(MatSolveTranspose(mat, b, x));
4304:       PetscCall(VecAXPY(x, one, tmp));
4305:       PetscCall(VecDestroy(&tmp));
4306:     }
4307:   }
4308:   PetscCall(PetscLogEventEnd(MAT_SolveTransposeAdd, mat, b, x, y));
4309:   PetscCall(PetscObjectStateIncrease((PetscObject)x));
4310:   PetscFunctionReturn(PETSC_SUCCESS);
4311: }

4313: // PetscClangLinter pragma disable: -fdoc-section-header-unknown
4314: /*@
4315:   MatSOR - Computes relaxation (SOR, Gauss-Seidel) sweeps.

4317:   Neighbor-wise Collective

4319:   Input Parameters:
4320: + mat   - the matrix
4321: . b     - the right-hand side
4322: . omega - the relaxation factor
4323: . flag  - flag indicating the type of SOR (see below)
4324: . shift - diagonal shift
4325: . its   - the number of iterations
4326: - lits  - the number of local iterations

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

4331:   SOR Flags:
4332: +     `SOR_FORWARD_SWEEP` - forward SOR
4333: .     `SOR_BACKWARD_SWEEP` - backward SOR
4334: .     `SOR_SYMMETRIC_SWEEP` - SSOR (symmetric SOR)
4335: .     `SOR_LOCAL_FORWARD_SWEEP` - local forward SOR
4336: .     `SOR_LOCAL_BACKWARD_SWEEP` - local forward SOR
4337: .     `SOR_LOCAL_SYMMETRIC_SWEEP` - local SSOR
4338: .     `SOR_EISENSTAT` - SOR with Eisenstat trick
4339: .     `SOR_APPLY_UPPER`, `SOR_APPLY_LOWER` - applies upper/lower triangular part of matrix to vector (with `omega`)
4340: -     `SOR_ZERO_INITIAL_GUESS` - zero initial guess

4342:   Level: developer

4344:   Notes:
4345:   `SOR_LOCAL_FORWARD_SWEEP`, `SOR_LOCAL_BACKWARD_SWEEP`, and
4346:   `SOR_LOCAL_SYMMETRIC_SWEEP` perform separate independent smoothings
4347:   on each processor.

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

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

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

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

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

4364: .seealso: [](ch_matrices), `Mat`, `MatMult()`, `KSP`, `PC`, `MatGetFactor()`
4365: @*/
4366: PetscErrorCode MatSOR(Mat mat, Vec b, PetscReal omega, MatSORType flag, PetscReal shift, PetscInt its, PetscInt lits, Vec x)
4367: {
4368:   PetscFunctionBegin;
4373:   PetscCheckSameComm(mat, 1, b, 2);
4374:   PetscCheckSameComm(mat, 1, x, 8);
4375:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
4376:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
4377:   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);
4378:   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);
4379:   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);
4380:   PetscCheck(its > 0, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Relaxation requires global its %" PetscInt_FMT " positive", its);
4381:   PetscCheck(lits > 0, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Relaxation requires local its %" PetscInt_FMT " positive", lits);
4382:   PetscCheck(b != x, PETSC_COMM_SELF, PETSC_ERR_ARG_IDN, "b and x vector cannot be the same");

4384:   MatCheckPreallocated(mat, 1);
4385:   PetscCall(PetscLogEventBegin(MAT_SOR, mat, b, x, 0));
4386:   PetscUseTypeMethod(mat, sor, b, omega, flag, shift, its, lits, x);
4387:   PetscCall(PetscLogEventEnd(MAT_SOR, mat, b, x, 0));
4388:   PetscCall(PetscObjectStateIncrease((PetscObject)x));
4389:   PetscFunctionReturn(PETSC_SUCCESS);
4390: }

4392: /*
4393:       Default matrix copy routine.
4394: */
4395: PetscErrorCode MatCopy_Basic(Mat A, Mat B, MatStructure str)
4396: {
4397:   PetscInt           i, rstart = 0, rend = 0, nz;
4398:   const PetscInt    *cwork;
4399:   const PetscScalar *vwork;

4401:   PetscFunctionBegin;
4402:   if (B->assembled) PetscCall(MatZeroEntries(B));
4403:   if (str == SAME_NONZERO_PATTERN) {
4404:     PetscCall(MatGetOwnershipRange(A, &rstart, &rend));
4405:     for (i = rstart; i < rend; i++) {
4406:       PetscCall(MatGetRow(A, i, &nz, &cwork, &vwork));
4407:       PetscCall(MatSetValues(B, 1, &i, nz, cwork, vwork, INSERT_VALUES));
4408:       PetscCall(MatRestoreRow(A, i, &nz, &cwork, &vwork));
4409:     }
4410:   } else {
4411:     PetscCall(MatAYPX(B, 0.0, A, str));
4412:   }
4413:   PetscCall(MatAssemblyBegin(B, MAT_FINAL_ASSEMBLY));
4414:   PetscCall(MatAssemblyEnd(B, MAT_FINAL_ASSEMBLY));
4415:   PetscFunctionReturn(PETSC_SUCCESS);
4416: }

4418: /*@
4419:   MatCopy - Copies a matrix to another matrix.

4421:   Collective

4423:   Input Parameters:
4424: + A   - the matrix
4425: - str - `SAME_NONZERO_PATTERN` or `DIFFERENT_NONZERO_PATTERN`

4427:   Output Parameter:
4428: . B - where the copy is put

4430:   Level: intermediate

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

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

4439: .seealso: [](ch_matrices), `Mat`, `MatConvert()`, `MatDuplicate()`
4440: @*/
4441: PetscErrorCode MatCopy(Mat A, Mat B, MatStructure str)
4442: {
4443:   PetscInt i;

4445:   PetscFunctionBegin;
4450:   PetscCheckSameComm(A, 1, B, 2);
4451:   MatCheckPreallocated(B, 2);
4452:   PetscCheck(A->assembled, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
4453:   PetscCheck(!A->factortype, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
4454:   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,
4455:              A->cmap->N, B->cmap->N);
4456:   MatCheckPreallocated(A, 1);
4457:   if (A == B) PetscFunctionReturn(PETSC_SUCCESS);

4459:   PetscCall(PetscLogEventBegin(MAT_Copy, A, B, 0, 0));
4460:   if (A->ops->copy) PetscUseTypeMethod(A, copy, B, str);
4461:   else PetscCall(MatCopy_Basic(A, B, str));

4463:   B->stencil.dim = A->stencil.dim;
4464:   B->stencil.noc = A->stencil.noc;
4465:   for (i = 0; i <= A->stencil.dim + (A->stencil.noc ? 0 : -1); i++) {
4466:     B->stencil.dims[i]   = A->stencil.dims[i];
4467:     B->stencil.starts[i] = A->stencil.starts[i];
4468:   }

4470:   PetscCall(PetscLogEventEnd(MAT_Copy, A, B, 0, 0));
4471:   PetscCall(PetscObjectStateIncrease((PetscObject)B));
4472:   PetscFunctionReturn(PETSC_SUCCESS);
4473: }

4475: /*@
4476:   MatConvert - Converts a matrix to another matrix, either of the same
4477:   or different type.

4479:   Collective

4481:   Input Parameters:
4482: + mat     - the matrix
4483: . newtype - new matrix type.  Use `MATSAME` to create a new matrix of the
4484:             same type as the original matrix.
4485: - reuse   - denotes if the destination matrix is to be created or reused.
4486:             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
4487:             `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).

4489:   Output Parameter:
4490: . M - pointer to place new matrix

4492:   Level: intermediate

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

4499:   Cannot be used to convert a sequential matrix to parallel or parallel to sequential,
4500:   the MPI communicator of the generated matrix is always the same as the communicator
4501:   of the input matrix.

4503: .seealso: [](ch_matrices), `Mat`, `MatCopy()`, `MatDuplicate()`, `MAT_INITIAL_MATRIX`, `MAT_REUSE_MATRIX`, `MAT_INPLACE_MATRIX`
4504: @*/
4505: PetscErrorCode MatConvert(Mat mat, MatType newtype, MatReuse reuse, Mat *M)
4506: {
4507:   PetscBool  sametype, issame, flg;
4508:   PetscBool3 issymmetric, ishermitian, isspd;
4509:   char       convname[256], mtype[256];
4510:   Mat        B;

4512:   PetscFunctionBegin;
4515:   PetscAssertPointer(M, 4);
4516:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
4517:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
4518:   MatCheckPreallocated(mat, 1);

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

4523:   PetscCall(PetscObjectTypeCompare((PetscObject)mat, newtype, &sametype));
4524:   PetscCall(PetscStrcmp(newtype, "same", &issame));
4525:   PetscCheck(!(reuse == MAT_INPLACE_MATRIX) || !(mat != *M), PetscObjectComm((PetscObject)mat), PETSC_ERR_SUP, "MAT_INPLACE_MATRIX requires same input and output matrix");
4526:   if (reuse == MAT_REUSE_MATRIX) {
4528:     PetscCheck(mat != *M, PetscObjectComm((PetscObject)mat), PETSC_ERR_SUP, "MAT_REUSE_MATRIX means reuse matrix in final argument, perhaps you mean MAT_INPLACE_MATRIX");
4529:   }

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

4536:   /* Cache Mat options because some converters use MatHeaderReplace() */
4537:   issymmetric = mat->symmetric;
4538:   ishermitian = mat->hermitian;
4539:   isspd       = mat->spd;

4541:   if ((sametype || issame) && (reuse == MAT_INITIAL_MATRIX) && mat->ops->duplicate) {
4542:     PetscCall(PetscInfo(mat, "Calling duplicate for initial matrix %s %d %d\n", ((PetscObject)mat)->type_name, sametype, issame));
4543:     PetscUseTypeMethod(mat, duplicate, MAT_COPY_VALUES, M);
4544:   } else {
4545:     PetscErrorCode (*conv)(Mat, MatType, MatReuse, Mat *) = NULL;
4546:     const char *prefix[3]                                 = {"seq", "mpi", ""};
4547:     PetscInt    i;
4548:     /*
4549:        Order of precedence:
4550:        0) See if newtype is a superclass of the current matrix.
4551:        1) See if a specialized converter is known to the current matrix.
4552:        2) See if a specialized converter is known to the desired matrix class.
4553:        3) See if a good general converter is registered for the desired class
4554:           (as of 6/27/03 only MATMPIADJ falls into this category).
4555:        4) See if a good general converter is known for the current matrix.
4556:        5) Use a really basic converter.
4557:     */

4559:     /* 0) See if newtype is a superclass of the current matrix.
4560:           i.e mat is mpiaij and newtype is aij */
4561:     for (i = 0; i < (PetscInt)PETSC_STATIC_ARRAY_LENGTH(prefix); i++) {
4562:       PetscCall(PetscStrncpy(convname, prefix[i], sizeof(convname)));
4563:       PetscCall(PetscStrlcat(convname, newtype, sizeof(convname)));
4564:       PetscCall(PetscStrcmp(convname, ((PetscObject)mat)->type_name, &flg));
4565:       PetscCall(PetscInfo(mat, "Check superclass %s %s -> %d\n", convname, ((PetscObject)mat)->type_name, flg));
4566:       if (flg) {
4567:         if (reuse == MAT_INPLACE_MATRIX) {
4568:           PetscCall(PetscInfo(mat, "Early return\n"));
4569:           PetscFunctionReturn(PETSC_SUCCESS);
4570:         } else if (reuse == MAT_INITIAL_MATRIX && mat->ops->duplicate) {
4571:           PetscCall(PetscInfo(mat, "Calling MatDuplicate\n"));
4572:           PetscUseTypeMethod(mat, duplicate, MAT_COPY_VALUES, M);
4573:           PetscFunctionReturn(PETSC_SUCCESS);
4574:         } else if (reuse == MAT_REUSE_MATRIX && mat->ops->copy) {
4575:           PetscCall(PetscInfo(mat, "Calling MatCopy\n"));
4576:           PetscCall(MatCopy(mat, *M, SAME_NONZERO_PATTERN));
4577:           PetscFunctionReturn(PETSC_SUCCESS);
4578:         }
4579:       }
4580:     }
4581:     /* 1) See if a specialized converter is known to the current matrix and the desired class */
4582:     for (i = 0; i < (PetscInt)PETSC_STATIC_ARRAY_LENGTH(prefix); i++) {
4583:       PetscCall(PetscStrncpy(convname, "MatConvert_", sizeof(convname)));
4584:       PetscCall(PetscStrlcat(convname, ((PetscObject)mat)->type_name, sizeof(convname)));
4585:       PetscCall(PetscStrlcat(convname, "_", sizeof(convname)));
4586:       PetscCall(PetscStrlcat(convname, prefix[i], sizeof(convname)));
4587:       PetscCall(PetscStrlcat(convname, issame ? ((PetscObject)mat)->type_name : newtype, sizeof(convname)));
4588:       PetscCall(PetscStrlcat(convname, "_C", sizeof(convname)));
4589:       PetscCall(PetscObjectQueryFunction((PetscObject)mat, convname, &conv));
4590:       PetscCall(PetscInfo(mat, "Check specialized (1) %s (%s) -> %d\n", convname, ((PetscObject)mat)->type_name, !!conv));
4591:       if (conv) goto foundconv;
4592:     }

4594:     /* 2)  See if a specialized converter is known to the desired matrix class. */
4595:     PetscCall(MatCreate(PetscObjectComm((PetscObject)mat), &B));
4596:     PetscCall(MatSetSizes(B, mat->rmap->n, mat->cmap->n, mat->rmap->N, mat->cmap->N));
4597:     PetscCall(MatSetType(B, newtype));
4598:     for (i = 0; i < (PetscInt)PETSC_STATIC_ARRAY_LENGTH(prefix); i++) {
4599:       PetscCall(PetscStrncpy(convname, "MatConvert_", sizeof(convname)));
4600:       PetscCall(PetscStrlcat(convname, ((PetscObject)mat)->type_name, sizeof(convname)));
4601:       PetscCall(PetscStrlcat(convname, "_", sizeof(convname)));
4602:       PetscCall(PetscStrlcat(convname, prefix[i], sizeof(convname)));
4603:       PetscCall(PetscStrlcat(convname, newtype, sizeof(convname)));
4604:       PetscCall(PetscStrlcat(convname, "_C", sizeof(convname)));
4605:       PetscCall(PetscObjectQueryFunction((PetscObject)B, convname, &conv));
4606:       PetscCall(PetscInfo(mat, "Check specialized (2) %s (%s) -> %d\n", convname, ((PetscObject)B)->type_name, !!conv));
4607:       if (conv) {
4608:         PetscCall(MatDestroy(&B));
4609:         goto foundconv;
4610:       }
4611:     }

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

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

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

4628:   foundconv:
4629:     PetscCall(PetscLogEventBegin(MAT_Convert, mat, 0, 0, 0));
4630:     PetscCall((*conv)(mat, newtype, reuse, M));
4631:     if (mat->rmap->mapping && mat->cmap->mapping && !(*M)->rmap->mapping && !(*M)->cmap->mapping) {
4632:       /* the block sizes must be same if the mappings are copied over */
4633:       (*M)->rmap->bs = mat->rmap->bs;
4634:       (*M)->cmap->bs = mat->cmap->bs;
4635:       PetscCall(PetscObjectReference((PetscObject)mat->rmap->mapping));
4636:       PetscCall(PetscObjectReference((PetscObject)mat->cmap->mapping));
4637:       (*M)->rmap->mapping = mat->rmap->mapping;
4638:       (*M)->cmap->mapping = mat->cmap->mapping;
4639:     }
4640:     (*M)->stencil.dim = mat->stencil.dim;
4641:     (*M)->stencil.noc = mat->stencil.noc;
4642:     for (i = 0; i <= mat->stencil.dim + (mat->stencil.noc ? 0 : -1); i++) {
4643:       (*M)->stencil.dims[i]   = mat->stencil.dims[i];
4644:       (*M)->stencil.starts[i] = mat->stencil.starts[i];
4645:     }
4646:     PetscCall(PetscLogEventEnd(MAT_Convert, mat, 0, 0, 0));
4647:   }
4648:   PetscCall(PetscObjectStateIncrease((PetscObject)*M));

4650:   /* Reset Mat options */
4651:   if (issymmetric != PETSC_BOOL3_UNKNOWN) PetscCall(MatSetOption(*M, MAT_SYMMETRIC, PetscBool3ToBool(issymmetric)));
4652:   if (ishermitian != PETSC_BOOL3_UNKNOWN) PetscCall(MatSetOption(*M, MAT_HERMITIAN, PetscBool3ToBool(ishermitian)));
4653:   if (isspd != PETSC_BOOL3_UNKNOWN) PetscCall(MatSetOption(*M, MAT_SPD, PetscBool3ToBool(isspd)));
4654:   PetscFunctionReturn(PETSC_SUCCESS);
4655: }

4657: /*@
4658:   MatFactorGetSolverType - Returns name of the package providing the factorization routines

4660:   Not Collective

4662:   Input Parameter:
4663: . mat - the matrix, must be a factored matrix

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

4668:   Level: intermediate

4670: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatGetFactor()`, `MatSolverType`, `MatCopy()`, `MatDuplicate()`, `MatGetFactorAvailable()`
4671: @*/
4672: PetscErrorCode MatFactorGetSolverType(Mat mat, MatSolverType *type)
4673: {
4674:   PetscErrorCode (*conv)(Mat, MatSolverType *);

4676:   PetscFunctionBegin;
4679:   PetscAssertPointer(type, 2);
4680:   PetscCheck(mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Only for factored matrix");
4681:   PetscCall(PetscObjectQueryFunction((PetscObject)mat, "MatFactorGetSolverType_C", &conv));
4682:   if (conv) PetscCall((*conv)(mat, type));
4683:   else *type = MATSOLVERPETSC;
4684:   PetscFunctionReturn(PETSC_SUCCESS);
4685: }

4687: typedef struct _MatSolverTypeForSpecifcType *MatSolverTypeForSpecifcType;
4688: struct _MatSolverTypeForSpecifcType {
4689:   MatType mtype;
4690:   /* no entry for MAT_FACTOR_NONE */
4691:   PetscErrorCode (*createfactor[MAT_FACTOR_NUM_TYPES - 1])(Mat, MatFactorType, Mat *);
4692:   MatSolverTypeForSpecifcType next;
4693: };

4695: typedef struct _MatSolverTypeHolder *MatSolverTypeHolder;
4696: struct _MatSolverTypeHolder {
4697:   char                       *name;
4698:   MatSolverTypeForSpecifcType handlers;
4699:   MatSolverTypeHolder         next;
4700: };

4702: static MatSolverTypeHolder MatSolverTypeHolders = NULL;

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

4707:   Logically Collective, No Fortran Support

4709:   Input Parameters:
4710: + package      - name of the package, for example `petsc` or `superlu`
4711: . mtype        - the matrix type that works with this package
4712: . ftype        - the type of factorization supported by the package
4713: - createfactor - routine that will create the factored matrix ready to be used

4715:   Level: developer

4717: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatFactorGetSolverType()`, `MatCopy()`, `MatDuplicate()`, `MatGetFactorAvailable()`,
4718:   `MatGetFactor()`
4719: @*/
4720: PetscErrorCode MatSolverTypeRegister(MatSolverType package, MatType mtype, MatFactorType ftype, PetscErrorCode (*createfactor)(Mat, MatFactorType, Mat *))
4721: {
4722:   MatSolverTypeHolder         next = MatSolverTypeHolders, prev = NULL;
4723:   PetscBool                   flg;
4724:   MatSolverTypeForSpecifcType inext, iprev = NULL;

4726:   PetscFunctionBegin;
4727:   PetscCall(MatInitializePackage());
4728:   if (!next) {
4729:     PetscCall(PetscNew(&MatSolverTypeHolders));
4730:     PetscCall(PetscStrallocpy(package, &MatSolverTypeHolders->name));
4731:     PetscCall(PetscNew(&MatSolverTypeHolders->handlers));
4732:     PetscCall(PetscStrallocpy(mtype, (char **)&MatSolverTypeHolders->handlers->mtype));
4733:     MatSolverTypeHolders->handlers->createfactor[(int)ftype - 1] = createfactor;
4734:     PetscFunctionReturn(PETSC_SUCCESS);
4735:   }
4736:   while (next) {
4737:     PetscCall(PetscStrcasecmp(package, next->name, &flg));
4738:     if (flg) {
4739:       PetscCheck(next->handlers, PETSC_COMM_SELF, PETSC_ERR_PLIB, "MatSolverTypeHolder is missing handlers");
4740:       inext = next->handlers;
4741:       while (inext) {
4742:         PetscCall(PetscStrcasecmp(mtype, inext->mtype, &flg));
4743:         if (flg) {
4744:           inext->createfactor[(int)ftype - 1] = createfactor;
4745:           PetscFunctionReturn(PETSC_SUCCESS);
4746:         }
4747:         iprev = inext;
4748:         inext = inext->next;
4749:       }
4750:       PetscCall(PetscNew(&iprev->next));
4751:       PetscCall(PetscStrallocpy(mtype, (char **)&iprev->next->mtype));
4752:       iprev->next->createfactor[(int)ftype - 1] = createfactor;
4753:       PetscFunctionReturn(PETSC_SUCCESS);
4754:     }
4755:     prev = next;
4756:     next = next->next;
4757:   }
4758:   PetscCall(PetscNew(&prev->next));
4759:   PetscCall(PetscStrallocpy(package, &prev->next->name));
4760:   PetscCall(PetscNew(&prev->next->handlers));
4761:   PetscCall(PetscStrallocpy(mtype, (char **)&prev->next->handlers->mtype));
4762:   prev->next->handlers->createfactor[(int)ftype - 1] = createfactor;
4763:   PetscFunctionReturn(PETSC_SUCCESS);
4764: }

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

4769:   Input Parameters:
4770: + 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
4771: . ftype - the type of factorization supported by the type
4772: - mtype - the matrix type that works with this type

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

4779:   Calling sequence of `createfactor`:
4780: + A     - the matrix providing the factor matrix
4781: . ftype - the `MatFactorType` of the factor requested
4782: - B     - the new factor matrix that responds to MatXXFactorSymbolic,Numeric() functions, such as `MatLUFactorSymbolic()`

4784:   Level: developer

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

4791: .seealso: [](ch_matrices), `Mat`, `MatFactorType`, `MatType`, `MatCopy()`, `MatDuplicate()`, `MatGetFactorAvailable()`, `MatSolverTypeRegister()`, `MatGetFactor()`,
4792:           `MatInitializePackage()`
4793: @*/
4794: PetscErrorCode MatSolverTypeGet(MatSolverType type, MatType mtype, MatFactorType ftype, PetscBool *foundtype, PetscBool *foundmtype, PetscErrorCode (**createfactor)(Mat A, MatFactorType ftype, Mat *B))
4795: {
4796:   MatSolverTypeHolder         next = MatSolverTypeHolders;
4797:   PetscBool                   flg;
4798:   MatSolverTypeForSpecifcType inext;

4800:   PetscFunctionBegin;
4801:   if (foundtype) *foundtype = PETSC_FALSE;
4802:   if (foundmtype) *foundmtype = PETSC_FALSE;
4803:   if (createfactor) *createfactor = NULL;

4805:   if (type) {
4806:     while (next) {
4807:       PetscCall(PetscStrcasecmp(type, next->name, &flg));
4808:       if (flg) {
4809:         if (foundtype) *foundtype = PETSC_TRUE;
4810:         inext = next->handlers;
4811:         while (inext) {
4812:           PetscCall(PetscStrbeginswith(mtype, inext->mtype, &flg));
4813:           if (flg) {
4814:             if (foundmtype) *foundmtype = PETSC_TRUE;
4815:             if (createfactor) *createfactor = inext->createfactor[(int)ftype - 1];
4816:             PetscFunctionReturn(PETSC_SUCCESS);
4817:           }
4818:           inext = inext->next;
4819:         }
4820:       }
4821:       next = next->next;
4822:     }
4823:   } else {
4824:     while (next) {
4825:       inext = next->handlers;
4826:       while (inext) {
4827:         PetscCall(PetscStrcmp(mtype, inext->mtype, &flg));
4828:         if (flg && inext->createfactor[(int)ftype - 1]) {
4829:           if (foundtype) *foundtype = PETSC_TRUE;
4830:           if (foundmtype) *foundmtype = PETSC_TRUE;
4831:           if (createfactor) *createfactor = inext->createfactor[(int)ftype - 1];
4832:           PetscFunctionReturn(PETSC_SUCCESS);
4833:         }
4834:         inext = inext->next;
4835:       }
4836:       next = next->next;
4837:     }
4838:     /* try with base classes inext->mtype */
4839:     next = MatSolverTypeHolders;
4840:     while (next) {
4841:       inext = next->handlers;
4842:       while (inext) {
4843:         PetscCall(PetscStrbeginswith(mtype, inext->mtype, &flg));
4844:         if (flg && inext->createfactor[(int)ftype - 1]) {
4845:           if (foundtype) *foundtype = PETSC_TRUE;
4846:           if (foundmtype) *foundmtype = PETSC_TRUE;
4847:           if (createfactor) *createfactor = inext->createfactor[(int)ftype - 1];
4848:           PetscFunctionReturn(PETSC_SUCCESS);
4849:         }
4850:         inext = inext->next;
4851:       }
4852:       next = next->next;
4853:     }
4854:   }
4855:   PetscFunctionReturn(PETSC_SUCCESS);
4856: }

4858: PetscErrorCode MatSolverTypeDestroy(void)
4859: {
4860:   MatSolverTypeHolder         next = MatSolverTypeHolders, prev;
4861:   MatSolverTypeForSpecifcType inext, iprev;

4863:   PetscFunctionBegin;
4864:   while (next) {
4865:     PetscCall(PetscFree(next->name));
4866:     inext = next->handlers;
4867:     while (inext) {
4868:       PetscCall(PetscFree(inext->mtype));
4869:       iprev = inext;
4870:       inext = inext->next;
4871:       PetscCall(PetscFree(iprev));
4872:     }
4873:     prev = next;
4874:     next = next->next;
4875:     PetscCall(PetscFree(prev));
4876:   }
4877:   MatSolverTypeHolders = NULL;
4878:   PetscFunctionReturn(PETSC_SUCCESS);
4879: }

4881: static PetscErrorCode MatGetFactor_Private(Mat mat, MatFactorType ftype, PetscBool exact, PetscBool *found, Mat *f)
4882: {
4883:   MatSolverTypeHolder         next = MatSolverTypeHolders;
4884:   MatSolverTypeForSpecifcType inext;
4885:   PetscBool                   flg, same;

4887:   PetscFunctionBegin;
4888:   *found = PETSC_FALSE;
4889:   *f     = NULL;
4890:   /* When no solver type is requested, MatGetFactor() must honor registration order, but a registered
4891:      MatSolverType may only be able to reject a particular MatType at runtime by returning NULL in *f.
4892:      Keep walking the registry until a matching backend actually creates a factor. */
4893:   while (next) {
4894:     inext = next->handlers;
4895:     while (inext) {
4896:       PetscCall(PetscStrcmp(((PetscObject)mat)->type_name, inext->mtype, &same));
4897:       if (exact) flg = same;
4898:       else {
4899:         /* Do the base-type pass separately from the exact pass so exact registrations for the MatType
4900:            are all tried before broader registrations such as implementation base classes. */
4901:         PetscCall(PetscStrbeginswith(((PetscObject)mat)->type_name, inext->mtype, &flg));
4902:         flg = (PetscBool)(flg && !same);
4903:       }
4904:       if (flg && inext->createfactor[(int)ftype - 1]) {
4905:         *found = PETSC_TRUE;
4906:         PetscCall((*inext->createfactor[(int)ftype - 1])(mat, ftype, f));
4907:         if (*f) PetscFunctionReturn(PETSC_SUCCESS);
4908:       }
4909:       inext = inext->next;
4910:     }
4911:     next = next->next;
4912:   }
4913:   PetscFunctionReturn(PETSC_SUCCESS);
4914: }

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

4919:   Logically Collective

4921:   Input Parameter:
4922: . mat - the matrix

4924:   Output Parameter:
4925: . flg - `PETSC_TRUE` if uses the ordering

4927:   Level: developer

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

4933: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatCopy()`, `MatDuplicate()`, `MatGetFactorAvailable()`, `MatGetFactor()`, `MatLUFactorSymbolic()`, `MatCholeskyFactorSymbolic()`
4934: @*/
4935: PetscErrorCode MatFactorGetCanUseOrdering(Mat mat, PetscBool *flg)
4936: {
4937:   PetscFunctionBegin;
4938:   *flg = mat->canuseordering;
4939:   PetscFunctionReturn(PETSC_SUCCESS);
4940: }

4942: /*@
4943:   MatFactorGetPreferredOrdering - The preferred ordering for a particular matrix factor object

4945:   Logically Collective

4947:   Input Parameters:
4948: + mat   - the matrix obtained with `MatGetFactor()`
4949: - ftype - the factorization type to be used

4951:   Output Parameter:
4952: . otype - the preferred ordering type

4954:   Level: developer

4956: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatFactorType`, `MatOrderingType`, `MatCopy()`, `MatDuplicate()`, `MatGetFactorAvailable()`, `MatGetFactor()`, `MatLUFactorSymbolic()`, `MatCholeskyFactorSymbolic()`
4957: @*/
4958: PetscErrorCode MatFactorGetPreferredOrdering(Mat mat, MatFactorType ftype, MatOrderingType *otype)
4959: {
4960:   PetscFunctionBegin;
4961:   *otype = mat->preferredordering[ftype];
4962:   PetscCheck(*otype, PETSC_COMM_SELF, PETSC_ERR_PLIB, "MatFactor did not have a preferred ordering");
4963:   PetscFunctionReturn(PETSC_SUCCESS);
4964: }

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

4970:   Collective

4972:   Input Parameters:
4973: + mat   - the matrix
4974: . 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
4975:           the other criteria is returned
4976: - ftype - factor type, `MAT_FACTOR_LU`, `MAT_FACTOR_CHOLESKY`, `MAT_FACTOR_ICC`, `MAT_FACTOR_ILU`, `MAT_FACTOR_QR`

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

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

4986:   Level: intermediate

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

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

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

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

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

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

5011: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `KSP`, `MatSolverType`, `MatFactorType`, `MatCopy()`, `MatDuplicate()`,
5012:           `MatGetFactorAvailable()`, `MatFactorGetCanUseOrdering()`, `MatSolverTypeRegister()`, `MatSolverTypeGet()`,
5013:           `MAT_FACTOR_LU`, `MAT_FACTOR_CHOLESKY`, `MAT_FACTOR_ICC`, `MAT_FACTOR_ILU`, `MAT_FACTOR_QR`, `MatInitializePackage()`,
5014:           `MatLUFactorSymbolic()`, `MatCholeskyFactorSymbolic()`, `MatILUFactorSymbolic()`,
5015:           `MatICCFactorSymbolic()`, `MatLUFactorNumeric()`, `MatCholeskyFactorNumeric()`
5016: @*/
5017: PetscErrorCode MatGetFactor(Mat mat, MatSolverType type, MatFactorType ftype, Mat *f)
5018: {
5019:   PetscBool foundtype, foundmtype, shell, hasop = PETSC_FALSE;
5020:   PetscErrorCode (*conv)(Mat, MatFactorType, Mat *);

5022:   PetscFunctionBegin;

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

5029:   PetscCall(MatIsShell(mat, &shell));
5030:   if (shell) PetscCall(MatHasOperation(mat, MATOP_GET_FACTOR, &hasop));
5031:   if (hasop) {
5032:     PetscUseTypeMethod(mat, getfactor, type, ftype, f);
5033:     PetscFunctionReturn(PETSC_SUCCESS);
5034:   }

5036:   if (!type) {
5037:     PetscBool foundbase;

5039:     /* First try exact MatType registrations in solver registration order. If all matching backends
5040:        decline this matrix instance by returning NULL, then try base-type registrations. */
5041:     PetscCall(MatGetFactor_Private(mat, ftype, PETSC_TRUE, &foundtype, f));
5042:     if (!*f) {
5043:       PetscCall(MatGetFactor_Private(mat, ftype, PETSC_FALSE, &foundbase, f));
5044:       foundtype = (PetscBool)(foundtype || foundbase);
5045:     }
5046:     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);
5047:     if (mat->factorprefix) PetscCall(MatSetOptionsPrefix(*f, mat->factorprefix));
5048:     PetscFunctionReturn(PETSC_SUCCESS);
5049:   }

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

5057:   PetscCall((*conv)(mat, ftype, f));
5058:   if (mat->factorprefix) PetscCall(MatSetOptionsPrefix(*f, mat->factorprefix));
5059:   PetscFunctionReturn(PETSC_SUCCESS);
5060: }

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

5065:   Not Collective

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

5072:   Output Parameter:
5073: . flg - PETSC_TRUE if the factorization is available

5075:   Level: intermediate

5077:   Notes:
5078:   Some PETSc matrix formats have alternative solvers available that are contained in alternative packages
5079:   such as pastix, superlu, mumps etc.

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

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

5086: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatSolverType`, `MatFactorType`, `MatGetFactor()`, `MatCopy()`, `MatDuplicate()`, `MatSolverTypeRegister()`,
5087:           `MAT_FACTOR_LU`, `MAT_FACTOR_CHOLESKY`, `MAT_FACTOR_ICC`, `MAT_FACTOR_ILU`, `MAT_FACTOR_QR`, `MatSolverTypeGet()`
5088: @*/
5089: PetscErrorCode MatGetFactorAvailable(Mat mat, MatSolverType type, MatFactorType ftype, PetscBool *flg)
5090: {
5091:   PetscErrorCode (*gconv)(Mat, MatFactorType, Mat *);

5093:   PetscFunctionBegin;
5095:   PetscAssertPointer(flg, 4);

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

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

5103:   PetscCall(MatSolverTypeGet(type, ((PetscObject)mat)->type_name, ftype, NULL, NULL, &gconv));
5104:   *flg = gconv ? PETSC_TRUE : PETSC_FALSE;
5105:   PetscFunctionReturn(PETSC_SUCCESS);
5106: }

5108: /*@
5109:   MatDuplicate - Duplicates a matrix including the non-zero structure.

5111:   Collective

5113:   Input Parameters:
5114: + mat - the matrix
5115: - op  - One of `MAT_DO_NOT_COPY_VALUES`, `MAT_COPY_VALUES`, or `MAT_SHARE_NONZERO_PATTERN`.
5116:         See the manual page for `MatDuplicateOption()` for an explanation of these options.

5118:   Output Parameter:
5119: . M - pointer to place new matrix

5121:   Level: intermediate

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

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

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

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

5134: .seealso: [](ch_matrices), `Mat`, `MatCopy()`, `MatConvert()`, `MatDuplicateOption`
5135: @*/
5136: PetscErrorCode MatDuplicate(Mat mat, MatDuplicateOption op, Mat *M)
5137: {
5138:   Mat               B;
5139:   VecType           vtype;
5140:   PetscInt          i;
5141:   PetscObject       dm, container_h, container_d;
5142:   PetscErrorCodeFn *viewf;

5144:   PetscFunctionBegin;
5147:   PetscAssertPointer(M, 3);
5148:   PetscCheck(op != MAT_COPY_VALUES || mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "MAT_COPY_VALUES not allowed for unassembled matrix");
5149:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
5150:   MatCheckPreallocated(mat, 1);

5152:   PetscCall(PetscLogEventBegin(MAT_Convert, mat, 0, 0, 0));
5153:   PetscUseTypeMethod(mat, duplicate, op, M);
5154:   PetscCall(PetscLogEventEnd(MAT_Convert, mat, 0, 0, 0));
5155:   B = *M;

5157:   PetscCall(MatGetOperation(mat, MATOP_VIEW, &viewf));
5158:   if (viewf) PetscCall(MatSetOperation(B, MATOP_VIEW, viewf));
5159:   PetscCall(MatGetVecType(mat, &vtype));
5160:   PetscCall(MatSetVecType(B, vtype));

5162:   B->stencil.dim = mat->stencil.dim;
5163:   B->stencil.noc = mat->stencil.noc;
5164:   for (i = 0; i <= mat->stencil.dim + (mat->stencil.noc ? 0 : -1); i++) {
5165:     B->stencil.dims[i]   = mat->stencil.dims[i];
5166:     B->stencil.starts[i] = mat->stencil.starts[i];
5167:   }

5169:   B->nooffproczerorows = mat->nooffproczerorows;
5170:   B->nooffprocentries  = mat->nooffprocentries;

5172:   PetscCall(PetscObjectQuery((PetscObject)mat, "__PETSc_dm", &dm));
5173:   if (dm) PetscCall(PetscObjectCompose((PetscObject)B, "__PETSc_dm", dm));
5174:   PetscCall(PetscObjectQuery((PetscObject)mat, "__PETSc_MatCOOStruct_Host", &container_h));
5175:   if (container_h) PetscCall(PetscObjectCompose((PetscObject)B, "__PETSc_MatCOOStruct_Host", container_h));
5176:   PetscCall(PetscObjectQuery((PetscObject)mat, "__PETSc_MatCOOStruct_Device", &container_d));
5177:   if (container_d) PetscCall(PetscObjectCompose((PetscObject)B, "__PETSc_MatCOOStruct_Device", container_d));
5178:   if (op == MAT_COPY_VALUES) PetscCall(MatPropagateSymmetryOptions(mat, B));
5179:   PetscCall(PetscObjectStateIncrease((PetscObject)B));
5180:   PetscFunctionReturn(PETSC_SUCCESS);
5181: }

5183: /*@
5184:   MatGetDiagonal - Gets the diagonal of a matrix as a `Vec`

5186:   Logically Collective

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

5191:   Output Parameter:
5192: . v - the diagonal of the matrix

5194:   Level: intermediate

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

5201:   Currently only correct in parallel for square matrices.

5203: .seealso: [](ch_matrices), `Mat`, `Vec`, `MatGetRow()`, `MatCreateSubMatrices()`, `MatCreateSubMatrix()`, `MatGetRowMaxAbs()`
5204: @*/
5205: PetscErrorCode MatGetDiagonal(Mat mat, Vec v)
5206: {
5207:   PetscFunctionBegin;
5211:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
5212:   MatCheckPreallocated(mat, 1);
5213:   if (PetscDefined(USE_DEBUG)) {
5214:     PetscInt nv, row, col, ndiag;

5216:     PetscCall(VecGetLocalSize(v, &nv));
5217:     PetscCall(MatGetLocalSize(mat, &row, &col));
5218:     ndiag = PetscMin(row, col);
5219:     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);
5220:   }

5222:   PetscUseTypeMethod(mat, getdiagonal, v);
5223:   PetscCall(PetscObjectStateIncrease((PetscObject)v));
5224:   PetscFunctionReturn(PETSC_SUCCESS);
5225: }

5227: /*@
5228:   MatGetRowMin - Gets the minimum value (of the real part) of each
5229:   row of the matrix

5231:   Logically Collective

5233:   Input Parameter:
5234: . mat - the matrix

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

5240:   Level: intermediate

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

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

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

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

5273: /*@
5274:   MatGetRowMinAbs - Gets the minimum value (in absolute value) of each
5275:   row of the matrix

5277:   Logically Collective

5279:   Input Parameter:
5280: . mat - the matrix

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

5286:   Level: intermediate

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

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

5294: .seealso: [](ch_matrices), `Mat`, `MatGetDiagonal()`, `MatCreateSubMatrices()`, `MatCreateSubMatrix()`, `MatGetRowMax()`, `MatGetRowMaxAbs()`, `MatGetRowMin()`
5295: @*/
5296: PetscErrorCode MatGetRowMinAbs(Mat mat, Vec v, PetscInt idx[])
5297: {
5298:   PetscFunctionBegin;
5302:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
5303:   PetscCheck(!mat->factortype, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");

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

5320: /*@
5321:   MatGetRowMax - Gets the maximum value (of the real part) of each
5322:   row of the matrix

5324:   Logically Collective

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

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

5333:   Level: intermediate

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

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

5341: .seealso: [](ch_matrices), `Mat`, `MatGetDiagonal()`, `MatCreateSubMatrices()`, `MatCreateSubMatrix()`, `MatGetRowMaxAbs()`, `MatGetRowMin()`, `MatGetRowMinAbs()`
5342: @*/
5343: PetscErrorCode MatGetRowMax(Mat mat, Vec v, PetscInt idx[])
5344: {
5345:   PetscFunctionBegin;
5349:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");

5351:   if (!mat->cmap->N) {
5352:     PetscCall(VecSet(v, PETSC_MIN_REAL));
5353:     if (idx) {
5354:       PetscInt i, m = mat->rmap->n;
5355:       for (i = 0; i < m; i++) idx[i] = -1;
5356:     }
5357:   } else {
5358:     MatCheckPreallocated(mat, 1);
5359:     PetscUseTypeMethod(mat, getrowmax, v, idx);
5360:   }
5361:   PetscCall(PetscObjectStateIncrease((PetscObject)v));
5362:   PetscFunctionReturn(PETSC_SUCCESS);
5363: }

5365: /*@
5366:   MatGetRowMaxAbs - Gets the maximum value (in absolute value) of each
5367:   row of the matrix

5369:   Logically Collective

5371:   Input Parameter:
5372: . mat - the matrix

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

5378:   Level: intermediate

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

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

5386: .seealso: [](ch_matrices), `Mat`, `MatGetDiagonal()`, `MatCreateSubMatrices()`, `MatCreateSubMatrix()`, `MatGetRowSum()`, `MatGetRowMin()`, `MatGetRowMinAbs()`
5387: @*/
5388: PetscErrorCode MatGetRowMaxAbs(Mat mat, Vec v, PetscInt idx[])
5389: {
5390:   PetscFunctionBegin;
5394:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");

5396:   if (!mat->cmap->N) {
5397:     PetscCall(VecSet(v, 0.0));
5398:     if (idx) {
5399:       PetscInt i, m = mat->rmap->n;
5400:       for (i = 0; i < m; i++) idx[i] = -1;
5401:     }
5402:   } else {
5403:     MatCheckPreallocated(mat, 1);
5404:     if (idx) PetscCall(PetscArrayzero(idx, mat->rmap->n));
5405:     PetscUseTypeMethod(mat, getrowmaxabs, v, idx);
5406:   }
5407:   PetscCall(PetscObjectStateIncrease((PetscObject)v));
5408:   PetscFunctionReturn(PETSC_SUCCESS);
5409: }

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

5414:   Logically Collective

5416:   Input Parameter:
5417: . mat - the matrix

5419:   Output Parameter:
5420: . v - the vector for storing the sum

5422:   Level: intermediate

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

5426: .seealso: [](ch_matrices), `Mat`, `MatGetDiagonal()`, `MatCreateSubMatrices()`, `MatCreateSubMatrix()`, `MatGetRowMax()`, `MatGetRowMin()`, `MatGetRowMinAbs()`
5427: @*/
5428: PetscErrorCode MatGetRowSumAbs(Mat mat, Vec v)
5429: {
5430:   PetscFunctionBegin;
5434:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");

5436:   if (!mat->cmap->N) PetscCall(VecSet(v, 0.0));
5437:   else {
5438:     MatCheckPreallocated(mat, 1);
5439:     PetscUseTypeMethod(mat, getrowsumabs, v);
5440:   }
5441:   PetscCall(PetscObjectStateIncrease((PetscObject)v));
5442:   PetscFunctionReturn(PETSC_SUCCESS);
5443: }

5445: /*@
5446:   MatGetRowSum - Gets the sum of each row of the matrix

5448:   Logically or Neighborhood Collective

5450:   Input Parameter:
5451: . mat - the matrix

5453:   Output Parameter:
5454: . v - the vector for storing the sum of rows

5456:   Level: intermediate

5458:   Note:
5459:   This code is slow since it is not currently specialized for different formats

5461: .seealso: [](ch_matrices), `Mat`, `MatGetDiagonal()`, `MatCreateSubMatrices()`, `MatCreateSubMatrix()`, `MatGetRowMax()`, `MatGetRowMin()`, `MatGetRowMaxAbs()`, `MatGetRowMinAbs()`, `MatGetRowSumAbs()`
5462: @*/
5463: PetscErrorCode MatGetRowSum(Mat mat, Vec v)
5464: {
5465:   Vec ones;

5467:   PetscFunctionBegin;
5471:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
5472:   MatCheckPreallocated(mat, 1);
5473:   PetscCall(MatCreateVecs(mat, &ones, NULL));
5474:   PetscCall(VecSet(ones, 1.));
5475:   PetscCall(MatMult(mat, ones, v));
5476:   PetscCall(VecDestroy(&ones));
5477:   PetscFunctionReturn(PETSC_SUCCESS);
5478: }

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

5484:   Collective

5486:   Input Parameter:
5487: . mat - the matrix to provide the transpose

5489:   Output Parameter:
5490: . 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

5492:   Level: advanced

5494:   Note:
5495:   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
5496:   routine allows bypassing that call.

5498: .seealso: [](ch_matrices), `Mat`, `MatTransposeSymbolic()`, `MatTranspose()`, `MatMultTranspose()`, `MatMultTransposeAdd()`, `MatIsTranspose()`, `MatReuse`, `MAT_INITIAL_MATRIX`, `MAT_REUSE_MATRIX`, `MAT_INPLACE_MATRIX`
5499: @*/
5500: PetscErrorCode MatTransposeSetPrecursor(Mat mat, Mat B)
5501: {
5502:   MatParentState *rb = NULL;

5504:   PetscFunctionBegin;
5505:   PetscCall(PetscNew(&rb));
5506:   rb->id    = ((PetscObject)mat)->id;
5507:   rb->state = 0;
5508:   PetscCall(MatGetNonzeroState(mat, &rb->nonzerostate));
5509:   PetscCall(PetscObjectContainerCompose((PetscObject)B, "MatTransposeParent", rb, PetscCtxDestroyDefault));
5510:   PetscFunctionReturn(PETSC_SUCCESS);
5511: }

5513: static PetscErrorCode MatTranspose_Private(Mat mat, MatReuse reuse, Mat *B, PetscBool conjugate)
5514: {
5515:   PetscContainer  rB                        = NULL;
5516:   MatParentState *rb                        = NULL;
5517:   PetscErrorCode (*f)(Mat, MatReuse, Mat *) = NULL;

5519:   PetscFunctionBegin;
5522:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
5523:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
5524:   PetscCheck(reuse != MAT_INPLACE_MATRIX || mat == *B, PetscObjectComm((PetscObject)mat), PETSC_ERR_SUP, "MAT_INPLACE_MATRIX requires last matrix to match first");
5525:   PetscCheck(reuse != MAT_REUSE_MATRIX || mat != *B, PetscObjectComm((PetscObject)mat), PETSC_ERR_SUP, "Perhaps you mean MAT_INPLACE_MATRIX");
5526:   MatCheckPreallocated(mat, 1);
5527:   if (reuse == MAT_REUSE_MATRIX) {
5528:     PetscCall(PetscObjectQuery((PetscObject)*B, "MatTransposeParent", (PetscObject *)&rB));
5529:     PetscCheck(rB, PetscObjectComm((PetscObject)*B), PETSC_ERR_ARG_WRONG, "Reuse matrix used was not generated from call to MatTranspose(). Suggest MatTransposeSetPrecursor().");
5530:     PetscCall(PetscContainerGetPointer(rB, &rb));
5531:     PetscCheck(rb->id == ((PetscObject)mat)->id, PetscObjectComm((PetscObject)*B), PETSC_ERR_ARG_WRONG, "Reuse matrix used was not generated from input matrix");
5532:     if (rb->state == ((PetscObject)mat)->state) PetscFunctionReturn(PETSC_SUCCESS);
5533:   }

5535:   if (conjugate) {
5536:     f = mat->ops->hermitiantranspose;
5537:     if (f) PetscCall((*f)(mat, reuse, B));
5538:   }
5539:   if (!f && !(reuse == MAT_INPLACE_MATRIX && mat->hermitian == PETSC_BOOL3_TRUE && conjugate)) {
5540:     PetscCall(PetscLogEventBegin(MAT_Transpose, mat, 0, 0, 0));
5541:     if (reuse != MAT_INPLACE_MATRIX || mat->symmetric != PETSC_BOOL3_TRUE) {
5542:       PetscUseTypeMethod(mat, transpose, reuse, B);
5543:       PetscCall(PetscObjectStateIncrease((PetscObject)*B));
5544:     }
5545:     PetscCall(PetscLogEventEnd(MAT_Transpose, mat, 0, 0, 0));
5546:     if (conjugate) PetscCall(MatConjugate(*B));
5547:   }

5549:   if (reuse == MAT_INITIAL_MATRIX) PetscCall(MatTransposeSetPrecursor(mat, *B));
5550:   if (reuse != MAT_INPLACE_MATRIX) {
5551:     PetscCall(PetscObjectQuery((PetscObject)*B, "MatTransposeParent", (PetscObject *)&rB));
5552:     PetscCall(PetscContainerGetPointer(rB, &rb));
5553:     rb->state        = ((PetscObject)mat)->state;
5554:     rb->nonzerostate = mat->nonzerostate;
5555:   }
5556:   PetscFunctionReturn(PETSC_SUCCESS);
5557: }

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

5562:   Collective

5564:   Input Parameters:
5565: + mat   - the matrix to transpose
5566: - reuse - either `MAT_INITIAL_MATRIX`, `MAT_REUSE_MATRIX`, or `MAT_INPLACE_MATRIX`

5568:   Output Parameter:
5569: . B - the transpose of the matrix

5571:   Level: intermediate

5573:   Notes:
5574:   If you use `MAT_INPLACE_MATRIX` then you must pass in `&mat` for `B`

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

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

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

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

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

5588: .seealso: [](ch_matrices), `Mat`, `MatTransposeSetPrecursor()`, `MatMultTranspose()`, `MatMultTransposeAdd()`, `MatIsTranspose()`, `MatReuse`, `MAT_INITIAL_MATRIX`, `MAT_REUSE_MATRIX`, `MAT_INPLACE_MATRIX`,
5589:           `MatTransposeSymbolic()`, `MatCreateTranspose()`
5590: @*/
5591: PetscErrorCode MatTranspose(Mat mat, MatReuse reuse, Mat *B)
5592: {
5593:   PetscFunctionBegin;
5594:   PetscCall(MatTranspose_Private(mat, reuse, B, PETSC_FALSE));
5595:   PetscFunctionReturn(PETSC_SUCCESS);
5596: }

5598: /*@
5599:   MatTransposeSymbolic - Computes the symbolic part of the transpose of a matrix.

5601:   Collective

5603:   Input Parameter:
5604: . A - the matrix to transpose

5606:   Output Parameter:
5607: . 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
5608:       numerical portion.

5610:   Level: intermediate

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

5615: .seealso: [](ch_matrices), `Mat`, `MatTransposeSetPrecursor()`, `MatTranspose()`, `MatMultTranspose()`, `MatMultTransposeAdd()`, `MatIsTranspose()`, `MatReuse`, `MAT_INITIAL_MATRIX`, `MAT_REUSE_MATRIX`, `MAT_INPLACE_MATRIX`
5616: @*/
5617: PetscErrorCode MatTransposeSymbolic(Mat A, Mat *B)
5618: {
5619:   PetscFunctionBegin;
5622:   PetscCheck(A->assembled, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
5623:   PetscCheck(!A->factortype, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
5624:   PetscCall(PetscLogEventBegin(MAT_Transpose, A, 0, 0, 0));
5625:   PetscUseTypeMethod(A, transposesymbolic, B);
5626:   PetscCall(PetscLogEventEnd(MAT_Transpose, A, 0, 0, 0));

5628:   PetscCall(MatTransposeSetPrecursor(A, *B));
5629:   PetscFunctionReturn(PETSC_SUCCESS);
5630: }

5632: PetscErrorCode MatTransposeCheckNonzeroState_Private(Mat A, Mat B)
5633: {
5634:   PetscContainer  rB;
5635:   MatParentState *rb;

5637:   PetscFunctionBegin;
5640:   PetscCheck(A->assembled, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
5641:   PetscCheck(!A->factortype, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
5642:   PetscCall(PetscObjectQuery((PetscObject)B, "MatTransposeParent", (PetscObject *)&rB));
5643:   PetscCheck(rB, PetscObjectComm((PetscObject)B), PETSC_ERR_ARG_WRONG, "Reuse matrix used was not generated from call to MatTranspose()");
5644:   PetscCall(PetscContainerGetPointer(rB, &rb));
5645:   PetscCheck(rb->id == ((PetscObject)A)->id, PetscObjectComm((PetscObject)B), PETSC_ERR_ARG_WRONG, "Reuse matrix used was not generated from input matrix");
5646:   PetscCheck(rb->nonzerostate == A->nonzerostate, PetscObjectComm((PetscObject)B), PETSC_ERR_ARG_WRONGSTATE, "Reuse matrix has changed nonzero structure");
5647:   PetscFunctionReturn(PETSC_SUCCESS);
5648: }

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

5654:   Collective

5656:   Input Parameters:
5657: + A   - the matrix to test
5658: . B   - the matrix to test against, this can equal the first parameter
5659: - tol - tolerance, differences between entries smaller than this are counted as zero

5661:   Output Parameter:
5662: . flg - the result

5664:   Level: intermediate

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

5670: .seealso: [](ch_matrices), `Mat`, `MatTranspose()`, `MatIsSymmetric()`, `MatIsHermitian()`
5671: @*/
5672: PetscErrorCode MatIsTranspose(Mat A, Mat B, PetscReal tol, PetscBool *flg)
5673: {
5674:   PetscErrorCode (*f)(Mat, Mat, PetscReal, PetscBool *), (*g)(Mat, Mat, PetscReal, PetscBool *);

5676:   PetscFunctionBegin;
5679:   PetscAssertPointer(flg, 4);
5680:   PetscCall(PetscObjectQueryFunction((PetscObject)A, "MatIsTranspose_C", &f));
5681:   PetscCall(PetscObjectQueryFunction((PetscObject)B, "MatIsTranspose_C", &g));
5682:   *flg = PETSC_FALSE;
5683:   if (f && g) {
5684:     PetscCheck(f == g, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_NOTSAMETYPE, "Matrices do not have the same comparator for symmetry test");
5685:     PetscCall((*f)(A, B, tol, flg));
5686:   } else {
5687:     MatType mattype;

5689:     PetscCall(MatGetType(f ? B : A, &mattype));
5690:     SETERRQ(PETSC_COMM_SELF, PETSC_ERR_SUP, "Matrix of type %s does not support checking for transpose", mattype);
5691:   }
5692:   PetscFunctionReturn(PETSC_SUCCESS);
5693: }

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

5698:   Collective

5700:   Input Parameters:
5701: + mat   - the matrix to transpose and complex conjugate
5702: - reuse - either `MAT_INITIAL_MATRIX`, `MAT_REUSE_MATRIX`, or `MAT_INPLACE_MATRIX`

5704:   Output Parameter:
5705: . B - the Hermitian transpose

5707:   Level: intermediate

5709: .seealso: [](ch_matrices), `Mat`, `MatTranspose()`, `MatMultTranspose()`, `MatMultTransposeAdd()`, `MatIsTranspose()`, `MatReuse`
5710: @*/
5711: PetscErrorCode MatHermitianTranspose(Mat mat, MatReuse reuse, Mat *B)
5712: {
5713:   PetscFunctionBegin;
5714:   PetscCall(MatTranspose_Private(mat, reuse, B, PetscDefined(USE_COMPLEX) ? PETSC_TRUE : PETSC_FALSE));
5715:   PetscFunctionReturn(PETSC_SUCCESS);
5716: }

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

5721:   Collective

5723:   Input Parameters:
5724: + A   - the matrix to test
5725: . B   - the matrix to test against, this can equal the first parameter
5726: - tol - tolerance, differences between entries smaller than this are counted as zero

5728:   Output Parameter:
5729: . flg - the result

5731:   Level: intermediate

5733:   Notes:
5734:   Only available for `MATAIJ` matrices.

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

5740: .seealso: [](ch_matrices), `Mat`, `MatTranspose()`, `MatIsSymmetric()`, `MatIsHermitian()`, `MatIsTranspose()`
5741: @*/
5742: PetscErrorCode MatIsHermitianTranspose(Mat A, Mat B, PetscReal tol, PetscBool *flg)
5743: {
5744:   PetscErrorCode (*f)(Mat, Mat, PetscReal, PetscBool *), (*g)(Mat, Mat, PetscReal, PetscBool *);

5746:   PetscFunctionBegin;
5749:   PetscAssertPointer(flg, 4);
5750:   PetscCall(PetscObjectQueryFunction((PetscObject)A, "MatIsHermitianTranspose_C", &f));
5751:   PetscCall(PetscObjectQueryFunction((PetscObject)B, "MatIsHermitianTranspose_C", &g));
5752:   if (f && g) {
5753:     PetscCheck(f == g, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_NOTSAMETYPE, "Matrices do not have the same comparator for Hermitian test");
5754:     PetscCall((*f)(A, B, tol, flg));
5755:   } else {
5756:     MatType mattype;

5758:     PetscCall(MatGetType(f ? B : A, &mattype));
5759:     SETERRQ(PETSC_COMM_SELF, PETSC_ERR_SUP, "Matrix of type %s does not support checking for Hermitian transpose", mattype);
5760:   }
5761:   PetscFunctionReturn(PETSC_SUCCESS);
5762: }

5764: /*@
5765:   MatPermute - Creates a new matrix with rows and columns permuted from the
5766:   original.

5768:   Collective

5770:   Input Parameters:
5771: + mat - the matrix to permute
5772: . row - row permutation, each processor supplies only the permutation for its rows
5773: - col - column permutation, each processor supplies only the permutation for its columns

5775:   Output Parameter:
5776: . B - the permuted matrix

5778:   Level: advanced

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

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

5789: .seealso: [](ch_matrices), `Mat`, `MatGetOrdering()`, `ISAllGather()`, `MatCreateSubMatrix()`
5790: @*/
5791: PetscErrorCode MatPermute(Mat mat, IS row, IS col, Mat *B)
5792: {
5793:   PetscFunctionBegin;
5798:   PetscAssertPointer(B, 4);
5799:   PetscCheckSameComm(mat, 1, row, 2);
5800:   if (row != col) PetscCheckSameComm(row, 2, col, 3);
5801:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
5802:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
5803:   PetscCheck(mat->ops->permute || mat->ops->createsubmatrix, PETSC_COMM_SELF, PETSC_ERR_SUP, "MatPermute not available for Mat type %s", ((PetscObject)mat)->type_name);
5804:   MatCheckPreallocated(mat, 1);

5806:   if (mat->ops->permute) {
5807:     PetscUseTypeMethod(mat, permute, row, col, B);
5808:     PetscCall(PetscObjectStateIncrease((PetscObject)*B));
5809:   } else {
5810:     PetscCall(MatCreateSubMatrix(mat, row, col, MAT_INITIAL_MATRIX, B));
5811:   }
5812:   PetscFunctionReturn(PETSC_SUCCESS);
5813: }

5815: /*@
5816:   MatEqual - Compares two matrices.

5818:   Collective

5820:   Input Parameters:
5821: + A - the first matrix
5822: - B - the second matrix

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

5827:   Level: intermediate

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

5833: .seealso: [](ch_matrices), `Mat`, `MatMultEqual()`
5834: @*/
5835: PetscErrorCode MatEqual(Mat A, Mat B, PetscBool *flg)
5836: {
5837:   PetscFunctionBegin;
5842:   PetscAssertPointer(flg, 3);
5843:   PetscCheckSameComm(A, 1, B, 2);
5844:   MatCheckPreallocated(A, 1);
5845:   MatCheckPreallocated(B, 2);
5846:   PetscCheck(A->assembled, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
5847:   PetscCheck(B->assembled, PetscObjectComm((PetscObject)B), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
5848:   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,
5849:              B->cmap->N);
5850:   if (A->ops->equal && A->ops->equal == B->ops->equal) PetscUseTypeMethod(A, equal, B, flg);
5851:   else PetscCall(MatMultEqual(A, B, 10, flg));
5852:   PetscFunctionReturn(PETSC_SUCCESS);
5853: }

5855: /*@
5856:   MatDiagonalScale - Scales a matrix on the left and right by diagonal
5857:   matrices that are stored as vectors.  Either of the two scaling
5858:   matrices can be `NULL`.

5860:   Collective

5862:   Input Parameters:
5863: + mat - the matrix to be scaled
5864: . l   - the left scaling vector (or `NULL`)
5865: - r   - the right scaling vector (or `NULL`)

5867:   Level: intermediate

5869:   Note:
5870:   `MatDiagonalScale()` computes $A = LAR$, where
5871:   L = a diagonal matrix (stored as a vector), R = a diagonal matrix (stored as a vector)
5872:   The L scales the rows of the matrix, the R scales the columns of the matrix.

5874: .seealso: [](ch_matrices), `Mat`, `MatScale()`, `MatShift()`, `MatDiagonalSet()`
5875: @*/
5876: PetscErrorCode MatDiagonalScale(Mat mat, Vec l, Vec r)
5877: {
5878:   PetscBool flg = PETSC_FALSE;

5880:   PetscFunctionBegin;
5883:   if (l) {
5885:     PetscCheckSameComm(mat, 1, l, 2);
5886:   }
5887:   if (r) {
5889:     PetscCheckSameComm(mat, 1, r, 3);
5890:   }
5891:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
5892:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
5893:   MatCheckPreallocated(mat, 1);
5894:   if (!l && !r) PetscFunctionReturn(PETSC_SUCCESS);

5896:   PetscCall(PetscLogEventBegin(MAT_Scale, mat, 0, 0, 0));
5897:   PetscUseTypeMethod(mat, diagonalscale, l, r);
5898:   PetscCall(PetscLogEventEnd(MAT_Scale, mat, 0, 0, 0));
5899:   PetscCall(PetscObjectStateIncrease((PetscObject)mat));
5900:   if (l != r && (PetscBool3ToBool(mat->symmetric) || PetscBool3ToBool(mat->hermitian))) {
5901:     if (!PetscDefined(USE_COMPLEX) || PetscBool3ToBool(mat->symmetric)) {
5902:       if (l && r) PetscCall(VecEqual(l, r, &flg));
5903:       if (!flg) {
5904:         PetscCall(PetscObjectTypeCompareAny((PetscObject)mat, &flg, MATSEQSBAIJ, MATMPISBAIJ, ""));
5905:         PetscCheck(!flg, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_OUTOFRANGE, "For symmetric format, left and right scaling vectors must be the same");
5906:         mat->symmetric = mat->spd = PETSC_BOOL3_FALSE;
5907:         if (!PetscDefined(USE_COMPLEX)) mat->hermitian = PETSC_BOOL3_FALSE;
5908:         else mat->hermitian = PETSC_BOOL3_UNKNOWN;
5909:       }
5910:     }
5911:     if (PetscDefined(USE_COMPLEX) && PetscBool3ToBool(mat->hermitian)) {
5912:       flg = PETSC_FALSE;
5913:       if (l && r) {
5914:         Vec conjugate;

5916:         PetscCall(VecDuplicate(l, &conjugate));
5917:         PetscCall(VecCopy(l, conjugate));
5918:         PetscCall(VecConjugate(conjugate));
5919:         PetscCall(VecEqual(conjugate, r, &flg));
5920:         PetscCall(VecDestroy(&conjugate));
5921:       }
5922:       if (!flg) {
5923:         PetscCall(PetscObjectTypeCompareAny((PetscObject)mat, &flg, MATSEQSBAIJ, MATMPISBAIJ, ""));
5924:         PetscCheck(!flg, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_OUTOFRANGE, "For symmetric format and Hermitian matrix, left and right scaling vectors must be conjugate one of the other");
5925:         mat->hermitian = PETSC_BOOL3_FALSE;
5926:         mat->symmetric = mat->spd = PETSC_BOOL3_UNKNOWN;
5927:       }
5928:     }
5929:   }
5930:   PetscFunctionReturn(PETSC_SUCCESS);
5931: }

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

5936:   Logically Collective

5938:   Input Parameters:
5939: + mat - the matrix to be scaled
5940: - a   - the scaling value

5942:   Level: intermediate

5944: .seealso: [](ch_matrices), `Mat`, `MatDiagonalScale()`
5945: @*/
5946: PetscErrorCode MatScale(Mat mat, PetscScalar a)
5947: {
5948:   PetscFunctionBegin;
5951:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
5952:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
5954:   MatCheckPreallocated(mat, 1);

5956:   PetscCall(PetscLogEventBegin(MAT_Scale, mat, 0, 0, 0));
5957:   if (a != (PetscScalar)1.0) {
5958:     PetscUseTypeMethod(mat, scale, a);
5959:     PetscCall(PetscObjectStateIncrease((PetscObject)mat));
5960:   }
5961:   PetscCall(PetscLogEventEnd(MAT_Scale, mat, 0, 0, 0));
5962:   PetscFunctionReturn(PETSC_SUCCESS);
5963: }

5965: /*@
5966:   MatNorm - Calculates various norms of a matrix.

5968:   Collective

5970:   Input Parameters:
5971: + mat  - the matrix
5972: - type - the type of norm, `NORM_1`, `NORM_FROBENIUS`, `NORM_INFINITY`

5974:   Output Parameter:
5975: . nrm - the resulting norm

5977:   Level: intermediate

5979: .seealso: [](ch_matrices), `Mat`, `MatNormApproximate()`
5980: @*/
5981: PetscErrorCode MatNorm(Mat mat, NormType type, PetscReal *nrm)
5982: {
5983:   PetscFunctionBegin;
5987:   PetscAssertPointer(nrm, 3);

5989:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
5990:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
5991:   MatCheckPreallocated(mat, 1);

5993:   PetscUseTypeMethod(mat, norm, type, nrm);
5994:   PetscFunctionReturn(PETSC_SUCCESS);
5995: }

5997: static PetscErrorCode VecSetFinalNormApp_Private(Vec x)
5998: {
5999:   PetscScalar *ax, nm1;
6000:   PetscInt     st, en, n;

6002:   PetscFunctionBegin;
6003:   PetscCall(VecGetSize(x, &n));
6004:   if (n < 2) PetscFunctionReturn(PETSC_SUCCESS);
6005:   nm1 = n - 1;
6006:   PetscCall(VecGetOwnershipRange(x, &st, &en));
6007:   PetscCall(VecGetArrayWrite(x, &ax));
6008:   for (PetscInt i = st; i < en; i++) {
6009:     const PetscInt    ii = i - st;
6010:     const PetscScalar s  = i % 2 ? -1.0 : 1.0;

6012:     ax[ii] = s * (1.0 + i / nm1);
6013:   }
6014:   PetscCall(VecRestoreArrayWrite(x, &ax));
6015:   PetscFunctionReturn(PETSC_SUCCESS);
6016: }

6018: static PetscErrorCode MatNormApproximateForwardOnly_Private(Mat A, NormType normtype, PetscInt maxit, PetscBool boundtocpu, PetscReal *n)
6019: {
6020:   Vec         x, y;
6021:   PetscReal   normx, normy;
6022:   PetscInt    i, N;
6023:   PetscRandom rnd;

6025:   PetscFunctionBegin;
6026:   if (maxit < 0) maxit = 1;
6027:   PetscCall(PetscRandomCreate(PetscObjectComm((PetscObject)A), &rnd));
6028:   PetscCall(PetscRandomSetFromOptions(rnd));
6029:   PetscCall(MatCreateVecs(A, &x, &y));
6030:   PetscCall(VecBindToCPU(x, boundtocpu));
6031:   PetscCall(VecBindToCPU(y, boundtocpu));
6032:   PetscCall(VecGetSize(x, &N));
6033:   *n = 0.0;
6034:   for (i = 0; i < maxit; i++) {
6035:     PetscCall(VecSetRandom(x, rnd));
6036:     switch (normtype) {
6037:     case NORM_1:
6038:       PetscCall(VecNorm(x, NORM_1, &normx));
6039:       if (normx > 0.0) PetscCall(VecScale(x, 1.0 / normx));
6040:       break;
6041:     case NORM_INFINITY:
6042:       PetscCall(VecShift(x, -0.5));
6043:       PetscCall(VecPointwiseSign(x, x, VEC_SIGN_ZERO_TO_SIGNED_UNIT));
6044:       break;
6045:     case NORM_2:
6046:       PetscCall(VecNormalize(x, NULL));
6047:       break;
6048:     default:
6049:       PetscUnreachable();
6050:     }
6051:     PetscCall(MatMult(A, x, y));
6052:     PetscCall(VecNorm(y, normtype, &normy));
6053:     *n = PetscMax(*n, normy);
6054:     PetscCall(PetscInfo(A, "%s norm forward-only sample %" PetscInt_FMT " -> %g\n", NormTypes[normtype], i, (double)normy));
6055:   }
6056:   PetscCall(VecDestroy(&x));
6057:   PetscCall(VecDestroy(&y));
6058:   PetscCall(PetscRandomDestroy(&rnd));
6059:   PetscFunctionReturn(PETSC_SUCCESS);
6060: }

6062: /*@
6063:   MatNormApproximate - Approximate the norm of a matrix.

6065:   Collective

6067:   Input Parameters:
6068: + A        - the matrix
6069: . normtype - the `NormType`
6070: - maxit    - maximum number of iterations to use

6072:   Output Parameter:
6073: . n - the norm estimate

6075:   Level: intermediate

6077:   Notes:
6078:   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`.

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

6082: .seealso: [](ch_matrices), `Mat`, `MatNorm()`
6083: @*/
6084: PetscErrorCode MatNormApproximate(Mat A, NormType normtype, PetscInt maxit, PetscReal *n)
6085: {
6086:   Vec         x, y, w, z;
6087:   PetscReal   normz, adot;
6088:   PetscScalar dot;
6089:   PetscInt    i, j, N, jold = -1;
6090:   PetscBool   boundtocpu = PETSC_TRUE, setherm, isherm, hasop;

6092:   PetscFunctionBegin;
6097:   PetscAssertPointer(n, 4);
6098: #if PetscDefined(HAVE_DEVICE)
6099:   boundtocpu = A->boundtocpu;
6100: #endif
6101:   PetscCall(MatHasOperation(A, MATOP_MULT_HERMITIAN_TRANSPOSE, &hasop));
6102:   switch (normtype) {
6103:   case NORM_INFINITY:
6104:   case NORM_1:
6105:     if (!hasop) {
6106:       PetscCall(MatNormApproximateForwardOnly_Private(A, normtype, maxit, boundtocpu, n));
6107:       i = maxit;
6108:       break;
6109:     } else {
6110:       PetscCall(MatIsHermitianKnown(A, &setherm, &isherm));
6111:       if ((setherm && isherm) || normtype == NORM_1) PetscCall(PetscObjectReference((PetscObject)A));
6112:       else {
6113:         Mat B;

6115:         PetscCall(MatCreateHermitianTranspose(A, &B));
6116:         A = B;
6117:       }
6118:     }
6119:     if (maxit < 0) maxit = 10; /* pure guess */
6120:     PetscCall(MatCreateVecs(A, &x, &y));
6121:     PetscCall(MatCreateVecs(A, &z, &w));
6122:     PetscCall(VecBindToCPU(x, boundtocpu));
6123:     PetscCall(VecBindToCPU(y, boundtocpu));
6124:     PetscCall(VecBindToCPU(z, boundtocpu));
6125:     PetscCall(VecBindToCPU(w, boundtocpu));
6126:     PetscCall(VecGetSize(x, &N));
6127:     PetscCall(VecSet(x, 1. / N));
6128:     *n = 0.0;
6129:     for (i = 0; i < maxit; i++) {
6130:       PetscCall(MatMult(A, x, y));
6131:       PetscCall(VecNorm(y, NORM_1, n));
6132:       if (PetscDefined(USE_COMPLEX)) {
6133:         PetscCall(VecCopy(y, w));
6134:         PetscCall(VecAbs(w));
6135:         PetscCall(VecPointwiseDivide(w, y, w));
6136:       } else PetscCall(VecPointwiseSign(w, y, VEC_SIGN_ZERO_TO_SIGNED_UNIT));
6137:       PetscCall(MatMultHermitianTranspose(A, w, z));
6138:       PetscCall(VecRealPart(z));
6139:       PetscCall(VecNorm(z, NORM_INFINITY, &normz));
6140:       PetscCall(VecDot(x, z, &dot));
6141:       adot = PetscAbsScalar(dot);
6142:       PetscCall(PetscInfo(A, "%s norm it %" PetscInt_FMT " -> %g (%g %g)\n", NormTypes[normtype], i, (double)*n, (double)normz, (double)adot));
6143:       if (normz <= adot && i > 0) {
6144:         PetscCall(PetscInfo(A, "%s norm    converged\n", NormTypes[normtype]));
6145:         break;
6146:       }
6147:       PetscCall(VecAbs(z));
6148:       PetscCall(VecMax(z, &j, &normz));
6149:       if (j == jold) {
6150:         PetscCall(PetscInfo(A, "%s norm it %" PetscInt_FMT " -> breakdown (j==jold)\n", NormTypes[normtype], i));
6151:         break;
6152:       }
6153:       jold = j;
6154:       if (i < maxit - 1) PetscCall(VecSetStdBasis(x, j));
6155:     }
6156:     /* last check */
6157:     if (N > 1) {
6158:       PetscReal ny;

6160:       PetscCall(VecSetFinalNormApp_Private(x));
6161:       PetscCall(MatMult(A, x, y));
6162:       PetscCall(VecNorm(y, NORM_1, &ny));
6163:       ny = 2 * ny / (3 * N);
6164:       PetscCall(PetscInfo(A, "%s norm final check: current %g test %g\n", NormTypes[normtype], (double)*n, (double)ny));
6165:       *n = PetscMax(*n, ny);
6166:     }
6167:     PetscCall(MatDestroy(&A));
6168:     PetscCall(VecDestroy(&x));
6169:     PetscCall(VecDestroy(&w));
6170:     PetscCall(VecDestroy(&y));
6171:     PetscCall(VecDestroy(&z));
6172:     break;
6173:   case NORM_2:
6174:     if (!hasop) {
6175:       PetscCall(MatNormApproximateForwardOnly_Private(A, normtype, maxit, boundtocpu, n));
6176:       i = maxit;
6177:       break;
6178:     }
6179:     if (maxit < 0) maxit = 20; /* pure guess */
6180:     PetscCall(MatCreateVecs(A, &x, &y));
6181:     PetscCall(MatCreateVecs(A, &z, NULL));
6182:     PetscCall(VecBindToCPU(x, boundtocpu));
6183:     PetscCall(VecBindToCPU(y, boundtocpu));
6184:     PetscCall(VecBindToCPU(z, boundtocpu));
6185:     PetscCall(VecSetRandom(x, NULL));
6186:     PetscCall(VecNormalize(x, NULL));
6187:     *n = 0.0;
6188:     for (i = 0; i < maxit; i++) {
6189:       PetscCall(MatMult(A, x, y));
6190:       PetscCall(VecNormalize(y, n));
6191:       PetscCall(MatMultHermitianTranspose(A, y, z));
6192:       PetscCall(VecNorm(z, NORM_2, &normz));
6193:       PetscCall(VecDot(x, z, &dot));
6194:       adot = PetscAbsScalar(dot);
6195:       PetscCall(PetscInfo(A, "%s norm it %" PetscInt_FMT " -> %g (%g %g)\n", NormTypes[normtype], i, (double)*n, (double)normz, (double)adot));
6196:       if (normz <= adot) {
6197:         PetscCall(PetscInfo(A, "%s norm    converged\n", NormTypes[normtype]));
6198:         break;
6199:       }
6200:       if (i < maxit - 1) {
6201:         Vec t;

6203:         PetscCall(VecNormalize(z, NULL));
6204:         t = x;
6205:         x = z;
6206:         z = t;
6207:       }
6208:     }
6209:     PetscCall(VecDestroy(&x));
6210:     PetscCall(VecDestroy(&y));
6211:     PetscCall(VecDestroy(&z));
6212:     break;
6213:   default:
6214:     SETERRQ(PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "%s norm not supported", NormTypes[normtype]);
6215:   }
6216:   PetscCall(PetscInfo(A, "%s norm %g computed in %" PetscInt_FMT " iterations\n", NormTypes[normtype], (double)*n, i));
6217:   PetscFunctionReturn(PETSC_SUCCESS);
6218: }

6220: /*
6221:      This variable is used to prevent counting of MatAssemblyBegin() that
6222:    are called from within a MatAssemblyEnd().
6223: */
6224: static PetscInt MatAssemblyEnd_InUse = 0;
6225: /*@
6226:   MatAssemblyBegin - Begins assembling the matrix.  This routine should
6227:   be called after completing all calls to `MatSetValues()`.

6229:   Collective

6231:   Input Parameters:
6232: + mat  - the matrix
6233: - type - type of assembly, either `MAT_FLUSH_ASSEMBLY` or `MAT_FINAL_ASSEMBLY`

6235:   Level: beginner

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

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

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

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

6253: .seealso: [](ch_matrices), `Mat`, `MatAssemblyEnd()`, `MatSetValues()`, `MatAssembled()`
6254: @*/
6255: PetscErrorCode MatAssemblyBegin(Mat mat, MatAssemblyType type)
6256: {
6257:   PetscFunctionBegin;
6260:   MatCheckPreallocated(mat, 1);
6261:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix. Did you forget to call MatSetUnfactored()?");
6262:   if (mat->assembled) {
6263:     mat->was_assembled = PETSC_TRUE;
6264:     mat->assembled     = PETSC_FALSE;
6265:   }

6267:   if (!MatAssemblyEnd_InUse) {
6268:     PetscCall(PetscLogEventBegin(MAT_AssemblyBegin, mat, 0, 0, 0));
6269:     PetscTryTypeMethod(mat, assemblybegin, type);
6270:     PetscCall(PetscLogEventEnd(MAT_AssemblyBegin, mat, 0, 0, 0));
6271:   } else PetscTryTypeMethod(mat, assemblybegin, type);
6272:   PetscFunctionReturn(PETSC_SUCCESS);
6273: }

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

6279:   Not Collective

6281:   Input Parameter:
6282: . mat - the matrix

6284:   Output Parameter:
6285: . assembled - `PETSC_TRUE` or `PETSC_FALSE`

6287:   Level: advanced

6289: .seealso: [](ch_matrices), `Mat`, `MatAssemblyEnd()`, `MatSetValues()`, `MatAssemblyBegin()`
6290: @*/
6291: PetscErrorCode MatAssembled(Mat mat, PetscBool *assembled)
6292: {
6293:   PetscFunctionBegin;
6295:   PetscAssertPointer(assembled, 2);
6296:   *assembled = mat->assembled;
6297:   PetscFunctionReturn(PETSC_SUCCESS);
6298: }

6300: /*@
6301:   MatAssemblyEnd - Completes assembling the matrix.  This routine should
6302:   be called after `MatAssemblyBegin()`.

6304:   Collective

6306:   Input Parameters:
6307: + mat  - the matrix
6308: - type - type of assembly, either `MAT_FLUSH_ASSEMBLY` or `MAT_FINAL_ASSEMBLY`

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

6313:   Level: beginner

6315: .seealso: [](ch_matrices), `Mat`, `MatAssemblyBegin()`, `MatSetValues()`, `PetscDrawOpenX()`, `PetscDrawCreate()`, `MatView()`, `MatAssembled()`, `PetscViewerSocketOpen()`,
6316:           `MatViewFromOptions()`, `PetscObjectViewFromOptions()`
6317: @*/
6318: PetscErrorCode MatAssemblyEnd(Mat mat, MatAssemblyType type)
6319: {
6320:   static PetscInt inassm = 0;
6321:   PetscBool       flg    = PETSC_FALSE;

6323:   PetscFunctionBegin;

6327:   inassm++;
6328:   MatAssemblyEnd_InUse++;
6329:   if (MatAssemblyEnd_InUse == 1) { /* Do the logging only the first time through */
6330:     PetscCall(PetscLogEventBegin(MAT_AssemblyEnd, mat, 0, 0, 0));
6331:     PetscTryTypeMethod(mat, assemblyend, type);
6332:     PetscCall(PetscLogEventEnd(MAT_AssemblyEnd, mat, 0, 0, 0));
6333:   } else PetscTryTypeMethod(mat, assemblyend, type);

6335:   /* Flush assembly is not a true assembly */
6336:   if (type != MAT_FLUSH_ASSEMBLY) {
6337:     if (mat->num_ass) {
6338:       if (!mat->symmetry_eternal) {
6339:         mat->symmetric = PETSC_BOOL3_UNKNOWN;
6340:         mat->hermitian = PETSC_BOOL3_UNKNOWN;
6341:       }
6342:       if (!mat->structural_symmetry_eternal && mat->ass_nonzerostate != mat->nonzerostate) mat->structurally_symmetric = PETSC_BOOL3_UNKNOWN;
6343:       if (!mat->spd_eternal) mat->spd = PETSC_BOOL3_UNKNOWN;
6344:     }
6345:     mat->num_ass++;
6346:     mat->assembled        = PETSC_TRUE;
6347:     mat->ass_nonzerostate = mat->nonzerostate;
6348:   }

6350:   mat->insertmode = NOT_SET_VALUES;
6351:   MatAssemblyEnd_InUse--;
6352:   PetscCall(PetscObjectStateIncrease((PetscObject)mat));
6353:   if (inassm == 1 && type != MAT_FLUSH_ASSEMBLY) {
6354:     PetscCall(MatViewFromOptions(mat, NULL, "-mat_view"));

6356:     if (mat->checksymmetryonassembly) {
6357:       PetscCall(MatIsSymmetric(mat, mat->checksymmetrytol, &flg));
6358:       if (flg) {
6359:         PetscCall(PetscPrintf(PetscObjectComm((PetscObject)mat), "Matrix is symmetric (tolerance %g)\n", (double)mat->checksymmetrytol));
6360:       } else {
6361:         PetscCall(PetscPrintf(PetscObjectComm((PetscObject)mat), "Matrix is not symmetric (tolerance %g)\n", (double)mat->checksymmetrytol));
6362:       }
6363:     }
6364:     if (mat->nullsp && mat->checknullspaceonassembly) PetscCall(MatNullSpaceTest(mat->nullsp, mat, NULL));
6365:   }
6366:   inassm--;
6367:   PetscFunctionReturn(PETSC_SUCCESS);
6368: }

6370: // PetscClangLinter pragma disable: -fdoc-section-header-unknown
6371: /*@
6372:   MatSetOption - Sets a parameter option for a matrix. Some options
6373:   may be specific to certain storage formats.  Some options
6374:   determine how values will be inserted (or added). Sorted,
6375:   row-oriented input will generally assemble the fastest. The default
6376:   is row-oriented.

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

6380:   Input Parameters:
6381: + mat - the matrix
6382: . op  - the option, one of those listed below (and possibly others),
6383: - flg - turn the option on (`PETSC_TRUE`) or off (`PETSC_FALSE`)

6385:   Options Describing Matrix Structure:
6386: + `MAT_SPD`                         - symmetric positive definite
6387: . `MAT_SYMMETRIC`                   - symmetric in terms of both structure and value
6388: . `MAT_HERMITIAN`                   - transpose is the complex conjugation
6389: . `MAT_STRUCTURALLY_SYMMETRIC`      - symmetric nonzero structure
6390: . `MAT_SYMMETRY_ETERNAL`            - indicates the symmetry (or Hermitian structure) or its absence will persist through any changes to the matrix
6391: . `MAT_STRUCTURAL_SYMMETRY_ETERNAL` - indicates the structural symmetry or its absence will persist through any changes to the matrix
6392: . `MAT_SPD_ETERNAL`                 - indicates the value of `MAT_SPD` (true or false) will persist through any changes to the matrix

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

6397:    Options For Use with `MatSetValues()` and `MatGetValues()`:
6398:    Insert a logically dense subblock, which can be
6399: . `MAT_ROW_ORIENTED`                - row-oriented (default)

6401:    These options reflect the data you pass in with `MatSetValues()` or receive with `MatGetValues()`; it has
6402:    nothing to do with how the data is stored internally in the matrix
6403:    data structure.

6405:    When (re)assembling a matrix, we can restrict the input for
6406:    efficiency/debugging purposes.  These options include
6407: . `MAT_NEW_NONZERO_LOCATIONS`       - additional insertions will be allowed if they generate a new nonzero (slow)
6408: . `MAT_FORCE_DIAGONAL_ENTRIES`      - forces diagonal entries to be allocated
6409: . `MAT_IGNORE_OFF_PROC_ENTRIES`     - drops off-processor entries
6410: . `MAT_NEW_NONZERO_LOCATION_ERR`    - generates an error for new matrix entry
6411: . `MAT_USE_HASH_TABLE`              - uses a hash table to speed up matrix assembly
6412: . `MAT_NO_OFF_PROC_ENTRIES`         - you know each process will only set values for its own rows, will generate an error if
6413:                                       any process sets values for another process. This avoids all reductions in the MatAssembly routines and thus improves
6414:                                       performance for very large process counts.
6415: - `MAT_SUBSET_OFF_PROC_ENTRIES`     - you know that the first assembly after setting this flag will set a superset
6416:                                       of the off-process entries required for all subsequent assemblies. This avoids a rendezvous step in the MatAssembly
6417:                                       functions, instead sending only neighbor messages.

6419:   Level: intermediate

6421:   Notes:
6422:   Except for `MAT_UNUSED_NONZERO_LOCATION_ERR` and  `MAT_ROW_ORIENTED` all processes that share the matrix must pass the same value in flg!

6424:   Some options are relevant only for particular matrix types and
6425:   are thus ignored by others.  Other options are not supported by
6426:   certain matrix types and will generate an error message if set.

6428:   If using Fortran to compute a matrix, one may need to
6429:   use the column-oriented option (or convert to the row-oriented
6430:   format).

6432:   `MAT_NEW_NONZERO_LOCATIONS` set to `PETSC_FALSE` indicates that any add or insertion
6433:   that would generate a new entry in the nonzero structure is instead
6434:   ignored.  Thus, if memory has not already been allocated for this particular
6435:   data, then the insertion is ignored. For dense matrices, in which
6436:   the entire array is allocated, no entries are ever ignored.
6437:   Set after the first `MatAssemblyEnd()`. If this option is set, then the `MatAssemblyBegin()`/`MatAssemblyEnd()` processes has one less global reduction

6439:   `MAT_NEW_NONZERO_LOCATION_ERR` set to PETSC_TRUE indicates that any add or insertion
6440:   that would generate a new entry in the nonzero structure instead produces
6441:   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

6443:   `MAT_NEW_NONZERO_ALLOCATION_ERR` set to `PETSC_TRUE` indicates that any add or insertion
6444:   that would generate a new entry that has not been preallocated will
6445:   instead produce an error. (Currently supported for `MATAIJ` and `MATBAIJ` formats
6446:   only.) This is a useful flag when debugging matrix memory preallocation.
6447:   If this option is set, then the `MatAssemblyBegin()`/`MatAssemblyEnd()` processes has one less global reduction

6449:   `MAT_IGNORE_OFF_PROC_ENTRIES` set to `PETSC_TRUE` indicates entries destined for
6450:   other processors should be dropped, rather than stashed.
6451:   This is useful if you know that the "owning" processor is also
6452:   always generating the correct matrix entries, so that PETSc need
6453:   not transfer duplicate entries generated on another processor.

6455:   `MAT_USE_HASH_TABLE` indicates that a hash table be used to improve the
6456:   searches during matrix assembly. When this flag is set, the hash table
6457:   is created during the first matrix assembly. This hash table is
6458:   used the next time through, during `MatSetValues()`/`MatSetValuesBlocked()`
6459:   to improve the searching of indices. `MAT_NEW_NONZERO_LOCATIONS` flag
6460:   should be used with `MAT_USE_HASH_TABLE` flag. This option is currently
6461:   supported by `MATMPIBAIJ` format only.

6463:   `MAT_KEEP_NONZERO_PATTERN` indicates when `MatZeroRows()` is called the zeroed entries
6464:   are kept in the nonzero structure. This flag is not used for `MatZeroRowsColumns()`

6466:   `MAT_IGNORE_ZERO_ENTRIES` - for `MATAIJ` and `MATIS` matrices this will stop zero values from creating
6467:   a zero location in the matrix

6469:   `MAT_USE_INODES` - indicates using inode version of the code - works with `MATAIJ` matrix types

6471:   `MAT_NO_OFF_PROC_ZERO_ROWS` - you know each process will only zero its own rows. This avoids all reductions in the
6472:   zero row routines and thus improves performance for very large process counts.

6474:   `MAT_IGNORE_LOWER_TRIANGULAR` - For `MATSBAIJ` matrices will ignore any insertions you make in the lower triangular
6475:   part of the matrix (since they should match the upper triangular part).

6477:   `MAT_SORTED_FULL` - each process provides exactly its local rows; all column indices for a given row are passed in a
6478:   single call to `MatSetValues()`, preallocation is perfect, row-oriented, `INSERT_VALUES` is used. Common
6479:   with finite difference schemes with non-periodic boundary conditions.

6481:   Developer Note:
6482:   `MAT_SYMMETRY_ETERNAL`, `MAT_STRUCTURAL_SYMMETRY_ETERNAL`, and `MAT_SPD_ETERNAL` are used by `MatAssemblyEnd()` and in other
6483:   places where otherwise the value of `MAT_SYMMETRIC`, `MAT_STRUCTURALLY_SYMMETRIC` or `MAT_SPD` would need to be changed back
6484:   to `PETSC_BOOL3_UNKNOWN` because the matrix values had changed so the code cannot be certain that the related property had
6485:   not changed.

6487: .seealso: [](ch_matrices), `MatOption`, `Mat`, `MatGetOption()`
6488: @*/
6489: PetscErrorCode MatSetOption(Mat mat, MatOption op, PetscBool flg)
6490: {
6491:   PetscFunctionBegin;
6493:   if (op > 0) {
6496:   }

6498:   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);

6500:   switch (op) {
6501:   case MAT_FORCE_DIAGONAL_ENTRIES:
6502:     mat->force_diagonals = flg;
6503:     PetscFunctionReturn(PETSC_SUCCESS);
6504:   case MAT_NO_OFF_PROC_ENTRIES:
6505:     mat->nooffprocentries = flg;
6506:     PetscFunctionReturn(PETSC_SUCCESS);
6507:   case MAT_SUBSET_OFF_PROC_ENTRIES:
6508:     mat->assembly_subset = flg;
6509:     if (!mat->assembly_subset) { /* See the same logic in VecAssembly wrt VEC_SUBSET_OFF_PROC_ENTRIES */
6510: #if !PetscDefined(HAVE_MPIUNI)
6511:       PetscCall(MatStashScatterDestroy_BTS(&mat->stash));
6512: #endif
6513:       mat->stash.first_assembly_done = PETSC_FALSE;
6514:     }
6515:     PetscFunctionReturn(PETSC_SUCCESS);
6516:   case MAT_NO_OFF_PROC_ZERO_ROWS:
6517:     mat->nooffproczerorows = flg;
6518:     PetscFunctionReturn(PETSC_SUCCESS);
6519:   case MAT_SPD:
6520:     if (flg) {
6521:       mat->spd                    = PETSC_BOOL3_TRUE;
6522:       mat->symmetric              = PETSC_BOOL3_TRUE;
6523:       mat->structurally_symmetric = PETSC_BOOL3_TRUE;
6524: #if !PetscDefined(USE_COMPLEX)
6525:       mat->hermitian = PETSC_BOOL3_TRUE;
6526: #endif
6527:     } else {
6528:       mat->spd = PETSC_BOOL3_FALSE;
6529:     }
6530:     break;
6531:   case MAT_SYMMETRIC:
6532:     mat->symmetric = PetscBoolToBool3(flg);
6533:     if (flg) mat->structurally_symmetric = PETSC_BOOL3_TRUE;
6534: #if !PetscDefined(USE_COMPLEX)
6535:     mat->hermitian = PetscBoolToBool3(flg);
6536: #endif
6537:     break;
6538:   case MAT_HERMITIAN:
6539:     mat->hermitian = PetscBoolToBool3(flg);
6540:     if (flg) mat->structurally_symmetric = PETSC_BOOL3_TRUE;
6541: #if !PetscDefined(USE_COMPLEX)
6542:     mat->symmetric = PetscBoolToBool3(flg);
6543: #endif
6544:     break;
6545:   case MAT_STRUCTURALLY_SYMMETRIC:
6546:     mat->structurally_symmetric = PetscBoolToBool3(flg);
6547:     break;
6548:   case MAT_SYMMETRY_ETERNAL:
6549:     PetscCheck(mat->symmetric != PETSC_BOOL3_UNKNOWN, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Cannot set MAT_SYMMETRY_ETERNAL without first setting MAT_SYMMETRIC to true or false");
6550:     mat->symmetry_eternal = flg;
6551:     if (flg) mat->structural_symmetry_eternal = PETSC_TRUE;
6552:     break;
6553:   case MAT_STRUCTURAL_SYMMETRY_ETERNAL:
6554:     PetscCheck(mat->structurally_symmetric != PETSC_BOOL3_UNKNOWN, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Cannot set MAT_STRUCTURAL_SYMMETRY_ETERNAL without first setting MAT_STRUCTURALLY_SYMMETRIC to true or false");
6555:     mat->structural_symmetry_eternal = flg;
6556:     break;
6557:   case MAT_SPD_ETERNAL:
6558:     PetscCheck(mat->spd != PETSC_BOOL3_UNKNOWN, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Cannot set MAT_SPD_ETERNAL without first setting MAT_SPD to true or false");
6559:     mat->spd_eternal = flg;
6560:     if (flg) {
6561:       mat->structural_symmetry_eternal = PETSC_TRUE;
6562:       mat->symmetry_eternal            = PETSC_TRUE;
6563:     }
6564:     break;
6565:   case MAT_STRUCTURE_ONLY:
6566:     mat->structure_only = flg;
6567:     break;
6568:   case MAT_SORTED_FULL:
6569:     mat->sortedfull = flg;
6570:     break;
6571:   default:
6572:     break;
6573:   }
6574:   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");
6575:   PetscTryTypeMethod(mat, setoption, op, flg);
6576:   PetscFunctionReturn(PETSC_SUCCESS);
6577: }

6579: /*@
6580:   MatGetOption - Gets a parameter option that has been set for a matrix.

6582:   Logically Collective

6584:   Input Parameters:
6585: + mat - the matrix
6586: - op  - the option, this only responds to certain options, check the code for which ones

6588:   Output Parameter:
6589: . flg - turn the option on (`PETSC_TRUE`) or off (`PETSC_FALSE`)

6591:   Level: intermediate

6593:   Notes:
6594:   Can only be called after `MatSetSizes()` and `MatSetType()` have been set.

6596:   Certain option values may be unknown, for those use the routines `MatIsSymmetric()`, `MatIsHermitian()`, `MatIsStructurallySymmetric()`, or
6597:   `MatIsSymmetricKnown()`, `MatIsHermitianKnown()`, `MatIsStructurallySymmetricKnown()`

6599: .seealso: [](ch_matrices), `Mat`, `MatOption`, `MatSetOption()`, `MatIsSymmetric()`, `MatIsHermitian()`, `MatIsStructurallySymmetric()`,
6600:     `MatIsSymmetricKnown()`, `MatIsHermitianKnown()`, `MatIsStructurallySymmetricKnown()`
6601: @*/
6602: PetscErrorCode MatGetOption(Mat mat, MatOption op, PetscBool *flg)
6603: {
6604:   PetscFunctionBegin;

6608:   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);
6609:   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()");

6611:   switch (op) {
6612:   case MAT_NO_OFF_PROC_ENTRIES:
6613:     *flg = mat->nooffprocentries;
6614:     break;
6615:   case MAT_NO_OFF_PROC_ZERO_ROWS:
6616:     *flg = mat->nooffproczerorows;
6617:     break;
6618:   case MAT_SYMMETRIC:
6619:     SETERRQ(PetscObjectComm((PetscObject)mat), PETSC_ERR_SUP, "Use MatIsSymmetric() or MatIsSymmetricKnown()");
6620:     break;
6621:   case MAT_HERMITIAN:
6622:     SETERRQ(PetscObjectComm((PetscObject)mat), PETSC_ERR_SUP, "Use MatIsHermitian() or MatIsHermitianKnown()");
6623:     break;
6624:   case MAT_STRUCTURALLY_SYMMETRIC:
6625:     SETERRQ(PetscObjectComm((PetscObject)mat), PETSC_ERR_SUP, "Use MatIsStructurallySymmetric() or MatIsStructurallySymmetricKnown()");
6626:     break;
6627:   case MAT_SPD:
6628:     SETERRQ(PetscObjectComm((PetscObject)mat), PETSC_ERR_SUP, "Use MatIsSPDKnown()");
6629:     break;
6630:   case MAT_SYMMETRY_ETERNAL:
6631:     *flg = mat->symmetry_eternal;
6632:     break;
6633:   case MAT_STRUCTURAL_SYMMETRY_ETERNAL:
6634:     *flg = mat->symmetry_eternal;
6635:     break;
6636:   default:
6637:     break;
6638:   }
6639:   PetscFunctionReturn(PETSC_SUCCESS);
6640: }

6642: /*@
6643:   MatZeroEntries - Zeros all entries of a matrix.  For sparse matrices
6644:   this routine retains the old nonzero structure.

6646:   Logically Collective

6648:   Input Parameter:
6649: . mat - the matrix

6651:   Level: intermediate

6653:   Note:
6654:   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.
6655:   See the Performance chapter of the users manual for information on preallocating matrices.

6657: .seealso: [](ch_matrices), `Mat`, `MatZeroRows()`, `MatZeroRowsColumns()`
6658: @*/
6659: PetscErrorCode MatZeroEntries(Mat mat)
6660: {
6661:   PetscFunctionBegin;
6664:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
6665:   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");
6666:   MatCheckPreallocated(mat, 1);

6668:   PetscCall(PetscLogEventBegin(MAT_ZeroEntries, mat, 0, 0, 0));
6669:   PetscUseTypeMethod(mat, zeroentries);
6670:   PetscCall(PetscLogEventEnd(MAT_ZeroEntries, mat, 0, 0, 0));
6671:   PetscCall(PetscObjectStateIncrease((PetscObject)mat));
6672:   PetscFunctionReturn(PETSC_SUCCESS);
6673: }

6675: /*@
6676:   MatZeroRowsColumns - Zeros all entries (except possibly the main diagonal)
6677:   of a set of rows and columns of a matrix.

6679:   Collective

6681:   Input Parameters:
6682: + mat     - the matrix
6683: . numRows - the number of rows/columns to zero
6684: . rows    - the global row indices
6685: . diag    - value put in the diagonal of the eliminated rows
6686: . x       - optional vector of the solution for zeroed rows (other entries in vector are not used), these must be set before this call
6687: - b       - optional vector of the right-hand side, that will be adjusted by provided solution entries

6689:   Level: intermediate

6691:   Notes:
6692:   This routine, along with `MatZeroRows()`, is typically used to eliminate known Dirichlet boundary conditions from a linear system.

6694:   For each zeroed row, the value of the corresponding `b` is set to diag times the value of the corresponding `x`.
6695:   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

6697:   If the resulting linear system is to be solved with `KSP` then one can (but does not have to) call `KSPSetInitialGuessNonzero()` to allow the
6698:   Krylov method to take advantage of the known solution on the zeroed rows.

6700:   For the parallel case, all processes that share the matrix (i.e.,
6701:   those in the communicator used for matrix creation) MUST call this
6702:   routine, regardless of whether any rows being zeroed are owned by
6703:   them.

6705:   Unlike `MatZeroRows()`, this ignores the `MAT_KEEP_NONZERO_PATTERN` option value set with `MatSetOption()`, it merely zeros those entries in the matrix, but never
6706:   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
6707:   missing.

6709:   Each processor can indicate any rows in the entire matrix to be zeroed (i.e. each process does NOT have to
6710:   list only rows local to itself).

6712:   The option `MAT_NO_OFF_PROC_ZERO_ROWS` does not apply to this routine.

6714: .seealso: [](ch_matrices), `Mat`, `MatZeroRowsIS()`, `MatZeroRows()`, `MatZeroRowsLocalIS()`, `MatZeroRowsStencil()`, `MatZeroEntries()`, `MatZeroRowsLocal()`, `MatSetOption()`,
6715:           `MatZeroRowsColumnsLocal()`, `MatZeroRowsColumnsLocalIS()`, `MatZeroRowsColumnsIS()`, `MatZeroRowsColumnsStencil()`
6716: @*/
6717: PetscErrorCode MatZeroRowsColumns(Mat mat, PetscInt numRows, const PetscInt rows[], PetscScalar diag, Vec x, Vec b)
6718: {
6719:   PetscFunctionBegin;
6722:   if (numRows) PetscAssertPointer(rows, 3);
6723:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
6724:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
6725:   MatCheckPreallocated(mat, 1);

6727:   PetscUseTypeMethod(mat, zerorowscolumns, numRows, rows, diag, x, b);
6728:   PetscCall(MatViewFromOptions(mat, NULL, "-mat_view"));
6729:   PetscCall(PetscObjectStateIncrease((PetscObject)mat));
6730:   PetscFunctionReturn(PETSC_SUCCESS);
6731: }

6733: /*@
6734:   MatZeroRowsColumnsIS - Zeros all entries (except possibly the main diagonal)
6735:   of a set of rows and columns of a matrix.

6737:   Collective

6739:   Input Parameters:
6740: + mat  - the matrix
6741: . is   - the rows to zero
6742: . diag - value put in all diagonals of eliminated rows (0.0 will even eliminate diagonal entry)
6743: . x    - optional vector of solutions for zeroed rows (other entries in vector are not used)
6744: - b    - optional vector of right-hand side, that will be adjusted by provided solution

6746:   Level: intermediate

6748:   Note:
6749:   See `MatZeroRowsColumns()` for details on how this routine operates.

6751: .seealso: [](ch_matrices), `Mat`, `MatZeroRowsIS()`, `MatZeroRowsColumns()`, `MatZeroRowsLocalIS()`, `MatZeroRowsStencil()`, `MatZeroEntries()`, `MatZeroRowsLocal()`, `MatSetOption()`,
6752:           `MatZeroRowsColumnsLocal()`, `MatZeroRowsColumnsLocalIS()`, `MatZeroRows()`, `MatZeroRowsColumnsStencil()`
6753: @*/
6754: PetscErrorCode MatZeroRowsColumnsIS(Mat mat, IS is, PetscScalar diag, Vec x, Vec b)
6755: {
6756:   PetscInt        numRows;
6757:   const PetscInt *rows;

6759:   PetscFunctionBegin;
6764:   PetscCall(ISGetLocalSize(is, &numRows));
6765:   PetscCall(ISGetIndices(is, &rows));
6766:   PetscCall(MatZeroRowsColumns(mat, numRows, rows, diag, x, b));
6767:   PetscCall(ISRestoreIndices(is, &rows));
6768:   PetscFunctionReturn(PETSC_SUCCESS);
6769: }

6771: /*@
6772:   MatZeroRows - Zeros all entries (except possibly the main diagonal)
6773:   of a set of rows of a matrix.

6775:   Collective

6777:   Input Parameters:
6778: + mat     - the matrix
6779: . numRows - the number of rows to zero
6780: . rows    - the global row indices
6781: . diag    - value put in the diagonal of the zeroed rows
6782: . x       - optional vector of solutions for zeroed rows (other entries in vector are not used), these must be set before this call
6783: - b       - optional vector of right-hand side, that will be adjusted by provided solution entries

6785:   Level: intermediate

6787:   Notes:
6788:   This routine, along with `MatZeroRowsColumns()`, is typically used to eliminate known Dirichlet boundary conditions from a linear system.

6790:   For each zeroed row, the value of the corresponding `b` is set to `diag` times the value of the corresponding `x`.

6792:   If the resulting linear system is to be solved with `KSP` then one can (but does not have to) call `KSPSetInitialGuessNonzero()` to allow the
6793:   Krylov method to take advantage of the known solution on the zeroed rows.

6795:   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)
6796:   from the matrix.

6798:   Unlike `MatZeroRowsColumns()` for the `MATAIJ` and `MATBAIJ` matrix formats this removes the old nonzero structure, from the eliminated rows of the matrix
6799:   but does not release memory.  Because of this removal matrix-vector products with the adjusted matrix will be a bit faster. For the dense
6800:   formats this does not alter the nonzero structure.

6802:   If the option `MatSetOption`(mat,`MAT_KEEP_NONZERO_PATTERN`,`PETSC_TRUE`) the nonzero structure
6803:   of the matrix is not changed the values are
6804:   merely zeroed.

6806:   The user can set a value in the diagonal entry (or for the `MATAIJ` format
6807:   formats can optionally remove the main diagonal entry from the
6808:   nonzero structure as well, by passing 0.0 as the final argument).

6810:   For the parallel case, all processes that share the matrix (i.e.,
6811:   those in the communicator used for matrix creation) MUST call this
6812:   routine, regardless of whether any rows being zeroed are owned by
6813:   them.

6815:   Each processor can indicate any rows in the entire matrix to be zeroed (i.e. each process does NOT have to
6816:   list only rows local to itself).

6818:   You can call `MatSetOption`(mat,`MAT_NO_OFF_PROC_ZERO_ROWS`,`PETSC_TRUE`) if each process indicates only rows it
6819:   owns that are to be zeroed. This saves a global synchronization in the implementation.

6821: .seealso: [](ch_matrices), `Mat`, `MatZeroRowsIS()`, `MatZeroRowsColumns()`, `MatZeroRowsLocalIS()`, `MatZeroRowsStencil()`, `MatZeroEntries()`, `MatZeroRowsLocal()`, `MatSetOption()`,
6822:           `MatZeroRowsColumnsLocal()`, `MatZeroRowsColumnsLocalIS()`, `MatZeroRowsColumnsIS()`, `MatZeroRowsColumnsStencil()`, `PCREDISTRIBUTE`, `MAT_KEEP_NONZERO_PATTERN`
6823: @*/
6824: PetscErrorCode MatZeroRows(Mat mat, PetscInt numRows, const PetscInt rows[], PetscScalar diag, Vec x, Vec b)
6825: {
6826:   PetscFunctionBegin;
6829:   if (numRows) PetscAssertPointer(rows, 3);
6830:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
6831:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
6832:   MatCheckPreallocated(mat, 1);

6834:   PetscUseTypeMethod(mat, zerorows, numRows, rows, diag, x, b);
6835:   PetscCall(MatViewFromOptions(mat, NULL, "-mat_view"));
6836:   PetscCall(PetscObjectStateIncrease((PetscObject)mat));
6837:   PetscFunctionReturn(PETSC_SUCCESS);
6838: }

6840: /*@
6841:   MatZeroRowsIS - Zeros all entries (except possibly the main diagonal)
6842:   of a set of rows of a matrix indicated by an `IS`

6844:   Collective

6846:   Input Parameters:
6847: + mat  - the matrix
6848: . is   - index set, `IS`, of rows to remove (if `NULL` then no row is removed)
6849: . diag - value put in all diagonals of eliminated rows
6850: . x    - optional vector of solutions for zeroed rows (other entries in vector are not used)
6851: - b    - optional vector of right-hand side, that will be adjusted by provided solution

6853:   Level: intermediate

6855:   Note:
6856:   See `MatZeroRows()` for details on how this routine operates.

6858: .seealso: [](ch_matrices), `Mat`, `MatZeroRows()`, `MatZeroRowsColumns()`, `MatZeroRowsLocalIS()`, `MatZeroRowsStencil()`, `MatZeroEntries()`, `MatZeroRowsLocal()`, `MatSetOption()`,
6859:           `MatZeroRowsColumnsLocal()`, `MatZeroRowsColumnsLocalIS()`, `MatZeroRowsColumnsIS()`, `MatZeroRowsColumnsStencil()`, `IS`
6860: @*/
6861: PetscErrorCode MatZeroRowsIS(Mat mat, IS is, PetscScalar diag, Vec x, Vec b)
6862: {
6863:   PetscInt        numRows = 0;
6864:   const PetscInt *rows    = NULL;

6866:   PetscFunctionBegin;
6869:   if (is) {
6871:     PetscCall(ISGetLocalSize(is, &numRows));
6872:     PetscCall(ISGetIndices(is, &rows));
6873:   }
6874:   PetscCall(MatZeroRows(mat, numRows, rows, diag, x, b));
6875:   if (is) PetscCall(ISRestoreIndices(is, &rows));
6876:   PetscFunctionReturn(PETSC_SUCCESS);
6877: }

6879: /*@
6880:   MatZeroRowsStencil - Zeros all entries (except possibly the main diagonal)
6881:   of a set of rows of a matrix indicated by a `MatStencil`. These rows must be local to the process.

6883:   Collective

6885:   Input Parameters:
6886: + mat     - the matrix
6887: . numRows - the number of rows to remove
6888: . rows    - the grid coordinates (and component number when dof > 1) for matrix rows indicated by an array of `MatStencil`
6889: . diag    - value put in all diagonals of eliminated rows (0.0 will even eliminate diagonal entry)
6890: . x       - optional vector of solutions for zeroed rows (other entries in vector are not used)
6891: - b       - optional vector of right-hand side, that will be adjusted by provided solution

6893:   Level: intermediate

6895:   Notes:
6896:   See `MatZeroRows()` for details on how this routine operates.

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

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

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

6908:   Fortran Note:
6909:   `idxm` and `idxn` should be declared as
6910: .vb
6911:     MatStencil idxm(4, m)
6912: .ve
6913:   and the values inserted using
6914: .vb
6915:     idxm(MatStencil_i, 1) = i
6916:     idxm(MatStencil_j, 1) = j
6917:     idxm(MatStencil_k, 1) = k
6918:     idxm(MatStencil_c, 1) = c
6919:    etc
6920: .ve

6922: .seealso: [](ch_matrices), `Mat`, `MatStencil`, `MatZeroRowsIS()`, `MatZeroRowsColumns()`, `MatZeroRowsLocalIS()`, `MatZeroRows()`, `MatZeroEntries()`, `MatZeroRowsLocal()`, `MatSetOption()`,
6923:           `MatZeroRowsColumnsLocal()`, `MatZeroRowsColumnsLocalIS()`, `MatZeroRowsColumnsIS()`, `MatZeroRowsColumnsStencil()`
6924: @*/
6925: PetscErrorCode MatZeroRowsStencil(Mat mat, PetscInt numRows, const MatStencil rows[], PetscScalar diag, Vec x, Vec b)
6926: {
6927:   PetscInt  dim    = mat->stencil.dim;
6928:   PetscInt  sdim   = dim - (1 - (PetscInt)mat->stencil.noc);
6929:   PetscInt *dims   = mat->stencil.dims + 1;
6930:   PetscInt *starts = mat->stencil.starts;
6931:   PetscInt *dxm    = (PetscInt *)rows;
6932:   PetscInt *jdxm, i, j, tmp, numNewRows = 0;

6934:   PetscFunctionBegin;
6937:   if (numRows) PetscAssertPointer(rows, 3);

6939:   PetscCall(PetscMalloc1(numRows, &jdxm));
6940:   for (i = 0; i < numRows; ++i) {
6941:     /* Skip unused dimensions (they are ordered k, j, i, c) */
6942:     for (j = 0; j < 3 - sdim; ++j) dxm++;
6943:     /* Local index in X dir */
6944:     tmp = *dxm++ - starts[0];
6945:     /* Loop over remaining dimensions */
6946:     for (j = 0; j < dim - 1; ++j) {
6947:       /* If nonlocal, set index to be negative */
6948:       if ((*dxm++ - starts[j + 1]) < 0 || tmp < 0) tmp = PETSC_INT_MIN;
6949:       /* Update local index */
6950:       else tmp = tmp * dims[j] + *(dxm - 1) - starts[j + 1];
6951:     }
6952:     /* Skip component slot if necessary */
6953:     if (mat->stencil.noc) dxm++;
6954:     /* Local row number */
6955:     if (tmp >= 0) jdxm[numNewRows++] = tmp;
6956:   }
6957:   PetscCall(MatZeroRowsLocal(mat, numNewRows, jdxm, diag, x, b));
6958:   PetscCall(PetscFree(jdxm));
6959:   PetscFunctionReturn(PETSC_SUCCESS);
6960: }

6962: /*@
6963:   MatZeroRowsColumnsStencil - Zeros all row and column entries (except possibly the main diagonal)
6964:   of a set of rows and columns of a matrix.

6966:   Collective

6968:   Input Parameters:
6969: + mat     - the matrix
6970: . numRows - the number of rows/columns to remove
6971: . rows    - the grid coordinates (and component number when dof > 1) for matrix rows
6972: . diag    - value put in all diagonals of eliminated rows (0.0 will even eliminate diagonal entry)
6973: . x       - optional vector of solutions for zeroed rows (other entries in vector are not used)
6974: - b       - optional vector of right-hand side, that will be adjusted by provided solution

6976:   Level: intermediate

6978:   Notes:
6979:   See `MatZeroRowsColumns()` for details on how this routine operates.

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

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

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

6991:   Fortran Note:
6992:   `idxm` and `idxn` should be declared as
6993: .vb
6994:     MatStencil idxm(4, m)
6995: .ve
6996:   and the values inserted using
6997: .vb
6998:     idxm(MatStencil_i, 1) = i
6999:     idxm(MatStencil_j, 1) = j
7000:     idxm(MatStencil_k, 1) = k
7001:     idxm(MatStencil_c, 1) = c
7002:     etc
7003: .ve

7005: .seealso: [](ch_matrices), `Mat`, `MatZeroRowsIS()`, `MatZeroRowsColumns()`, `MatZeroRowsLocalIS()`, `MatZeroRowsStencil()`, `MatZeroEntries()`, `MatZeroRowsLocal()`, `MatSetOption()`,
7006:           `MatZeroRowsColumnsLocal()`, `MatZeroRowsColumnsLocalIS()`, `MatZeroRowsColumnsIS()`, `MatZeroRows()`
7007: @*/
7008: PetscErrorCode MatZeroRowsColumnsStencil(Mat mat, PetscInt numRows, const MatStencil rows[], PetscScalar diag, Vec x, Vec b)
7009: {
7010:   PetscInt  dim    = mat->stencil.dim;
7011:   PetscInt  sdim   = dim - (1 - (PetscInt)mat->stencil.noc);
7012:   PetscInt *dims   = mat->stencil.dims + 1;
7013:   PetscInt *starts = mat->stencil.starts;
7014:   PetscInt *dxm    = (PetscInt *)rows;
7015:   PetscInt *jdxm, i, j, tmp, numNewRows = 0;

7017:   PetscFunctionBegin;
7020:   if (numRows) PetscAssertPointer(rows, 3);

7022:   PetscCall(PetscMalloc1(numRows, &jdxm));
7023:   for (i = 0; i < numRows; ++i) {
7024:     /* Skip unused dimensions (they are ordered k, j, i, c) */
7025:     for (j = 0; j < 3 - sdim; ++j) dxm++;
7026:     /* Local index in X dir */
7027:     tmp = *dxm++ - starts[0];
7028:     /* Loop over remaining dimensions */
7029:     for (j = 0; j < dim - 1; ++j) {
7030:       /* If nonlocal, set index to be negative */
7031:       if ((*dxm++ - starts[j + 1]) < 0 || tmp < 0) tmp = PETSC_INT_MIN;
7032:       /* Update local index */
7033:       else tmp = tmp * dims[j] + *(dxm - 1) - starts[j + 1];
7034:     }
7035:     /* Skip component slot if necessary */
7036:     if (mat->stencil.noc) dxm++;
7037:     /* Local row number */
7038:     if (tmp >= 0) jdxm[numNewRows++] = tmp;
7039:   }
7040:   PetscCall(MatZeroRowsColumnsLocal(mat, numNewRows, jdxm, diag, x, b));
7041:   PetscCall(PetscFree(jdxm));
7042:   PetscFunctionReturn(PETSC_SUCCESS);
7043: }

7045: /*@
7046:   MatZeroRowsLocal - Zeros all entries (except possibly the main diagonal)
7047:   of a set of rows of a matrix; using local numbering of rows.

7049:   Collective

7051:   Input Parameters:
7052: + mat     - the matrix
7053: . numRows - the number of rows to remove
7054: . rows    - the local row indices
7055: . diag    - value put in all diagonals of eliminated rows
7056: . x       - optional vector of solutions for zeroed rows (other entries in vector are not used)
7057: - b       - optional vector of right-hand side, that will be adjusted by provided solution

7059:   Level: intermediate

7061:   Notes:
7062:   Before calling `MatZeroRowsLocal()`, the user must first set the
7063:   local-to-global mapping by calling MatSetLocalToGlobalMapping(), this is often already set for matrices obtained with `DMCreateMatrix()`.

7065:   See `MatZeroRows()` for details on how this routine operates.

7067: .seealso: [](ch_matrices), `Mat`, `MatZeroRowsIS()`, `MatZeroRowsColumns()`, `MatZeroRowsLocalIS()`, `MatZeroRowsStencil()`, `MatZeroEntries()`, `MatZeroRows()`, `MatSetOption()`,
7068:           `MatZeroRowsColumnsLocal()`, `MatZeroRowsColumnsLocalIS()`, `MatZeroRowsColumnsIS()`, `MatZeroRowsColumnsStencil()`
7069: @*/
7070: PetscErrorCode MatZeroRowsLocal(Mat mat, PetscInt numRows, const PetscInt rows[], PetscScalar diag, Vec x, Vec b)
7071: {
7072:   PetscFunctionBegin;
7075:   if (numRows) PetscAssertPointer(rows, 3);
7076:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
7077:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
7078:   MatCheckPreallocated(mat, 1);

7080:   if (mat->ops->zerorowslocal) {
7081:     PetscUseTypeMethod(mat, zerorowslocal, numRows, rows, diag, x, b);
7082:   } else {
7083:     IS        is, newis;
7084:     PetscInt *newRows, nl = 0;

7086:     PetscCheck(mat->rmap->mapping, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Need to provide local to global mapping to matrix first");
7087:     PetscCall(ISCreateGeneral(PETSC_COMM_SELF, numRows, rows, PETSC_USE_POINTER, &is));
7088:     PetscCall(ISLocalToGlobalMappingApplyIS(mat->rmap->mapping, is, &newis));
7089:     PetscCall(ISGetIndices(newis, (const PetscInt **)&newRows));
7090:     for (PetscInt i = 0; i < numRows; i++)
7091:       if (newRows[i] > -1) newRows[nl++] = newRows[i];
7092:     PetscUseTypeMethod(mat, zerorows, nl, newRows, diag, x, b);
7093:     PetscCall(ISRestoreIndices(newis, (const PetscInt **)&newRows));
7094:     PetscCall(ISDestroy(&newis));
7095:     PetscCall(ISDestroy(&is));
7096:   }
7097:   PetscCall(PetscObjectStateIncrease((PetscObject)mat));
7098:   PetscFunctionReturn(PETSC_SUCCESS);
7099: }

7101: /*@
7102:   MatZeroRowsLocalIS - Zeros all entries (except possibly the main diagonal)
7103:   of a set of rows of a matrix; using local numbering of rows.

7105:   Collective

7107:   Input Parameters:
7108: + mat  - the matrix
7109: . is   - index set of rows to remove
7110: . diag - value put in all diagonals of eliminated rows
7111: . x    - optional vector of solutions for zeroed rows (other entries in vector are not used)
7112: - b    - optional vector of right-hand side, that will be adjusted by provided solution

7114:   Level: intermediate

7116:   Notes:
7117:   Before calling `MatZeroRowsLocalIS()`, the user must first set the
7118:   local-to-global mapping by calling `MatSetLocalToGlobalMapping()`, this is often already set for matrices obtained with `DMCreateMatrix()`.

7120:   See `MatZeroRows()` for details on how this routine operates.

7122: .seealso: [](ch_matrices), `Mat`, `MatZeroRowsIS()`, `MatZeroRowsColumns()`, `MatZeroRows()`, `MatZeroRowsStencil()`, `MatZeroEntries()`, `MatZeroRowsLocal()`, `MatSetOption()`,
7123:           `MatZeroRowsColumnsLocal()`, `MatZeroRowsColumnsLocalIS()`, `MatZeroRowsColumnsIS()`, `MatZeroRowsColumnsStencil()`
7124: @*/
7125: PetscErrorCode MatZeroRowsLocalIS(Mat mat, IS is, PetscScalar diag, Vec x, Vec b)
7126: {
7127:   PetscInt        numRows;
7128:   const PetscInt *rows;

7130:   PetscFunctionBegin;
7134:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
7135:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
7136:   MatCheckPreallocated(mat, 1);

7138:   PetscCall(ISGetLocalSize(is, &numRows));
7139:   PetscCall(ISGetIndices(is, &rows));
7140:   PetscCall(MatZeroRowsLocal(mat, numRows, rows, diag, x, b));
7141:   PetscCall(ISRestoreIndices(is, &rows));
7142:   PetscFunctionReturn(PETSC_SUCCESS);
7143: }

7145: /*@
7146:   MatZeroRowsColumnsLocal - Zeros all entries (except possibly the main diagonal)
7147:   of a set of rows and columns of a matrix; using local numbering of rows.

7149:   Collective

7151:   Input Parameters:
7152: + mat     - the matrix
7153: . numRows - the number of rows to remove
7154: . rows    - the global row indices
7155: . diag    - value put in all diagonals of eliminated rows
7156: . x       - optional vector of solutions for zeroed rows (other entries in vector are not used)
7157: - b       - optional vector of right-hand side, that will be adjusted by provided solution

7159:   Level: intermediate

7161:   Notes:
7162:   Before calling `MatZeroRowsColumnsLocal()`, the user must first set the
7163:   local-to-global mapping by calling `MatSetLocalToGlobalMapping()`, this is often already set for matrices obtained with `DMCreateMatrix()`.

7165:   See `MatZeroRowsColumns()` for details on how this routine operates.

7167: .seealso: [](ch_matrices), `Mat`, `MatZeroRowsIS()`, `MatZeroRowsColumns()`, `MatZeroRowsLocalIS()`, `MatZeroRowsStencil()`, `MatZeroEntries()`, `MatZeroRowsLocal()`, `MatSetOption()`,
7168:           `MatZeroRows()`, `MatZeroRowsColumnsLocalIS()`, `MatZeroRowsColumnsIS()`, `MatZeroRowsColumnsStencil()`
7169: @*/
7170: PetscErrorCode MatZeroRowsColumnsLocal(Mat mat, PetscInt numRows, const PetscInt rows[], PetscScalar diag, Vec x, Vec b)
7171: {
7172:   PetscFunctionBegin;
7175:   if (numRows) PetscAssertPointer(rows, 3);
7176:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
7177:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
7178:   MatCheckPreallocated(mat, 1);

7180:   if (mat->ops->zerorowscolumnslocal) {
7181:     PetscUseTypeMethod(mat, zerorowscolumnslocal, numRows, rows, diag, x, b);
7182:   } else {
7183:     IS        is, newis;
7184:     PetscInt *newRows, nl = 0;

7186:     PetscCheck(mat->rmap->mapping, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Need to provide local to global mapping to matrix first");
7187:     PetscCall(ISCreateGeneral(PETSC_COMM_SELF, numRows, rows, PETSC_USE_POINTER, &is));
7188:     PetscCall(ISLocalToGlobalMappingApplyIS(mat->rmap->mapping, is, &newis));
7189:     PetscCall(ISGetIndices(newis, (const PetscInt **)&newRows));
7190:     for (PetscInt i = 0; i < numRows; i++)
7191:       if (newRows[i] > -1) newRows[nl++] = newRows[i];
7192:     PetscUseTypeMethod(mat, zerorowscolumns, nl, newRows, diag, x, b);
7193:     PetscCall(ISRestoreIndices(newis, (const PetscInt **)&newRows));
7194:     PetscCall(ISDestroy(&newis));
7195:     PetscCall(ISDestroy(&is));
7196:   }
7197:   PetscCall(PetscObjectStateIncrease((PetscObject)mat));
7198:   PetscFunctionReturn(PETSC_SUCCESS);
7199: }

7201: /*@
7202:   MatZeroRowsColumnsLocalIS - Zeros all entries (except possibly the main diagonal)
7203:   of a set of rows and columns of a matrix; using local numbering of rows.

7205:   Collective

7207:   Input Parameters:
7208: + mat  - the matrix
7209: . is   - index set of rows to remove
7210: . diag - value put in all diagonals of eliminated rows
7211: . x    - optional vector of solutions for zeroed rows (other entries in vector are not used)
7212: - b    - optional vector of right-hand side, that will be adjusted by provided solution

7214:   Level: intermediate

7216:   Notes:
7217:   Before calling `MatZeroRowsColumnsLocalIS()`, the user must first set the
7218:   local-to-global mapping by calling `MatSetLocalToGlobalMapping()`, this is often already set for matrices obtained with `DMCreateMatrix()`.

7220:   See `MatZeroRowsColumns()` for details on how this routine operates.

7222: .seealso: [](ch_matrices), `Mat`, `MatZeroRowsIS()`, `MatZeroRowsColumns()`, `MatZeroRowsLocalIS()`, `MatZeroRowsStencil()`, `MatZeroEntries()`, `MatZeroRowsLocal()`, `MatSetOption()`,
7223:           `MatZeroRowsColumnsLocal()`, `MatZeroRows()`, `MatZeroRowsColumnsIS()`, `MatZeroRowsColumnsStencil()`
7224: @*/
7225: PetscErrorCode MatZeroRowsColumnsLocalIS(Mat mat, IS is, PetscScalar diag, Vec x, Vec b)
7226: {
7227:   PetscInt        numRows;
7228:   const PetscInt *rows;

7230:   PetscFunctionBegin;
7234:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
7235:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
7236:   MatCheckPreallocated(mat, 1);

7238:   PetscCall(ISGetLocalSize(is, &numRows));
7239:   PetscCall(ISGetIndices(is, &rows));
7240:   PetscCall(MatZeroRowsColumnsLocal(mat, numRows, rows, diag, x, b));
7241:   PetscCall(ISRestoreIndices(is, &rows));
7242:   PetscFunctionReturn(PETSC_SUCCESS);
7243: }

7245: /*@
7246:   MatGetSize - Returns the numbers of rows and columns in a matrix.

7248:   Not Collective

7250:   Input Parameter:
7251: . mat - the matrix

7253:   Output Parameters:
7254: + m - the number of global rows
7255: - n - the number of global columns

7257:   Level: beginner

7259:   Note:
7260:   Both output parameters can be `NULL` on input.

7262: .seealso: [](ch_matrices), `Mat`, `MatSetSizes()`, `MatGetLocalSize()`
7263: @*/
7264: PetscErrorCode MatGetSize(Mat mat, PetscInt *m, PetscInt *n)
7265: {
7266:   PetscFunctionBegin;
7268:   if (m) *m = mat->rmap->N;
7269:   if (n) *n = mat->cmap->N;
7270:   PetscFunctionReturn(PETSC_SUCCESS);
7271: }

7273: /*@
7274:   MatGetLocalSize - For most matrix formats, excluding `MATELEMENTAL` and `MATSCALAPACK`, Returns the number of local rows and local columns
7275:   of a matrix. For all matrices this is the local size of the left and right vectors as returned by `MatCreateVecs()`.

7277:   Not Collective

7279:   Input Parameter:
7280: . mat - the matrix

7282:   Output Parameters:
7283: + m - the number of local rows, use `NULL` to not obtain this value
7284: - n - the number of local columns, use `NULL` to not obtain this value

7286:   Level: beginner

7288: .seealso: [](ch_matrices), `Mat`, `MatSetSizes()`, `MatGetSize()`
7289: @*/
7290: PetscErrorCode MatGetLocalSize(Mat mat, PetscInt *m, PetscInt *n)
7291: {
7292:   PetscFunctionBegin;
7294:   if (m) PetscAssertPointer(m, 2);
7295:   if (n) PetscAssertPointer(n, 3);
7296:   if (m) *m = mat->rmap->n;
7297:   if (n) *n = mat->cmap->n;
7298:   PetscFunctionReturn(PETSC_SUCCESS);
7299: }

7301: /*@
7302:   MatGetOwnershipRangeColumn - Returns the range of matrix columns associated with rows of a
7303:   vector one multiplies this matrix by that are owned by this processor.

7305:   Not Collective, unless matrix has not been allocated, then collective

7307:   Input Parameter:
7308: . mat - the matrix

7310:   Output Parameters:
7311: + m - the global index of the first local column, use `NULL` to not obtain this value
7312: - n - one more than the global index of the last local column, use `NULL` to not obtain this value

7314:   Level: developer

7316:   Notes:
7317:   If the `Mat` was obtained from a `DM` with `DMCreateMatrix()`, then the range values are determined by the specific `DM`.

7319:   If the `Mat` was created directly the range values are determined by the local size passed to `MatSetSizes()` or `MatCreateAIJ()`.
7320:   If `PETSC_DECIDE` was passed as the local size, then the vector uses default values for the range using `PetscSplitOwnership()`.

7322:   For certain `DM`, such as `DMDA`, it is better to use `DM` specific routines, such as `DMDAGetGhostCorners()`, to determine
7323:   the local values in the matrix.

7325:   Returns the columns of the "diagonal block" for most sparse matrix formats. See [Matrix
7326:   Layouts](sec_matlayout) for details on matrix layouts.

7328: .seealso: [](ch_matrices), `Mat`, `MatGetOwnershipRange()`, `MatGetOwnershipRanges()`, `MatGetOwnershipRangesColumn()`, `PetscLayout`,
7329:           `MatSetSizes()`, `MatCreateAIJ()`, `DMDAGetGhostCorners()`, `DM`
7330: @*/
7331: PetscErrorCode MatGetOwnershipRangeColumn(Mat mat, PetscInt *m, PetscInt *n)
7332: {
7333:   PetscFunctionBegin;
7336:   if (m) PetscAssertPointer(m, 2);
7337:   if (n) PetscAssertPointer(n, 3);
7338:   MatCheckPreallocated(mat, 1);
7339:   if (m) *m = mat->cmap->rstart;
7340:   if (n) *n = mat->cmap->rend;
7341:   PetscFunctionReturn(PETSC_SUCCESS);
7342: }

7344: /*@
7345:   MatGetOwnershipRange - For matrices that own values by row, excludes `MATELEMENTAL` and `MATSCALAPACK`, returns the range of matrix rows owned by
7346:   this MPI process.

7348:   Not Collective

7350:   Input Parameter:
7351: . mat - the matrix

7353:   Output Parameters:
7354: + m - the global index of the first local row, use `NULL` to not obtain this value
7355: - n - one more than the global index of the last local row, use `NULL` to not obtain this value

7357:   Level: beginner

7359:   Notes:
7360:   If the `Mat` was obtained from a `DM` with `DMCreateMatrix()`, then the range values are determined by the specific `DM`.

7362:   If the `Mat` was created directly the range values are determined by the local size passed to `MatSetSizes()` or `MatCreateAIJ()`.
7363:   If `PETSC_DECIDE` was passed as the local size, then the vector uses default values for the range using `PetscSplitOwnership()`.

7365:   For certain `DM`, such as `DMDA`, it is better to use `DM` specific routines, such as `DMDAGetGhostCorners()`, to determine
7366:   the local values in the matrix.

7368:   The high argument is one more than the last element stored locally.

7370:   For all matrices  it returns the range of matrix rows associated with rows of a vector that
7371:   would contain the result of a matrix vector product with this matrix. See [Matrix
7372:   Layouts](sec_matlayout) for details on matrix layouts.

7374: .seealso: [](ch_matrices), `Mat`, `MatGetOwnershipRanges()`, `MatGetOwnershipRangeColumn()`, `MatGetOwnershipRangesColumn()`, `PetscSplitOwnership()`,
7375:           `PetscSplitOwnershipBlock()`, `PetscLayout`, `MatSetSizes()`, `MatCreateAIJ()`, `DMDAGetGhostCorners()`, `DM`
7376: @*/
7377: PetscErrorCode MatGetOwnershipRange(Mat mat, PetscInt *m, PetscInt *n)
7378: {
7379:   PetscFunctionBegin;
7382:   if (m) PetscAssertPointer(m, 2);
7383:   if (n) PetscAssertPointer(n, 3);
7384:   MatCheckPreallocated(mat, 1);
7385:   if (m) *m = mat->rmap->rstart;
7386:   if (n) *n = mat->rmap->rend;
7387:   PetscFunctionReturn(PETSC_SUCCESS);
7388: }

7390: /*@C
7391:   MatGetOwnershipRanges - For matrices that own values by row, excludes `MATELEMENTAL` and
7392:   `MATSCALAPACK`, returns the range of matrix rows owned by each process.

7394:   Not Collective, unless matrix has not been allocated

7396:   Input Parameter:
7397: . mat - the matrix

7399:   Output Parameter:
7400: . ranges - start of each processors portion plus one more than the total length at the end, of length `size` + 1
7401:            where `size` is the number of MPI processes used by `mat`

7403:   Level: beginner

7405:   Notes:
7406:   If the `Mat` was obtained from a `DM` with `DMCreateMatrix()`, then the range values are determined by the specific `DM`.

7408:   If the `Mat` was created directly the range values are determined by the local size passed to `MatSetSizes()` or `MatCreateAIJ()`.
7409:   If `PETSC_DECIDE` was passed as the local size, then the vector uses default values for the range using `PetscSplitOwnership()`.

7411:   For certain `DM`, such as `DMDA`, it is better to use `DM` specific routines, such as `DMDAGetGhostCorners()`, to determine
7412:   the local values in the matrix.

7414:   For all matrices  it returns the ranges of matrix rows associated with rows of a vector that
7415:   would contain the result of a matrix vector product with this matrix. See [Matrix
7416:   Layouts](sec_matlayout) for details on matrix layouts.

7418: .seealso: [](ch_matrices), `Mat`, `MatGetOwnershipRange()`, `MatGetOwnershipRangeColumn()`, `MatGetOwnershipRangesColumn()`, `PetscLayout`,
7419:           `PetscSplitOwnership()`, `PetscSplitOwnershipBlock()`, `MatSetSizes()`, `MatCreateAIJ()`,
7420:           `DMDAGetGhostCorners()`, `DM`
7421: @*/
7422: PetscErrorCode MatGetOwnershipRanges(Mat mat, const PetscInt *ranges[])
7423: {
7424:   PetscFunctionBegin;
7427:   MatCheckPreallocated(mat, 1);
7428:   PetscCall(PetscLayoutGetRanges(mat->rmap, ranges));
7429:   PetscFunctionReturn(PETSC_SUCCESS);
7430: }

7432: /*@C
7433:   MatGetOwnershipRangesColumn - Returns the ranges of matrix columns associated with rows of a
7434:   vector one multiplies this vector by that are owned by each processor.

7436:   Not Collective, unless matrix has not been allocated

7438:   Input Parameter:
7439: . mat - the matrix

7441:   Output Parameter:
7442: . ranges - start of each processors portion plus one more than the total length at the end

7444:   Level: beginner

7446:   Notes:
7447:   If the `Mat` was obtained from a `DM` with `DMCreateMatrix()`, then the range values are determined by the specific `DM`.

7449:   If the `Mat` was created directly the range values are determined by the local size passed to `MatSetSizes()` or `MatCreateAIJ()`.
7450:   If `PETSC_DECIDE` was passed as the local size, then the vector uses default values for the range using `PetscSplitOwnership()`.

7452:   For certain `DM`, such as `DMDA`, it is better to use `DM` specific routines, such as `DMDAGetGhostCorners()`, to determine
7453:   the local values in the matrix.

7455:   Returns the columns of the "diagonal blocks", for most sparse matrix formats. See [Matrix
7456:   Layouts](sec_matlayout) for details on matrix layouts.

7458: .seealso: [](ch_matrices), `Mat`, `MatGetOwnershipRange()`, `MatGetOwnershipRangeColumn()`, `MatGetOwnershipRanges()`,
7459:           `PetscSplitOwnership()`, `PetscSplitOwnershipBlock()`, `PetscLayout`, `MatSetSizes()`, `MatCreateAIJ()`,
7460:           `DMDAGetGhostCorners()`, `DM`
7461: @*/
7462: PetscErrorCode MatGetOwnershipRangesColumn(Mat mat, const PetscInt *ranges[])
7463: {
7464:   PetscFunctionBegin;
7467:   MatCheckPreallocated(mat, 1);
7468:   PetscCall(PetscLayoutGetRanges(mat->cmap, ranges));
7469:   PetscFunctionReturn(PETSC_SUCCESS);
7470: }

7472: /*@
7473:   MatGetOwnershipIS - Get row and column ownership of a matrices' values as index sets.

7475:   Not Collective

7477:   Input Parameter:
7478: . A - matrix

7480:   Output Parameters:
7481: + rows - rows in which this process owns elements, , use `NULL` to not obtain this value
7482: - cols - columns in which this process owns elements, use `NULL` to not obtain this value

7484:   Level: intermediate

7486:   Note:
7487:   You should call `ISDestroy()` on the returned `IS`

7489:   For most matrices, excluding `MATELEMENTAL` and `MATSCALAPACK`, this corresponds to values
7490:   returned by `MatGetOwnershipRange()`, `MatGetOwnershipRangeColumn()`. For `MATELEMENTAL` and
7491:   `MATSCALAPACK` the ownership is more complicated. See [Matrix Layouts](sec_matlayout) for
7492:   details on matrix layouts.

7494: .seealso: [](ch_matrices), `IS`, `Mat`, `MatGetOwnershipRanges()`, `MatSetValues()`, `MATELEMENTAL`, `MATSCALAPACK`
7495: @*/
7496: PetscErrorCode MatGetOwnershipIS(Mat A, IS *rows, IS *cols)
7497: {
7498:   PetscErrorCode (*f)(Mat, IS *, IS *);

7500:   PetscFunctionBegin;
7503:   MatCheckPreallocated(A, 1);
7504:   PetscCall(PetscObjectQueryFunction((PetscObject)A, "MatGetOwnershipIS_C", &f));
7505:   if (f) {
7506:     PetscCall((*f)(A, rows, cols));
7507:   } else { /* Create a standard row-based partition, each process is responsible for ALL columns in their row block */
7508:     if (rows) PetscCall(ISCreateStride(PETSC_COMM_SELF, A->rmap->n, A->rmap->rstart, 1, rows));
7509:     if (cols) PetscCall(ISCreateStride(PETSC_COMM_SELF, A->cmap->N, 0, 1, cols));
7510:   }
7511:   PetscFunctionReturn(PETSC_SUCCESS);
7512: }

7514: /*@
7515:   MatILUFactorSymbolic - Performs symbolic ILU factorization of a matrix obtained with `MatGetFactor()`
7516:   Uses levels of fill only, not drop tolerance. Use `MatLUFactorNumeric()`
7517:   to complete the factorization.

7519:   Collective

7521:   Input Parameters:
7522: + fact - the factorized matrix obtained with `MatGetFactor()`
7523: . mat  - the matrix
7524: . row  - row permutation
7525: . col  - column permutation
7526: - info - structure containing
7527: .vb
7528:       levels - number of levels of fill.
7529:       expected fill - as ratio of original fill.
7530:       1 or 0 - indicating force fill on diagonal (improves robustness for matrices
7531:                 missing diagonal entries)
7532: .ve

7534:   Level: developer

7536:   Notes:
7537:   See [Matrix Factorization](sec_matfactor) for additional information.

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

7543:   Uses the definition of level of fill as in Y. Saad, {cite}`saad2003`

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

7548: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatGetFactor()`, `MatLUFactorSymbolic()`, `MatLUFactorNumeric()`, `MatCholeskyFactor()`,
7549:           `MatGetOrdering()`, `MatFactorInfo`
7550: @*/
7551: PetscErrorCode MatILUFactorSymbolic(Mat fact, Mat mat, IS row, IS col, const MatFactorInfo *info)
7552: {
7553:   PetscFunctionBegin;
7558:   PetscAssertPointer(info, 5);
7559:   PetscAssertPointer(fact, 1);
7560:   PetscCheck(info->levels >= 0, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_OUTOFRANGE, "Levels of fill negative %" PetscInt_FMT, (PetscInt)info->levels);
7561:   PetscCheck(info->fill >= 1.0, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_OUTOFRANGE, "Expected fill less than 1.0 %g", (double)info->fill);
7562:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
7563:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
7564:   MatCheckPreallocated(mat, 2);

7566:   if (!fact->trivialsymbolic) PetscCall(PetscLogEventBegin(MAT_ILUFactorSymbolic, mat, row, col, 0));
7567:   PetscUseTypeMethod(fact, ilufactorsymbolic, mat, row, col, info);
7568:   if (!fact->trivialsymbolic) PetscCall(PetscLogEventEnd(MAT_ILUFactorSymbolic, mat, row, col, 0));
7569:   PetscFunctionReturn(PETSC_SUCCESS);
7570: }

7572: /*@
7573:   MatICCFactorSymbolic - Performs symbolic incomplete
7574:   Cholesky factorization for a symmetric matrix.  Use
7575:   `MatCholeskyFactorNumeric()` to complete the factorization.

7577:   Collective

7579:   Input Parameters:
7580: + fact - the factorized matrix obtained with `MatGetFactor()`
7581: . mat  - the matrix to be factored
7582: . perm - row and column permutation
7583: - info - structure containing
7584: .vb
7585:       levels - number of levels of fill.
7586:       expected fill - as ratio of original fill.
7587: .ve

7589:   Level: developer

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

7596:   This uses the definition of level of fill as in Y. Saad {cite}`saad2003`

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

7601: .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatCholeskyFactorNumeric()`, `MatCholeskyFactor()`, `MatFactorInfo`
7602: @*/
7603: PetscErrorCode MatICCFactorSymbolic(Mat fact, Mat mat, IS perm, const MatFactorInfo *info)
7604: {
7605:   PetscFunctionBegin;
7609:   PetscAssertPointer(info, 4);
7610:   PetscAssertPointer(fact, 1);
7611:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
7612:   PetscCheck(info->levels >= 0, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_OUTOFRANGE, "Levels negative %" PetscInt_FMT, (PetscInt)info->levels);
7613:   PetscCheck(info->fill >= 1.0, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_OUTOFRANGE, "Expected fill less than 1.0 %g", (double)info->fill);
7614:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
7615:   MatCheckPreallocated(mat, 2);

7617:   if (!fact->trivialsymbolic) PetscCall(PetscLogEventBegin(MAT_ICCFactorSymbolic, mat, perm, 0, 0));
7618:   PetscUseTypeMethod(fact, iccfactorsymbolic, mat, perm, info);
7619:   if (!fact->trivialsymbolic) PetscCall(PetscLogEventEnd(MAT_ICCFactorSymbolic, mat, perm, 0, 0));
7620:   PetscFunctionReturn(PETSC_SUCCESS);
7621: }

7623: /*@C
7624:   MatCreateSubMatrices - Extracts several submatrices from a matrix. If submat
7625:   points to an array of valid matrices, they may be reused to store the new
7626:   submatrices.

7628:   Collective

7630:   Input Parameters:
7631: + mat   - the matrix
7632: . n     - the number of submatrixes to be extracted (on this processor, may be zero)
7633: . irow  - index set of rows to extract
7634: . icol  - index set of columns to extract
7635: - scall - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`

7637:   Output Parameter:
7638: . submat - the array of submatrices

7640:   Level: advanced

7642:   Notes:
7643:   `MatCreateSubMatrices()` can extract ONLY sequential submatrices
7644:   (from both sequential and parallel matrices). Use `MatCreateSubMatrix()`
7645:   to extract a parallel submatrix.

7647:   Some matrix types place restrictions on the row and column
7648:   indices, such as that they be sorted or that they be equal to each other.

7650:   The index sets may not have duplicate entries.

7652:   When extracting submatrices from a parallel matrix, each processor can
7653:   form a different submatrix by setting the rows and columns of its
7654:   individual index sets according to the local submatrix desired.

7656:   When finished using the submatrices, the user should destroy
7657:   them with `MatDestroySubMatrices()`.

7659:   `MAT_REUSE_MATRIX` can only be used when the nonzero structure of the
7660:   original matrix has not changed from that last call to `MatCreateSubMatrices()`.

7662:   This routine creates the matrices in submat; you should NOT create them before
7663:   calling it. It also allocates the array of matrix pointers submat.

7665:   For `MATBAIJ` matrices the index sets must respect the block structure, that is if they
7666:   request one row/column in a block, they must request all rows/columns that are in
7667:   that block. For example, if the block size is 2 you cannot request just row 0 and
7668:   column 0.

7670:   Fortran Note:
7671: .vb
7672:   Mat, pointer :: submat(:)
7673: .ve

7675: .seealso: [](ch_matrices), `Mat`, `MatDestroySubMatrices()`, `MatCreateSubMatrix()`, `MatGetRow()`, `MatGetDiagonal()`, `MatReuse`
7676: @*/
7677: PetscErrorCode MatCreateSubMatrices(Mat mat, PetscInt n, const IS irow[], const IS icol[], MatReuse scall, Mat *submat[])
7678: {
7679:   PetscInt  i;
7680:   PetscBool eq;

7682:   PetscFunctionBegin;
7685:   if (n) {
7686:     PetscAssertPointer(irow, 3);
7688:     PetscAssertPointer(icol, 4);
7690:   }
7691:   PetscAssertPointer(submat, 6);
7692:   if (n && scall == MAT_REUSE_MATRIX) {
7693:     PetscAssertPointer(*submat, 6);
7695:   }
7696:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
7697:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
7698:   MatCheckPreallocated(mat, 1);
7699:   PetscCall(PetscLogEventBegin(MAT_CreateSubMats, mat, 0, 0, 0));
7700:   PetscUseTypeMethod(mat, createsubmatrices, n, irow, icol, scall, submat);
7701:   PetscCall(PetscLogEventEnd(MAT_CreateSubMats, mat, 0, 0, 0));
7702:   for (i = 0; i < n; i++) {
7703:     (*submat)[i]->factortype = MAT_FACTOR_NONE; /* in case in place factorization was previously done on submatrix */
7704:     PetscCall(ISEqualUnsorted(irow[i], icol[i], &eq));
7705:     if (eq) PetscCall(MatPropagateSymmetryOptions(mat, (*submat)[i]));
7706: #if PetscDefined(HAVE_VIENNACL) || PetscDefined(HAVE_CUDA) || PetscDefined(HAVE_HIP)
7707:     if (mat->boundtocpu && mat->bindingpropagates) {
7708:       PetscCall(MatBindToCPU((*submat)[i], PETSC_TRUE));
7709:       PetscCall(MatSetBindingPropagates((*submat)[i], PETSC_TRUE));
7710:     }
7711: #endif
7712:   }
7713:   PetscFunctionReturn(PETSC_SUCCESS);
7714: }

7716: /*@C
7717:   MatCreateSubMatricesMPI - Extracts MPI submatrices across a sub communicator of `mat` (by pairs of `IS` that may live on subcomms).

7719:   Collective

7721:   Input Parameters:
7722: + mat   - the matrix
7723: . n     - the number of submatrixes to be extracted
7724: . irow  - index set of rows to extract
7725: . icol  - index set of columns to extract
7726: - scall - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`

7728:   Output Parameter:
7729: . submat - the array of submatrices

7731:   Level: advanced

7733:   Note:
7734:   This is used by `PCGASM`

7736: .seealso: [](ch_matrices), `Mat`, `PCGASM`, `MatCreateSubMatrices()`, `MatCreateSubMatrix()`, `MatGetRow()`, `MatGetDiagonal()`, `MatReuse`
7737: @*/
7738: PetscErrorCode MatCreateSubMatricesMPI(Mat mat, PetscInt n, const IS irow[], const IS icol[], MatReuse scall, Mat *submat[])
7739: {
7740:   PetscInt  i;
7741:   PetscBool eq;

7743:   PetscFunctionBegin;
7746:   if (n) {
7747:     PetscAssertPointer(irow, 3);
7749:     PetscAssertPointer(icol, 4);
7751:   }
7752:   PetscAssertPointer(submat, 6);
7753:   if (n && scall == MAT_REUSE_MATRIX) {
7754:     PetscAssertPointer(*submat, 6);
7756:   }
7757:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
7758:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
7759:   MatCheckPreallocated(mat, 1);

7761:   PetscCall(PetscLogEventBegin(MAT_CreateSubMats, mat, 0, 0, 0));
7762:   PetscUseTypeMethod(mat, createsubmatricesmpi, n, irow, icol, scall, submat);
7763:   PetscCall(PetscLogEventEnd(MAT_CreateSubMats, mat, 0, 0, 0));
7764:   for (i = 0; i < n; i++) {
7765:     PetscCall(ISEqualUnsorted(irow[i], icol[i], &eq));
7766:     if (eq) PetscCall(MatPropagateSymmetryOptions(mat, (*submat)[i]));
7767:   }
7768:   PetscFunctionReturn(PETSC_SUCCESS);
7769: }

7771: /*@C
7772:   MatDestroyMatrices - Destroys an array of matrices

7774:   Collective

7776:   Input Parameters:
7777: + n   - the number of local matrices
7778: - mat - the matrices (this is a pointer to the array of matrices)

7780:   Level: advanced

7782:   Notes:
7783:   Frees not only the matrices, but also the array that contains the matrices

7785:   For matrices obtained with  `MatCreateSubMatrices()` use `MatDestroySubMatrices()`

7787: .seealso: [](ch_matrices), `Mat`, `MatCreateSubMatrices()`, `MatDestroySubMatrices()`
7788: @*/
7789: PetscErrorCode MatDestroyMatrices(PetscInt n, Mat *mat[])
7790: {
7791:   PetscInt i;

7793:   PetscFunctionBegin;
7794:   if (!*mat) PetscFunctionReturn(PETSC_SUCCESS);
7795:   PetscCheck(n >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Trying to destroy negative number of matrices %" PetscInt_FMT, n);
7796:   PetscAssertPointer(mat, 2);

7798:   for (i = 0; i < n; i++) PetscCall(MatDestroy(&(*mat)[i]));

7800:   /* memory is allocated even if n = 0 */
7801:   PetscCall(PetscFree(*mat));
7802:   PetscFunctionReturn(PETSC_SUCCESS);
7803: }

7805: /*@C
7806:   MatDestroySubMatrices - Destroys a set of matrices obtained with `MatCreateSubMatrices()`.

7808:   Collective

7810:   Input Parameters:
7811: + n   - the number of local matrices
7812: - mat - the matrices (this is a pointer to the array of matrices, to match the calling sequence of `MatCreateSubMatrices()`)

7814:   Level: advanced

7816:   Note:
7817:   Frees not only the matrices, but also the array that contains the matrices

7819: .seealso: [](ch_matrices), `Mat`, `MatCreateSubMatrices()`, `MatDestroyMatrices()`
7820: @*/
7821: PetscErrorCode MatDestroySubMatrices(PetscInt n, Mat *mat[])
7822: {
7823:   Mat mat0;

7825:   PetscFunctionBegin;
7826:   if (!*mat) PetscFunctionReturn(PETSC_SUCCESS);
7827:   /* mat[] is an array of length n+1, see MatCreateSubMatrices_xxx() */
7828:   PetscCheck(n >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Trying to destroy negative number of matrices %" PetscInt_FMT, n);
7829:   PetscAssertPointer(mat, 2);

7831:   mat0 = (*mat)[0];
7832:   if (mat0 && mat0->ops->destroysubmatrices) {
7833:     PetscCall((*mat0->ops->destroysubmatrices)(n, mat));
7834:   } else {
7835:     PetscCall(MatDestroyMatrices(n, mat));
7836:   }
7837:   PetscFunctionReturn(PETSC_SUCCESS);
7838: }

7840: /*@
7841:   MatGetSeqNonzeroStructure - Extracts the nonzero structure from a matrix and stores it, in its entirety, on each process

7843:   Collective

7845:   Input Parameter:
7846: . mat - the matrix

7848:   Output Parameter:
7849: . matstruct - the sequential matrix with the nonzero structure of `mat`

7851:   Level: developer

7853: .seealso: [](ch_matrices), `Mat`, `MatDestroySeqNonzeroStructure()`, `MatCreateSubMatrices()`, `MatDestroyMatrices()`
7854: @*/
7855: PetscErrorCode MatGetSeqNonzeroStructure(Mat mat, Mat *matstruct)
7856: {
7857:   PetscFunctionBegin;
7859:   PetscAssertPointer(matstruct, 2);

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

7865:   PetscCall(PetscLogEventBegin(MAT_GetSeqNonzeroStructure, mat, 0, 0, 0));
7866:   PetscUseTypeMethod(mat, getseqnonzerostructure, matstruct);
7867:   PetscCall(PetscLogEventEnd(MAT_GetSeqNonzeroStructure, mat, 0, 0, 0));
7868:   PetscFunctionReturn(PETSC_SUCCESS);
7869: }

7871: /*@C
7872:   MatDestroySeqNonzeroStructure - Destroys matrix obtained with `MatGetSeqNonzeroStructure()`.

7874:   Collective

7876:   Input Parameter:
7877: . mat - the matrix

7879:   Level: advanced

7881:   Note:
7882:   This is not needed, one can just call `MatDestroy()`

7884: .seealso: [](ch_matrices), `Mat`, `MatGetSeqNonzeroStructure()`
7885: @*/
7886: PetscErrorCode MatDestroySeqNonzeroStructure(Mat *mat)
7887: {
7888:   PetscFunctionBegin;
7889:   PetscAssertPointer(mat, 1);
7890:   PetscCall(MatDestroy(mat));
7891:   PetscFunctionReturn(PETSC_SUCCESS);
7892: }

7894: /*@
7895:   MatIncreaseOverlap - Given a set of submatrices indicated by index sets,
7896:   replaces the index sets by larger ones that represent submatrices with
7897:   additional overlap.

7899:   Collective

7901:   Input Parameters:
7902: + mat - the matrix
7903: . n   - the number of index sets
7904: . is  - the array of index sets (these index sets will changed during the call)
7905: - ov  - the additional overlap requested

7907:   Options Database Key:
7908: . -mat_increase_overlap_scalable - use a scalable algorithm to compute the overlap (supported by MPIAIJ matrix)

7910:   Level: developer

7912:   Note:
7913:   The computed overlap preserves the matrix block sizes when the blocks are square.
7914:   That is: if a matrix nonzero for a given block would increase the overlap all columns associated with
7915:   that block are included in the overlap regardless of whether each specific column would increase the overlap.

7917: .seealso: [](ch_matrices), `Mat`, `PCASM`, `MatSetBlockSize()`, `MatIncreaseOverlapSplit()`, `MatCreateSubMatrices()`
7918: @*/
7919: PetscErrorCode MatIncreaseOverlap(Mat mat, PetscInt n, IS is[], PetscInt ov)
7920: {
7921:   PetscInt i, bs, cbs;

7923:   PetscFunctionBegin;
7927:   PetscCheck(n >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Must have one or more domains, you have %" PetscInt_FMT, n);
7928:   if (n) {
7929:     PetscAssertPointer(is, 3);
7931:   }
7932:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
7933:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
7934:   MatCheckPreallocated(mat, 1);

7936:   if (!ov || !n) PetscFunctionReturn(PETSC_SUCCESS);
7937:   PetscCall(PetscLogEventBegin(MAT_IncreaseOverlap, mat, 0, 0, 0));
7938:   PetscUseTypeMethod(mat, increaseoverlap, n, is, ov);
7939:   PetscCall(PetscLogEventEnd(MAT_IncreaseOverlap, mat, 0, 0, 0));
7940:   PetscCall(MatGetBlockSizes(mat, &bs, &cbs));
7941:   if (bs == cbs) {
7942:     for (i = 0; i < n; i++) PetscCall(ISSetBlockSize(is[i], bs));
7943:   }
7944:   PetscFunctionReturn(PETSC_SUCCESS);
7945: }

7947: PetscErrorCode MatIncreaseOverlapSplit_Single(Mat, IS *, PetscInt);

7949: /*@
7950:   MatIncreaseOverlapSplit - Given a set of submatrices indicated by index sets across
7951:   a sub communicator, replaces the index sets by larger ones that represent submatrices with
7952:   additional overlap.

7954:   Collective

7956:   Input Parameters:
7957: + mat - the matrix
7958: . n   - the number of index sets
7959: . is  - the array of index sets (these index sets will changed during the call)
7960: - ov  - the additional overlap requested

7962:   `   Options Database Key:
7963: . -mat_increase_overlap_scalable - use a scalable algorithm to compute the overlap (supported by MPIAIJ matrix)

7965:   Level: developer

7967: .seealso: [](ch_matrices), `Mat`, `MatCreateSubMatrices()`, `MatIncreaseOverlap()`
7968: @*/
7969: PetscErrorCode MatIncreaseOverlapSplit(Mat mat, PetscInt n, IS is[], PetscInt ov)
7970: {
7971:   PetscInt i;

7973:   PetscFunctionBegin;
7976:   PetscCheck(n >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Must have one or more domains, you have %" PetscInt_FMT, n);
7977:   if (n) {
7978:     PetscAssertPointer(is, 3);
7980:   }
7981:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
7982:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
7983:   MatCheckPreallocated(mat, 1);
7984:   if (!ov) PetscFunctionReturn(PETSC_SUCCESS);
7985:   PetscCall(PetscLogEventBegin(MAT_IncreaseOverlap, mat, 0, 0, 0));
7986:   for (i = 0; i < n; i++) PetscCall(MatIncreaseOverlapSplit_Single(mat, &is[i], ov));
7987:   PetscCall(PetscLogEventEnd(MAT_IncreaseOverlap, mat, 0, 0, 0));
7988:   PetscFunctionReturn(PETSC_SUCCESS);
7989: }

7991: /*@
7992:   MatGetBlockSize - Returns the matrix block size.

7994:   Not Collective

7996:   Input Parameter:
7997: . mat - the matrix

7999:   Output Parameter:
8000: . bs - block size

8002:   Level: intermediate

8004:   Notes:
8005:   Block row formats are `MATBAIJ` and `MATSBAIJ` ALWAYS have square block storage in the matrix.

8007:   If the block size has not been set yet this routine returns 1.

8009: .seealso: [](ch_matrices), `Mat`, `MATBAIJ`, `MATSBAIJ`, `MatCreateSeqBAIJ()`, `MatCreateBAIJ()`, `MatGetBlockSizes()`
8010: @*/
8011: PetscErrorCode MatGetBlockSize(Mat mat, PetscInt *bs)
8012: {
8013:   PetscFunctionBegin;
8015:   PetscAssertPointer(bs, 2);
8016:   *bs = mat->rmap->bs;
8017:   PetscFunctionReturn(PETSC_SUCCESS);
8018: }

8020: /*@
8021:   MatGetBlockSizes - Returns the matrix block row and column sizes.

8023:   Not Collective

8025:   Input Parameter:
8026: . mat - the matrix

8028:   Output Parameters:
8029: + rbs - row block size
8030: - cbs - column block size

8032:   Level: intermediate

8034:   Notes:
8035:   Block row formats are `MATBAIJ` and `MATSBAIJ` ALWAYS have square block storage in the matrix.
8036:   If you pass a different block size for the columns than the rows, the row block size determines the square block storage.

8038:   If a block size has not been set yet this routine returns 1.

8040: .seealso: [](ch_matrices), `Mat`, `MATBAIJ`, `MATSBAIJ`, `MatCreateSeqBAIJ()`, `MatCreateBAIJ()`, `MatGetBlockSize()`, `MatSetBlockSize()`, `MatSetBlockSizes()`
8041: @*/
8042: PetscErrorCode MatGetBlockSizes(Mat mat, PetscInt *rbs, PetscInt *cbs)
8043: {
8044:   PetscFunctionBegin;
8046:   if (rbs) PetscAssertPointer(rbs, 2);
8047:   if (cbs) PetscAssertPointer(cbs, 3);
8048:   if (rbs) *rbs = mat->rmap->bs;
8049:   if (cbs) *cbs = mat->cmap->bs;
8050:   PetscFunctionReturn(PETSC_SUCCESS);
8051: }

8053: /*@
8054:   MatSetBlockSize - Sets the matrix block size.

8056:   Logically Collective

8058:   Input Parameters:
8059: + mat - the matrix
8060: - bs  - block size

8062:   Level: intermediate

8064:   Notes:
8065:   Block row formats are `MATBAIJ` and `MATSBAIJ` formats ALWAYS have square block storage in the matrix.
8066:   This must be called before `MatSetUp()` or MatXXXSetPreallocation() (or will default to 1) and the block size cannot be changed later.

8068:   For `MATAIJ` matrix format, this function can be called at a later stage, provided that the specified block size
8069:   is compatible with the matrix local sizes.

8071: .seealso: [](ch_matrices), `Mat`, `MATBAIJ`, `MATSBAIJ`, `MATAIJ`, `MatCreateSeqBAIJ()`, `MatCreateBAIJ()`, `MatGetBlockSize()`, `MatSetBlockSizes()`, `MatGetBlockSizes()`
8072: @*/
8073: PetscErrorCode MatSetBlockSize(Mat mat, PetscInt bs)
8074: {
8075:   PetscFunctionBegin;
8078:   PetscCall(MatSetBlockSizes(mat, bs, bs));
8079:   PetscFunctionReturn(PETSC_SUCCESS);
8080: }

8082: typedef struct {
8083:   PetscInt         n;
8084:   IS              *is;
8085:   Mat             *mat;
8086:   PetscObjectState nonzerostate;
8087:   Mat              C;
8088: } EnvelopeData;

8090: static PetscErrorCode EnvelopeDataDestroy(PetscCtxRt ptr)
8091: {
8092:   EnvelopeData *edata = *(EnvelopeData **)ptr;

8094:   PetscFunctionBegin;
8095:   for (PetscInt i = 0; i < edata->n; i++) PetscCall(ISDestroy(&edata->is[i]));
8096:   PetscCall(PetscFree(edata->is));
8097:   PetscCall(PetscFree(edata));
8098:   PetscFunctionReturn(PETSC_SUCCESS);
8099: }

8101: /*@
8102:   MatComputeVariableBlockEnvelope - Given a matrix whose nonzeros are in blocks along the diagonal this computes and stores
8103:   the sizes of these blocks in the matrix. An individual block may lie over several processes.

8105:   Collective

8107:   Input Parameter:
8108: . mat - the matrix

8110:   Level: intermediate

8112:   Notes:
8113:   There can be zeros within the blocks

8115:   The blocks can overlap between processes, including laying on more than two processes

8117: .seealso: [](ch_matrices), `Mat`, `MatInvertVariableBlockEnvelope()`, `MatSetVariableBlockSizes()`
8118: @*/
8119: PetscErrorCode MatComputeVariableBlockEnvelope(Mat mat)
8120: {
8121:   PetscInt           n, *sizes, *starts, i = 0, env = 0, tbs = 0, lblocks = 0, rstart, II, ln = 0, cnt = 0, cstart, cend;
8122:   PetscInt          *diag, *odiag, sc;
8123:   VecScatter         scatter;
8124:   PetscScalar       *seqv;
8125:   const PetscScalar *parv;
8126:   const PetscInt    *ia, *ja;
8127:   PetscBool          set, flag, done;
8128:   Mat                AA = mat, A;
8129:   MPI_Comm           comm;
8130:   PetscMPIInt        rank, size, tag;
8131:   MPI_Status         status;
8132:   PetscContainer     container;
8133:   EnvelopeData      *edata;
8134:   Vec                seq, par;
8135:   IS                 isglobal;

8137:   PetscFunctionBegin;
8139:   PetscCall(MatIsSymmetricKnown(mat, &set, &flag));
8140:   if (!set || !flag) {
8141:     /* TODO: only needs nonzero structure of transpose */
8142:     PetscCall(MatTranspose(mat, MAT_INITIAL_MATRIX, &AA));
8143:     PetscCall(MatAXPY(AA, 1.0, mat, DIFFERENT_NONZERO_PATTERN));
8144:   }
8145:   PetscCall(MatAIJGetLocalMat(AA, &A));
8146:   PetscCall(MatGetRowIJ(A, 0, PETSC_FALSE, PETSC_FALSE, &n, &ia, &ja, &done));
8147:   PetscCheck(done, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "Unable to get IJ structure from matrix");

8149:   PetscCall(MatGetLocalSize(mat, &n, NULL));
8150:   PetscCall(PetscObjectGetNewTag((PetscObject)mat, &tag));
8151:   PetscCall(PetscObjectGetComm((PetscObject)mat, &comm));
8152:   PetscCallMPI(MPI_Comm_size(comm, &size));
8153:   PetscCallMPI(MPI_Comm_rank(comm, &rank));

8155:   PetscCall(PetscMalloc2(n, &sizes, n, &starts));

8157:   if (rank > 0) {
8158:     PetscCallMPI(MPI_Recv(&env, 1, MPIU_INT, rank - 1, tag, comm, &status));
8159:     PetscCallMPI(MPI_Recv(&tbs, 1, MPIU_INT, rank - 1, tag, comm, &status));
8160:   }
8161:   PetscCall(MatGetOwnershipRange(mat, &rstart, NULL));
8162:   for (i = 0; i < n; i++) {
8163:     env = PetscMax(env, ja[ia[i + 1] - 1]);
8164:     II  = rstart + i;
8165:     if (env == II) {
8166:       starts[lblocks]  = tbs;
8167:       sizes[lblocks++] = 1 + II - tbs;
8168:       tbs              = 1 + II;
8169:     }
8170:   }
8171:   if (rank < size - 1) {
8172:     PetscCallMPI(MPI_Send(&env, 1, MPIU_INT, rank + 1, tag, comm));
8173:     PetscCallMPI(MPI_Send(&tbs, 1, MPIU_INT, rank + 1, tag, comm));
8174:   }

8176:   PetscCall(MatRestoreRowIJ(A, 0, PETSC_FALSE, PETSC_FALSE, &n, &ia, &ja, &done));
8177:   if (!set || !flag) PetscCall(MatDestroy(&AA));
8178:   PetscCall(MatDestroy(&A));

8180:   PetscCall(PetscNew(&edata));
8181:   PetscCall(MatGetNonzeroState(mat, &edata->nonzerostate));
8182:   edata->n = lblocks;
8183:   /* create IS needed for extracting blocks from the original matrix */
8184:   PetscCall(PetscMalloc1(lblocks, &edata->is));
8185:   for (PetscInt i = 0; i < lblocks; i++) PetscCall(ISCreateStride(PETSC_COMM_SELF, sizes[i], starts[i], 1, &edata->is[i]));

8187:   /* Create the resulting inverse matrix nonzero structure with preallocation information */
8188:   PetscCall(MatCreate(PetscObjectComm((PetscObject)mat), &edata->C));
8189:   PetscCall(MatSetSizes(edata->C, mat->rmap->n, mat->cmap->n, mat->rmap->N, mat->cmap->N));
8190:   PetscCall(MatSetBlockSizesFromMats(edata->C, mat, mat));
8191:   PetscCall(MatSetType(edata->C, MATAIJ));

8193:   /* Communicate the start and end of each row, from each block to the correct rank */
8194:   /* TODO: Use PetscSF instead of VecScatter */
8195:   for (PetscInt i = 0; i < lblocks; i++) ln += sizes[i];
8196:   PetscCall(VecCreateSeq(PETSC_COMM_SELF, 2 * ln, &seq));
8197:   PetscCall(VecGetArrayWrite(seq, &seqv));
8198:   for (PetscInt i = 0; i < lblocks; i++) {
8199:     for (PetscInt j = 0; j < sizes[i]; j++) {
8200:       seqv[cnt]     = starts[i];
8201:       seqv[cnt + 1] = starts[i] + sizes[i];
8202:       cnt += 2;
8203:     }
8204:   }
8205:   PetscCall(VecRestoreArrayWrite(seq, &seqv));
8206:   PetscCallMPI(MPI_Scan(&cnt, &sc, 1, MPIU_INT, MPI_SUM, PetscObjectComm((PetscObject)mat)));
8207:   sc -= cnt;
8208:   PetscCall(VecCreateMPI(PetscObjectComm((PetscObject)mat), 2 * mat->rmap->n, 2 * mat->rmap->N, &par));
8209:   PetscCall(ISCreateStride(PETSC_COMM_SELF, cnt, sc, 1, &isglobal));
8210:   PetscCall(VecScatterCreate(seq, NULL, par, isglobal, &scatter));
8211:   PetscCall(ISDestroy(&isglobal));
8212:   PetscCall(VecScatterBegin(scatter, seq, par, INSERT_VALUES, SCATTER_FORWARD));
8213:   PetscCall(VecScatterEnd(scatter, seq, par, INSERT_VALUES, SCATTER_FORWARD));
8214:   PetscCall(VecScatterDestroy(&scatter));
8215:   PetscCall(VecDestroy(&seq));
8216:   PetscCall(MatGetOwnershipRangeColumn(mat, &cstart, &cend));
8217:   PetscCall(PetscMalloc2(mat->rmap->n, &diag, mat->rmap->n, &odiag));
8218:   PetscCall(VecGetArrayRead(par, &parv));
8219:   cnt = 0;
8220:   PetscCall(MatGetSize(mat, NULL, &n));
8221:   for (PetscInt i = 0; i < mat->rmap->n; i++) {
8222:     PetscInt start, end, d = 0, od = 0;

8224:     start = (PetscInt)PetscRealPart(parv[cnt]);
8225:     end   = (PetscInt)PetscRealPart(parv[cnt + 1]);
8226:     cnt += 2;

8228:     if (start < cstart) {
8229:       od += cstart - start + n - cend;
8230:       d += cend - cstart;
8231:     } else if (start < cend) {
8232:       od += n - cend;
8233:       d += cend - start;
8234:     } else od += n - start;
8235:     if (end <= cstart) {
8236:       od -= cstart - end + n - cend;
8237:       d -= cend - cstart;
8238:     } else if (end < cend) {
8239:       od -= n - cend;
8240:       d -= cend - end;
8241:     } else od -= n - end;

8243:     odiag[i] = od;
8244:     diag[i]  = d;
8245:   }
8246:   PetscCall(VecRestoreArrayRead(par, &parv));
8247:   PetscCall(VecDestroy(&par));
8248:   PetscCall(MatXAIJSetPreallocation(edata->C, mat->rmap->bs, diag, odiag, NULL, NULL));
8249:   PetscCall(PetscFree2(diag, odiag));
8250:   PetscCall(PetscFree2(sizes, starts));

8252:   PetscCall(PetscContainerCreate(PETSC_COMM_SELF, &container));
8253:   PetscCall(PetscContainerSetPointer(container, edata));
8254:   PetscCall(PetscContainerSetCtxDestroy(container, EnvelopeDataDestroy));
8255:   PetscCall(PetscObjectCompose((PetscObject)mat, "EnvelopeData", (PetscObject)container));
8256:   PetscCall(PetscObjectDereference((PetscObject)container));
8257:   PetscFunctionReturn(PETSC_SUCCESS);
8258: }

8260: /*@
8261:   MatInvertVariableBlockEnvelope - set matrix C to be the inverted block diagonal of matrix A

8263:   Collective

8265:   Input Parameters:
8266: + A     - the matrix
8267: - reuse - indicates if the `C` matrix was obtained from a previous call to this routine

8269:   Output Parameter:
8270: . C - matrix with inverted block diagonal of `A`

8272:   Level: advanced

8274:   Note:
8275:   For efficiency the matrix `A` should have all the nonzero entries clustered in smallish blocks along the diagonal.

8277: .seealso: [](ch_matrices), `Mat`, `MatInvertBlockDiagonal()`, `MatComputeBlockDiagonal()`
8278: @*/
8279: PetscErrorCode MatInvertVariableBlockEnvelope(Mat A, MatReuse reuse, Mat *C)
8280: {
8281:   PetscContainer   container;
8282:   EnvelopeData    *edata;
8283:   PetscObjectState nonzerostate;

8285:   PetscFunctionBegin;
8286:   PetscCall(PetscObjectQuery((PetscObject)A, "EnvelopeData", (PetscObject *)&container));
8287:   if (!container) {
8288:     PetscCall(MatComputeVariableBlockEnvelope(A));
8289:     PetscCall(PetscObjectQuery((PetscObject)A, "EnvelopeData", (PetscObject *)&container));
8290:   }
8291:   PetscCall(PetscContainerGetPointer(container, &edata));
8292:   PetscCall(MatGetNonzeroState(A, &nonzerostate));
8293:   PetscCheck(nonzerostate <= edata->nonzerostate, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "Cannot handle changes to matrix nonzero structure");
8294:   PetscCheck(reuse != MAT_REUSE_MATRIX || *C == edata->C, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "C matrix must be the same as previously output");

8296:   PetscCall(MatCreateSubMatrices(A, edata->n, edata->is, edata->is, MAT_INITIAL_MATRIX, &edata->mat));
8297:   *C = edata->C;

8299:   for (PetscInt i = 0; i < edata->n; i++) {
8300:     Mat          D;
8301:     PetscScalar *dvalues;

8303:     PetscCall(MatConvert(edata->mat[i], MATSEQDENSE, MAT_INITIAL_MATRIX, &D));
8304:     PetscCall(MatSetOption(*C, MAT_ROW_ORIENTED, PETSC_FALSE));
8305:     PetscCall(MatSeqDenseInvert(D));
8306:     PetscCall(MatDenseGetArray(D, &dvalues));
8307:     PetscCall(MatSetValuesIS(*C, edata->is[i], edata->is[i], dvalues, INSERT_VALUES));
8308:     PetscCall(MatDestroy(&D));
8309:   }
8310:   PetscCall(MatDestroySubMatrices(edata->n, &edata->mat));
8311:   PetscCall(MatAssemblyBegin(*C, MAT_FINAL_ASSEMBLY));
8312:   PetscCall(MatAssemblyEnd(*C, MAT_FINAL_ASSEMBLY));
8313:   PetscFunctionReturn(PETSC_SUCCESS);
8314: }

8316: /*@
8317:   MatSetVariableBlockSizes - Sets diagonal point-blocks of the matrix that need not be of the same size

8319:   Not Collective

8321:   Input Parameters:
8322: + mat     - the matrix
8323: . nblocks - the number of blocks on this process, each block can only exist on a single process
8324: - bsizes  - the block sizes

8326:   Level: intermediate

8328:   Notes:
8329:   Currently used by `PCVPBJACOBI` for `MATAIJ` matrices

8331:   Each variable point-block set of degrees of freedom must live on a single MPI process. That is a point block cannot straddle two MPI processes.

8333: .seealso: [](ch_matrices), `Mat`, `MatCreateSeqBAIJ()`, `MatCreateBAIJ()`, `MatGetBlockSize()`, `MatSetBlockSizes()`, `MatGetBlockSizes()`, `MatGetVariableBlockSizes()`,
8334:           `MatComputeVariableBlockEnvelope()`, `PCVPBJACOBI`
8335: @*/
8336: PetscErrorCode MatSetVariableBlockSizes(Mat mat, PetscInt nblocks, const PetscInt bsizes[])
8337: {
8338:   PetscInt ncnt = 0, nlocal;

8340:   PetscFunctionBegin;
8342:   PetscCall(MatGetLocalSize(mat, &nlocal, NULL));
8343:   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);
8344:   for (PetscInt i = 0; i < nblocks; i++) ncnt += bsizes[i];
8345:   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);
8346:   PetscCall(PetscFree(mat->bsizes));
8347:   mat->nblocks = nblocks;
8348:   PetscCall(PetscMalloc1(nblocks, &mat->bsizes));
8349:   PetscCall(PetscArraycpy(mat->bsizes, bsizes, nblocks));
8350:   PetscFunctionReturn(PETSC_SUCCESS);
8351: }

8353: /*@C
8354:   MatGetVariableBlockSizes - Gets a diagonal blocks of the matrix that need not be of the same size

8356:   Not Collective; No Fortran Support

8358:   Input Parameter:
8359: . mat - the matrix

8361:   Output Parameters:
8362: + nblocks - the number of blocks on this process
8363: - bsizes  - the block sizes

8365:   Level: intermediate

8367: .seealso: [](ch_matrices), `Mat`, `MatCreateSeqBAIJ()`, `MatCreateBAIJ()`, `MatGetBlockSize()`, `MatSetBlockSizes()`, `MatGetBlockSizes()`, `MatSetVariableBlockSizes()`, `MatComputeVariableBlockEnvelope()`
8368: @*/
8369: PetscErrorCode MatGetVariableBlockSizes(Mat mat, PetscInt *nblocks, const PetscInt *bsizes[])
8370: {
8371:   PetscFunctionBegin;
8373:   if (nblocks) *nblocks = mat->nblocks;
8374:   if (bsizes) *bsizes = mat->bsizes;
8375:   PetscFunctionReturn(PETSC_SUCCESS);
8376: }

8378: /*@
8379:   MatSelectVariableBlockSizes - When creating a submatrix, pass on the variable block sizes

8381:   Not Collective

8383:   Input Parameter:
8384: + subA  - the submatrix
8385: . A     - the original matrix
8386: - isrow - The `IS` of selected rows for the submatrix, must be sorted

8388:   Level: developer

8390:   Notes:
8391:   If the index set is not sorted or contains off-process entries, this function will do nothing.

8393: .seealso: [](ch_matrices), `Mat`, `MatSetVariableBlockSizes()`, `MatComputeVariableBlockEnvelope()`
8394: @*/
8395: PetscErrorCode MatSelectVariableBlockSizes(Mat subA, Mat A, IS isrow)
8396: {
8397:   const PetscInt *rows;
8398:   PetscInt        n, rStart, rEnd, Nb = 0;
8399:   PetscBool       flg = A->bsizes ? PETSC_TRUE : PETSC_FALSE;

8401:   PetscFunctionBegin;
8402:   // The code for block size extraction does not support an unsorted IS
8403:   if (flg) PetscCall(ISSorted(isrow, &flg));
8404:   // We don't support originally off-diagonal blocks
8405:   if (flg) {
8406:     PetscCall(MatGetOwnershipRange(A, &rStart, &rEnd));
8407:     PetscCall(ISGetLocalSize(isrow, &n));
8408:     PetscCall(ISGetIndices(isrow, &rows));
8409:     for (PetscInt i = 0; i < n && flg; ++i) {
8410:       if (rows[i] < rStart || rows[i] >= rEnd) flg = PETSC_FALSE;
8411:     }
8412:     PetscCall(ISRestoreIndices(isrow, &rows));
8413:   }
8414:   // quiet return if we can't extract block size
8415:   PetscCallMPI(MPIU_Allreduce(MPI_IN_PLACE, &flg, 1, MPI_C_BOOL, MPI_LAND, PetscObjectComm((PetscObject)subA)));
8416:   if (!flg) PetscFunctionReturn(PETSC_SUCCESS);

8418:   // extract block sizes
8419:   PetscCall(ISGetIndices(isrow, &rows));
8420:   for (PetscInt b = 0, gr = rStart, i = 0; b < A->nblocks; ++b) {
8421:     PetscBool occupied = PETSC_FALSE;

8423:     for (PetscInt br = 0; br < A->bsizes[b]; ++br) {
8424:       const PetscInt row = gr + br;

8426:       if (i == n) break;
8427:       if (rows[i] == row) {
8428:         occupied = PETSC_TRUE;
8429:         ++i;
8430:       }
8431:       while (i < n && rows[i] < row) ++i;
8432:     }
8433:     gr += A->bsizes[b];
8434:     if (occupied) ++Nb;
8435:   }
8436:   subA->nblocks = Nb;
8437:   PetscCall(PetscFree(subA->bsizes));
8438:   PetscCall(PetscMalloc1(subA->nblocks, &subA->bsizes));
8439:   PetscInt sb = 0;
8440:   for (PetscInt b = 0, gr = rStart, i = 0; b < A->nblocks; ++b) {
8441:     if (sb < subA->nblocks) subA->bsizes[sb] = 0;
8442:     for (PetscInt br = 0; br < A->bsizes[b]; ++br) {
8443:       const PetscInt row = gr + br;

8445:       if (i == n) break;
8446:       if (rows[i] == row) {
8447:         ++subA->bsizes[sb];
8448:         ++i;
8449:       }
8450:       while (i < n && rows[i] < row) ++i;
8451:     }
8452:     gr += A->bsizes[b];
8453:     if (sb < subA->nblocks && subA->bsizes[sb]) ++sb;
8454:   }
8455:   PetscCheck(sb == subA->nblocks, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Invalid number of blocks %" PetscInt_FMT " != %" PetscInt_FMT, sb, subA->nblocks);
8456:   PetscInt nlocal, ncnt = 0;
8457:   PetscCall(MatGetLocalSize(subA, &nlocal, NULL));
8458:   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);
8459:   for (PetscInt i = 0; i < subA->nblocks; i++) ncnt += subA->bsizes[i];
8460:   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);
8461:   PetscCall(ISRestoreIndices(isrow, &rows));
8462:   PetscFunctionReturn(PETSC_SUCCESS);
8463: }

8465: /*@
8466:   MatSetBlockSizes - Sets the matrix block row and column sizes.

8468:   Logically Collective

8470:   Input Parameters:
8471: + mat - the matrix
8472: . rbs - row block size
8473: - cbs - column block size

8475:   Level: intermediate

8477:   Notes:
8478:   Block row formats are `MATBAIJ` and  `MATSBAIJ`. These formats ALWAYS have square block storage in the matrix.
8479:   If you pass a different block size for the columns than the rows, the row block size determines the square block storage.
8480:   This must be called before `MatSetUp()` or MatXXXSetPreallocation() (or will default to 1) and the block size cannot be changed later.

8482:   For `MATAIJ` matrix this function can be called at a later stage, provided that the specified block sizes
8483:   are compatible with the matrix local sizes.

8485:   The row and column block size determine the blocksize of the "row" and "column" vectors returned by `MatCreateVecs()`.

8487: .seealso: [](ch_matrices), `Mat`, `MatCreateSeqBAIJ()`, `MatCreateBAIJ()`, `MatGetBlockSize()`, `MatSetBlockSize()`, `MatGetBlockSizes()`
8488: @*/
8489: PetscErrorCode MatSetBlockSizes(Mat mat, PetscInt rbs, PetscInt cbs)
8490: {
8491:   PetscFunctionBegin;
8495:   PetscTryTypeMethod(mat, setblocksizes, rbs, cbs);
8496:   if (mat->rmap->refcnt) {
8497:     ISLocalToGlobalMapping l2g  = NULL;
8498:     PetscLayout            nmap = NULL;

8500:     PetscCall(PetscLayoutDuplicate(mat->rmap, &nmap));
8501:     if (mat->rmap->mapping) PetscCall(ISLocalToGlobalMappingDuplicate(mat->rmap->mapping, &l2g));
8502:     PetscCall(PetscLayoutDestroy(&mat->rmap));
8503:     mat->rmap          = nmap;
8504:     mat->rmap->mapping = l2g;
8505:   }
8506:   if (mat->cmap->refcnt) {
8507:     ISLocalToGlobalMapping l2g  = NULL;
8508:     PetscLayout            nmap = NULL;

8510:     PetscCall(PetscLayoutDuplicate(mat->cmap, &nmap));
8511:     if (mat->cmap->mapping) PetscCall(ISLocalToGlobalMappingDuplicate(mat->cmap->mapping, &l2g));
8512:     PetscCall(PetscLayoutDestroy(&mat->cmap));
8513:     mat->cmap          = nmap;
8514:     mat->cmap->mapping = l2g;
8515:   }
8516:   PetscCall(PetscLayoutSetBlockSize(mat->rmap, rbs));
8517:   PetscCall(PetscLayoutSetBlockSize(mat->cmap, cbs));
8518:   PetscFunctionReturn(PETSC_SUCCESS);
8519: }

8521: /*@
8522:   MatSetBlockSizesFromMats - Sets the matrix block row and column sizes to match a pair of matrices

8524:   Logically Collective

8526:   Input Parameters:
8527: + mat     - the matrix
8528: . fromRow - matrix from which to copy row block size
8529: - fromCol - matrix from which to copy column block size (can be same as `fromRow`)

8531:   Level: developer

8533: .seealso: [](ch_matrices), `Mat`, `MatCreateSeqBAIJ()`, `MatCreateBAIJ()`, `MatGetBlockSize()`, `MatSetBlockSizes()`
8534: @*/
8535: PetscErrorCode MatSetBlockSizesFromMats(Mat mat, Mat fromRow, Mat fromCol)
8536: {
8537:   PetscFunctionBegin;
8541:   PetscTryTypeMethod(mat, setblocksizes, fromRow->rmap->bs, fromCol->cmap->bs);
8542:   PetscCall(PetscLayoutSetBlockSize(mat->rmap, fromRow->rmap->bs));
8543:   PetscCall(PetscLayoutSetBlockSize(mat->cmap, fromCol->cmap->bs));
8544:   PetscFunctionReturn(PETSC_SUCCESS);
8545: }

8547: /*@
8548:   MatResidual - Default routine to calculate the residual r = b - Ax

8550:   Collective

8552:   Input Parameters:
8553: + mat - the matrix
8554: . b   - the right-hand-side
8555: - x   - the approximate solution

8557:   Output Parameter:
8558: . r - location to store the residual

8560:   Level: developer

8562: .seealso: [](ch_matrices), `Mat`, `MatMult()`, `MatMultAdd()`, `PCMGSetResidual()`
8563: @*/
8564: PetscErrorCode MatResidual(Mat mat, Vec b, Vec x, Vec r)
8565: {
8566:   PetscFunctionBegin;
8572:   MatCheckPreallocated(mat, 1);
8573:   PetscCall(PetscLogEventBegin(MAT_Residual, mat, 0, 0, 0));
8574:   if (!mat->ops->residual) {
8575:     PetscCall(MatMult(mat, x, r));
8576:     PetscCall(VecAYPX(r, -1.0, b));
8577:   } else {
8578:     PetscUseTypeMethod(mat, residual, b, x, r);
8579:   }
8580:   PetscCall(PetscLogEventEnd(MAT_Residual, mat, 0, 0, 0));
8581:   PetscFunctionReturn(PETSC_SUCCESS);
8582: }

8584: /*@C
8585:   MatGetRowIJ - Returns the compressed row storage i and j indices for the local rows of a sparse matrix

8587:   Collective

8589:   Input Parameters:
8590: + mat             - the matrix
8591: . shift           - 0 or 1 indicating we want the indices starting at 0 or 1
8592: . symmetric       - `PETSC_TRUE` or `PETSC_FALSE` indicating the matrix data structure should be symmetrized
8593: - inodecompressed - `PETSC_TRUE` or `PETSC_FALSE`  indicating if the nonzero structure of the
8594:                  inodes or the nonzero elements is wanted. For `MATBAIJ` matrices the compressed version is
8595:                  always used.

8597:   Output Parameters:
8598: + n    - number of local rows in the (possibly compressed) matrix, use `NULL` if not needed
8599: . 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
8600: . ja   - the column indices, use `NULL` if not needed
8601: - done - indicates if the routine actually worked and returned appropriate ia[] and ja[] arrays; callers
8602:            are responsible for handling the case when done == `PETSC_FALSE` and ia and ja are not set

8604:   Level: developer

8606:   Notes:
8607:   You CANNOT change any of the ia[] or ja[] values.

8609:   Use `MatRestoreRowIJ()` when you are finished accessing the ia[] and ja[] values.

8611:   Fortran Notes:
8612:   Use
8613: .vb
8614:     PetscInt, pointer :: ia(:),ja(:)
8615:     call MatGetRowIJ(mat,shift,symmetric,inodecompressed,n,ia,ja,done,ierr)
8616:     ! Access the ith and jth entries via ia(i) and ja(j)
8617: .ve

8619: .seealso: [](ch_matrices), `Mat`, `MATAIJ`, `MatGetColumnIJ()`, `MatRestoreRowIJ()`, `MatSeqAIJGetArray()`
8620: @*/
8621: PetscErrorCode MatGetRowIJ(Mat mat, PetscInt shift, PetscBool symmetric, PetscBool inodecompressed, PetscInt *n, const PetscInt *ia[], const PetscInt *ja[], PetscBool *done)
8622: {
8623:   PetscFunctionBegin;
8626:   if (n) PetscAssertPointer(n, 5);
8627:   if (ia) PetscAssertPointer(ia, 6);
8628:   if (ja) PetscAssertPointer(ja, 7);
8629:   if (done) PetscAssertPointer(done, 8);
8630:   MatCheckPreallocated(mat, 1);
8631:   if (!mat->ops->getrowij && done) *done = PETSC_FALSE;
8632:   else {
8633:     if (done) *done = PETSC_TRUE;
8634:     PetscCall(PetscLogEventBegin(MAT_GetRowIJ, mat, 0, 0, 0));
8635:     PetscUseTypeMethod(mat, getrowij, shift, symmetric, inodecompressed, n, ia, ja, done);
8636:     PetscCall(PetscLogEventEnd(MAT_GetRowIJ, mat, 0, 0, 0));
8637:   }
8638:   PetscFunctionReturn(PETSC_SUCCESS);
8639: }

8641: /*@C
8642:   MatGetColumnIJ - Returns the compressed column storage i and j indices for sequential matrices.

8644:   Collective

8646:   Input Parameters:
8647: + mat             - the matrix
8648: . shift           - 1 or zero indicating we want the indices starting at 0 or 1
8649: . symmetric       - `PETSC_TRUE` or `PETSC_FALSE` indicating the matrix data structure should be
8650:                 symmetrized
8651: - inodecompressed - `PETSC_TRUE` or `PETSC_FALSE` indicating if the nonzero structure of the
8652:                  inodes or the nonzero elements is wanted. For `MATBAIJ` matrices the compressed version is
8653:                  always used.

8655:   Output Parameters:
8656: + n    - number of columns in the (possibly compressed) matrix
8657: . ia   - the column pointers; that is ia[0] = 0, ia[col] = i[col-1] + number of elements in that col of the matrix
8658: . ja   - the row indices
8659: - done - `PETSC_TRUE` or `PETSC_FALSE`, indicating whether the values have been returned

8661:   Level: developer

8663: .seealso: [](ch_matrices), `Mat`, `MatGetRowIJ()`, `MatRestoreColumnIJ()`
8664: @*/
8665: PetscErrorCode MatGetColumnIJ(Mat mat, PetscInt shift, PetscBool symmetric, PetscBool inodecompressed, PetscInt *n, const PetscInt *ia[], const PetscInt *ja[], PetscBool *done)
8666: {
8667:   PetscFunctionBegin;
8670:   PetscAssertPointer(n, 5);
8671:   if (ia) PetscAssertPointer(ia, 6);
8672:   if (ja) PetscAssertPointer(ja, 7);
8673:   PetscAssertPointer(done, 8);
8674:   MatCheckPreallocated(mat, 1);
8675:   if (!mat->ops->getcolumnij) *done = PETSC_FALSE;
8676:   else {
8677:     *done = PETSC_TRUE;
8678:     PetscUseTypeMethod(mat, getcolumnij, shift, symmetric, inodecompressed, n, ia, ja, done);
8679:   }
8680:   PetscFunctionReturn(PETSC_SUCCESS);
8681: }

8683: /*@C
8684:   MatRestoreRowIJ - Call after you are completed with the ia,ja indices obtained with `MatGetRowIJ()`.

8686:   Collective

8688:   Input Parameters:
8689: + mat             - the matrix
8690: . shift           - 1 or zero indicating we want the indices starting at 0 or 1
8691: . symmetric       - `PETSC_TRUE` or `PETSC_FALSE` indicating the matrix data structure should be symmetrized
8692: . inodecompressed - `PETSC_TRUE` or `PETSC_FALSE` indicating if the nonzero structure of the
8693:                     inodes or the nonzero elements is wanted. For `MATBAIJ` matrices the compressed version is
8694:                     always used.
8695: . n               - size of (possibly compressed) matrix
8696: . ia              - the row pointers
8697: - ja              - the column indices

8699:   Output Parameter:
8700: . done - `PETSC_TRUE` or `PETSC_FALSE` indicated that the values have been returned

8702:   Level: developer

8704:   Note:
8705:   This routine zeros out `n`, `ia`, and `ja`. This is to prevent accidental
8706:   us of the array after it has been restored. If you pass `NULL`, it will
8707:   not zero the pointers.  Use of ia or ja after `MatRestoreRowIJ()` is invalid.

8709: .seealso: [](ch_matrices), `Mat`, `MatGetRowIJ()`, `MatRestoreColumnIJ()`
8710: @*/
8711: PetscErrorCode MatRestoreRowIJ(Mat mat, PetscInt shift, PetscBool symmetric, PetscBool inodecompressed, PetscInt *n, const PetscInt *ia[], const PetscInt *ja[], PetscBool *done)
8712: {
8713:   PetscFunctionBegin;
8716:   if (ia) PetscAssertPointer(ia, 6);
8717:   if (ja) PetscAssertPointer(ja, 7);
8718:   if (done) PetscAssertPointer(done, 8);
8719:   MatCheckPreallocated(mat, 1);

8721:   if (!mat->ops->restorerowij && done) *done = PETSC_FALSE;
8722:   else {
8723:     if (done) *done = PETSC_TRUE;
8724:     PetscUseTypeMethod(mat, restorerowij, shift, symmetric, inodecompressed, n, ia, ja, done);
8725:     if (n) *n = 0;
8726:     if (ia) *ia = NULL;
8727:     if (ja) *ja = NULL;
8728:   }
8729:   PetscFunctionReturn(PETSC_SUCCESS);
8730: }

8732: /*@C
8733:   MatRestoreColumnIJ - Call after you are completed with the ia,ja indices obtained with `MatGetColumnIJ()`.

8735:   Collective

8737:   Input Parameters:
8738: + mat             - the matrix
8739: . shift           - 1 or zero indicating we want the indices starting at 0 or 1
8740: . symmetric       - `PETSC_TRUE` or `PETSC_FALSE` indicating the matrix data structure should be symmetrized
8741: - inodecompressed - `PETSC_TRUE` or `PETSC_FALSE` indicating if the nonzero structure of the
8742:                     inodes or the nonzero elements is wanted. For `MATBAIJ` matrices the compressed version is
8743:                     always used.

8745:   Output Parameters:
8746: + n    - size of (possibly compressed) matrix
8747: . ia   - the column pointers
8748: . ja   - the row indices
8749: - done - `PETSC_TRUE` or `PETSC_FALSE` indicated that the values have been returned

8751:   Level: developer

8753: .seealso: [](ch_matrices), `Mat`, `MatGetColumnIJ()`, `MatRestoreRowIJ()`
8754: @*/
8755: PetscErrorCode MatRestoreColumnIJ(Mat mat, PetscInt shift, PetscBool symmetric, PetscBool inodecompressed, PetscInt *n, const PetscInt *ia[], const PetscInt *ja[], PetscBool *done)
8756: {
8757:   PetscFunctionBegin;
8760:   if (ia) PetscAssertPointer(ia, 6);
8761:   if (ja) PetscAssertPointer(ja, 7);
8762:   PetscAssertPointer(done, 8);
8763:   MatCheckPreallocated(mat, 1);

8765:   if (!mat->ops->restorecolumnij) *done = PETSC_FALSE;
8766:   else {
8767:     *done = PETSC_TRUE;
8768:     PetscUseTypeMethod(mat, restorecolumnij, shift, symmetric, inodecompressed, n, ia, ja, done);
8769:     if (n) *n = 0;
8770:     if (ia) *ia = NULL;
8771:     if (ja) *ja = NULL;
8772:   }
8773:   PetscFunctionReturn(PETSC_SUCCESS);
8774: }

8776: /*@
8777:   MatColoringPatch - Used inside matrix coloring routines that use `MatGetRowIJ()` and/or
8778:   `MatGetColumnIJ()`.

8780:   Collective

8782:   Input Parameters:
8783: + mat        - the matrix
8784: . ncolors    - maximum color value
8785: . n          - number of entries in colorarray
8786: - colorarray - array indicating color for each column

8788:   Output Parameter:
8789: . iscoloring - coloring generated using colorarray information

8791:   Level: developer

8793: .seealso: [](ch_matrices), `Mat`, `MatGetRowIJ()`, `MatGetColumnIJ()`
8794: @*/
8795: PetscErrorCode MatColoringPatch(Mat mat, PetscInt ncolors, PetscInt n, ISColoringValue colorarray[], ISColoring *iscoloring)
8796: {
8797:   PetscFunctionBegin;
8800:   PetscAssertPointer(colorarray, 4);
8801:   PetscAssertPointer(iscoloring, 5);
8802:   MatCheckPreallocated(mat, 1);

8804:   if (!mat->ops->coloringpatch) {
8805:     PetscCall(ISColoringCreate(PetscObjectComm((PetscObject)mat), ncolors, n, colorarray, PETSC_OWN_POINTER, iscoloring));
8806:   } else {
8807:     PetscUseTypeMethod(mat, coloringpatch, ncolors, n, colorarray, iscoloring);
8808:   }
8809:   PetscFunctionReturn(PETSC_SUCCESS);
8810: }

8812: /*@
8813:   MatSetUnfactored - Resets a factored matrix to be treated as unfactored.

8815:   Logically Collective

8817:   Input Parameter:
8818: . mat - the factored matrix to be reset

8820:   Level: developer

8822:   Notes:
8823:   This routine should be used only with factored matrices formed by in-place
8824:   factorization via ILU(0) (or by in-place LU factorization for the `MATSEQDENSE`
8825:   format).  This option can save memory, for example, when solving nonlinear
8826:   systems with a matrix-free Newton-Krylov method and a matrix-based, in-place
8827:   ILU(0) preconditioner.

8829:   One can specify in-place ILU(0) factorization by calling
8830: .vb
8831:      PCType(pc,PCILU);
8832:      PCFactorSeUseInPlace(pc);
8833: .ve
8834:   or by using the options -pc_type ilu -pc_factor_in_place

8836:   In-place factorization ILU(0) can also be used as a local
8837:   solver for the blocks within the block Jacobi or additive Schwarz
8838:   methods (runtime option: -sub_pc_factor_in_place).  See Users-Manual: ch_pc
8839:   for details on setting local solver options.

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

8845: .seealso: [](ch_matrices), `Mat`, `PCFactorSetUseInPlace()`, `PCFactorGetUseInPlace()`
8846: @*/
8847: PetscErrorCode MatSetUnfactored(Mat mat)
8848: {
8849:   PetscFunctionBegin;
8852:   MatCheckPreallocated(mat, 1);
8853:   mat->factortype = MAT_FACTOR_NONE;
8854:   if (!mat->ops->setunfactored) PetscFunctionReturn(PETSC_SUCCESS);
8855:   PetscUseTypeMethod(mat, setunfactored);
8856:   PetscFunctionReturn(PETSC_SUCCESS);
8857: }

8859: /*@
8860:   MatCreateSubMatrix - Gets a single submatrix on the same number of processors
8861:   as the original matrix.

8863:   Collective

8865:   Input Parameters:
8866: + mat   - the original matrix
8867: . isrow - parallel `IS` containing the rows this processor should obtain
8868: . 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.
8869: - cll   - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`

8871:   Output Parameter:
8872: . newmat - the new submatrix, of the same type as the original matrix

8874:   Level: advanced

8876:   Notes:
8877:   The submatrix will be able to be multiplied with vectors using the same layout as `iscol`.

8879:   Some matrix types place restrictions on the row and column indices, such
8880:   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;
8881:   for example, if the block size is 3 one cannot select the 0 and 2 rows without selecting the 1 row.

8883:   The index sets may not have duplicate entries.

8885:   The first time this is called you should use a `cll` of `MAT_INITIAL_MATRIX`,
8886:   the `MatCreateSubMatrix()` routine will create the newmat for you. Any additional calls
8887:   to this routine with a mat of the same nonzero structure and with a call of `MAT_REUSE_MATRIX`
8888:   will reuse the matrix generated the first time.  You should call `MatDestroy()` on `newmat` when
8889:   you are finished using it.

8891:   The communicator of the newly obtained matrix is ALWAYS the same as the communicator of
8892:   the input matrix.

8894:   If `iscol` is `NULL` then all columns are obtained (not supported in Fortran).

8896:   If `isrow` and `iscol` have a nontrivial block-size, then the resulting matrix has this block-size as well. This feature
8897:   is used by `PCFIELDSPLIT` to allow easy nesting of its use.

8899:   Example usage:
8900:   Consider the following 8x8 matrix with 34 non-zero values, that is
8901:   assembled across 3 processors. Let's assume that proc0 owns 3 rows,
8902:   proc1 owns 3 rows, proc2 owns 2 rows. This division can be shown
8903:   as follows
8904: .vb
8905:             1  2  0  |  0  3  0  |  0  4
8906:     Proc0   0  5  6  |  7  0  0  |  8  0
8907:             9  0 10  | 11  0  0  | 12  0
8908:     -------------------------------------
8909:            13  0 14  | 15 16 17  |  0  0
8910:     Proc1   0 18  0  | 19 20 21  |  0  0
8911:             0  0  0  | 22 23  0  | 24  0
8912:     -------------------------------------
8913:     Proc2  25 26 27  |  0  0 28  | 29  0
8914:            30  0  0  | 31 32 33  |  0 34
8915: .ve

8917:   Suppose `isrow` = [0 1 | 4 | 6 7] and `iscol` = [1 2 | 3 4 5 | 6].  The resulting submatrix is

8919: .vb
8920:             2  0  |  0  3  0  |  0
8921:     Proc0   5  6  |  7  0  0  |  8
8922:     -------------------------------
8923:     Proc1  18  0  | 19 20 21  |  0
8924:     -------------------------------
8925:     Proc2  26 27  |  0  0 28  | 29
8926:             0  0  | 31 32 33  |  0
8927: .ve

8929: .seealso: [](ch_matrices), `Mat`, `MatCreateSubMatrices()`, `MatCreateSubMatricesMPI()`, `MatCreateSubMatrixVirtual()`, `MatSubMatrixVirtualUpdate()`
8930: @*/
8931: PetscErrorCode MatCreateSubMatrix(Mat mat, IS isrow, IS iscol, MatReuse cll, Mat *newmat)
8932: {
8933:   PetscMPIInt size;
8934:   Mat        *local;
8935:   IS          iscoltmp;
8936:   PetscBool   flg;

8938:   PetscFunctionBegin;
8942:   PetscAssertPointer(newmat, 5);
8945:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
8946:   PetscCheck(cll != MAT_IGNORE_MATRIX, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Cannot use MAT_IGNORE_MATRIX");
8947:   PetscCheck(cll != MAT_INPLACE_MATRIX, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Cannot use MAT_INPLACE_MATRIX");

8949:   MatCheckPreallocated(mat, 1);
8950:   PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)mat), &size));

8952:   if (!iscol || isrow == iscol) {
8953:     PetscBool   stride;
8954:     PetscMPIInt grab = 0;
8955:     PetscCall(PetscObjectTypeCompare((PetscObject)isrow, ISSTRIDE, &stride));
8956:     if (stride) {
8957:       PetscInt first, step, n, rstart, rend;
8958:       PetscCall(ISStrideGetInfo(isrow, &first, &step));
8959:       if (step == 1) {
8960:         PetscCall(MatGetOwnershipRange(mat, &rstart, &rend));
8961:         if (rstart == first) {
8962:           PetscCall(ISGetLocalSize(isrow, &n));
8963:           if (n == rend - rstart) grab = 1;
8964:         }
8965:       }
8966:     }
8967:     PetscCallMPI(MPIU_Allreduce(MPI_IN_PLACE, &grab, 1, MPI_INT, MPI_MIN, PetscObjectComm((PetscObject)mat)));
8968:     if (grab) {
8969:       PetscCall(PetscInfo(mat, "Getting entire matrix as submatrix\n"));
8970:       if (cll == MAT_INITIAL_MATRIX) {
8971:         *newmat = mat;
8972:         PetscCall(PetscObjectReference((PetscObject)mat));
8973:       }
8974:       PetscFunctionReturn(PETSC_SUCCESS);
8975:     }
8976:   }

8978:   if (!iscol) {
8979:     PetscCall(ISCreateStride(PetscObjectComm((PetscObject)mat), mat->cmap->n, mat->cmap->rstart, 1, &iscoltmp));
8980:   } else {
8981:     iscoltmp = iscol;
8982:   }

8984:   /* if original matrix is on just one processor then use submatrix generated */
8985:   if (mat->ops->createsubmatrices && !mat->ops->createsubmatrix && size == 1 && cll == MAT_REUSE_MATRIX) {
8986:     PetscCall(MatCreateSubMatrices(mat, 1, &isrow, &iscoltmp, MAT_REUSE_MATRIX, &newmat));
8987:     goto setproperties;
8988:   } else if (mat->ops->createsubmatrices && !mat->ops->createsubmatrix && size == 1) {
8989:     PetscCall(MatCreateSubMatrices(mat, 1, &isrow, &iscoltmp, MAT_INITIAL_MATRIX, &local));
8990:     *newmat = *local;
8991:     PetscCall(PetscFree(local));
8992:     goto setproperties;
8993:   } else if (!mat->ops->createsubmatrix) {
8994:     /* Create a new matrix type that implements the operation using the full matrix */
8995:     PetscCall(PetscLogEventBegin(MAT_CreateSubMat, mat, 0, 0, 0));
8996:     switch (cll) {
8997:     case MAT_INITIAL_MATRIX:
8998:       PetscCall(MatCreateSubMatrixVirtual(mat, isrow, iscoltmp, newmat));
8999:       break;
9000:     case MAT_REUSE_MATRIX:
9001:       PetscCall(MatSubMatrixVirtualUpdate(*newmat, mat, isrow, iscoltmp));
9002:       break;
9003:     default:
9004:       SETERRQ(PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_OUTOFRANGE, "Invalid MatReuse, must be either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX");
9005:     }
9006:     PetscCall(PetscLogEventEnd(MAT_CreateSubMat, mat, 0, 0, 0));
9007:     goto setproperties;
9008:   }

9010:   PetscCall(PetscLogEventBegin(MAT_CreateSubMat, mat, 0, 0, 0));
9011:   PetscUseTypeMethod(mat, createsubmatrix, isrow, iscoltmp, cll, newmat);
9012:   PetscCall(PetscLogEventEnd(MAT_CreateSubMat, mat, 0, 0, 0));

9014: setproperties:
9015:   if ((*newmat)->symmetric == PETSC_BOOL3_UNKNOWN && (*newmat)->structurally_symmetric == PETSC_BOOL3_UNKNOWN && (*newmat)->spd == PETSC_BOOL3_UNKNOWN && (*newmat)->hermitian == PETSC_BOOL3_UNKNOWN) {
9016:     PetscCall(ISEqualUnsorted(isrow, iscoltmp, &flg));
9017:     if (flg) PetscCall(MatPropagateSymmetryOptions(mat, *newmat));
9018:   }
9019:   if (!iscol) PetscCall(ISDestroy(&iscoltmp));
9020:   if (*newmat && cll == MAT_INITIAL_MATRIX) PetscCall(PetscObjectStateIncrease((PetscObject)*newmat));
9021:   if (!iscol || isrow == iscol) PetscCall(MatSelectVariableBlockSizes(*newmat, mat, isrow));
9022:   PetscFunctionReturn(PETSC_SUCCESS);
9023: }

9025: /*@
9026:   MatPropagateSymmetryOptions - Propagates symmetry options set on a matrix to another matrix

9028:   Not Collective

9030:   Input Parameters:
9031: + A - the matrix we wish to propagate options from
9032: - B - the matrix we wish to propagate options to

9034:   Level: beginner

9036:   Note:
9037:   Propagates the options associated to `MAT_SYMMETRY_ETERNAL`, `MAT_STRUCTURALLY_SYMMETRIC`, `MAT_HERMITIAN`, `MAT_SPD`, `MAT_SYMMETRIC`, and `MAT_STRUCTURAL_SYMMETRY_ETERNAL`

9039: .seealso: [](ch_matrices), `Mat`, `MatSetOption()`, `MatIsSymmetricKnown()`, `MatIsSPDKnown()`, `MatIsHermitianKnown()`, `MatIsStructurallySymmetricKnown()`
9040: @*/
9041: PetscErrorCode MatPropagateSymmetryOptions(Mat A, Mat B)
9042: {
9043:   PetscFunctionBegin;
9046:   B->symmetry_eternal            = A->symmetry_eternal;
9047:   B->structural_symmetry_eternal = A->structural_symmetry_eternal;
9048:   B->symmetric                   = A->symmetric;
9049:   B->structurally_symmetric      = A->structurally_symmetric;
9050:   B->spd                         = A->spd;
9051:   B->hermitian                   = A->hermitian;
9052:   PetscFunctionReturn(PETSC_SUCCESS);
9053: }

9055: /*@
9056:   MatStashSetInitialSize - sets the sizes of the matrix stash, that is
9057:   used during the assembly process to store values that belong to
9058:   other processors.

9060:   Not Collective

9062:   Input Parameters:
9063: + mat   - the matrix
9064: . size  - the initial size of the stash.
9065: - bsize - the initial size of the block-stash(if used).

9067:   Options Database Keys:
9068: + -matstash_initial_size size or size0,size1,...,sizep-1            - set initial size
9069: - -matstash_block_initial_size bsize  or bsize0,bsize1,...,bsizep-1 - set initial block size

9071:   Level: intermediate

9073:   Notes:
9074:   The block-stash is used for values set with `MatSetValuesBlocked()` while
9075:   the stash is used for values set with `MatSetValues()`

9077:   Run with the option -info and look for output of the form
9078:   MatAssemblyBegin_MPIXXX:Stash has MM entries, uses nn mallocs.
9079:   to determine the appropriate value, MM, to use for size and
9080:   MatAssemblyBegin_MPIXXX:Block-Stash has BMM entries, uses nn mallocs.
9081:   to determine the value, BMM to use for bsize

9083: .seealso: [](ch_matrices), `MatAssemblyBegin()`, `MatAssemblyEnd()`, `Mat`, `MatStashGetInfo()`
9084: @*/
9085: PetscErrorCode MatStashSetInitialSize(Mat mat, PetscInt size, PetscInt bsize)
9086: {
9087:   PetscFunctionBegin;
9090:   PetscCall(MatStashSetInitialSize_Private(&mat->stash, size));
9091:   PetscCall(MatStashSetInitialSize_Private(&mat->bstash, bsize));
9092:   PetscFunctionReturn(PETSC_SUCCESS);
9093: }

9095: /*@
9096:   MatInterpolateAdd - $w = y + A*x$ or $A^T*x$ depending on the shape of
9097:   the matrix

9099:   Neighbor-wise Collective

9101:   Input Parameters:
9102: + A - the matrix
9103: . x - the vector to be multiplied by the interpolation operator
9104: - y - the vector to be added to the result

9106:   Output Parameter:
9107: . w - the resulting vector

9109:   Level: intermediate

9111:   Notes:
9112:   `w` may be the same vector as `y`.

9114:   This allows one to use either the restriction or interpolation (its transpose)
9115:   matrix to do the interpolation

9117: .seealso: [](ch_matrices), `Mat`, `MatMultAdd()`, `MatMultTransposeAdd()`, `MatRestrict()`, `PCMG`
9118: @*/
9119: PetscErrorCode MatInterpolateAdd(Mat A, Vec x, Vec y, Vec w)
9120: {
9121:   PetscInt M, N, Ny;

9123:   PetscFunctionBegin;
9128:   PetscCall(MatGetSize(A, &M, &N));
9129:   PetscCall(VecGetSize(y, &Ny));
9130:   if (M == Ny) PetscCall(MatMultAdd(A, x, y, w));
9131:   else PetscCall(MatMultTransposeAdd(A, x, y, w));
9132:   PetscFunctionReturn(PETSC_SUCCESS);
9133: }

9135: /*@
9136:   MatInterpolate - $y = A*x$ or $A^T*x$ depending on the shape of
9137:   the matrix

9139:   Neighbor-wise Collective

9141:   Input Parameters:
9142: + A - the matrix
9143: - x - the vector to be interpolated

9145:   Output Parameter:
9146: . y - the resulting vector

9148:   Level: intermediate

9150:   Note:
9151:   This allows one to use either the restriction or interpolation (its transpose)
9152:   matrix to do the interpolation

9154: .seealso: [](ch_matrices), `Mat`, `MatMultAdd()`, `MatMultTransposeAdd()`, `MatRestrict()`, `PCMG`
9155: @*/
9156: PetscErrorCode MatInterpolate(Mat A, Vec x, Vec y)
9157: {
9158:   PetscInt M, N, Ny;

9160:   PetscFunctionBegin;
9164:   PetscCall(MatGetSize(A, &M, &N));
9165:   PetscCall(VecGetSize(y, &Ny));
9166:   if (M == Ny) PetscCall(MatMult(A, x, y));
9167:   else PetscCall(MatMultTranspose(A, x, y));
9168:   PetscFunctionReturn(PETSC_SUCCESS);
9169: }

9171: /*@
9172:   MatRestrict - $y = A*x$ or $A^T*x$

9174:   Neighbor-wise Collective

9176:   Input Parameters:
9177: + A - the matrix
9178: - x - the vector to be restricted

9180:   Output Parameter:
9181: . y - the resulting vector

9183:   Level: intermediate

9185:   Note:
9186:   This allows one to use either the restriction or interpolation (its transpose)
9187:   matrix to do the restriction

9189: .seealso: [](ch_matrices), `Mat`, `MatMultAdd()`, `MatMultTransposeAdd()`, `MatInterpolate()`, `PCMG`
9190: @*/
9191: PetscErrorCode MatRestrict(Mat A, Vec x, Vec y)
9192: {
9193:   PetscInt M, N, Nx;

9195:   PetscFunctionBegin;
9199:   PetscCall(MatGetSize(A, &M, &N));
9200:   PetscCall(VecGetSize(x, &Nx));
9201:   if (M == Nx) PetscCall(MatMultTranspose(A, x, y));
9202:   else PetscCall(MatMult(A, x, y));
9203:   PetscFunctionReturn(PETSC_SUCCESS);
9204: }

9206: /*@
9207:   MatMatInterpolateAdd - $Y = W + A*X$ or $W + A^T*X$ depending on the shape of `A`

9209:   Neighbor-wise Collective

9211:   Input Parameters:
9212: + A - the matrix
9213: . x - the input dense matrix to be multiplied
9214: - w - the input dense matrix to be added to the result

9216:   Output Parameter:
9217: . y - the output dense matrix

9219:   Level: intermediate

9221:   Note:
9222:   This allows one to use either the restriction or interpolation (its transpose)
9223:   matrix to do the interpolation. `y` matrix can be reused if already created with the proper sizes,
9224:   otherwise it will be recreated. `y` must be initialized to `NULL` if not supplied.

9226: .seealso: [](ch_matrices), `Mat`, `MatInterpolateAdd()`, `MatMatInterpolate()`, `MatMatRestrict()`, `PCMG`
9227: @*/
9228: PetscErrorCode MatMatInterpolateAdd(Mat A, Mat x, Mat w, Mat *y)
9229: {
9230:   PetscInt  M, N, Mx, Nx, Mo, My = 0, Ny = 0;
9231:   PetscBool trans = PETSC_TRUE;
9232:   MatReuse  reuse = MAT_INITIAL_MATRIX;

9234:   PetscFunctionBegin;
9240:   PetscCall(MatGetSize(A, &M, &N));
9241:   PetscCall(MatGetSize(x, &Mx, &Nx));
9242:   if (N == Mx) trans = PETSC_FALSE;
9243:   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);
9244:   Mo = trans ? N : M;
9245:   if (*y) {
9246:     PetscCall(MatGetSize(*y, &My, &Ny));
9247:     if (Mo == My && Nx == Ny) reuse = MAT_REUSE_MATRIX;
9248:     else {
9249:       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);
9250:       PetscCall(MatDestroy(y));
9251:     }
9252:   }

9254:   if (w && *y == w) { /* this is to minimize changes in PCMG */
9255:     PetscBool flg;

9257:     PetscCall(PetscObjectQuery((PetscObject)*y, "__MatMatIntAdd_w", (PetscObject *)&w));
9258:     if (w) {
9259:       PetscInt My, Ny, Mw, Nw;

9261:       PetscCall(PetscObjectTypeCompare((PetscObject)*y, ((PetscObject)w)->type_name, &flg));
9262:       PetscCall(MatGetSize(*y, &My, &Ny));
9263:       PetscCall(MatGetSize(w, &Mw, &Nw));
9264:       if (!flg || My != Mw || Ny != Nw) w = NULL;
9265:     }
9266:     if (!w) {
9267:       PetscCall(MatDuplicate(*y, MAT_COPY_VALUES, &w));
9268:       PetscCall(PetscObjectCompose((PetscObject)*y, "__MatMatIntAdd_w", (PetscObject)w));
9269:       PetscCall(PetscObjectDereference((PetscObject)w));
9270:     } else PetscCall(MatCopy(*y, w, UNKNOWN_NONZERO_PATTERN));
9271:   }
9272:   if (!trans) PetscCall(MatMatMult(A, x, reuse, PETSC_DETERMINE, y));
9273:   else PetscCall(MatTransposeMatMult(A, x, reuse, PETSC_DETERMINE, y));
9274:   if (w) PetscCall(MatAXPY(*y, 1.0, w, UNKNOWN_NONZERO_PATTERN));
9275:   PetscFunctionReturn(PETSC_SUCCESS);
9276: }

9278: /*@
9279:   MatMatInterpolate - $Y = A*X$ or $A^T*X$ depending on the shape of `A`

9281:   Neighbor-wise Collective

9283:   Input Parameters:
9284: + A - the matrix
9285: - x - the input dense matrix

9287:   Output Parameter:
9288: . y - the output dense matrix

9290:   Level: intermediate

9292:   Note:
9293:   This allows one to use either the restriction or interpolation (its transpose)
9294:   matrix to do the interpolation. `y` matrix can be reused if already created with the proper sizes,
9295:   otherwise it will be recreated. `y` must be initialized to `NULL` if not supplied.

9297: .seealso: [](ch_matrices), `Mat`, `MatInterpolate()`, `MatRestrict()`, `MatMatRestrict()`, `PCMG`
9298: @*/
9299: PetscErrorCode MatMatInterpolate(Mat A, Mat x, Mat *y)
9300: {
9301:   PetscFunctionBegin;
9302:   PetscCall(MatMatInterpolateAdd(A, x, NULL, y));
9303:   PetscFunctionReturn(PETSC_SUCCESS);
9304: }

9306: /*@
9307:   MatMatRestrict - $Y = A*X$ or $A^T*X$ depending on the shape of `A`

9309:   Neighbor-wise Collective

9311:   Input Parameters:
9312: + A - the matrix
9313: - x - the input dense matrix

9315:   Output Parameter:
9316: . y - the output dense matrix

9318:   Level: intermediate

9320:   Note:
9321:   This allows one to use either the restriction or interpolation (its transpose)
9322:   matrix to do the restriction. `y` matrix can be reused if already created with the proper sizes,
9323:   otherwise it will be recreated. `y` must be initialized to `NULL` if not supplied.

9325: .seealso: [](ch_matrices), `Mat`, `MatRestrict()`, `MatInterpolate()`, `MatMatInterpolate()`, `PCMG`
9326: @*/
9327: PetscErrorCode MatMatRestrict(Mat A, Mat x, Mat *y)
9328: {
9329:   PetscFunctionBegin;
9330:   PetscCall(MatMatInterpolateAdd(A, x, NULL, y));
9331:   PetscFunctionReturn(PETSC_SUCCESS);
9332: }

9334: /*@
9335:   MatGetNullSpace - retrieves the null space of a matrix.

9337:   Logically Collective

9339:   Input Parameters:
9340: + mat    - the matrix
9341: - nullsp - the null space object

9343:   Level: developer

9345: .seealso: [](ch_matrices), `Mat`, `MatCreate()`, `MatNullSpaceCreate()`, `MatSetNearNullSpace()`, `MatSetNullSpace()`, `MatNullSpace`
9346: @*/
9347: PetscErrorCode MatGetNullSpace(Mat mat, MatNullSpace *nullsp)
9348: {
9349:   PetscFunctionBegin;
9351:   PetscAssertPointer(nullsp, 2);
9352:   *nullsp = (mat->symmetric == PETSC_BOOL3_TRUE && !mat->nullsp) ? mat->transnullsp : mat->nullsp;
9353:   PetscFunctionReturn(PETSC_SUCCESS);
9354: }

9356: /*@C
9357:   MatGetNullSpaces - gets the null spaces, transpose null spaces, and near null spaces from an array of matrices

9359:   Logically Collective

9361:   Input Parameters:
9362: + n   - the number of matrices
9363: - mat - the array of matrices

9365:   Output Parameters:
9366: . nullsp - an array of null spaces, `NULL` for each matrix that does not have a null space, length 3 * `n`

9368:   Level: developer

9370:   Note:
9371:   Call `MatRestoreNullspaces()` to provide these to another array of matrices

9373: .seealso: [](ch_matrices), `Mat`, `MatCreate()`, `MatNullSpaceCreate()`, `MatSetNearNullSpace()`, `MatGetNullSpace()`, `MatSetTransposeNullSpace()`, `MatGetTransposeNullSpace()`,
9374:           `MatNullSpaceRemove()`, `MatRestoreNullSpaces()`
9375: @*/
9376: PetscErrorCode MatGetNullSpaces(PetscInt n, Mat mat[], MatNullSpace *nullsp[])
9377: {
9378:   PetscFunctionBegin;
9379:   PetscCheck(n >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Number of matrices %" PetscInt_FMT " must be non-negative", n);
9380:   PetscAssertPointer(mat, 2);
9381:   PetscAssertPointer(nullsp, 3);

9383:   PetscCall(PetscCalloc1(3 * n, nullsp));
9384:   for (PetscInt i = 0; i < n; i++) {
9386:     (*nullsp)[i] = mat[i]->nullsp;
9387:     PetscCall(PetscObjectReference((PetscObject)(*nullsp)[i]));
9388:     (*nullsp)[n + i] = mat[i]->nearnullsp;
9389:     PetscCall(PetscObjectReference((PetscObject)(*nullsp)[n + i]));
9390:     (*nullsp)[2 * n + i] = mat[i]->transnullsp;
9391:     PetscCall(PetscObjectReference((PetscObject)(*nullsp)[2 * n + i]));
9392:   }
9393:   PetscFunctionReturn(PETSC_SUCCESS);
9394: }

9396: /*@C
9397:   MatRestoreNullSpaces - sets the null spaces, transpose null spaces, and near null spaces obtained with `MatGetNullSpaces()` for an array of matrices

9399:   Logically Collective

9401:   Input Parameters:
9402: + n      - the number of matrices
9403: . mat    - the array of matrices
9404: - nullsp - an array of null spaces

9406:   Level: developer

9408:   Note:
9409:   Call `MatGetNullSpaces()` to create `nullsp`

9411: .seealso: [](ch_matrices), `Mat`, `MatCreate()`, `MatNullSpaceCreate()`, `MatSetNearNullSpace()`, `MatGetNullSpace()`, `MatSetTransposeNullSpace()`, `MatGetTransposeNullSpace()`,
9412:           `MatNullSpaceRemove()`, `MatGetNullSpaces()`
9413: @*/
9414: PetscErrorCode MatRestoreNullSpaces(PetscInt n, Mat mat[], MatNullSpace *nullsp[])
9415: {
9416:   PetscFunctionBegin;
9417:   PetscCheck(n >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Number of matrices %" PetscInt_FMT " must be non-negative", n);
9418:   PetscAssertPointer(mat, 2);
9419:   PetscAssertPointer(nullsp, 3);
9420:   PetscAssertPointer(*nullsp, 3);

9422:   for (PetscInt i = 0; i < n; i++) {
9424:     PetscCall(MatSetNullSpace(mat[i], (*nullsp)[i]));
9425:     PetscCall(PetscObjectDereference((PetscObject)(*nullsp)[i]));
9426:     PetscCall(MatSetNearNullSpace(mat[i], (*nullsp)[n + i]));
9427:     PetscCall(PetscObjectDereference((PetscObject)(*nullsp)[n + i]));
9428:     PetscCall(MatSetTransposeNullSpace(mat[i], (*nullsp)[2 * n + i]));
9429:     PetscCall(PetscObjectDereference((PetscObject)(*nullsp)[2 * n + i]));
9430:   }
9431:   PetscCall(PetscFree(*nullsp));
9432:   PetscFunctionReturn(PETSC_SUCCESS);
9433: }

9435: /*@
9436:   MatSetNullSpace - attaches a null space to a matrix.

9438:   Logically Collective

9440:   Input Parameters:
9441: + mat    - the matrix
9442: - nullsp - the null space object

9444:   Level: advanced

9446:   Notes:
9447:   This null space is used by the `KSP` linear solvers to solve singular systems.

9449:   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`

9451:   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
9452:   to zero but the linear system will still be solved in a least squares sense.

9454:   The fundamental theorem of linear algebra (Gilbert Strang, Introduction to Applied Mathematics, page 72) states that
9455:   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)$.
9456:   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
9457:   $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
9458:   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)$.
9459:   This  $\hat{b}$ can be obtained by calling `MatNullSpaceRemove()` with the null space of the transpose of the matrix.

9461:   If the matrix is known to be symmetric because it is an `MATSBAIJ` matrix or one has called
9462:   `MatSetOption`(mat,`MAT_SYMMETRIC` or possibly `MAT_SYMMETRY_ETERNAL`,`PETSC_TRUE`); this
9463:   routine also automatically calls `MatSetTransposeNullSpace()`.

9465:   The user should call `MatNullSpaceDestroy()`.

9467: .seealso: [](ch_matrices), `Mat`, `MatCreate()`, `MatNullSpaceCreate()`, `MatSetNearNullSpace()`, `MatGetNullSpace()`, `MatSetTransposeNullSpace()`, `MatGetTransposeNullSpace()`, `MatNullSpaceRemove()`,
9468:           `KSPSetPCSide()`
9469: @*/
9470: PetscErrorCode MatSetNullSpace(Mat mat, MatNullSpace nullsp)
9471: {
9472:   PetscFunctionBegin;
9475:   PetscCall(PetscObjectReference((PetscObject)nullsp));
9476:   PetscCall(MatNullSpaceDestroy(&mat->nullsp));
9477:   mat->nullsp = nullsp;
9478:   if (mat->symmetric == PETSC_BOOL3_TRUE) PetscCall(MatSetTransposeNullSpace(mat, nullsp));
9479:   PetscFunctionReturn(PETSC_SUCCESS);
9480: }

9482: /*@
9483:   MatGetTransposeNullSpace - retrieves the null space of the transpose of a matrix.

9485:   Logically Collective

9487:   Input Parameters:
9488: + mat    - the matrix
9489: - nullsp - the null space object

9491:   Level: developer

9493: .seealso: [](ch_matrices), `Mat`, `MatNullSpace`, `MatCreate()`, `MatNullSpaceCreate()`, `MatSetNearNullSpace()`, `MatSetTransposeNullSpace()`, `MatSetNullSpace()`, `MatGetNullSpace()`
9494: @*/
9495: PetscErrorCode MatGetTransposeNullSpace(Mat mat, MatNullSpace *nullsp)
9496: {
9497:   PetscFunctionBegin;
9500:   PetscAssertPointer(nullsp, 2);
9501:   *nullsp = (mat->symmetric == PETSC_BOOL3_TRUE && !mat->transnullsp) ? mat->nullsp : mat->transnullsp;
9502:   PetscFunctionReturn(PETSC_SUCCESS);
9503: }

9505: /*@
9506:   MatSetTransposeNullSpace - attaches the null space of a transpose of a matrix to the matrix

9508:   Logically Collective

9510:   Input Parameters:
9511: + mat    - the matrix
9512: - nullsp - the null space object

9514:   Level: advanced

9516:   Notes:
9517:   This allows solving singular linear systems defined by the transpose of the matrix using `KSP` solvers with left preconditioning.

9519:   See `MatSetNullSpace()`

9521: .seealso: [](ch_matrices), `Mat`, `MatNullSpace`, `MatCreate()`, `MatNullSpaceCreate()`, `MatSetNearNullSpace()`, `MatGetNullSpace()`, `MatSetNullSpace()`, `MatGetTransposeNullSpace()`, `MatNullSpaceRemove()`, `KSPSetPCSide()`
9522: @*/
9523: PetscErrorCode MatSetTransposeNullSpace(Mat mat, MatNullSpace nullsp)
9524: {
9525:   PetscFunctionBegin;
9528:   PetscCall(PetscObjectReference((PetscObject)nullsp));
9529:   PetscCall(MatNullSpaceDestroy(&mat->transnullsp));
9530:   mat->transnullsp = nullsp;
9531:   PetscFunctionReturn(PETSC_SUCCESS);
9532: }

9534: /*@
9535:   MatSetNearNullSpace - attaches a null space to a matrix, which is often the null space (rigid body modes) of the operator without boundary conditions
9536:   This null space will be used to provide near null space vectors to a multigrid preconditioner built from this matrix.

9538:   Logically Collective

9540:   Input Parameters:
9541: + mat    - the matrix
9542: - nullsp - the null space object

9544:   Level: advanced

9546:   Notes:
9547:   Overwrites any previous near null space that may have been attached

9549:   You can remove the null space by calling this routine with an `nullsp` of `NULL`

9551: .seealso: [](ch_matrices), `Mat`, `MatNullSpace`, `MatCreate()`, `MatNullSpaceCreate()`, `MatSetNullSpace()`, `MatNullSpaceCreateRigidBody()`, `MatGetNearNullSpace()`
9552: @*/
9553: PetscErrorCode MatSetNearNullSpace(Mat mat, MatNullSpace nullsp)
9554: {
9555:   PetscFunctionBegin;
9559:   MatCheckPreallocated(mat, 1);
9560:   PetscCall(PetscObjectReference((PetscObject)nullsp));
9561:   PetscCall(MatNullSpaceDestroy(&mat->nearnullsp));
9562:   mat->nearnullsp = nullsp;
9563:   PetscFunctionReturn(PETSC_SUCCESS);
9564: }

9566: /*@
9567:   MatGetNearNullSpace - Get null space attached with `MatSetNearNullSpace()`

9569:   Not Collective

9571:   Input Parameter:
9572: . mat - the matrix

9574:   Output Parameter:
9575: . nullsp - the null space object, `NULL` if not set

9577:   Level: advanced

9579: .seealso: [](ch_matrices), `Mat`, `MatNullSpace`, `MatSetNearNullSpace()`, `MatGetNullSpace()`, `MatNullSpaceCreate()`
9580: @*/
9581: PetscErrorCode MatGetNearNullSpace(Mat mat, MatNullSpace *nullsp)
9582: {
9583:   PetscFunctionBegin;
9586:   PetscAssertPointer(nullsp, 2);
9587:   MatCheckPreallocated(mat, 1);
9588:   *nullsp = mat->nearnullsp;
9589:   PetscFunctionReturn(PETSC_SUCCESS);
9590: }

9592: /*@
9593:   MatICCFactor - Performs in-place incomplete Cholesky factorization of matrix.

9595:   Collective

9597:   Input Parameters:
9598: + mat  - the matrix
9599: . row  - row/column permutation
9600: - info - information on desired factorization process

9602:   Level: developer

9604:   Notes:
9605:   Probably really in-place only when level of fill is zero, otherwise allocates
9606:   new space to store factored matrix and deletes previous memory.

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

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

9615: .seealso: [](ch_matrices), `Mat`, `MatFactorInfo`, `MatGetFactor()`, `MatICCFactorSymbolic()`, `MatLUFactorNumeric()`, `MatCholeskyFactor()`
9616: @*/
9617: PetscErrorCode MatICCFactor(Mat mat, IS row, const MatFactorInfo *info)
9618: {
9619:   PetscFunctionBegin;
9623:   PetscAssertPointer(info, 3);
9624:   PetscCheck(mat->rmap->N == mat->cmap->N, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONG, "matrix must be square");
9625:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
9626:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
9627:   MatCheckPreallocated(mat, 1);
9628:   PetscUseTypeMethod(mat, iccfactor, row, info);
9629:   PetscCall(PetscObjectStateIncrease((PetscObject)mat));
9630:   PetscFunctionReturn(PETSC_SUCCESS);
9631: }

9633: /*@
9634:   MatDiagonalScaleLocal - Scales columns of a matrix given the scaling values including the
9635:   ghosted ones.

9637:   Not Collective

9639:   Input Parameters:
9640: + mat  - the matrix
9641: - diag - the diagonal values, including ghost ones

9643:   Level: developer

9645:   Notes:
9646:   Works only for `MATMPIAIJ` and `MATMPIBAIJ` matrices

9648:   This allows one to avoid during communication to perform the scaling that must be done with `MatDiagonalScale()`

9650: .seealso: [](ch_matrices), `Mat`, `MatDiagonalScale()`
9651: @*/
9652: PetscErrorCode MatDiagonalScaleLocal(Mat mat, Vec diag)
9653: {
9654:   PetscMPIInt size;

9656:   PetscFunctionBegin;

9661:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Matrix must be already assembled");
9662:   PetscCall(PetscLogEventBegin(MAT_Scale, mat, 0, 0, 0));
9663:   PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)mat), &size));
9664:   if (size == 1) {
9665:     PetscInt n, m;
9666:     PetscCall(VecGetSize(diag, &n));
9667:     PetscCall(MatGetSize(mat, NULL, &m));
9668:     PetscCheck(m == n, PETSC_COMM_SELF, PETSC_ERR_SUP, "Only supported for sequential matrices when no ghost points/periodic conditions");
9669:     PetscCall(MatDiagonalScale(mat, NULL, diag));
9670:   } else PetscUseMethod(mat, "MatDiagonalScaleLocal_C", (Mat, Vec), (mat, diag));
9671:   PetscCall(PetscLogEventEnd(MAT_Scale, mat, 0, 0, 0));
9672:   PetscCall(PetscObjectStateIncrease((PetscObject)mat));
9673:   PetscFunctionReturn(PETSC_SUCCESS);
9674: }

9676: /*@
9677:   MatGetInertia - Gets the inertia from a factored matrix

9679:   Collective

9681:   Input Parameter:
9682: . mat - the matrix

9684:   Output Parameters:
9685: + nneg  - number of negative eigenvalues
9686: . nzero - number of zero eigenvalues
9687: - npos  - number of positive eigenvalues

9689:   Level: advanced

9691:   Note:
9692:   Matrix must have been factored by `MatCholeskyFactor()`

9694: .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatCholeskyFactor()`
9695: @*/
9696: PetscErrorCode MatGetInertia(Mat mat, PetscInt *nneg, PetscInt *nzero, PetscInt *npos)
9697: {
9698:   PetscFunctionBegin;
9701:   PetscCheck(mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Unfactored matrix");
9702:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Numeric factor mat is not assembled");
9703:   PetscUseTypeMethod(mat, getinertia, nneg, nzero, npos);
9704:   PetscFunctionReturn(PETSC_SUCCESS);
9705: }

9707: /*@C
9708:   MatSolves - Solves $A x = b$, given a factored matrix, for a collection of vectors

9710:   Neighbor-wise Collective

9712:   Input Parameters:
9713: + mat - the factored matrix obtained with `MatGetFactor()`
9714: - b   - the right-hand-side vectors

9716:   Output Parameter:
9717: . x - the result vectors

9719:   Level: developer

9721:   Note:
9722:   The vectors `b` and `x` cannot be the same.  I.e., one cannot
9723:   call `MatSolves`(A,x,x).

9725: .seealso: [](ch_matrices), `Mat`, `Vecs`, `MatSolveAdd()`, `MatSolveTranspose()`, `MatSolveTransposeAdd()`, `MatSolve()`
9726: @*/
9727: PetscErrorCode MatSolves(Mat mat, Vecs b, Vecs x)
9728: {
9729:   PetscFunctionBegin;
9732:   PetscCheck(x != b, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_IDN, "x and b must be different vectors");
9733:   PetscCheck(mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Unfactored matrix");
9734:   if (!mat->rmap->N && !mat->cmap->N) PetscFunctionReturn(PETSC_SUCCESS);

9736:   MatCheckPreallocated(mat, 1);
9737:   PetscCall(PetscLogEventBegin(MAT_Solves, mat, 0, 0, 0));
9738:   PetscUseTypeMethod(mat, solves, b, x);
9739:   PetscCall(PetscLogEventEnd(MAT_Solves, mat, 0, 0, 0));
9740:   PetscFunctionReturn(PETSC_SUCCESS);
9741: }

9743: /*@
9744:   MatIsSymmetric - Test whether a matrix is symmetric

9746:   Collective

9748:   Input Parameters:
9749: + A   - the matrix to test
9750: - tol - difference between value and its transpose less than this amount counts as equal (use 0.0 for exact transpose)

9752:   Output Parameter:
9753: . flg - the result

9755:   Level: intermediate

9757:   Notes:
9758:   For real numbers `MatIsSymmetric()` and `MatIsHermitian()` return identical results

9760:   If the matrix does not yet know if it is symmetric or not this can be an expensive operation, also available `MatIsSymmetricKnown()`

9762:   One can declare that a matrix is symmetric with `MatSetOption`(mat,`MAT_SYMMETRIC`,`PETSC_TRUE`) and if it is known to remain symmetric
9763:   after changes to the matrices values one can call `MatSetOption`(mat,`MAT_SYMMETRY_ETERNAL`,`PETSC_TRUE`)

9765: .seealso: [](ch_matrices), `Mat`, `MatTranspose()`, `MatIsTranspose()`, `MatIsHermitian()`, `MatIsStructurallySymmetric()`, `MatSetOption()`, `MatIsSymmetricKnown()`,
9766:           `MAT_SYMMETRIC`, `MAT_SYMMETRY_ETERNAL`
9767: @*/
9768: PetscErrorCode MatIsSymmetric(Mat A, PetscReal tol, PetscBool *flg)
9769: {
9770:   PetscFunctionBegin;
9772:   PetscAssertPointer(flg, 3);
9773:   if (A->symmetric != PETSC_BOOL3_UNKNOWN && !tol) *flg = PetscBool3ToBool(A->symmetric);
9774:   else {
9775:     if (A->ops->issymmetric) PetscUseTypeMethod(A, issymmetric, tol, flg);
9776:     else PetscCall(MatIsTranspose(A, A, tol, flg));
9777:     if (!tol) PetscCall(MatSetOption(A, MAT_SYMMETRIC, *flg));
9778:   }
9779:   PetscFunctionReturn(PETSC_SUCCESS);
9780: }

9782: /*@
9783:   MatIsHermitian - Test whether a matrix is Hermitian

9785:   Collective

9787:   Input Parameters:
9788: + A   - the matrix to test
9789: - tol - difference between value and its transpose less than this amount counts as equal (use 0.0 for exact Hermitian)

9791:   Output Parameter:
9792: . flg - the result

9794:   Level: intermediate

9796:   Notes:
9797:   For real numbers `MatIsSymmetric()` and `MatIsHermitian()` return identical results

9799:   If the matrix does not yet know if it is Hermitian or not this can be an expensive operation, also available `MatIsHermitianKnown()`

9801:   One can declare that a matrix is Hermitian with `MatSetOption`(mat,`MAT_HERMITIAN`,`PETSC_TRUE`) and if it is known to remain Hermitian
9802:   after changes to the matrices values one can call `MatSetOption`(mat,`MAT_SYMEMTRY_ETERNAL`,`PETSC_TRUE`)

9804: .seealso: [](ch_matrices), `Mat`, `MatTranspose()`, `MatIsTranspose()`, `MatIsHermitianKnown()`, `MatIsStructurallySymmetric()`, `MatSetOption()`,
9805:           `MatIsSymmetricKnown()`, `MatIsSymmetric()`, `MAT_HERMITIAN`, `MAT_SYMMETRY_ETERNAL`
9806: @*/
9807: PetscErrorCode MatIsHermitian(Mat A, PetscReal tol, PetscBool *flg)
9808: {
9809:   PetscFunctionBegin;
9811:   PetscAssertPointer(flg, 3);
9812:   if (A->hermitian != PETSC_BOOL3_UNKNOWN && !tol) *flg = PetscBool3ToBool(A->hermitian);
9813:   else {
9814:     if (A->ops->ishermitian) PetscUseTypeMethod(A, ishermitian, tol, flg);
9815:     else PetscCall(MatIsHermitianTranspose(A, A, tol, flg));
9816:     if (!tol) PetscCall(MatSetOption(A, MAT_HERMITIAN, *flg));
9817:   }
9818:   PetscFunctionReturn(PETSC_SUCCESS);
9819: }

9821: /*@
9822:   MatIsSymmetricKnown - Checks if a matrix knows if it is symmetric or not and its symmetric state

9824:   Not Collective

9826:   Input Parameter:
9827: . A - the matrix to check

9829:   Output Parameters:
9830: + set - `PETSC_TRUE` if the matrix knows its symmetry state (this tells you if the next flag is valid)
9831: - flg - the result (only valid if set is `PETSC_TRUE`)

9833:   Level: advanced

9835:   Notes:
9836:   Does not check the matrix values directly, so this may return unknown (set = `PETSC_FALSE`). Use `MatIsSymmetric()`
9837:   if you want it explicitly checked

9839:   One can declare that a matrix is symmetric with `MatSetOption`(mat,`MAT_SYMMETRIC`,`PETSC_TRUE`) and if it is known to remain symmetric
9840:   after changes to the matrices values one can call `MatSetOption`(mat,`MAT_SYMMETRY_ETERNAL`,`PETSC_TRUE`)

9842: .seealso: [](ch_matrices), `Mat`, `MAT_SYMMETRY_ETERNAL`, `MatTranspose()`, `MatIsTranspose()`, `MatIsHermitian()`, `MatIsStructurallySymmetric()`, `MatSetOption()`, `MatIsSymmetric()`, `MatIsHermitianKnown()`
9843: @*/
9844: PetscErrorCode MatIsSymmetricKnown(Mat A, PetscBool *set, PetscBool *flg)
9845: {
9846:   PetscFunctionBegin;
9848:   PetscAssertPointer(set, 2);
9849:   PetscAssertPointer(flg, 3);
9850:   if (A->symmetric != PETSC_BOOL3_UNKNOWN) {
9851:     *set = PETSC_TRUE;
9852:     *flg = PetscBool3ToBool(A->symmetric);
9853:   } else *set = PETSC_FALSE;
9854:   PetscFunctionReturn(PETSC_SUCCESS);
9855: }

9857: /*@
9858:   MatIsSPDKnown - Checks if a matrix knows if it is symmetric positive definite or not and its symmetric positive definite state

9860:   Not Collective

9862:   Input Parameter:
9863: . A - the matrix to check

9865:   Output Parameters:
9866: + set - `PETSC_TRUE` if the matrix knows its symmetric positive definite state (this tells you if the next flag is valid)
9867: - flg - the result (only valid if set is `PETSC_TRUE`)

9869:   Level: advanced

9871:   Notes:
9872:   Does not check the matrix values directly, so this may return unknown (set = `PETSC_FALSE`).

9874:   One can declare that a matrix is SPD with `MatSetOption`(mat,`MAT_SPD`,`PETSC_TRUE`) and if it is known to remain SPD
9875:   after changes to the matrices values one can call `MatSetOption`(mat,`MAT_SPD_ETERNAL`,`PETSC_TRUE`)

9877: .seealso: [](ch_matrices), `Mat`, `MAT_SPD_ETERNAL`, `MAT_SPD`, `MatTranspose()`, `MatIsTranspose()`, `MatIsHermitian()`, `MatIsStructurallySymmetric()`, `MatSetOption()`, `MatIsSymmetric()`, `MatIsHermitianKnown()`
9878: @*/
9879: PetscErrorCode MatIsSPDKnown(Mat A, PetscBool *set, PetscBool *flg)
9880: {
9881:   PetscFunctionBegin;
9883:   PetscAssertPointer(set, 2);
9884:   PetscAssertPointer(flg, 3);
9885:   if (A->spd != PETSC_BOOL3_UNKNOWN) {
9886:     *set = PETSC_TRUE;
9887:     *flg = PetscBool3ToBool(A->spd);
9888:   } else *set = PETSC_FALSE;
9889:   PetscFunctionReturn(PETSC_SUCCESS);
9890: }

9892: /*@
9893:   MatIsHermitianKnown - Checks if a matrix knows if it is Hermitian or not and its Hermitian state

9895:   Not Collective

9897:   Input Parameter:
9898: . A - the matrix to check

9900:   Output Parameters:
9901: + set - `PETSC_TRUE` if the matrix knows its Hermitian state (this tells you if the next flag is valid)
9902: - flg - the result (only valid if set is `PETSC_TRUE`)

9904:   Level: advanced

9906:   Notes:
9907:   Does not check the matrix values directly, so this may return unknown (set = `PETSC_FALSE`). Use `MatIsHermitian()`
9908:   if you want it explicitly checked

9910:   One can declare that a matrix is Hermitian with `MatSetOption`(mat,`MAT_HERMITIAN`,`PETSC_TRUE`) and if it is known to remain Hermitian
9911:   after changes to the matrices values one can call `MatSetOption`(mat,`MAT_SYMMETRY_ETERNAL`,`PETSC_TRUE`)

9913: .seealso: [](ch_matrices), `Mat`, `MAT_SYMMETRY_ETERNAL`, `MAT_HERMITIAN`, `MatTranspose()`, `MatIsTranspose()`, `MatIsHermitian()`, `MatIsStructurallySymmetric()`, `MatSetOption()`, `MatIsSymmetric()`
9914: @*/
9915: PetscErrorCode MatIsHermitianKnown(Mat A, PetscBool *set, PetscBool *flg)
9916: {
9917:   PetscFunctionBegin;
9919:   PetscAssertPointer(set, 2);
9920:   PetscAssertPointer(flg, 3);
9921:   if (A->hermitian != PETSC_BOOL3_UNKNOWN) {
9922:     *set = PETSC_TRUE;
9923:     *flg = PetscBool3ToBool(A->hermitian);
9924:   } else *set = PETSC_FALSE;
9925:   PetscFunctionReturn(PETSC_SUCCESS);
9926: }

9928: /*@
9929:   MatIsStructurallySymmetric - Test whether a matrix is structurally symmetric

9931:   Collective

9933:   Input Parameter:
9934: . A - the matrix to test

9936:   Output Parameter:
9937: . flg - the result

9939:   Level: intermediate

9941:   Notes:
9942:   If the matrix does yet know it is structurally symmetric this can be an expensive operation, also available `MatIsStructurallySymmetricKnown()`

9944:   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
9945:   symmetric after changes to the matrices values one can call `MatSetOption`(mat,`MAT_STRUCTURAL_SYMMETRY_ETERNAL`,`PETSC_TRUE`)

9947: .seealso: [](ch_matrices), `Mat`, `MAT_STRUCTURALLY_SYMMETRIC`, `MAT_STRUCTURAL_SYMMETRY_ETERNAL`, `MatTranspose()`, `MatIsTranspose()`, `MatIsHermitian()`, `MatIsSymmetric()`, `MatSetOption()`, `MatIsStructurallySymmetricKnown()`
9948: @*/
9949: PetscErrorCode MatIsStructurallySymmetric(Mat A, PetscBool *flg)
9950: {
9951:   PetscFunctionBegin;
9953:   PetscAssertPointer(flg, 2);
9954:   if (A->structurally_symmetric != PETSC_BOOL3_UNKNOWN) *flg = PetscBool3ToBool(A->structurally_symmetric);
9955:   else {
9956:     PetscUseTypeMethod(A, isstructurallysymmetric, flg);
9957:     PetscCall(MatSetOption(A, MAT_STRUCTURALLY_SYMMETRIC, *flg));
9958:   }
9959:   PetscFunctionReturn(PETSC_SUCCESS);
9960: }

9962: /*@
9963:   MatIsStructurallySymmetricKnown - Checks if a matrix knows if it is structurally symmetric or not and its structurally symmetric state

9965:   Not Collective

9967:   Input Parameter:
9968: . A - the matrix to check

9970:   Output Parameters:
9971: + set - PETSC_TRUE if the matrix knows its structurally symmetric state (this tells you if the next flag is valid)
9972: - flg - the result (only valid if set is PETSC_TRUE)

9974:   Level: advanced

9976:   Notes:
9977:   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
9978:   symmetric after changes to the matrices values one can call `MatSetOption`(mat,`MAT_STRUCTURAL_SYMMETRY_ETERNAL`,`PETSC_TRUE`)

9980:   Use `MatIsStructurallySymmetric()` to explicitly check if a matrix is structurally symmetric (this is an expensive operation)

9982: .seealso: [](ch_matrices), `Mat`, `MAT_STRUCTURALLY_SYMMETRIC`, `MatTranspose()`, `MatIsTranspose()`, `MatIsHermitian()`, `MatIsStructurallySymmetric()`, `MatSetOption()`, `MatIsSymmetric()`, `MatIsHermitianKnown()`
9983: @*/
9984: PetscErrorCode MatIsStructurallySymmetricKnown(Mat A, PetscBool *set, PetscBool *flg)
9985: {
9986:   PetscFunctionBegin;
9988:   PetscAssertPointer(set, 2);
9989:   PetscAssertPointer(flg, 3);
9990:   if (A->structurally_symmetric != PETSC_BOOL3_UNKNOWN) {
9991:     *set = PETSC_TRUE;
9992:     *flg = PetscBool3ToBool(A->structurally_symmetric);
9993:   } else *set = PETSC_FALSE;
9994:   PetscFunctionReturn(PETSC_SUCCESS);
9995: }

9997: /*@
9998:   MatStashGetInfo - Gets how many values are currently in the matrix stash, i.e. need
9999:   to be communicated to other processors during the `MatAssemblyBegin()`/`MatAssemblyEnd()` process

10001:   Not Collective

10003:   Input Parameter:
10004: . mat - the matrix

10006:   Output Parameters:
10007: + nstash    - the size of the stash
10008: . reallocs  - the number of additional mallocs incurred.
10009: . bnstash   - the size of the block stash
10010: - breallocs - the number of additional mallocs incurred.in the block stash

10012:   Level: advanced

10014: .seealso: [](ch_matrices), `MatAssemblyBegin()`, `MatAssemblyEnd()`, `Mat`, `MatStashSetInitialSize()`
10015: @*/
10016: PetscErrorCode MatStashGetInfo(Mat mat, PetscInt *nstash, PetscInt *reallocs, PetscInt *bnstash, PetscInt *breallocs)
10017: {
10018:   PetscFunctionBegin;
10019:   PetscCall(MatStashGetInfo_Private(&mat->stash, nstash, reallocs));
10020:   PetscCall(MatStashGetInfo_Private(&mat->bstash, bnstash, breallocs));
10021:   PetscFunctionReturn(PETSC_SUCCESS);
10022: }

10024: /*@
10025:   MatCreateVecs - Get vector(s) compatible with the matrix, i.e. with the same
10026:   parallel layout, `PetscLayout` for rows and columns

10028:   Collective

10030:   Input Parameter:
10031: . mat - the matrix

10033:   Output Parameters:
10034: + right - (optional) vector that the matrix can be multiplied against
10035: - left  - (optional) vector that the matrix vector product can be stored in

10037:   Options Database Key:
10038: . -mat_vec_type type - set the `VecType` of the created vectors during `MatSetFromOptions()`

10040:   Level: advanced

10042:   Notes:
10043:   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()`.

10045:   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`.

10047:   These are new vectors which are not owned by the `mat`, they should be destroyed with `VecDestroy()` when no longer needed.

10049:   PETSc `Vec` always have all zero entries when created with `MatCreateVecs()` until routines such as `VecSet()` or `VecSetValues()`
10050:   are used to change the values. There is no reason to call `VecZeroEntries()` after creation.

10052: .seealso: [](ch_matrices), `Mat`, `Vec`, `VecCreate()`, `VecDestroy()`, `DMCreateGlobalVector()`, `MatSetVecType()`
10053: @*/
10054: PetscErrorCode MatCreateVecs(Mat mat, Vec *right, Vec *left)
10055: {
10056:   PetscFunctionBegin;
10059:   if (mat->ops->getvecs) {
10060:     PetscUseTypeMethod(mat, getvecs, right, left);
10061:   } else {
10062:     if (right) {
10063:       PetscCheck(mat->cmap->n >= 0, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "PetscLayout for columns not yet setup");
10064:       PetscCall(VecCreateWithLayout_Private(mat->cmap, right));
10065:       PetscCall(VecSetType(*right, mat->defaultvectype));
10066: #if PetscDefined(HAVE_VIENNACL) || PetscDefined(HAVE_CUDA) || PetscDefined(HAVE_HIP)
10067:       if (mat->boundtocpu && mat->bindingpropagates) {
10068:         PetscCall(VecSetBindingPropagates(*right, PETSC_TRUE));
10069:         PetscCall(VecBindToCPU(*right, PETSC_TRUE));
10070:       }
10071: #endif
10072:     }
10073:     if (left) {
10074:       PetscCheck(mat->rmap->n >= 0, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "PetscLayout for rows not yet setup");
10075:       PetscCall(VecCreateWithLayout_Private(mat->rmap, left));
10076:       PetscCall(VecSetType(*left, mat->defaultvectype));
10077: #if PetscDefined(HAVE_VIENNACL) || PetscDefined(HAVE_CUDA) || PetscDefined(HAVE_HIP)
10078:       if (mat->boundtocpu && mat->bindingpropagates) {
10079:         PetscCall(VecSetBindingPropagates(*left, PETSC_TRUE));
10080:         PetscCall(VecBindToCPU(*left, PETSC_TRUE));
10081:       }
10082: #endif
10083:     }
10084:   }
10085:   PetscFunctionReturn(PETSC_SUCCESS);
10086: }

10088: /*@
10089:   MatFactorInfoInitialize - Initializes a `MatFactorInfo` data structure
10090:   with default values.

10092:   Not Collective

10094:   Input Parameter:
10095: . info - the `MatFactorInfo` data structure

10097:   Level: developer

10099:   Notes:
10100:   The solvers are generally used through the `KSP` and `PC` objects, for example
10101:   `PCLU`, `PCILU`, `PCCHOLESKY`, `PCICC`

10103:   Once the data structure is initialized one may change certain entries as desired for the particular factorization to be performed

10105: .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatFactorInfo`
10106: @*/
10107: PetscErrorCode MatFactorInfoInitialize(MatFactorInfo *info)
10108: {
10109:   PetscFunctionBegin;
10110:   PetscCall(PetscMemzero(info, sizeof(MatFactorInfo)));
10111:   PetscFunctionReturn(PETSC_SUCCESS);
10112: }

10114: /*@
10115:   MatFactorSetSchurIS - Set indices corresponding to the Schur complement you wish to have computed

10117:   Collective

10119:   Input Parameters:
10120: + mat - the factored matrix
10121: - is  - the index set defining the Schur indices (0-based)

10123:   Level: advanced

10125:   Notes:
10126:   Call `MatFactorSolveSchurComplement()` or `MatFactorSolveSchurComplementTranspose()` after this call to solve a Schur complement system.

10128:   You can call `MatFactorGetSchurComplement()` or `MatFactorCreateSchurComplement()` after this call.

10130:   This functionality is only supported for `MATSOLVERMUMPS` and `MATSOLVERMKL_PARDISO`

10132: .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatFactorGetSchurComplement()`, `MatFactorRestoreSchurComplement()`, `MatFactorCreateSchurComplement()`, `MatFactorSolveSchurComplement()`,
10133:           `MatFactorSolveSchurComplementTranspose()`, `MATSOLVERMUMPS`, `MATSOLVERMKL_PARDISO`
10134: @*/
10135: PetscErrorCode MatFactorSetSchurIS(Mat mat, IS is)
10136: {
10137:   PetscErrorCode (*f)(Mat, IS);

10139:   PetscFunctionBegin;
10144:   PetscCheckSameComm(mat, 1, is, 2);
10145:   PetscCheck(mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Only for factored matrix");
10146:   PetscCall(PetscObjectQueryFunction((PetscObject)mat, "MatFactorSetSchurIS_C", &f));
10147:   PetscCheck(f, PetscObjectComm((PetscObject)mat), PETSC_ERR_SUP, "The selected MatSolverType does not support Schur complement computation. You should use MATSOLVERMUMPS or MATSOLVERMKL_PARDISO");
10148:   PetscCall((*f)(mat, is));
10149:   PetscCheck(mat->schur, PetscObjectComm((PetscObject)mat), PETSC_ERR_PLIB, "Schur complement has not been created");
10150:   PetscFunctionReturn(PETSC_SUCCESS);
10151: }

10153: /*@
10154:   MatFactorCreateSchurComplement - Create a Schur complement matrix object using Schur data computed during the factorization step

10156:   Logically Collective

10158:   Input Parameters:
10159: + F      - the factored matrix obtained by calling `MatGetFactor()`
10160: . S      - location where to return the Schur complement, can be `NULL`
10161: - status - the status of the Schur complement matrix, can be `NULL`

10163:   Level: advanced

10165:   Notes:
10166:   You must call `MatFactorSetSchurIS()` before calling this routine.

10168:   This functionality is only supported for `MATSOLVERMUMPS` and `MATSOLVERMKL_PARDISO`

10170:   The routine provides a copy of the Schur matrix stored within the solver data structures.
10171:   The caller must destroy the object when it is no longer needed.
10172:   If `MatFactorInvertSchurComplement()` has been called, the routine gets back the inverse.

10174:   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)

10176:   See `MatCreateSchurComplement()` or `MatGetSchurComplement()` for ways to create virtual or approximate Schur complements.

10178:   Developer Note:
10179:   The reason this routine exists is because the representation of the Schur complement within the factor matrix may be different than a standard PETSc
10180:   matrix representation and we normally do not want to use the time or memory to make a copy as a regular PETSc matrix.

10182: .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatFactorSetSchurIS()`, `MatFactorGetSchurComplement()`, `MatFactorSchurStatus`, `MATSOLVERMUMPS`, `MATSOLVERMKL_PARDISO`
10183: @*/
10184: PetscErrorCode MatFactorCreateSchurComplement(Mat F, Mat *S, MatFactorSchurStatus *status)
10185: {
10186:   PetscFunctionBegin;
10188:   if (S) PetscAssertPointer(S, 2);
10189:   if (status) PetscAssertPointer(status, 3);
10190:   if (S) {
10191:     PetscErrorCode (*f)(Mat, Mat *);

10193:     PetscCall(PetscObjectQueryFunction((PetscObject)F, "MatFactorCreateSchurComplement_C", &f));
10194:     if (f) PetscCall((*f)(F, S));
10195:     else PetscCall(MatDuplicate(F->schur, MAT_COPY_VALUES, S));
10196:   }
10197:   if (status) *status = F->schur_status;
10198:   PetscFunctionReturn(PETSC_SUCCESS);
10199: }

10201: /*@
10202:   MatFactorGetSchurComplement - Gets access to a Schur complement matrix using the current Schur data within a factored matrix

10204:   Logically Collective

10206:   Input Parameters:
10207: + F      - the factored matrix obtained by calling `MatGetFactor()`
10208: . S      - location where to return the Schur complement, can be `NULL`
10209: - status - the status of the Schur complement matrix, can be `NULL`

10211:   Level: advanced

10213:   Notes:
10214:   You must call `MatFactorSetSchurIS()` before calling this routine.

10216:   Schur complement mode is currently implemented for sequential matrices with factor type of `MATSOLVERMUMPS`

10218:   The routine returns a the Schur Complement stored within the data structures of the solver.

10220:   If `MatFactorInvertSchurComplement()` has previously been called, the returned matrix is actually the inverse of the Schur complement.

10222:   The returned matrix should not be destroyed; the caller should call `MatFactorRestoreSchurComplement()` when the object is no longer needed.

10224:   Use `MatFactorCreateSchurComplement()` to create a copy of the Schur complement matrix that is within a factored matrix

10226:   See `MatCreateSchurComplement()` or `MatGetSchurComplement()` for ways to create virtual or approximate Schur complements.

10228: .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatFactorSetSchurIS()`, `MatFactorRestoreSchurComplement()`, `MatFactorCreateSchurComplement()`, `MatFactorSchurStatus`
10229: @*/
10230: PetscErrorCode MatFactorGetSchurComplement(Mat F, Mat *S, MatFactorSchurStatus *status)
10231: {
10232:   PetscFunctionBegin;
10234:   if (S) {
10235:     PetscAssertPointer(S, 2);
10236:     *S = F->schur;
10237:   }
10238:   if (status) {
10239:     PetscAssertPointer(status, 3);
10240:     *status = F->schur_status;
10241:   }
10242:   PetscFunctionReturn(PETSC_SUCCESS);
10243: }

10245: static PetscErrorCode MatFactorUpdateSchurStatus_Private(Mat F)
10246: {
10247:   Mat S = F->schur;

10249:   PetscFunctionBegin;
10250:   switch (F->schur_status) {
10251:   case MAT_FACTOR_SCHUR_UNFACTORED: // fall-through
10252:   case MAT_FACTOR_SCHUR_INVERTED:
10253:     if (S) {
10254:       S->ops->solve             = NULL;
10255:       S->ops->matsolve          = NULL;
10256:       S->ops->solvetranspose    = NULL;
10257:       S->ops->matsolvetranspose = NULL;
10258:       S->ops->solveadd          = NULL;
10259:       S->ops->solvetransposeadd = NULL;
10260:       S->factortype             = MAT_FACTOR_NONE;
10261:       PetscCall(PetscFree(S->solvertype));
10262:     }
10263:   case MAT_FACTOR_SCHUR_FACTORED: // fall-through
10264:     break;
10265:   default:
10266:     SETERRQ(PetscObjectComm((PetscObject)F), PETSC_ERR_SUP, "Unhandled MatFactorSchurStatus %d", F->schur_status);
10267:   }
10268:   PetscFunctionReturn(PETSC_SUCCESS);
10269: }

10271: /*@
10272:   MatFactorRestoreSchurComplement - Restore the Schur complement matrix object obtained from a call to `MatFactorGetSchurComplement()`

10274:   Logically Collective

10276:   Input Parameters:
10277: + F      - the factored matrix obtained by calling `MatGetFactor()`
10278: . S      - location where the Schur complement is stored
10279: - status - the status of the Schur complement matrix (see `MatFactorSchurStatus`)

10281:   Level: advanced

10283: .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatFactorSetSchurIS()`, `MatFactorCreateSchurComplement()`, `MatFactorSchurStatus`
10284: @*/
10285: PetscErrorCode MatFactorRestoreSchurComplement(Mat F, Mat *S, MatFactorSchurStatus status)
10286: {
10287:   PetscFunctionBegin;
10289:   if (S) {
10291:     *S = NULL;
10292:   }
10293:   F->schur_status = status;
10294:   PetscCall(MatFactorUpdateSchurStatus_Private(F));
10295:   PetscFunctionReturn(PETSC_SUCCESS);
10296: }

10298: /*@
10299:   MatFactorSolveSchurComplementTranspose - Solve the transpose of the Schur complement system computed during the factorization step

10301:   Logically Collective

10303:   Input Parameters:
10304: + F   - the factored matrix obtained by calling `MatGetFactor()`
10305: . rhs - location where the right-hand side of the Schur complement system is stored
10306: - sol - location where the solution of the Schur complement system has to be returned

10308:   Level: advanced

10310:   Notes:
10311:   The sizes of the vectors should match the size of the Schur complement

10313:   Must be called after `MatFactorSetSchurIS()`

10315: .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatFactorSetSchurIS()`, `MatFactorSolveSchurComplement()`
10316: @*/
10317: PetscErrorCode MatFactorSolveSchurComplementTranspose(Mat F, Vec rhs, Vec sol)
10318: {
10319:   PetscFunctionBegin;
10326:   PetscCheckSameComm(F, 1, rhs, 2);
10327:   PetscCheckSameComm(F, 1, sol, 3);
10328:   PetscCall(MatFactorFactorizeSchurComplement(F));
10329:   switch (F->schur_status) {
10330:   case MAT_FACTOR_SCHUR_FACTORED:
10331:     PetscCall(MatSolveTranspose(F->schur, rhs, sol));
10332:     break;
10333:   case MAT_FACTOR_SCHUR_INVERTED:
10334:     PetscCall(MatMultTranspose(F->schur, rhs, sol));
10335:     break;
10336:   default:
10337:     SETERRQ(PetscObjectComm((PetscObject)F), PETSC_ERR_SUP, "Unhandled MatFactorSchurStatus %d", F->schur_status);
10338:   }
10339:   PetscFunctionReturn(PETSC_SUCCESS);
10340: }

10342: /*@
10343:   MatFactorSolveSchurComplement - Solve the Schur complement system computed during the factorization step

10345:   Logically Collective

10347:   Input Parameters:
10348: + F   - the factored matrix obtained by calling `MatGetFactor()`
10349: . rhs - location where the right-hand side of the Schur complement system is stored
10350: - sol - location where the solution of the Schur complement system has to be returned

10352:   Level: advanced

10354:   Notes:
10355:   The sizes of the vectors should match the size of the Schur complement

10357:   Must be called after `MatFactorSetSchurIS()`

10359: .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatFactorSetSchurIS()`, `MatFactorSolveSchurComplementTranspose()`
10360: @*/
10361: PetscErrorCode MatFactorSolveSchurComplement(Mat F, Vec rhs, Vec sol)
10362: {
10363:   PetscFunctionBegin;
10370:   PetscCheckSameComm(F, 1, rhs, 2);
10371:   PetscCheckSameComm(F, 1, sol, 3);
10372:   PetscCall(MatFactorFactorizeSchurComplement(F));
10373:   switch (F->schur_status) {
10374:   case MAT_FACTOR_SCHUR_FACTORED:
10375:     PetscCall(MatSolve(F->schur, rhs, sol));
10376:     break;
10377:   case MAT_FACTOR_SCHUR_INVERTED:
10378:     PetscCall(MatMult(F->schur, rhs, sol));
10379:     break;
10380:   default:
10381:     SETERRQ(PetscObjectComm((PetscObject)F), PETSC_ERR_SUP, "Unhandled MatFactorSchurStatus %d", F->schur_status);
10382:   }
10383:   PetscFunctionReturn(PETSC_SUCCESS);
10384: }

10386: PETSC_SINGLE_LIBRARY_INTERN PetscErrorCode MatSeqDenseInvertFactors_Private(Mat);
10387: #if PetscDefined(HAVE_CUDA)
10388: PETSC_SINGLE_LIBRARY_INTERN PetscErrorCode MatSeqDenseCUDAInvertFactors_Internal(Mat);
10389: #endif

10391: /* Schur status updated in the interface */
10392: static PetscErrorCode MatFactorInvertSchurComplement_Private(Mat F)
10393: {
10394:   Mat S = F->schur;

10396:   PetscFunctionBegin;
10397:   if (S) {
10398:     PetscMPIInt size;
10399:     PetscBool   isdense, isdensecuda;

10401:     PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)S), &size));
10402:     PetscCheck(size <= 1, PetscObjectComm((PetscObject)S), PETSC_ERR_SUP, "Not yet implemented");
10403:     PetscCall(PetscObjectTypeCompare((PetscObject)S, MATSEQDENSE, &isdense));
10404:     PetscCall(PetscObjectTypeCompare((PetscObject)S, MATSEQDENSECUDA, &isdensecuda));
10405:     PetscCheck(isdense || isdensecuda, PetscObjectComm((PetscObject)S), PETSC_ERR_SUP, "Not implemented for type %s", ((PetscObject)S)->type_name);
10406:     PetscCall(PetscLogEventBegin(MAT_FactorInvS, F, 0, 0, 0));
10407:     if (isdense) {
10408:       PetscCall(MatSeqDenseInvertFactors_Private(S));
10409:     } else if (isdensecuda) {
10410: #if PetscDefined(HAVE_CUDA)
10411:       PetscCall(MatSeqDenseCUDAInvertFactors_Internal(S));
10412: #endif
10413:     }
10414:     // HIP??????????????
10415:     PetscCall(PetscLogEventEnd(MAT_FactorInvS, F, 0, 0, 0));
10416:   }
10417:   PetscFunctionReturn(PETSC_SUCCESS);
10418: }

10420: /*@
10421:   MatFactorInvertSchurComplement - Invert the Schur complement matrix computed during the factorization step

10423:   Logically Collective

10425:   Input Parameter:
10426: . F - the factored matrix obtained by calling `MatGetFactor()`

10428:   Level: advanced

10430:   Notes:
10431:   Must be called after `MatFactorSetSchurIS()`.

10433:   Call `MatFactorGetSchurComplement()` or  `MatFactorCreateSchurComplement()` AFTER this call to actually compute the inverse and get access to it.

10435: .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatFactorSetSchurIS()`, `MatFactorGetSchurComplement()`, `MatFactorCreateSchurComplement()`
10436: @*/
10437: PetscErrorCode MatFactorInvertSchurComplement(Mat F)
10438: {
10439:   PetscFunctionBegin;
10442:   if (F->schur_status == MAT_FACTOR_SCHUR_INVERTED) PetscFunctionReturn(PETSC_SUCCESS);
10443:   PetscCall(MatFactorFactorizeSchurComplement(F));
10444:   PetscCall(MatFactorInvertSchurComplement_Private(F));
10445:   F->schur_status = MAT_FACTOR_SCHUR_INVERTED;
10446:   PetscFunctionReturn(PETSC_SUCCESS);
10447: }

10449: /*@
10450:   MatFactorFactorizeSchurComplement - Factorize the Schur complement matrix computed during the factorization step

10452:   Logically Collective

10454:   Input Parameter:
10455: . F - the factored matrix obtained by calling `MatGetFactor()`

10457:   Level: advanced

10459:   Note:
10460:   Must be called after `MatFactorSetSchurIS()`

10462: .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatFactorSetSchurIS()`, `MatFactorInvertSchurComplement()`
10463: @*/
10464: PetscErrorCode MatFactorFactorizeSchurComplement(Mat F)
10465: {
10466:   MatFactorInfo info;

10468:   PetscFunctionBegin;
10471:   if (F->schur_status == MAT_FACTOR_SCHUR_INVERTED || F->schur_status == MAT_FACTOR_SCHUR_FACTORED) PetscFunctionReturn(PETSC_SUCCESS);
10472:   PetscCall(PetscLogEventBegin(MAT_FactorFactS, F, 0, 0, 0));
10473:   PetscCall(PetscMemzero(&info, sizeof(MatFactorInfo)));
10474:   if (F->factortype == MAT_FACTOR_CHOLESKY) { /* LDL^t regarded as Cholesky */
10475:     PetscCall(MatCholeskyFactor(F->schur, NULL, &info));
10476:   } else {
10477:     PetscCall(MatLUFactor(F->schur, NULL, NULL, &info));
10478:   }
10479:   PetscCall(PetscLogEventEnd(MAT_FactorFactS, F, 0, 0, 0));
10480:   F->schur_status = MAT_FACTOR_SCHUR_FACTORED;
10481:   PetscFunctionReturn(PETSC_SUCCESS);
10482: }

10484: /*@
10485:   MatPtAP - Creates the matrix product $C = P^T * A * P$

10487:   Neighbor-wise Collective

10489:   Input Parameters:
10490: + A     - the matrix
10491: . P     - the projection matrix
10492: . scall - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`
10493: - 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
10494:           if the result is a dense matrix this is irrelevant

10496:   Output Parameter:
10497: . C - the product matrix

10499:   Level: intermediate

10501:   Notes:
10502:   `C` will be created and must be destroyed by the user with `MatDestroy()`.

10504:   This is a convenience routine that wraps the use of the `MatProductCreate()` with a `MatProductType` of `MATPRODUCT_PtAP`
10505:   functionality into a single function call. For more involved matrix-matrix operations see `MatProductCreate()`.

10507:   The deprecated `PETSC_DEFAULT` in `fill` also means use the current value

10509:   Developer Note:
10510:   For matrix types without special implementation the function fallbacks to `MatMatMult()` followed by `MatTransposeMatMult()`.

10512: .seealso: [](ch_matrices), `Mat`, `MatProductCreate()`, `MatMatMult()`, `MatRARt()`
10513: @*/
10514: PetscErrorCode MatPtAP(Mat A, Mat P, MatReuse scall, PetscReal fill, Mat *C)
10515: {
10516:   PetscFunctionBegin;
10517:   if (scall == MAT_REUSE_MATRIX) MatCheckProduct(*C, 5);
10518:   PetscCheck(scall != MAT_INPLACE_MATRIX, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "Inplace product not supported");

10520:   if (scall == MAT_INITIAL_MATRIX) {
10521:     PetscCall(MatProductCreate(A, P, NULL, C));
10522:     PetscCall(MatProductSetType(*C, MATPRODUCT_PtAP));
10523:     PetscCall(MatProductSetAlgorithm(*C, "default"));
10524:     PetscCall(MatProductSetFill(*C, fill));

10526:     (*C)->product->api_user = PETSC_TRUE;
10527:     PetscCall(MatProductSetFromOptions(*C));
10528:     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);
10529:     PetscCall(MatProductSymbolic(*C));
10530:   } else { /* scall == MAT_REUSE_MATRIX */
10531:     PetscCall(MatProductReplaceMats(A, P, NULL, *C));
10532:   }

10534:   PetscCall(MatProductNumeric(*C));
10535:   if (A->symmetric == PETSC_BOOL3_TRUE) {
10536:     PetscCall(MatSetOption(*C, MAT_SYMMETRIC, PETSC_TRUE));
10537:     (*C)->spd = A->spd;
10538:   }
10539:   PetscFunctionReturn(PETSC_SUCCESS);
10540: }

10542: /*@
10543:   MatRARt - Creates the matrix product $C = R * A * R^T$

10545:   Neighbor-wise Collective

10547:   Input Parameters:
10548: + A     - the matrix
10549: . R     - the projection matrix
10550: . scall - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`
10551: - fill  - expected fill as ratio of nnz(C)/nnz(A), use `PETSC_DETERMINE` or `PETSC_CURRENT` if you do not have a good estimate
10552:           if the result is a dense matrix this is irrelevant

10554:   Output Parameter:
10555: . C - the product matrix

10557:   Level: intermediate

10559:   Notes:
10560:   `C` will be created and must be destroyed by the user with `MatDestroy()`.

10562:   This is a convenience routine that wraps the use of the `MatProductCreate()` with a `MatProductType` of `MATPRODUCT_RARt`
10563:   functionality into a single function call. For more involved matrix-matrix operations see `MatProductCreate()`.

10565:   This routine is currently only implemented for pairs of `MATAIJ` matrices and classes
10566:   which inherit from `MATAIJ`. Due to PETSc sparse matrix block row distribution among processes,
10567:   the parallel `MatRARt()` is implemented computing the explicit transpose of `R`, which can be very expensive.
10568:   We recommend using `MatPtAP()` when possible.

10570:   The deprecated `PETSC_DEFAULT` in `fill` also means use the current value

10572: .seealso: [](ch_matrices), `Mat`, `MatProductCreate()`, `MatMatMult()`, `MatPtAP()`
10573: @*/
10574: PetscErrorCode MatRARt(Mat A, Mat R, MatReuse scall, PetscReal fill, Mat *C)
10575: {
10576:   PetscFunctionBegin;
10577:   if (scall == MAT_REUSE_MATRIX) MatCheckProduct(*C, 5);
10578:   PetscCheck(scall != MAT_INPLACE_MATRIX, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "Inplace product not supported");

10580:   if (scall == MAT_INITIAL_MATRIX) {
10581:     PetscCall(MatProductCreate(A, R, NULL, C));
10582:     PetscCall(MatProductSetType(*C, MATPRODUCT_RARt));
10583:     PetscCall(MatProductSetAlgorithm(*C, "default"));
10584:     PetscCall(MatProductSetFill(*C, fill));

10586:     (*C)->product->api_user = PETSC_TRUE;
10587:     PetscCall(MatProductSetFromOptions(*C));
10588:     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);
10589:     PetscCall(MatProductSymbolic(*C));
10590:   } else { /* scall == MAT_REUSE_MATRIX */
10591:     PetscCall(MatProductReplaceMats(A, R, NULL, *C));
10592:   }

10594:   PetscCall(MatProductNumeric(*C));
10595:   if (A->symmetric == PETSC_BOOL3_TRUE) PetscCall(MatSetOption(*C, MAT_SYMMETRIC, PETSC_TRUE));
10596:   PetscFunctionReturn(PETSC_SUCCESS);
10597: }

10599: static PetscErrorCode MatProduct_Private(Mat A, Mat B, MatReuse scall, PetscReal fill, MatProductType ptype, Mat *C)
10600: {
10601:   PetscBool flg = PETSC_TRUE;

10603:   PetscFunctionBegin;
10604:   PetscCheck(scall != MAT_INPLACE_MATRIX, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "MAT_INPLACE_MATRIX product not supported");
10605:   if (scall == MAT_INITIAL_MATRIX) {
10606:     PetscCall(PetscInfo(A, "Calling MatProduct API with MAT_INITIAL_MATRIX and product type %s\n", MatProductTypes[ptype]));
10607:     PetscCall(MatProductCreate(A, B, NULL, C));
10608:     PetscCall(MatProductSetAlgorithm(*C, MATPRODUCTALGORITHMDEFAULT));
10609:     PetscCall(MatProductSetFill(*C, fill));
10610:   } else { /* scall == MAT_REUSE_MATRIX */
10611:     Mat_Product *product = (*C)->product;

10613:     PetscCall(PetscObjectBaseTypeCompareAny((PetscObject)*C, &flg, MATSEQDENSE, MATMPIDENSE, ""));
10614:     if (flg && product && product->type != ptype) {
10615:       PetscCall(MatProductClear(*C));
10616:       product = NULL;
10617:     }
10618:     PetscCall(PetscInfo(A, "Calling MatProduct API with MAT_REUSE_MATRIX %s product present and product type %s\n", product ? "with" : "without", MatProductTypes[ptype]));
10619:     if (!product) { /* user provide the dense matrix *C without calling MatProductCreate() or reusing it from previous calls */
10620:       PetscCheck(flg, PetscObjectComm((PetscObject)*C), PETSC_ERR_SUP, "Call MatProductCreate() first");
10621:       PetscCall(MatProductCreate_Private(A, B, NULL, *C));
10622:       product        = (*C)->product;
10623:       product->fill  = fill;
10624:       product->clear = PETSC_TRUE;
10625:     } else { /* user may change input matrices A or B when MAT_REUSE_MATRIX */
10626:       flg = PETSC_FALSE;
10627:       PetscCall(MatProductReplaceMats(A, B, NULL, *C));
10628:     }
10629:   }
10630:   if (flg) {
10631:     (*C)->product->api_user = PETSC_TRUE;
10632:     PetscCall(MatProductSetType(*C, ptype));
10633:     PetscCall(MatProductSetFromOptions(*C));
10634:     PetscCall(MatProductSymbolic(*C));
10635:   }
10636:   PetscCall(MatProductNumeric(*C));
10637:   PetscFunctionReturn(PETSC_SUCCESS);
10638: }

10640: /*@
10641:   MatMatMult - Performs matrix-matrix multiplication $ C=A*B $.

10643:   Neighbor-wise Collective

10645:   Input Parameters:
10646: + A     - the left matrix
10647: . B     - the right matrix
10648: . scall - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`
10649: - 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
10650:           if the result is a dense matrix this is irrelevant

10652:   Output Parameter:
10653: . C - the product matrix

10655:   Notes:
10656:   Unless scall is `MAT_REUSE_MATRIX` C will be created.

10658:   `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
10659:   call to this function with `MAT_INITIAL_MATRIX`.

10661:   To determine the correct fill value, run with `-info` and search for the string "Fill ratio" to see the value actually needed.

10663:   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`,
10664:   rather than first having `MatMatMult()` create it for you. You can NEVER do this if the matrix `C` is sparse.

10666:   The deprecated `PETSC_DEFAULT` in `fill` also means use the current value

10668:   This is a convenience routine that wraps the use of the `MatProductCreate()` with a `MatProductType` of `MATPRODUCT_AB`
10669:   functionality into a single function call. For more involved matrix-matrix operations see `MatProductCreate()`.

10671:   Example of Usage:
10672: .vb
10673:      MatProductCreate(A,B,NULL,&C);
10674:      MatProductSetType(C,MATPRODUCT_AB);
10675:      MatProductSymbolic(C);
10676:      MatProductNumeric(C); // compute C=A * B
10677:      MatProductReplaceMats(A1,B1,NULL,C); // compute C=A1 * B1
10678:      MatProductNumeric(C);
10679:      MatProductReplaceMats(A2,NULL,NULL,C); // compute C=A2 * B1
10680:      MatProductNumeric(C);
10681: .ve

10683:   Level: intermediate

10685: .seealso: [](ch_matrices), `Mat`, `MatProductType`, `MATPRODUCT_AB`, `MatTransposeMatMult()`, `MatMatTransposeMult()`, `MatPtAP()`, `MatProductCreate()`, `MatProductSymbolic()`, `MatProductReplaceMats()`, `MatProductNumeric()`
10686: @*/
10687: PetscErrorCode MatMatMult(Mat A, Mat B, MatReuse scall, PetscReal fill, Mat *C)
10688: {
10689:   PetscFunctionBegin;
10690:   PetscCall(MatProduct_Private(A, B, scall, fill, MATPRODUCT_AB, C));
10691:   PetscFunctionReturn(PETSC_SUCCESS);
10692: }

10694: /*@
10695:   MatMatTransposeMult - Performs matrix-matrix multiplication $C = A*B^T$.

10697:   Neighbor-wise Collective

10699:   Input Parameters:
10700: + A     - the left matrix
10701: . B     - the right matrix
10702: . scall - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`
10703: - fill  - expected fill as ratio of nnz(C)/(nnz(A) + nnz(B)), use `PETSC_DETERMINE` or `PETSC_CURRENT` if not known

10705:   Output Parameter:
10706: . C - the product matrix

10708:   Options Database Key:
10709: . -matmattransmult_mpidense_mpidense_via {allgatherv,cyclic} - Choose between algorithms for `MATMPIDENSE` matrices: the
10710:               first redundantly copies the transposed `B` matrix on each process and requires O(log P) communication complexity;
10711:               the second never stores more than one portion of the `B` matrix at a time but requires O(P) communication complexity.

10713:   Level: intermediate

10715:   Notes:
10716:   C will be created if `MAT_INITIAL_MATRIX` and must be destroyed by the user with `MatDestroy()`.

10718:   `MAT_REUSE_MATRIX` can only be used if the matrices A and B have the same nonzero pattern as in the previous call

10720:   To determine the correct fill value, run with -info and search for the string "Fill ratio" to see the value
10721:   actually needed.

10723:   This routine is currently only implemented for pairs of `MATSEQAIJ` matrices, for the `MATSEQDENSE` class,
10724:   and for pairs of `MATMPIDENSE` matrices.

10726:   This is a convenience routine that wraps the use of the `MatProductCreate()` with a `MatProductType` of `MATPRODUCT_ABt`
10727:   functionality into a single function call. For more involved matrix-matrix operations see `MatProductCreate()`.

10729:   The deprecated `PETSC_DEFAULT` in `fill` also means use the current value

10731: .seealso: [](ch_matrices), `Mat`, `MatProductCreate()`, `MATPRODUCT_ABt`, `MatMatMult()`, `MatTransposeMatMult()`, `MatPtAP()`, `MatProductAlgorithm`, `MatProductType`
10732: @*/
10733: PetscErrorCode MatMatTransposeMult(Mat A, Mat B, MatReuse scall, PetscReal fill, Mat *C)
10734: {
10735:   PetscFunctionBegin;
10736:   PetscCall(MatProduct_Private(A, B, scall, fill, MATPRODUCT_ABt, C));
10737:   if (A == B) PetscCall(MatSetOption(*C, MAT_SYMMETRIC, PETSC_TRUE));
10738:   PetscFunctionReturn(PETSC_SUCCESS);
10739: }

10741: /*@
10742:   MatTransposeMatMult - Performs matrix-matrix multiplication $C = A^T*B$.

10744:   Neighbor-wise Collective

10746:   Input Parameters:
10747: + A     - the left matrix
10748: . B     - the right matrix
10749: . scall - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`
10750: - fill  - expected fill as ratio of nnz(C)/(nnz(A) + nnz(B)), use `PETSC_DETERMINE` or `PETSC_CURRENT` if not known

10752:   Output Parameter:
10753: . C - the product matrix

10755:   Level: intermediate

10757:   Notes:
10758:   `C` will be created if `MAT_INITIAL_MATRIX` and must be destroyed by the user with `MatDestroy()`.

10760:   `MAT_REUSE_MATRIX` can only be used if `A` and `B` have the same nonzero pattern as in the previous call.

10762:   This is a convenience routine that wraps the use of `MatProductCreate()` with a `MatProductType` of `MATPRODUCT_AtB`
10763:   functionality into a single function call. For more involved matrix-matrix operations see `MatProductCreate()`.

10765:   To determine the correct fill value, run with -info and search for the string "Fill ratio" to see the value
10766:   actually needed.

10768:   This routine is currently implemented for pairs of `MATAIJ` matrices and pairs of `MATSEQDENSE` matrices and classes
10769:   which inherit from `MATSEQAIJ`.  `C` will be of the same type as the input matrices.

10771:   The deprecated `PETSC_DEFAULT` in `fill` also means use the current value

10773: .seealso: [](ch_matrices), `Mat`, `MatProductCreate()`, `MATPRODUCT_AtB`, `MatMatMult()`, `MatMatTransposeMult()`, `MatPtAP()`
10774: @*/
10775: PetscErrorCode MatTransposeMatMult(Mat A, Mat B, MatReuse scall, PetscReal fill, Mat *C)
10776: {
10777:   PetscFunctionBegin;
10778:   PetscCall(MatProduct_Private(A, B, scall, fill, MATPRODUCT_AtB, C));
10779:   PetscFunctionReturn(PETSC_SUCCESS);
10780: }

10782: /*@
10783:   MatMatMatMult - Performs matrix-matrix-matrix multiplication D=A*B*C.

10785:   Neighbor-wise Collective

10787:   Input Parameters:
10788: + A     - the left matrix
10789: . B     - the middle matrix
10790: . C     - the right matrix
10791: . scall - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`
10792: - 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
10793:           if the result is a dense matrix this is irrelevant

10795:   Output Parameter:
10796: . D - the product matrix

10798:   Level: intermediate

10800:   Notes:
10801:   Unless `scall` is `MAT_REUSE_MATRIX` `D` will be created.

10803:   `MAT_REUSE_MATRIX` can only be used if the matrices `A`, `B`, and `C` have the same nonzero pattern as in the previous call

10805:   This is a convenience routine that wraps the use of the `MatProductCreate()` with a `MatProductType` of `MATPRODUCT_ABC`
10806:   functionality into a single function call. For more involved matrix-matrix operations see `MatProductCreate()`.

10808:   To determine the correct fill value, run with `-info` and search for the string "Fill ratio" to see the value
10809:   actually needed.

10811:   If you have many matrices with the same non-zero structure to multiply, you
10812:   should use `MAT_REUSE_MATRIX` in all calls but the first

10814:   The deprecated `PETSC_DEFAULT` in `fill` also means use the current value

10816: .seealso: [](ch_matrices), `Mat`, `MatProductCreate()`, `MATPRODUCT_ABC`, `MatMatMult`, `MatPtAP()`, `MatMatTransposeMult()`, `MatTransposeMatMult()`
10817: @*/
10818: PetscErrorCode MatMatMatMult(Mat A, Mat B, Mat C, MatReuse scall, PetscReal fill, Mat *D)
10819: {
10820:   PetscFunctionBegin;
10821:   if (scall == MAT_REUSE_MATRIX) MatCheckProduct(*D, 6);
10822:   PetscCheck(scall != MAT_INPLACE_MATRIX, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "Inplace product not supported");

10824:   if (scall == MAT_INITIAL_MATRIX) {
10825:     PetscCall(MatProductCreate(A, B, C, D));
10826:     PetscCall(MatProductSetType(*D, MATPRODUCT_ABC));
10827:     PetscCall(MatProductSetAlgorithm(*D, "default"));
10828:     PetscCall(MatProductSetFill(*D, fill));

10830:     (*D)->product->api_user = PETSC_TRUE;
10831:     PetscCall(MatProductSetFromOptions(*D));
10832:     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,
10833:                ((PetscObject)C)->type_name);
10834:     PetscCall(MatProductSymbolic(*D));
10835:   } else { /* user may change input matrices when REUSE */
10836:     PetscCall(MatProductReplaceMats(A, B, C, *D));
10837:   }
10838:   PetscCall(MatProductNumeric(*D));
10839:   PetscFunctionReturn(PETSC_SUCCESS);
10840: }

10842: /*@
10843:   MatCreateRedundantMatrix - Create redundant matrices and put them into processors of subcommunicators.

10845:   Collective

10847:   Input Parameters:
10848: + mat      - the matrix
10849: . nsubcomm - the number of subcommunicators (= number of redundant parallel or sequential matrices)
10850: . subcomm  - MPI communicator split from the communicator where mat resides in (or `MPI_COMM_NULL` if nsubcomm is used)
10851: - reuse    - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`

10853:   Output Parameter:
10854: . matredundant - redundant matrix

10856:   Level: advanced

10858:   Notes:
10859:   `MAT_REUSE_MATRIX` can only be used when the nonzero structure of the
10860:   original matrix has not changed from that last call to `MatCreateRedundantMatrix()`.

10862:   This routine creates the duplicated matrices in the subcommunicators; you should NOT create them before
10863:   calling it.

10865:   `PetscSubcommCreate()` can be used to manage the creation of the subcomm but need not be.

10867: .seealso: [](ch_matrices), `Mat`, `MatDestroy()`, `PetscSubcommCreate()`, `PetscSubcomm`
10868: @*/
10869: PetscErrorCode MatCreateRedundantMatrix(Mat mat, PetscInt nsubcomm, MPI_Comm subcomm, MatReuse reuse, Mat *matredundant)
10870: {
10871:   MPI_Comm       comm;
10872:   PetscMPIInt    size;
10873:   PetscInt       mloc_sub, nloc_sub, rstart, rend, M = mat->rmap->N, N = mat->cmap->N, bs = mat->rmap->bs;
10874:   Mat_Redundant *redund     = NULL;
10875:   PetscSubcomm   psubcomm   = NULL;
10876:   MPI_Comm       subcomm_in = subcomm;
10877:   Mat           *matseq;
10878:   IS             isrow, iscol;
10879:   PetscBool      newsubcomm = PETSC_FALSE;

10881:   PetscFunctionBegin;
10883:   if (nsubcomm && reuse == MAT_REUSE_MATRIX) {
10884:     PetscAssertPointer(*matredundant, 5);
10886:   }

10888:   PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)mat), &size));
10889:   if (size == 1 || nsubcomm == 1) {
10890:     if (reuse == MAT_INITIAL_MATRIX) {
10891:       PetscCall(MatDuplicate(mat, MAT_COPY_VALUES, matredundant));
10892:     } else {
10893:       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");
10894:       PetscCall(MatCopy(mat, *matredundant, SAME_NONZERO_PATTERN));
10895:     }
10896:     PetscFunctionReturn(PETSC_SUCCESS);
10897:   }

10899:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
10900:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
10901:   MatCheckPreallocated(mat, 1);

10903:   PetscCall(PetscLogEventBegin(MAT_RedundantMat, mat, 0, 0, 0));
10904:   if (subcomm_in == MPI_COMM_NULL && reuse == MAT_INITIAL_MATRIX) { /* get subcomm if user does not provide subcomm */
10905:     /* create psubcomm, then get subcomm */
10906:     PetscCall(PetscObjectGetComm((PetscObject)mat, &comm));
10907:     PetscCallMPI(MPI_Comm_size(comm, &size));
10908:     PetscCheck(nsubcomm >= 1 && nsubcomm <= size, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "nsubcomm must between 1 and %d", size);

10910:     PetscCall(PetscSubcommCreate(comm, &psubcomm));
10911:     PetscCall(PetscSubcommSetNumber(psubcomm, nsubcomm));
10912:     PetscCall(PetscSubcommSetType(psubcomm, PETSC_SUBCOMM_CONTIGUOUS));
10913:     PetscCall(PetscSubcommSetFromOptions(psubcomm));
10914:     PetscCall(PetscCommDuplicate(PetscSubcommChild(psubcomm), &subcomm, NULL));
10915:     newsubcomm = PETSC_TRUE;
10916:     PetscCall(PetscSubcommDestroy(&psubcomm));
10917:   }

10919:   /* get isrow, iscol and a local sequential matrix matseq[0] */
10920:   if (reuse == MAT_INITIAL_MATRIX) {
10921:     mloc_sub = PETSC_DECIDE;
10922:     nloc_sub = PETSC_DECIDE;
10923:     if (bs < 1) {
10924:       PetscCall(PetscSplitOwnership(subcomm, &mloc_sub, &M));
10925:       PetscCall(PetscSplitOwnership(subcomm, &nloc_sub, &N));
10926:     } else {
10927:       PetscCall(PetscSplitOwnershipBlock(subcomm, bs, &mloc_sub, &M));
10928:       PetscCall(PetscSplitOwnershipBlock(subcomm, bs, &nloc_sub, &N));
10929:     }
10930:     PetscCallMPI(MPI_Scan(&mloc_sub, &rend, 1, MPIU_INT, MPI_SUM, subcomm));
10931:     rstart = rend - mloc_sub;
10932:     PetscCall(ISCreateStride(PETSC_COMM_SELF, mloc_sub, rstart, 1, &isrow));
10933:     PetscCall(ISCreateStride(PETSC_COMM_SELF, N, 0, 1, &iscol));
10934:     PetscCall(ISSetIdentity(iscol));
10935:   } else { /* reuse == MAT_REUSE_MATRIX */
10936:     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");
10937:     /* retrieve subcomm */
10938:     PetscCall(PetscObjectGetComm((PetscObject)*matredundant, &subcomm));
10939:     redund = (*matredundant)->redundant;
10940:     isrow  = redund->isrow;
10941:     iscol  = redund->iscol;
10942:     matseq = redund->matseq;
10943:   }
10944:   PetscCall(MatCreateSubMatrices(mat, 1, &isrow, &iscol, reuse, &matseq));

10946:   /* get matredundant over subcomm */
10947:   if (reuse == MAT_INITIAL_MATRIX) {
10948:     PetscCall(MatCreateMPIMatConcatenateSeqMat(subcomm, matseq[0], nloc_sub, reuse, matredundant));

10950:     /* create a supporting struct and attach it to C for reuse */
10951:     PetscCall(PetscNew(&redund));
10952:     (*matredundant)->redundant = redund;
10953:     redund->isrow              = isrow;
10954:     redund->iscol              = iscol;
10955:     redund->matseq             = matseq;
10956:     if (newsubcomm) {
10957:       redund->subcomm = subcomm;
10958:     } else {
10959:       redund->subcomm = MPI_COMM_NULL;
10960:     }
10961:   } else {
10962:     PetscCall(MatCreateMPIMatConcatenateSeqMat(subcomm, matseq[0], PETSC_DECIDE, reuse, matredundant));
10963:   }
10964: #if PetscDefined(HAVE_VIENNACL) || PetscDefined(HAVE_CUDA) || PetscDefined(HAVE_HIP)
10965:   if (matseq[0]->boundtocpu && matseq[0]->bindingpropagates) {
10966:     PetscCall(MatBindToCPU(*matredundant, PETSC_TRUE));
10967:     PetscCall(MatSetBindingPropagates(*matredundant, PETSC_TRUE));
10968:   }
10969: #endif
10970:   PetscCall(PetscLogEventEnd(MAT_RedundantMat, mat, 0, 0, 0));
10971:   PetscFunctionReturn(PETSC_SUCCESS);
10972: }

10974: /*@C
10975:   MatGetMultiProcBlock - Create multiple 'parallel submatrices' from
10976:   a given `Mat`. Each submatrix can span multiple procs.

10978:   Collective

10980:   Input Parameters:
10981: + mat     - the matrix
10982: . subComm - the sub communicator obtained as if by `MPI_Comm_split(PetscObjectComm((PetscObject)mat))`
10983: - scall   - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`

10985:   Output Parameter:
10986: . subMat - parallel sub-matrices each spanning a given `subcomm`

10988:   Level: advanced

10990:   Notes:
10991:   The submatrix partition across processors is dictated by `subComm` a
10992:   communicator obtained by `MPI_comm_split()` or via `PetscSubcommCreate()`. The `subComm`
10993:   is not restricted to be grouped with consecutive original MPI processes.

10995:   Due the `MPI_Comm_split()` usage, the parallel layout of the submatrices
10996:   map directly to the layout of the original matrix [wrt the local
10997:   row,col partitioning]. So the original 'DiagonalMat' naturally maps
10998:   into the 'DiagonalMat' of the `subMat`, hence it is used directly from
10999:   the `subMat`. However the offDiagMat looses some columns - and this is
11000:   reconstructed with `MatSetValues()`

11002:   This is used by `PCBJACOBI` when a single block spans multiple MPI processes.

11004: .seealso: [](ch_matrices), `Mat`, `MatCreateRedundantMatrix()`, `MatCreateSubMatrices()`, `PCBJACOBI`
11005: @*/
11006: PetscErrorCode MatGetMultiProcBlock(Mat mat, MPI_Comm subComm, MatReuse scall, Mat *subMat)
11007: {
11008:   PetscMPIInt commsize, subCommSize;

11010:   PetscFunctionBegin;
11011:   PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)mat), &commsize));
11012:   PetscCallMPI(MPI_Comm_size(subComm, &subCommSize));
11013:   PetscCheck(subCommSize <= commsize, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_OUTOFRANGE, "CommSize %d < SubCommZize %d", commsize, subCommSize);

11015:   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");
11016:   PetscCall(PetscLogEventBegin(MAT_GetMultiProcBlock, mat, 0, 0, 0));
11017:   PetscUseTypeMethod(mat, getmultiprocblock, subComm, scall, subMat);
11018:   PetscCall(PetscLogEventEnd(MAT_GetMultiProcBlock, mat, 0, 0, 0));
11019:   PetscFunctionReturn(PETSC_SUCCESS);
11020: }

11022: /*@
11023:   MatGetLocalSubMatrix - Gets a reference to a submatrix specified in local numbering

11025:   Not Collective

11027:   Input Parameters:
11028: + mat   - matrix to extract local submatrix from
11029: . isrow - local row indices for submatrix
11030: - iscol - local column indices for submatrix

11032:   Output Parameter:
11033: . submat - the submatrix

11035:   Level: intermediate

11037:   Notes:
11038:   `submat` should be disposed of with `MatRestoreLocalSubMatrix()`.

11040:   Depending on the format of `mat`, the returned `submat` may not implement `MatMult()`.  Its communicator may be
11041:   the same as `mat`, it may be `PETSC_COMM_SELF`, or some other sub-communictor of `mat`'s.

11043:   `submat` always implements `MatSetValuesLocal()`.  If `isrow` and `iscol` have the same block size, then
11044:   `MatSetValuesBlockedLocal()` will also be implemented.

11046:   `mat` must have had a `ISLocalToGlobalMapping` provided to it with `MatSetLocalToGlobalMapping()`.
11047:   Matrices obtained with `DMCreateMatrix()` generally already have the local to global mapping provided.

11049: .seealso: [](ch_matrices), `Mat`, `MatRestoreLocalSubMatrix()`, `MatCreateLocalRef()`, `MatSetLocalToGlobalMapping()`
11050: @*/
11051: PetscErrorCode MatGetLocalSubMatrix(Mat mat, IS isrow, IS iscol, Mat *submat)
11052: {
11053:   PetscFunctionBegin;
11057:   PetscCheckSameComm(isrow, 2, iscol, 3);
11058:   PetscAssertPointer(submat, 4);
11059:   PetscCheck(mat->rmap->mapping, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Matrix must have local to global mapping provided before this call");

11061:   if (mat->ops->getlocalsubmatrix) {
11062:     PetscUseTypeMethod(mat, getlocalsubmatrix, isrow, iscol, submat);
11063:   } else {
11064:     PetscCall(MatCreateLocalRef(mat, isrow, iscol, submat));
11065:   }
11066:   (*submat)->assembled = mat->assembled;
11067:   PetscFunctionReturn(PETSC_SUCCESS);
11068: }

11070: /*@
11071:   MatRestoreLocalSubMatrix - Restores a reference to a submatrix specified in local numbering obtained with `MatGetLocalSubMatrix()`

11073:   Not Collective

11075:   Input Parameters:
11076: + mat    - matrix to extract local submatrix from
11077: . isrow  - local row indices for submatrix
11078: . iscol  - local column indices for submatrix
11079: - submat - the submatrix

11081:   Level: intermediate

11083: .seealso: [](ch_matrices), `Mat`, `MatGetLocalSubMatrix()`
11084: @*/
11085: PetscErrorCode MatRestoreLocalSubMatrix(Mat mat, IS isrow, IS iscol, Mat *submat)
11086: {
11087:   PetscFunctionBegin;
11091:   PetscCheckSameComm(isrow, 2, iscol, 3);
11092:   PetscAssertPointer(submat, 4);

11095:   if (mat->ops->restorelocalsubmatrix) {
11096:     PetscUseTypeMethod(mat, restorelocalsubmatrix, isrow, iscol, submat);
11097:   } else {
11098:     PetscCall(MatDestroy(submat));
11099:   }
11100:   *submat = NULL;
11101:   PetscFunctionReturn(PETSC_SUCCESS);
11102: }

11104: /*@
11105:   MatFindZeroDiagonals - Finds all the rows of a matrix that have zero or no diagonal entry in the matrix

11107:   Collective

11109:   Input Parameter:
11110: . mat - the matrix

11112:   Output Parameter:
11113: . is - if any rows have zero diagonals this contains the list of them

11115:   Level: developer

11117: .seealso: [](ch_matrices), `Mat`, `MatMultTranspose()`, `MatMultAdd()`, `MatMultTransposeAdd()`
11118: @*/
11119: PetscErrorCode MatFindZeroDiagonals(Mat mat, IS *is)
11120: {
11121:   PetscFunctionBegin;
11124:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
11125:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");

11127:   if (!mat->ops->findzerodiagonals) {
11128:     Vec                diag;
11129:     const PetscScalar *a;
11130:     PetscInt          *rows;
11131:     PetscInt           rStart, rEnd, r, nrow = 0;

11133:     PetscCall(MatCreateVecs(mat, &diag, NULL));
11134:     PetscCall(MatGetDiagonal(mat, diag));
11135:     PetscCall(MatGetOwnershipRange(mat, &rStart, &rEnd));
11136:     PetscCall(VecGetArrayRead(diag, &a));
11137:     for (r = 0; r < rEnd - rStart; ++r)
11138:       if (a[r] == 0.0) ++nrow;
11139:     PetscCall(PetscMalloc1(nrow, &rows));
11140:     nrow = 0;
11141:     for (r = 0; r < rEnd - rStart; ++r)
11142:       if (a[r] == 0.0) rows[nrow++] = r + rStart;
11143:     PetscCall(VecRestoreArrayRead(diag, &a));
11144:     PetscCall(VecDestroy(&diag));
11145:     PetscCall(ISCreateGeneral(PetscObjectComm((PetscObject)mat), nrow, rows, PETSC_OWN_POINTER, is));
11146:   } else {
11147:     PetscUseTypeMethod(mat, findzerodiagonals, is);
11148:   }
11149:   PetscFunctionReturn(PETSC_SUCCESS);
11150: }

11152: /*@
11153:   MatFindOffBlockDiagonalEntries - Finds all the rows of a matrix that have entries outside of the main diagonal block (defined by the matrix block size)

11155:   Collective

11157:   Input Parameter:
11158: . mat - the matrix

11160:   Output Parameter:
11161: . is - contains the list of rows with off block diagonal entries

11163:   Level: developer

11165: .seealso: [](ch_matrices), `Mat`, `MatMultTranspose()`, `MatMultAdd()`, `MatMultTransposeAdd()`
11166: @*/
11167: PetscErrorCode MatFindOffBlockDiagonalEntries(Mat mat, IS *is)
11168: {
11169:   PetscFunctionBegin;
11172:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
11173:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");

11175:   PetscUseTypeMethod(mat, findoffblockdiagonalentries, is);
11176:   PetscFunctionReturn(PETSC_SUCCESS);
11177: }

11179: /*@C
11180:   MatInvertBlockDiagonal - Inverts the block diagonal entries.

11182:   Collective; No Fortran Support

11184:   Input Parameter:
11185: . mat - the matrix

11187:   Output Parameter:
11188: . values - the block inverses in column major order (FORTRAN-like)

11190:   Level: advanced

11192:   Notes:
11193:   The size of the blocks is determined by the block size of the matrix.

11195:   The blocks never overlap between two MPI processes, use `MatInvertVariableBlockEnvelope()` for that case

11197:   The blocks all have the same size, use `MatInvertVariableBlockDiagonal()` for variable block size

11199: .seealso: [](ch_matrices), `Mat`, `MatInvertVariableBlockEnvelope()`, `MatInvertBlockDiagonalMat()`
11200: @*/
11201: PetscErrorCode MatInvertBlockDiagonal(Mat mat, const PetscScalar *values[])
11202: {
11203:   PetscFunctionBegin;
11205:   PetscCheck(mat->assembled, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
11206:   PetscCheck(!mat->factortype, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
11207:   PetscUseTypeMethod(mat, invertblockdiagonal, values);
11208:   PetscFunctionReturn(PETSC_SUCCESS);
11209: }

11211: /*@
11212:   MatInvertVariableBlockDiagonal - Inverts the point block diagonal entries.

11214:   Collective; No Fortran Support

11216:   Input Parameters:
11217: + mat     - the matrix
11218: . nblocks - the number of blocks on the process, set with `MatSetVariableBlockSizes()`
11219: - bsizes  - the size of each block on the process, set with `MatSetVariableBlockSizes()`

11221:   Output Parameter:
11222: . values - the block inverses in column major order (FORTRAN-like)

11224:   Level: advanced

11226:   Notes:
11227:   Use `MatInvertBlockDiagonal()` if all blocks have the same size

11229:   The blocks never overlap between two MPI processes, use `MatInvertVariableBlockEnvelope()` for that case

11231: .seealso: [](ch_matrices), `Mat`, `MatInvertBlockDiagonal()`, `MatSetVariableBlockSizes()`, `MatInvertVariableBlockEnvelope()`
11232: @*/
11233: PetscErrorCode MatInvertVariableBlockDiagonal(Mat mat, PetscInt nblocks, const PetscInt bsizes[], PetscScalar values[])
11234: {
11235:   PetscFunctionBegin;
11237:   PetscCheck(mat->assembled, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
11238:   PetscCheck(!mat->factortype, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
11239:   PetscUseTypeMethod(mat, invertvariableblockdiagonal, nblocks, bsizes, values);
11240:   PetscFunctionReturn(PETSC_SUCCESS);
11241: }

11243: /*@
11244:   MatInvertBlockDiagonalMat - set the values of matrix C to be the inverted block diagonal of matrix A

11246:   Collective

11248:   Input Parameters:
11249: + A - the matrix
11250: - C - matrix with inverted block diagonal of `A`.  This matrix should be created and may have its type set.

11252:   Level: advanced

11254:   Note:
11255:   The blocksize of the matrix is used to determine the blocks on the diagonal of `C`

11257: .seealso: [](ch_matrices), `Mat`, `MatInvertBlockDiagonal()`
11258: @*/
11259: PetscErrorCode MatInvertBlockDiagonalMat(Mat A, Mat C)
11260: {
11261:   const PetscScalar *vals;
11262:   PetscInt          *dnnz;
11263:   PetscInt           m, rstart, rend, bs, i, j;

11265:   PetscFunctionBegin;
11266:   PetscCall(MatInvertBlockDiagonal(A, &vals));
11267:   PetscCall(MatGetBlockSize(A, &bs));
11268:   PetscCall(MatGetLocalSize(A, &m, NULL));
11269:   PetscCall(MatSetLayouts(C, A->rmap, A->cmap));
11270:   PetscCall(MatSetBlockSizes(C, A->rmap->bs, A->cmap->bs));
11271:   PetscCall(PetscMalloc1(m / bs, &dnnz));
11272:   for (j = 0; j < m / bs; j++) dnnz[j] = 1;
11273:   PetscCall(MatXAIJSetPreallocation(C, bs, dnnz, NULL, NULL, NULL));
11274:   PetscCall(PetscFree(dnnz));
11275:   PetscCall(MatGetOwnershipRange(C, &rstart, &rend));
11276:   PetscCall(MatSetOption(C, MAT_ROW_ORIENTED, PETSC_FALSE));
11277:   for (i = rstart / bs; i < rend / bs; i++) PetscCall(MatSetValuesBlocked(C, 1, &i, 1, &i, &vals[(i - rstart / bs) * bs * bs], INSERT_VALUES));
11278:   PetscCall(MatSetOption(C, MAT_NO_OFF_PROC_ENTRIES, PETSC_TRUE));
11279:   PetscCall(MatAssemblyBegin(C, MAT_FINAL_ASSEMBLY));
11280:   PetscCall(MatAssemblyEnd(C, MAT_FINAL_ASSEMBLY));
11281:   PetscCall(MatSetOption(C, MAT_NO_OFF_PROC_ENTRIES, PETSC_FALSE));
11282:   PetscCall(MatSetOption(C, MAT_ROW_ORIENTED, PETSC_TRUE));
11283:   PetscFunctionReturn(PETSC_SUCCESS);
11284: }

11286: /*@
11287:   MatTransposeColoringDestroy - Destroys a coloring context for matrix product $C = A*B^T$ that was created
11288:   via `MatTransposeColoringCreate()`.

11290:   Collective

11292:   Input Parameter:
11293: . c - coloring context

11295:   Level: intermediate

11297: .seealso: [](ch_matrices), `Mat`, `MatTransposeColoringCreate()`
11298: @*/
11299: PetscErrorCode MatTransposeColoringDestroy(MatTransposeColoring *c)
11300: {
11301:   MatTransposeColoring matcolor = *c;

11303:   PetscFunctionBegin;
11304:   if (!matcolor) PetscFunctionReturn(PETSC_SUCCESS);
11305:   if (--((PetscObject)matcolor)->refct > 0) {
11306:     matcolor = NULL;
11307:     PetscFunctionReturn(PETSC_SUCCESS);
11308:   }

11310:   PetscCall(PetscFree3(matcolor->ncolumns, matcolor->nrows, matcolor->colorforrow));
11311:   PetscCall(PetscFree(matcolor->rows));
11312:   PetscCall(PetscFree(matcolor->den2sp));
11313:   PetscCall(PetscFree(matcolor->colorforcol));
11314:   PetscCall(PetscFree(matcolor->columns));
11315:   if (matcolor->brows > 0) PetscCall(PetscFree(matcolor->lstart));
11316:   PetscCall(PetscHeaderDestroy(c));
11317:   PetscFunctionReturn(PETSC_SUCCESS);
11318: }

11320: /*@
11321:   MatTransColoringApplySpToDen - Given a symbolic matrix product $C = A*B^T$ for which
11322:   a `MatTransposeColoring` context has been created, computes a dense $B^T$ by applying
11323:   `MatTransposeColoring` to sparse `B`.

11325:   Collective

11327:   Input Parameters:
11328: + coloring - coloring context created with `MatTransposeColoringCreate()`
11329: - B        - sparse matrix

11331:   Output Parameter:
11332: . Btdense - dense matrix $B^T$

11334:   Level: developer

11336:   Note:
11337:   These are used internally for some implementations of `MatRARt()`

11339: .seealso: [](ch_matrices), `Mat`, `MatTransposeColoringCreate()`, `MatTransposeColoringDestroy()`, `MatTransColoringApplyDenToSp()`
11340: @*/
11341: PetscErrorCode MatTransColoringApplySpToDen(MatTransposeColoring coloring, Mat B, Mat Btdense)
11342: {
11343:   PetscFunctionBegin;

11348:   PetscCall((*B->ops->transcoloringapplysptoden)(coloring, B, Btdense));
11349:   PetscFunctionReturn(PETSC_SUCCESS);
11350: }

11352: /*@
11353:   MatTransColoringApplyDenToSp - Given a symbolic matrix product $C_{sp} = A*B^T$ for which
11354:   a `MatTransposeColoring` context has been created and a dense matrix $C_{den} = A*B^T_{dense}$
11355:   in which `B^T_{dens}` is obtained from `MatTransColoringApplySpToDen()`, recover sparse matrix
11356:   $C_{sp}$ from $C_{den}$.

11358:   Collective

11360:   Input Parameters:
11361: + matcoloring - coloring context created with `MatTransposeColoringCreate()`
11362: - Cden        - matrix product of a sparse matrix and a dense matrix Btdense

11364:   Output Parameter:
11365: . Csp - sparse matrix

11367:   Level: developer

11369:   Note:
11370:   These are used internally for some implementations of `MatRARt()`

11372: .seealso: [](ch_matrices), `Mat`, `MatTransposeColoringCreate()`, `MatTransposeColoringDestroy()`, `MatTransColoringApplySpToDen()`
11373: @*/
11374: PetscErrorCode MatTransColoringApplyDenToSp(MatTransposeColoring matcoloring, Mat Cden, Mat Csp)
11375: {
11376:   PetscFunctionBegin;

11381:   PetscCall((*Csp->ops->transcoloringapplydentosp)(matcoloring, Cden, Csp));
11382:   PetscCall(MatAssemblyBegin(Csp, MAT_FINAL_ASSEMBLY));
11383:   PetscCall(MatAssemblyEnd(Csp, MAT_FINAL_ASSEMBLY));
11384:   PetscFunctionReturn(PETSC_SUCCESS);
11385: }

11387: /*@
11388:   MatTransposeColoringCreate - Creates a matrix coloring context for the matrix product $C = A*B^T$.

11390:   Collective

11392:   Input Parameters:
11393: + mat        - the matrix product C
11394: - iscoloring - the coloring of the matrix; usually obtained with `MatColoringCreate()` or `DMCreateColoring()`

11396:   Output Parameter:
11397: . color - the new coloring context

11399:   Level: intermediate

11401: .seealso: [](ch_matrices), `Mat`, `MatTransposeColoringDestroy()`, `MatTransColoringApplySpToDen()`,
11402:           `MatTransColoringApplyDenToSp()`
11403: @*/
11404: PetscErrorCode MatTransposeColoringCreate(Mat mat, ISColoring iscoloring, MatTransposeColoring *color)
11405: {
11406:   MatTransposeColoring c;
11407:   MPI_Comm             comm;

11409:   PetscFunctionBegin;
11410:   PetscAssertPointer(color, 3);

11412:   PetscCall(PetscLogEventBegin(MAT_TransposeColoringCreate, mat, 0, 0, 0));
11413:   PetscCall(PetscObjectGetComm((PetscObject)mat, &comm));
11414:   PetscCall(PetscHeaderCreate(c, MAT_TRANSPOSECOLORING_CLASSID, "MatTransposeColoring", "Matrix product C=A*B^T via coloring", "Mat", comm, MatTransposeColoringDestroy, NULL));
11415:   c->ctype = iscoloring->ctype;
11416:   PetscUseTypeMethod(mat, transposecoloringcreate, iscoloring, c);
11417:   *color = c;
11418:   PetscCall(PetscLogEventEnd(MAT_TransposeColoringCreate, mat, 0, 0, 0));
11419:   PetscFunctionReturn(PETSC_SUCCESS);
11420: }

11422: /*@
11423:   MatGetNonzeroState - Returns a 64-bit integer representing the current state of nonzeros in the matrix. If the
11424:   matrix has had new nonzero locations added to (or removed from) the matrix since the previous call, the value will be larger.

11426:   Not Collective

11428:   Input Parameter:
11429: . mat - the matrix

11431:   Output Parameter:
11432: . state - the current state

11434:   Level: intermediate

11436:   Notes:
11437:   You can only compare states from two different calls to the SAME matrix, you cannot compare calls between
11438:   different matrices

11440:   Use `PetscObjectStateGet()` to check for changes to the numerical values in a matrix

11442:   Use the result of `PetscObjectGetId()` to compare if a previously checked matrix is the same as the current matrix, do not compare object pointers.

11444: .seealso: [](ch_matrices), `Mat`, `PetscObjectStateGet()`, `PetscObjectGetId()`
11445: @*/
11446: PetscErrorCode MatGetNonzeroState(Mat mat, PetscObjectState *state)
11447: {
11448:   PetscFunctionBegin;
11450:   *state = mat->nonzerostate;
11451:   PetscFunctionReturn(PETSC_SUCCESS);
11452: }

11454: /*@
11455:   MatCreateMPIMatConcatenateSeqMat - Creates a single large PETSc matrix by concatenating sequential
11456:   matrices from each processor

11458:   Collective

11460:   Input Parameters:
11461: + comm   - the communicators the parallel matrix will live on
11462: . seqmat - the input sequential matrices
11463: . n      - number of local columns (or `PETSC_DECIDE`)
11464: - reuse  - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`

11466:   Output Parameter:
11467: . mpimat - the parallel matrix generated

11469:   Level: developer

11471:   Note:
11472:   The number of columns of the matrix in EACH processor MUST be the same.

11474: .seealso: [](ch_matrices), `Mat`
11475: @*/
11476: PetscErrorCode MatCreateMPIMatConcatenateSeqMat(MPI_Comm comm, Mat seqmat, PetscInt n, MatReuse reuse, Mat *mpimat)
11477: {
11478:   PetscMPIInt size;

11480:   PetscFunctionBegin;
11481:   PetscCallMPI(MPI_Comm_size(comm, &size));
11482:   if (size == 1) {
11483:     if (reuse == MAT_INITIAL_MATRIX) {
11484:       PetscCall(MatDuplicate(seqmat, MAT_COPY_VALUES, mpimat));
11485:     } else {
11486:       PetscCall(MatCopy(seqmat, *mpimat, SAME_NONZERO_PATTERN));
11487:     }
11488:     PetscFunctionReturn(PETSC_SUCCESS);
11489:   }

11491:   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");

11493:   PetscCall(PetscLogEventBegin(MAT_Merge, seqmat, 0, 0, 0));
11494:   PetscCall((*seqmat->ops->creatempimatconcatenateseqmat)(comm, seqmat, n, reuse, mpimat));
11495:   PetscCall(PetscLogEventEnd(MAT_Merge, seqmat, 0, 0, 0));
11496:   PetscFunctionReturn(PETSC_SUCCESS);
11497: }

11499: /*@
11500:   MatSubdomainsCreateCoalesce - Creates index subdomains by coalescing adjacent MPI processes' ownership ranges.

11502:   Collective

11504:   Input Parameters:
11505: + A - the matrix to create subdomains from
11506: - N - requested number of subdomains

11508:   Output Parameters:
11509: + n   - number of subdomains resulting on this MPI process
11510: - iss - `IS` list with indices of subdomains on this MPI process

11512:   Level: advanced

11514:   Note:
11515:   The number of subdomains must be smaller than the communicator size

11517: .seealso: [](ch_matrices), `Mat`, `IS`
11518: @*/
11519: PetscErrorCode MatSubdomainsCreateCoalesce(Mat A, PetscInt N, PetscInt *n, IS *iss[])
11520: {
11521:   MPI_Comm    comm, subcomm;
11522:   PetscMPIInt size, rank, color;
11523:   PetscInt    rstart, rend, k;

11525:   PetscFunctionBegin;
11526:   PetscCall(PetscObjectGetComm((PetscObject)A, &comm));
11527:   PetscCallMPI(MPI_Comm_size(comm, &size));
11528:   PetscCallMPI(MPI_Comm_rank(comm, &rank));
11529:   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);
11530:   *n    = 1;
11531:   k     = size / N + (size % N > 0); /* There are up to k ranks to a color */
11532:   color = rank / k;
11533:   PetscCallMPI(MPI_Comm_split(comm, color, rank, &subcomm));
11534:   PetscCall(PetscMalloc1(1, iss));
11535:   PetscCall(MatGetOwnershipRange(A, &rstart, &rend));
11536:   PetscCall(ISCreateStride(subcomm, rend - rstart, rstart, 1, iss[0]));
11537:   PetscCallMPI(MPI_Comm_free(&subcomm));
11538:   PetscFunctionReturn(PETSC_SUCCESS);
11539: }

11541: /*@
11542:   MatGalerkin - Constructs the coarse grid problem matrix via Galerkin projection.

11544:   If the interpolation and restriction operators are the same, uses `MatPtAP()`.
11545:   If they are not the same, uses `MatMatMatMult()`.

11547:   Once the coarse grid problem is constructed, correct for interpolation operators
11548:   that are not of full rank, which can legitimately happen in the case of non-nested
11549:   geometric multigrid.

11551:   Input Parameters:
11552: + restrct     - restriction operator
11553: . dA          - fine grid matrix
11554: . interpolate - interpolation operator
11555: . reuse       - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`
11556: - fill        - expected fill, use `PETSC_DETERMINE` or `PETSC_DETERMINE` if you do not have a good estimate

11558:   Output Parameter:
11559: . A - the Galerkin coarse matrix

11561:   Options Database Key:
11562: . -pc_mg_galerkin (both|pmat|mat|none) - for what matrices the Galerkin process should be used

11564:   Level: developer

11566:   Note:
11567:   The deprecated `PETSC_DEFAULT` in `fill` also means use the current value

11569: .seealso: [](ch_matrices), `Mat`, `MatPtAP()`, `MatMatMatMult()`
11570: @*/
11571: PetscErrorCode MatGalerkin(Mat restrct, Mat dA, Mat interpolate, MatReuse reuse, PetscReal fill, Mat *A)
11572: {
11573:   IS  zerorows;
11574:   Vec diag;

11576:   PetscFunctionBegin;
11577:   PetscCheck(reuse != MAT_INPLACE_MATRIX, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "Inplace product not supported");
11578:   /* Construct the coarse grid matrix */
11579:   if (interpolate == restrct) {
11580:     PetscCall(MatPtAP(dA, interpolate, reuse, fill, A));
11581:   } else {
11582:     PetscCall(MatMatMatMult(restrct, dA, interpolate, reuse, fill, A));
11583:   }

11585:   /* If the interpolation matrix is not of full rank, A will have zero rows.
11586:      This can legitimately happen in the case of non-nested geometric multigrid.
11587:      In that event, we set the rows of the matrix to the rows of the identity,
11588:      ignoring the equations (as the RHS will also be zero). */

11590:   PetscCall(MatFindZeroRows(*A, &zerorows));

11592:   if (zerorows != NULL) { /* if there are any zero rows */
11593:     PetscCall(MatCreateVecs(*A, &diag, NULL));
11594:     PetscCall(MatGetDiagonal(*A, diag));
11595:     PetscCall(VecISSet(diag, zerorows, 1.0));
11596:     PetscCall(MatDiagonalSet(*A, diag, INSERT_VALUES));
11597:     PetscCall(VecDestroy(&diag));
11598:     PetscCall(ISDestroy(&zerorows));
11599:   }
11600:   PetscFunctionReturn(PETSC_SUCCESS);
11601: }

11603: /*@C
11604:   MatSetOperation - Allows user to set a matrix operation for any matrix type

11606:   Logically Collective

11608:   Input Parameters:
11609: + mat - the matrix
11610: . op  - the name of the operation
11611: - f   - the function that provides the operation

11613:   Level: developer

11615:   Example Usage:
11616: .vb
11617:   extern PetscErrorCode usermult(Mat, Vec, Vec);

11619:   PetscCall(MatCreateXXX(comm, ..., &A));
11620:   PetscCall(MatSetOperation(A, MATOP_MULT, (PetscErrorCodeFn *)usermult));
11621: .ve

11623:   Notes:
11624:   See the file `include/petscmat.h` for a complete list of matrix
11625:   operations, which all have the form MATOP_<OPERATION>, where
11626:   <OPERATION> is the name (in all capital letters) of the
11627:   user interface routine (e.g., `MatMult()` -> `MATOP_MULT`).

11629:   All user-provided functions (except for `MATOP_DESTROY`) should have the same calling
11630:   sequence as the usual matrix interface routines, since they
11631:   are intended to be accessed via the usual matrix interface
11632:   routines, e.g.,
11633: .vb
11634:   MatMult(Mat, Vec, Vec) -> usermult(Mat, Vec, Vec)
11635: .ve

11637:   In particular each function MUST return `PETSC_SUCCESS` on success and
11638:   nonzero on failure.

11640:   This routine is distinct from `MatShellSetOperation()` in that it can be called on any matrix type.

11642: .seealso: [](ch_matrices), `Mat`, `MatGetOperation()`, `MatCreateShell()`, `MatShellSetContext()`, `MatShellSetOperation()`
11643: @*/
11644: PetscErrorCode MatSetOperation(Mat mat, MatOperation op, PetscErrorCodeFn *f)
11645: {
11646:   PetscFunctionBegin;
11649:   if (op == MATOP_VIEW && !mat->ops->viewnative && f != (PetscErrorCodeFn *)mat->ops->view) mat->ops->viewnative = mat->ops->view;
11650: #if !PetscDefined(USE_COMPLEX)
11651:   if (op == MATOP_MULT_HERMITIAN_TRANSPOSE) op = MATOP_MULT_TRANSPOSE;
11652:   else if (op == MATOP_MULT_HERMITIAN_TRANS_ADD) op = MATOP_MULT_TRANSPOSE_ADD;
11653:   else if (op == MATOP_HERMITIAN_TRANSPOSE) op = MATOP_TRANSPOSE;
11654: #endif
11655:   (((PetscErrorCodeFn **)mat->ops)[op]) = f;
11656:   PetscFunctionReturn(PETSC_SUCCESS);
11657: }

11659: /*@C
11660:   MatGetOperation - Gets a matrix operation for any matrix type.

11662:   Not Collective

11664:   Input Parameters:
11665: + mat - the matrix
11666: - op  - the name of the operation

11668:   Output Parameter:
11669: . f - the function that provides the operation

11671:   Level: developer

11673:   Example Usage:
11674: .vb
11675:   PetscErrorCode (*usermult)(Mat, Vec, Vec);

11677:   MatGetOperation(A, MATOP_MULT, (PetscErrorCodeFn **)&usermult);
11678: .ve

11680:   Notes:
11681:   See the file `include/petscmat.h` for a complete list of matrix
11682:   operations, which all have the form MATOP_<OPERATION>, where
11683:   <OPERATION> is the name (in all capital letters) of the
11684:   user interface routine (e.g., `MatMult()` -> `MATOP_MULT`).

11686:   This routine is distinct from `MatShellGetOperation()` in that it can be called on any matrix type.

11688: .seealso: [](ch_matrices), `Mat`, `MatSetOperation()`, `MatCreateShell()`, `MatShellGetContext()`, `MatShellGetOperation()`
11689: @*/
11690: PetscErrorCode MatGetOperation(Mat mat, MatOperation op, PetscErrorCodeFn **f)
11691: {
11692:   PetscFunctionBegin;
11694:   PetscAssertPointer(f, 3);
11695: #if !PetscDefined(USE_COMPLEX)
11696:   if (op == MATOP_MULT_HERMITIAN_TRANSPOSE) op = MATOP_MULT_TRANSPOSE;
11697:   else if (op == MATOP_MULT_HERMITIAN_TRANS_ADD) op = MATOP_MULT_TRANSPOSE_ADD;
11698:   else if (op == MATOP_HERMITIAN_TRANSPOSE) op = MATOP_TRANSPOSE;
11699: #endif
11700:   *f = (((PetscErrorCodeFn **)mat->ops)[op]);
11701:   PetscFunctionReturn(PETSC_SUCCESS);
11702: }

11704: /*@
11705:   MatHasOperation - Determines whether the given matrix supports the particular operation.

11707:   Not Collective

11709:   Input Parameters:
11710: + mat - the matrix
11711: - op  - the operation, for example, `MATOP_GET_DIAGONAL`

11713:   Output Parameter:
11714: . has - either `PETSC_TRUE` or `PETSC_FALSE`

11716:   Level: advanced

11718:   Note:
11719:   See `MatSetOperation()` for additional discussion on naming convention and usage of `op`.

11721: .seealso: [](ch_matrices), `Mat`, `MatCreateShell()`, `MatGetOperation()`, `MatSetOperation()`
11722: @*/
11723: PetscErrorCode MatHasOperation(Mat mat, MatOperation op, PetscBool *has)
11724: {
11725:   PetscFunctionBegin;
11727:   PetscAssertPointer(has, 3);
11728: #if !PetscDefined(USE_COMPLEX)
11729:   if (op == MATOP_MULT_HERMITIAN_TRANSPOSE) op = MATOP_MULT_TRANSPOSE;
11730:   else if (op == MATOP_MULT_HERMITIAN_TRANS_ADD) op = MATOP_MULT_TRANSPOSE_ADD;
11731:   else if (op == MATOP_HERMITIAN_TRANSPOSE) op = MATOP_TRANSPOSE;
11732: #endif
11733:   if (mat->ops->hasoperation) {
11734:     PetscUseTypeMethod(mat, hasoperation, op, has);
11735:   } else {
11736:     if (((void **)mat->ops)[op]) *has = PETSC_TRUE;
11737:     else {
11738:       *has = PETSC_FALSE;
11739:       if (op == MATOP_CREATE_SUBMATRIX) {
11740:         PetscMPIInt size;

11742:         PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)mat), &size));
11743:         if (size == 1) PetscCall(MatHasOperation(mat, MATOP_CREATE_SUBMATRICES, has));
11744:       }
11745:     }
11746:   }
11747:   PetscFunctionReturn(PETSC_SUCCESS);
11748: }

11750: /*@
11751:   MatHasCongruentLayouts - Determines whether the rows and columns layouts of the matrix are congruent

11753:   Collective

11755:   Input Parameter:
11756: . mat - the matrix

11758:   Output Parameter:
11759: . cong - either `PETSC_TRUE` or `PETSC_FALSE`

11761:   Level: beginner

11763: .seealso: [](ch_matrices), `Mat`, `MatCreate()`, `MatSetSizes()`, `PetscLayout`
11764: @*/
11765: PetscErrorCode MatHasCongruentLayouts(Mat mat, PetscBool *cong)
11766: {
11767:   PetscFunctionBegin;
11770:   PetscAssertPointer(cong, 2);
11771:   if (!mat->rmap || !mat->cmap) {
11772:     *cong = mat->rmap == mat->cmap ? PETSC_TRUE : PETSC_FALSE;
11773:     PetscFunctionReturn(PETSC_SUCCESS);
11774:   }
11775:   if (mat->congruentlayouts == PETSC_DECIDE) { /* first time we compare rows and cols layouts */
11776:     PetscCall(PetscLayoutSetUp(mat->rmap));
11777:     PetscCall(PetscLayoutSetUp(mat->cmap));
11778:     PetscCall(PetscLayoutCompare(mat->rmap, mat->cmap, cong));
11779:     if (*cong) mat->congruentlayouts = 1;
11780:     else mat->congruentlayouts = 0;
11781:   } else *cong = mat->congruentlayouts ? PETSC_TRUE : PETSC_FALSE;
11782:   PetscFunctionReturn(PETSC_SUCCESS);
11783: }

11785: /*@
11786:   MatSetInf - Set every entry (of a given nonzero pattern) of a matrix to positive infinity.

11788:   Logically Collective

11790:   Input Parameter:
11791: . A - the matrix

11793:   Level: developer

11795: .seealso: `Mat`, `MatZeroEntries()`, `MatSetValues()`
11796: @*/
11797: PetscErrorCode MatSetInf(Mat A)
11798: {
11799:   PetscFunctionBegin;
11800:   PetscUseTypeMethod(A, setinf);
11801:   PetscFunctionReturn(PETSC_SUCCESS);
11802: }

11804: /*@
11805:   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
11806:   and possibly removes small values from the graph structure.

11808:   Collective

11810:   Input Parameters:
11811: + A       - the matrix
11812: . sym     - `PETSC_TRUE` indicates that the graph should be symmetrized
11813: . scale   - `PETSC_TRUE` indicates that the graph edge weights should be symmetrically scaled with the diagonal entry
11814: . filter  - filter value - < 0: does nothing; == 0: removes only 0.0 entries; otherwise: removes entries with abs(entries) <= value
11815: . num_idx - size of `index` array
11816: - index   - array of block indices to use for graph strength of connection weight

11818:   Output Parameter:
11819: . graph - the resulting graph

11821:   Level: advanced

11823: .seealso: [](ch_matrices), `Mat`, `MatCreate()`, `PCGAMG`
11824: @*/
11825: PetscErrorCode MatCreateGraph(Mat A, PetscBool sym, PetscBool scale, PetscReal filter, PetscInt num_idx, PetscInt index[], Mat *graph)
11826: {
11827:   PetscFunctionBegin;
11831:   PetscAssertPointer(graph, 7);
11832:   PetscCall(PetscLogEventBegin(MAT_CreateGraph, A, 0, 0, 0));
11833:   PetscUseTypeMethod(A, creategraph, sym, scale, filter, num_idx, index, graph);
11834:   PetscCall(PetscLogEventEnd(MAT_CreateGraph, A, 0, 0, 0));
11835:   PetscFunctionReturn(PETSC_SUCCESS);
11836: }

11838: /*@
11839:   MatEliminateZeros - eliminate the nondiagonal zero entries in place from the nonzero structure of a sparse `Mat` in place,
11840:   meaning the same memory is used for the matrix, and no new memory is allocated.

11842:   Collective

11844:   Input Parameters:
11845: + A    - the matrix
11846: - 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

11848:   Level: intermediate

11850:   Developer Note:
11851:   The entries in the sparse matrix data structure are shifted to fill in the unneeded locations in the data. Thus the end
11852:   of the arrays in the data structure are unneeded.

11854: .seealso: [](ch_matrices), `Mat`, `MatCreate()`, `MatCreateGraph()`, `MatFilter()`
11855: @*/
11856: PetscErrorCode MatEliminateZeros(Mat A, PetscBool keep)
11857: {
11858:   PetscFunctionBegin;
11860:   PetscUseTypeMethod(A, eliminatezeros, keep);
11861:   PetscFunctionReturn(PETSC_SUCCESS);
11862: }

11864: /*@C
11865:   MatGetCurrentMemType - Get the memory location of the matrix

11867:   Not Collective, but the result will be the same on all MPI processes

11869:   Input Parameter:
11870: . A - the matrix whose memory type we are checking

11872:   Output Parameter:
11873: . m - the memory type

11875:   Level: intermediate

11877: .seealso: [](ch_matrices), `Mat`, `MatBoundToCPU()`, `PetscMemType`
11878: @*/
11879: PetscErrorCode MatGetCurrentMemType(Mat A, PetscMemType *m)
11880: {
11881:   PetscFunctionBegin;
11883:   PetscAssertPointer(m, 2);
11884:   if (A->ops->getcurrentmemtype) PetscUseTypeMethod(A, getcurrentmemtype, m);
11885:   else *m = PETSC_MEMTYPE_HOST;
11886:   PetscFunctionReturn(PETSC_SUCCESS);
11887: }