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: /*@
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: /*@
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 process. `MatGetRow()` can only obtain rows
591:   associated with the given process, it cannot get rows from the
592:   other processes; 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: /*@
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:   process. 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 process 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:   process. For example, a parallel solver may access only some of
1329:   the rows from each process. 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 process'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 process
1991: . starts - starting point of ghost nodes on your process 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-process) 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 processes, `MAT_GLOBAL_SUM` - sum over all processes)

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 process for right-hand side matrix. User must create `Bt` in sparse compressed row
3988:   format on the host process 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 process.

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: /*@
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: /*@
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 process supplies only the permutation for its rows
5773: - col - column permutation, each process 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.
5783:   `MATSEQSBAIJ` inputs may produce a `MATSEQBAIJ` matrix when the permutation does not preserve symmetry.

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

5790: .seealso: [](ch_matrices), `Mat`, `MatGetOrdering()`, `ISAllGather()`, `MatCreateSubMatrix()`
5791: @*/
5792: PetscErrorCode MatPermute(Mat mat, IS row, IS col, Mat *B)
5793: {
5794:   PetscFunctionBegin;
5799:   PetscAssertPointer(B, 4);
5800:   PetscCheckSameComm(mat, 1, row, 2);
5801:   if (row != col) PetscCheckSameComm(row, 2, col, 3);
5802:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
5803:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
5804:   PetscCheck(mat->ops->permute || mat->ops->createsubmatrix, PETSC_COMM_SELF, PETSC_ERR_SUP, "MatPermute not available for Mat type %s", ((PetscObject)mat)->type_name);
5805:   MatCheckPreallocated(mat, 1);

5807:   if (mat->ops->permute) {
5808:     PetscUseTypeMethod(mat, permute, row, col, B);
5809:     PetscCall(PetscObjectStateIncrease((PetscObject)*B));
5810:   } else {
5811:     PetscCall(MatCreateSubMatrix(mat, row, col, MAT_INITIAL_MATRIX, B));
5812:   }
5813:   PetscFunctionReturn(PETSC_SUCCESS);
5814: }

5816: /*@
5817:   MatEqual - Compares two matrices.

5819:   Collective

5821:   Input Parameters:
5822: + A - the first matrix
5823: - B - the second matrix

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

5828:   Level: intermediate

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

5834: .seealso: [](ch_matrices), `Mat`, `MatMultEqual()`
5835: @*/
5836: PetscErrorCode MatEqual(Mat A, Mat B, PetscBool *flg)
5837: {
5838:   PetscFunctionBegin;
5843:   PetscAssertPointer(flg, 3);
5844:   PetscCheckSameComm(A, 1, B, 2);
5845:   MatCheckPreallocated(A, 1);
5846:   MatCheckPreallocated(B, 2);
5847:   PetscCheck(A->assembled, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
5848:   PetscCheck(B->assembled, PetscObjectComm((PetscObject)B), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
5849:   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,
5850:              B->cmap->N);
5851:   if (A->ops->equal && A->ops->equal == B->ops->equal) PetscUseTypeMethod(A, equal, B, flg);
5852:   else PetscCall(MatMultEqual(A, B, 10, flg));
5853:   PetscFunctionReturn(PETSC_SUCCESS);
5854: }

5856: /*@
5857:   MatDiagonalScale - Scales a matrix on the left and right by diagonal
5858:   matrices that are stored as vectors. Either of the two scaling
5859:   matrices can be `NULL`.

5861:   Collective

5863:   Input Parameters:
5864: + mat - the matrix to be scaled
5865: . l   - the left scaling vector (or `NULL`)
5866: - r   - the right scaling vector (or `NULL`)

5868:   Level: intermediate

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

5876: .seealso: [](ch_matrices), `Mat`, `MatScale()`, `MatShift()`, `MatDiagonalSet()`
5877: @*/
5878: PetscErrorCode MatDiagonalScale(Mat mat, Vec l, Vec r)
5879: {
5880:   PetscBool flg = PETSC_FALSE;

5882:   PetscFunctionBegin;
5885:   if (l) {
5887:     PetscCheckSameComm(mat, 1, l, 2);
5888:   }
5889:   if (r) {
5891:     PetscCheckSameComm(mat, 1, r, 3);
5892:   }
5893:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
5894:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
5895:   MatCheckPreallocated(mat, 1);
5896:   if (!l && !r) PetscFunctionReturn(PETSC_SUCCESS);

5898:   PetscCall(PetscLogEventBegin(MAT_Scale, mat, 0, 0, 0));
5899:   PetscUseTypeMethod(mat, diagonalscale, l, r);
5900:   PetscCall(PetscLogEventEnd(MAT_Scale, mat, 0, 0, 0));
5901:   PetscCall(PetscObjectStateIncrease((PetscObject)mat));
5902:   if (l != r && (PetscBool3ToBool(mat->symmetric) || PetscBool3ToBool(mat->hermitian))) {
5903:     if (!PetscDefined(USE_COMPLEX) || PetscBool3ToBool(mat->symmetric)) {
5904:       if (l && r) PetscCall(VecEqual(l, r, &flg));
5905:       if (!flg) {
5906:         PetscCall(PetscObjectTypeCompare((PetscObject)mat, MATMPISBAIJ, &flg));
5907:         PetscCheck(!flg, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_OUTOFRANGE, "For MATMPISBAIJ, left and right scaling vectors must be the same");
5908:         mat->symmetric = mat->spd = PETSC_BOOL3_FALSE;
5909:         if (!PetscDefined(USE_COMPLEX)) mat->hermitian = PETSC_BOOL3_FALSE;
5910:         else mat->hermitian = PETSC_BOOL3_UNKNOWN;
5911:       }
5912:     }
5913:     if (PetscDefined(USE_COMPLEX) && PetscBool3ToBool(mat->hermitian)) {
5914:       flg = PETSC_FALSE;
5915:       if (l && r) {
5916:         Vec conjugate;

5918:         PetscCall(VecDuplicate(l, &conjugate));
5919:         PetscCall(VecCopy(l, conjugate));
5920:         PetscCall(VecConjugate(conjugate));
5921:         PetscCall(VecEqual(conjugate, r, &flg));
5922:         PetscCall(VecDestroy(&conjugate));
5923:       }
5924:       if (!flg) {
5925:         PetscCall(PetscObjectTypeCompare((PetscObject)mat, MATMPISBAIJ, &flg));
5926:         PetscCheck(!flg, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_OUTOFRANGE, "For Hermitian MATMPISBAIJ, left and right scaling vectors must be conjugate one of the other");
5927:         mat->hermitian = PETSC_BOOL3_FALSE;
5928:         mat->symmetric = mat->spd = PETSC_BOOL3_UNKNOWN;
5929:       }
5930:     }
5931:   }
5932:   PetscFunctionReturn(PETSC_SUCCESS);
5933: }

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

5938:   Logically Collective

5940:   Input Parameters:
5941: + mat - the matrix to be scaled
5942: - a   - the scaling value

5944:   Level: intermediate

5946: .seealso: [](ch_matrices), `Mat`, `MatDiagonalScale()`
5947: @*/
5948: PetscErrorCode MatScale(Mat mat, PetscScalar a)
5949: {
5950:   PetscFunctionBegin;
5953:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
5954:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
5956:   MatCheckPreallocated(mat, 1);

5958:   PetscCall(PetscLogEventBegin(MAT_Scale, mat, 0, 0, 0));
5959:   if (a != (PetscScalar)1.0) {
5960:     PetscUseTypeMethod(mat, scale, a);
5961:     PetscCall(PetscObjectStateIncrease((PetscObject)mat));
5962:   }
5963:   PetscCall(PetscLogEventEnd(MAT_Scale, mat, 0, 0, 0));
5964:   PetscFunctionReturn(PETSC_SUCCESS);
5965: }

5967: /*@
5968:   MatNorm - Calculates various norms of a matrix.

5970:   Collective

5972:   Input Parameters:
5973: + mat  - the matrix
5974: - type - the type of norm, `NORM_1`, `NORM_FROBENIUS`, `NORM_INFINITY`

5976:   Output Parameter:
5977: . nrm - the resulting norm

5979:   Level: intermediate

5981: .seealso: [](ch_matrices), `Mat`, `MatNormApproximate()`
5982: @*/
5983: PetscErrorCode MatNorm(Mat mat, NormType type, PetscReal *nrm)
5984: {
5985:   PetscFunctionBegin;
5989:   PetscAssertPointer(nrm, 3);

5991:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
5992:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
5993:   MatCheckPreallocated(mat, 1);

5995:   PetscUseTypeMethod(mat, norm, type, nrm);
5996:   PetscFunctionReturn(PETSC_SUCCESS);
5997: }

5999: static PetscErrorCode VecSetFinalNormApp_Private(Vec x)
6000: {
6001:   PetscScalar *ax, nm1;
6002:   PetscInt     st, en, n;

6004:   PetscFunctionBegin;
6005:   PetscCall(VecGetSize(x, &n));
6006:   if (n < 2) PetscFunctionReturn(PETSC_SUCCESS);
6007:   nm1 = n - 1;
6008:   PetscCall(VecGetOwnershipRange(x, &st, &en));
6009:   PetscCall(VecGetArrayWrite(x, &ax));
6010:   for (PetscInt i = st; i < en; i++) {
6011:     const PetscInt    ii = i - st;
6012:     const PetscScalar s  = i % 2 ? -1.0 : 1.0;

6014:     ax[ii] = s * (1.0 + i / nm1);
6015:   }
6016:   PetscCall(VecRestoreArrayWrite(x, &ax));
6017:   PetscFunctionReturn(PETSC_SUCCESS);
6018: }

6020: static PetscErrorCode MatNormApproximateForwardOnly_Private(Mat A, NormType normtype, PetscInt maxit, PetscBool boundtocpu, PetscReal *n)
6021: {
6022:   Vec         x, y;
6023:   PetscReal   normx, normy;
6024:   PetscInt    i, N;
6025:   PetscRandom rnd;

6027:   PetscFunctionBegin;
6028:   if (maxit < 0) maxit = 1;
6029:   PetscCall(PetscRandomCreate(PetscObjectComm((PetscObject)A), &rnd));
6030:   PetscCall(PetscRandomSetFromOptions(rnd));
6031:   PetscCall(MatCreateVecs(A, &x, &y));
6032:   PetscCall(VecBindToCPU(x, boundtocpu));
6033:   PetscCall(VecBindToCPU(y, boundtocpu));
6034:   PetscCall(VecGetSize(x, &N));
6035:   *n = 0.0;
6036:   for (i = 0; i < maxit; i++) {
6037:     PetscCall(VecSetRandom(x, rnd));
6038:     switch (normtype) {
6039:     case NORM_1:
6040:       PetscCall(VecNorm(x, NORM_1, &normx));
6041:       if (normx > 0.0) PetscCall(VecScale(x, 1.0 / normx));
6042:       break;
6043:     case NORM_INFINITY:
6044:       PetscCall(VecShift(x, -0.5));
6045:       PetscCall(VecPointwiseSign(x, x, VEC_SIGN_ZERO_TO_SIGNED_UNIT));
6046:       break;
6047:     case NORM_2:
6048:       PetscCall(VecNormalize(x, NULL));
6049:       break;
6050:     default:
6051:       PetscUnreachable();
6052:     }
6053:     PetscCall(MatMult(A, x, y));
6054:     PetscCall(VecNorm(y, normtype, &normy));
6055:     *n = PetscMax(*n, normy);
6056:     PetscCall(PetscInfo(A, "%s norm forward-only sample %" PetscInt_FMT " -> %g\n", NormTypes[normtype], i, (double)normy));
6057:   }
6058:   PetscCall(VecDestroy(&x));
6059:   PetscCall(VecDestroy(&y));
6060:   PetscCall(PetscRandomDestroy(&rnd));
6061:   PetscFunctionReturn(PETSC_SUCCESS);
6062: }

6064: /*@
6065:   MatNormApproximate - Approximate the norm of a matrix.

6067:   Collective

6069:   Input Parameters:
6070: + A        - the matrix
6071: . normtype - the `NormType`
6072: - maxit    - maximum number of iterations to use

6074:   Output Parameter:
6075: . n - the norm estimate

6077:   Level: intermediate

6079:   Notes:
6080:   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`.

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

6084: .seealso: [](ch_matrices), `Mat`, `MatNorm()`
6085: @*/
6086: PetscErrorCode MatNormApproximate(Mat A, NormType normtype, PetscInt maxit, PetscReal *n)
6087: {
6088:   Vec         x, y, w, z;
6089:   PetscReal   normz, adot;
6090:   PetscScalar dot;
6091:   PetscInt    i, j, N, jold = -1;
6092:   PetscBool   boundtocpu = PETSC_TRUE, setherm, isherm, hasop;

6094:   PetscFunctionBegin;
6099:   PetscAssertPointer(n, 4);
6100: #if PetscDefined(HAVE_DEVICE)
6101:   boundtocpu = A->boundtocpu;
6102: #endif
6103:   PetscCall(MatHasOperation(A, MATOP_MULT_HERMITIAN_TRANSPOSE, &hasop));
6104:   switch (normtype) {
6105:   case NORM_INFINITY:
6106:   case NORM_1:
6107:     if (!hasop) {
6108:       PetscCall(MatNormApproximateForwardOnly_Private(A, normtype, maxit, boundtocpu, n));
6109:       i = maxit;
6110:       break;
6111:     } else {
6112:       PetscCall(MatIsHermitianKnown(A, &setherm, &isherm));
6113:       if ((setherm && isherm) || normtype == NORM_1) PetscCall(PetscObjectReference((PetscObject)A));
6114:       else {
6115:         Mat B;

6117:         PetscCall(MatCreateHermitianTranspose(A, &B));
6118:         A = B;
6119:       }
6120:     }
6121:     if (maxit < 0) maxit = 10; /* pure guess */
6122:     PetscCall(MatCreateVecs(A, &x, &y));
6123:     PetscCall(MatCreateVecs(A, &z, &w));
6124:     PetscCall(VecBindToCPU(x, boundtocpu));
6125:     PetscCall(VecBindToCPU(y, boundtocpu));
6126:     PetscCall(VecBindToCPU(z, boundtocpu));
6127:     PetscCall(VecBindToCPU(w, boundtocpu));
6128:     PetscCall(VecGetSize(x, &N));
6129:     PetscCall(VecSet(x, 1. / N));
6130:     *n = 0.0;
6131:     for (i = 0; i < maxit; i++) {
6132:       PetscCall(MatMult(A, x, y));
6133:       PetscCall(VecNorm(y, NORM_1, n));
6134:       if (PetscDefined(USE_COMPLEX)) {
6135:         PetscCall(VecCopy(y, w));
6136:         PetscCall(VecAbs(w));
6137:         PetscCall(VecPointwiseDivide(w, y, w));
6138:       } else PetscCall(VecPointwiseSign(w, y, VEC_SIGN_ZERO_TO_SIGNED_UNIT));
6139:       PetscCall(MatMultHermitianTranspose(A, w, z));
6140:       PetscCall(VecRealPart(z));
6141:       PetscCall(VecNorm(z, NORM_INFINITY, &normz));
6142:       PetscCall(VecDot(x, z, &dot));
6143:       adot = PetscAbsScalar(dot);
6144:       PetscCall(PetscInfo(A, "%s norm it %" PetscInt_FMT " -> %g (%g %g)\n", NormTypes[normtype], i, (double)*n, (double)normz, (double)adot));
6145:       if (normz <= adot && i > 0) {
6146:         PetscCall(PetscInfo(A, "%s norm    converged\n", NormTypes[normtype]));
6147:         break;
6148:       }
6149:       PetscCall(VecAbs(z));
6150:       PetscCall(VecMax(z, &j, &normz));
6151:       if (j == jold) {
6152:         PetscCall(PetscInfo(A, "%s norm it %" PetscInt_FMT " -> breakdown (j==jold)\n", NormTypes[normtype], i));
6153:         break;
6154:       }
6155:       jold = j;
6156:       if (i < maxit - 1) PetscCall(VecSetStdBasis(x, j));
6157:     }
6158:     /* last check */
6159:     if (N > 1) {
6160:       PetscReal ny;

6162:       PetscCall(VecSetFinalNormApp_Private(x));
6163:       PetscCall(MatMult(A, x, y));
6164:       PetscCall(VecNorm(y, NORM_1, &ny));
6165:       ny = 2 * ny / (3 * N);
6166:       PetscCall(PetscInfo(A, "%s norm final check: current %g test %g\n", NormTypes[normtype], (double)*n, (double)ny));
6167:       *n = PetscMax(*n, ny);
6168:     }
6169:     PetscCall(MatDestroy(&A));
6170:     PetscCall(VecDestroy(&x));
6171:     PetscCall(VecDestroy(&w));
6172:     PetscCall(VecDestroy(&y));
6173:     PetscCall(VecDestroy(&z));
6174:     break;
6175:   case NORM_2:
6176:     if (!hasop) {
6177:       PetscCall(MatNormApproximateForwardOnly_Private(A, normtype, maxit, boundtocpu, n));
6178:       i = maxit;
6179:       break;
6180:     }
6181:     if (maxit < 0) maxit = 20; /* pure guess */
6182:     PetscCall(MatCreateVecs(A, &x, &y));
6183:     PetscCall(MatCreateVecs(A, &z, NULL));
6184:     PetscCall(VecBindToCPU(x, boundtocpu));
6185:     PetscCall(VecBindToCPU(y, boundtocpu));
6186:     PetscCall(VecBindToCPU(z, boundtocpu));
6187:     PetscCall(VecSetRandom(x, NULL));
6188:     PetscCall(VecNormalize(x, NULL));
6189:     *n = 0.0;
6190:     for (i = 0; i < maxit; i++) {
6191:       PetscCall(MatMult(A, x, y));
6192:       PetscCall(VecNormalize(y, n));
6193:       PetscCall(MatMultHermitianTranspose(A, y, z));
6194:       PetscCall(VecNorm(z, NORM_2, &normz));
6195:       PetscCall(VecDot(x, z, &dot));
6196:       adot = PetscAbsScalar(dot);
6197:       PetscCall(PetscInfo(A, "%s norm it %" PetscInt_FMT " -> %g (%g %g)\n", NormTypes[normtype], i, (double)*n, (double)normz, (double)adot));
6198:       if (normz <= adot) {
6199:         PetscCall(PetscInfo(A, "%s norm    converged\n", NormTypes[normtype]));
6200:         break;
6201:       }
6202:       if (i < maxit - 1) {
6203:         Vec t;

6205:         PetscCall(VecNormalize(z, NULL));
6206:         t = x;
6207:         x = z;
6208:         z = t;
6209:       }
6210:     }
6211:     PetscCall(VecDestroy(&x));
6212:     PetscCall(VecDestroy(&y));
6213:     PetscCall(VecDestroy(&z));
6214:     break;
6215:   default:
6216:     SETERRQ(PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "%s norm not supported", NormTypes[normtype]);
6217:   }
6218:   PetscCall(PetscInfo(A, "%s norm %g computed in %" PetscInt_FMT " iterations\n", NormTypes[normtype], (double)*n, i));
6219:   PetscFunctionReturn(PETSC_SUCCESS);
6220: }

6222: /*
6223:      This variable is used to prevent counting of MatAssemblyBegin() that
6224:    are called from within a MatAssemblyEnd().
6225: */
6226: static PetscInt MatAssemblyEnd_InUse = 0;
6227: /*@
6228:   MatAssemblyBegin - Begins assembling the matrix. This routine should
6229:   be called after completing all calls to `MatSetValues()`.

6231:   Collective

6233:   Input Parameters:
6234: + mat  - the matrix
6235: - type - type of assembly, either `MAT_FLUSH_ASSEMBLY` or `MAT_FINAL_ASSEMBLY`

6237:   Level: beginner

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

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

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

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

6255: .seealso: [](ch_matrices), `Mat`, `MatAssemblyEnd()`, `MatSetValues()`, `MatAssembled()`
6256: @*/
6257: PetscErrorCode MatAssemblyBegin(Mat mat, MatAssemblyType type)
6258: {
6259:   PetscFunctionBegin;
6262:   MatCheckPreallocated(mat, 1);
6263:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix. Did you forget to call MatSetUnfactored()?");
6264:   if (mat->assembled) {
6265:     mat->was_assembled = PETSC_TRUE;
6266:     mat->assembled     = PETSC_FALSE;
6267:   }

6269:   if (!MatAssemblyEnd_InUse) {
6270:     PetscCall(PetscLogEventBegin(MAT_AssemblyBegin, mat, 0, 0, 0));
6271:     PetscTryTypeMethod(mat, assemblybegin, type);
6272:     PetscCall(PetscLogEventEnd(MAT_AssemblyBegin, mat, 0, 0, 0));
6273:   } else PetscTryTypeMethod(mat, assemblybegin, type);
6274:   PetscFunctionReturn(PETSC_SUCCESS);
6275: }

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

6281:   Not Collective

6283:   Input Parameter:
6284: . mat - the matrix

6286:   Output Parameter:
6287: . assembled - `PETSC_TRUE` or `PETSC_FALSE`

6289:   Level: advanced

6291: .seealso: [](ch_matrices), `Mat`, `MatAssemblyEnd()`, `MatSetValues()`, `MatAssemblyBegin()`
6292: @*/
6293: PetscErrorCode MatAssembled(Mat mat, PetscBool *assembled)
6294: {
6295:   PetscFunctionBegin;
6297:   PetscAssertPointer(assembled, 2);
6298:   *assembled = mat->assembled;
6299:   PetscFunctionReturn(PETSC_SUCCESS);
6300: }

6302: /*@
6303:   MatAssemblyEnd - Completes assembling the matrix. This routine should
6304:   be called after `MatAssemblyBegin()`.

6306:   Collective

6308:   Input Parameters:
6309: + mat  - the matrix
6310: - type - type of assembly, either `MAT_FLUSH_ASSEMBLY` or `MAT_FINAL_ASSEMBLY`

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

6315:   Level: beginner

6317: .seealso: [](ch_matrices), `Mat`, `MatAssemblyBegin()`, `MatSetValues()`, `PetscDrawOpenX()`, `PetscDrawCreate()`, `MatView()`, `MatAssembled()`, `PetscViewerSocketOpen()`,
6318:           `MatViewFromOptions()`, `PetscObjectViewFromOptions()`
6319: @*/
6320: PetscErrorCode MatAssemblyEnd(Mat mat, MatAssemblyType type)
6321: {
6322:   static PetscInt inassm = 0;
6323:   PetscBool       flg    = PETSC_FALSE;

6325:   PetscFunctionBegin;

6329:   inassm++;
6330:   MatAssemblyEnd_InUse++;
6331:   if (MatAssemblyEnd_InUse == 1) { /* Do the logging only the first time through */
6332:     PetscCall(PetscLogEventBegin(MAT_AssemblyEnd, mat, 0, 0, 0));
6333:     PetscTryTypeMethod(mat, assemblyend, type);
6334:     PetscCall(PetscLogEventEnd(MAT_AssemblyEnd, mat, 0, 0, 0));
6335:   } else PetscTryTypeMethod(mat, assemblyend, type);

6337:   /* Flush assembly is not a true assembly */
6338:   if (type != MAT_FLUSH_ASSEMBLY) {
6339:     if (mat->num_ass) {
6340:       if (!mat->symmetry_eternal) {
6341:         mat->symmetric = PETSC_BOOL3_UNKNOWN;
6342:         mat->hermitian = PETSC_BOOL3_UNKNOWN;
6343:       }
6344:       if (!mat->structural_symmetry_eternal && mat->ass_nonzerostate != mat->nonzerostate) mat->structurally_symmetric = PETSC_BOOL3_UNKNOWN;
6345:       if (!mat->spd_eternal) mat->spd = PETSC_BOOL3_UNKNOWN;
6346:     }
6347:     mat->num_ass++;
6348:     mat->assembled        = PETSC_TRUE;
6349:     mat->ass_nonzerostate = mat->nonzerostate;
6350:   }

6352:   mat->insertmode = NOT_SET_VALUES;
6353:   MatAssemblyEnd_InUse--;
6354:   PetscCall(PetscObjectStateIncrease((PetscObject)mat));
6355:   if (inassm == 1 && type != MAT_FLUSH_ASSEMBLY) {
6356:     PetscCall(MatViewFromOptions(mat, NULL, "-mat_view"));

6358:     if (mat->checksymmetryonassembly) {
6359:       PetscCall(MatIsSymmetric(mat, mat->checksymmetrytol, &flg));
6360:       if (flg) {
6361:         PetscCall(PetscPrintf(PetscObjectComm((PetscObject)mat), "Matrix is symmetric (tolerance %g)\n", (double)mat->checksymmetrytol));
6362:       } else {
6363:         PetscCall(PetscPrintf(PetscObjectComm((PetscObject)mat), "Matrix is not symmetric (tolerance %g)\n", (double)mat->checksymmetrytol));
6364:       }
6365:     }
6366:     if (mat->nullsp && mat->checknullspaceonassembly) PetscCall(MatNullSpaceTest(mat->nullsp, mat, NULL));
6367:   }
6368:   inassm--;
6369:   PetscFunctionReturn(PETSC_SUCCESS);
6370: }

6372: // PetscClangLinter pragma disable: -fdoc-section-header-unknown
6373: /*@
6374:   MatSetOption - Sets a parameter option for a matrix. Some options
6375:   may be specific to certain storage formats. Some options
6376:   determine how values will be inserted (or added). Sorted,
6377:   row-oriented input will generally assemble the fastest. The default
6378:   is row-oriented.

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

6382:   Input Parameters:
6383: + mat - the matrix
6384: . op  - the option, one of those listed below (and possibly others),
6385: - flg - turn the option on (`PETSC_TRUE`) or off (`PETSC_FALSE`)

6387:   Options Describing Matrix Structure:
6388: + `MAT_SPD`                         - symmetric positive definite
6389: . `MAT_SYMMETRIC`                   - symmetric in terms of both structure and value
6390: . `MAT_HERMITIAN`                   - transpose is the complex conjugation
6391: . `MAT_STRUCTURALLY_SYMMETRIC`      - symmetric nonzero structure
6392: . `MAT_SYMMETRY_ETERNAL`            - indicates the symmetry (or Hermitian structure) or its absence will persist through any changes to the matrix
6393: . `MAT_STRUCTURAL_SYMMETRY_ETERNAL` - indicates the structural symmetry or its absence will persist through any changes to the matrix
6394: . `MAT_SPD_ETERNAL`                 - indicates the value of `MAT_SPD` (true or false) will persist through any changes to the matrix

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

6399:    Options For Use with `MatSetValues()` and `MatGetValues()`:
6400:    Insert a logically dense subblock, which can be
6401: . `MAT_ROW_ORIENTED`                - row-oriented (default)

6403:    These options reflect the data you pass in with `MatSetValues()` or receive with `MatGetValues()`; it has
6404:    nothing to do with how the data is stored internally in the matrix
6405:    data structure.

6407:    When (re)assembling a matrix, we can restrict the input for
6408:    efficiency/debugging purposes. These options include
6409: . `MAT_NEW_NONZERO_LOCATIONS`       - additional insertions will be allowed if they generate a new nonzero (slow)
6410: . `MAT_FORCE_DIAGONAL_ENTRIES`      - forces diagonal entries to be allocated
6411: . `MAT_IGNORE_OFF_PROC_ENTRIES`     - drops off-process entries
6412: . `MAT_NEW_NONZERO_LOCATION_ERR`    - generates an error for new matrix entry
6413: . `MAT_USE_HASH_TABLE`              - uses a hash table to speed up matrix assembly
6414: . `MAT_NO_OFF_PROC_ENTRIES`         - you know each process will only set values for its own rows, will generate an error if
6415:                                       any process sets values for another process. This avoids all reductions in the MatAssembly routines and thus improves
6416:                                       performance for very large process counts.
6417: - `MAT_SUBSET_OFF_PROC_ENTRIES`     - you know that the first assembly after setting this flag will set a superset
6418:                                       of the off-process entries required for all subsequent assemblies. This avoids a rendezvous step in the MatAssembly
6419:                                       functions, instead sending only neighbor messages.

6421:   Level: intermediate

6423:   Notes:
6424:   Except for `MAT_UNUSED_NONZERO_LOCATION_ERR` and  `MAT_ROW_ORIENTED` all processes that share the matrix must pass the same value in flg!

6426:   Some options are relevant only for particular matrix types and
6427:   are thus ignored by others. Other options are not supported by
6428:   certain matrix types and will generate an error message if set.

6430:   If using Fortran to compute a matrix, one may need to
6431:   use the column-oriented option (or convert to the row-oriented
6432:   format).

6434:   `MAT_NEW_NONZERO_LOCATIONS` set to `PETSC_FALSE` indicates that any add or insertion
6435:   that would generate a new entry in the nonzero structure is instead
6436:   ignored. Thus, if memory has not already been allocated for this particular
6437:   data, then the insertion is ignored. For dense matrices, in which
6438:   the entire array is allocated, no entries are ever ignored.
6439:   Set after the first `MatAssemblyEnd()`. If this option is set, then the `MatAssemblyBegin()`/`MatAssemblyEnd()` processes has one less global reduction

6441:   `MAT_NEW_NONZERO_LOCATION_ERR` set to PETSC_TRUE indicates that any add or insertion
6442:   that would generate a new entry in the nonzero structure instead produces
6443:   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

6445:   `MAT_NEW_NONZERO_ALLOCATION_ERR` set to `PETSC_TRUE` indicates that any add or insertion
6446:   that would generate a new entry that has not been preallocated will
6447:   instead produce an error. (Currently supported for `MATAIJ` and `MATBAIJ` formats
6448:   only.) This is a useful flag when debugging matrix memory preallocation.
6449:   If this option is set, then the `MatAssemblyBegin()`/`MatAssemblyEnd()` processes has one less global reduction

6451:   `MAT_IGNORE_OFF_PROC_ENTRIES` set to `PETSC_TRUE` indicates entries destined for
6452:   other processes should be dropped, rather than stashed.
6453:   This is useful if you know that the "owning" process is also
6454:   always generating the correct matrix entries, so that PETSc need
6455:   not transfer duplicate entries generated on another process.

6457:   `MAT_USE_HASH_TABLE` indicates that a hash table be used to improve the
6458:   searches during matrix assembly. When this flag is set, the hash table
6459:   is created during the first matrix assembly. This hash table is
6460:   used the next time through, during `MatSetValues()`/`MatSetValuesBlocked()`
6461:   to improve the searching of indices. `MAT_NEW_NONZERO_LOCATIONS` flag
6462:   should be used with `MAT_USE_HASH_TABLE` flag. This option is currently
6463:   supported by `MATMPIBAIJ` format only.

6465:   `MAT_KEEP_NONZERO_PATTERN` indicates when `MatZeroRows()` is called the zeroed entries
6466:   are kept in the nonzero structure. This flag is not used for `MatZeroRowsColumns()`

6468:   `MAT_IGNORE_ZERO_ENTRIES` - for `MATAIJ` and `MATIS` matrices this will stop zero values from creating
6469:   a zero location in the matrix

6471:   `MAT_USE_INODES` - indicates using inode version of the code - works with `MATAIJ` matrix types

6473:   `MAT_NO_OFF_PROC_ZERO_ROWS` - you know each process will only zero its own rows. This avoids all reductions in the
6474:   zero row routines and thus improves performance for very large process counts.

6476:   `MAT_IGNORE_LOWER_TRIANGULAR` - For `MATSBAIJ` matrices will ignore any insertions you make in the lower triangular
6477:   part of the matrix (since they should match the upper triangular part).

6479:   `MAT_SORTED_FULL` - each process provides exactly its local rows; all column indices for a given row are passed in a
6480:   single call to `MatSetValues()`, preallocation is perfect, row-oriented, `INSERT_VALUES` is used. Common
6481:   with finite difference schemes with non-periodic boundary conditions.

6483:   Developer Note:
6484:   `MAT_SYMMETRY_ETERNAL`, `MAT_STRUCTURAL_SYMMETRY_ETERNAL`, and `MAT_SPD_ETERNAL` are used by `MatAssemblyEnd()` and in other
6485:   places where otherwise the value of `MAT_SYMMETRIC`, `MAT_STRUCTURALLY_SYMMETRIC` or `MAT_SPD` would need to be changed back
6486:   to `PETSC_BOOL3_UNKNOWN` because the matrix values had changed so the code cannot be certain that the related property had
6487:   not changed.

6489: .seealso: [](ch_matrices), `MatOption`, `Mat`, `MatGetOption()`
6490: @*/
6491: PetscErrorCode MatSetOption(Mat mat, MatOption op, PetscBool flg)
6492: {
6493:   PetscFunctionBegin;
6495:   if (op > 0) {
6498:   }

6500:   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);

6502:   switch (op) {
6503:   case MAT_FORCE_DIAGONAL_ENTRIES:
6504:     mat->force_diagonals = flg;
6505:     PetscFunctionReturn(PETSC_SUCCESS);
6506:   case MAT_NO_OFF_PROC_ENTRIES:
6507:     mat->nooffprocentries = flg;
6508:     PetscFunctionReturn(PETSC_SUCCESS);
6509:   case MAT_SUBSET_OFF_PROC_ENTRIES:
6510:     mat->assembly_subset = flg;
6511:     if (!mat->assembly_subset) { /* See the same logic in VecAssembly wrt VEC_SUBSET_OFF_PROC_ENTRIES */
6512: #if !PetscDefined(HAVE_MPIUNI)
6513:       PetscCall(MatStashScatterDestroy_BTS(&mat->stash));
6514: #endif
6515:       mat->stash.first_assembly_done = PETSC_FALSE;
6516:     }
6517:     PetscFunctionReturn(PETSC_SUCCESS);
6518:   case MAT_NO_OFF_PROC_ZERO_ROWS:
6519:     mat->nooffproczerorows = flg;
6520:     PetscFunctionReturn(PETSC_SUCCESS);
6521:   case MAT_SPD:
6522:     if (flg) {
6523:       mat->spd                    = PETSC_BOOL3_TRUE;
6524:       mat->symmetric              = PETSC_BOOL3_TRUE;
6525:       mat->structurally_symmetric = PETSC_BOOL3_TRUE;
6526: #if !PetscDefined(USE_COMPLEX)
6527:       mat->hermitian = PETSC_BOOL3_TRUE;
6528: #endif
6529:     } else {
6530:       mat->spd = PETSC_BOOL3_FALSE;
6531:     }
6532:     break;
6533:   case MAT_SYMMETRIC:
6534:     mat->symmetric = PetscBoolToBool3(flg);
6535:     if (flg) mat->structurally_symmetric = PETSC_BOOL3_TRUE;
6536: #if !PetscDefined(USE_COMPLEX)
6537:     mat->hermitian = PetscBoolToBool3(flg);
6538: #endif
6539:     break;
6540:   case MAT_HERMITIAN:
6541:     mat->hermitian = PetscBoolToBool3(flg);
6542:     if (flg) mat->structurally_symmetric = PETSC_BOOL3_TRUE;
6543: #if !PetscDefined(USE_COMPLEX)
6544:     mat->symmetric = PetscBoolToBool3(flg);
6545: #endif
6546:     break;
6547:   case MAT_STRUCTURALLY_SYMMETRIC:
6548:     mat->structurally_symmetric = PetscBoolToBool3(flg);
6549:     break;
6550:   case MAT_SYMMETRY_ETERNAL:
6551:     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");
6552:     mat->symmetry_eternal = flg;
6553:     if (flg) mat->structural_symmetry_eternal = PETSC_TRUE;
6554:     break;
6555:   case MAT_STRUCTURAL_SYMMETRY_ETERNAL:
6556:     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");
6557:     mat->structural_symmetry_eternal = flg;
6558:     break;
6559:   case MAT_SPD_ETERNAL:
6560:     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");
6561:     mat->spd_eternal = flg;
6562:     if (flg) {
6563:       mat->structural_symmetry_eternal = PETSC_TRUE;
6564:       mat->symmetry_eternal            = PETSC_TRUE;
6565:     }
6566:     break;
6567:   case MAT_STRUCTURE_ONLY:
6568:     mat->structure_only = flg;
6569:     break;
6570:   case MAT_SORTED_FULL:
6571:     mat->sortedfull = flg;
6572:     break;
6573:   default:
6574:     break;
6575:   }
6576:   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");
6577:   PetscTryTypeMethod(mat, setoption, op, flg);
6578:   PetscFunctionReturn(PETSC_SUCCESS);
6579: }

6581: /*@
6582:   MatGetOption - Gets a parameter option that has been set for a matrix.

6584:   Logically Collective

6586:   Input Parameters:
6587: + mat - the matrix
6588: - op  - the option, this only responds to certain options, check the code for which ones

6590:   Output Parameter:
6591: . flg - turn the option on (`PETSC_TRUE`) or off (`PETSC_FALSE`)

6593:   Level: intermediate

6595:   Notes:
6596:   Can only be called after `MatSetSizes()` and `MatSetType()` have been set.

6598:   Certain option values may be unknown, for those use the routines `MatIsSymmetric()`, `MatIsHermitian()`, `MatIsStructurallySymmetric()`, or
6599:   `MatIsSymmetricKnown()`, `MatIsHermitianKnown()`, `MatIsStructurallySymmetricKnown()`

6601: .seealso: [](ch_matrices), `Mat`, `MatOption`, `MatSetOption()`, `MatIsSymmetric()`, `MatIsHermitian()`, `MatIsStructurallySymmetric()`,
6602:     `MatIsSymmetricKnown()`, `MatIsHermitianKnown()`, `MatIsStructurallySymmetricKnown()`
6603: @*/
6604: PetscErrorCode MatGetOption(Mat mat, MatOption op, PetscBool *flg)
6605: {
6606:   PetscFunctionBegin;

6610:   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);
6611:   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()");

6613:   switch (op) {
6614:   case MAT_NO_OFF_PROC_ENTRIES:
6615:     *flg = mat->nooffprocentries;
6616:     break;
6617:   case MAT_NO_OFF_PROC_ZERO_ROWS:
6618:     *flg = mat->nooffproczerorows;
6619:     break;
6620:   case MAT_SYMMETRIC:
6621:     SETERRQ(PetscObjectComm((PetscObject)mat), PETSC_ERR_SUP, "Use MatIsSymmetric() or MatIsSymmetricKnown()");
6622:     break;
6623:   case MAT_HERMITIAN:
6624:     SETERRQ(PetscObjectComm((PetscObject)mat), PETSC_ERR_SUP, "Use MatIsHermitian() or MatIsHermitianKnown()");
6625:     break;
6626:   case MAT_STRUCTURALLY_SYMMETRIC:
6627:     SETERRQ(PetscObjectComm((PetscObject)mat), PETSC_ERR_SUP, "Use MatIsStructurallySymmetric() or MatIsStructurallySymmetricKnown()");
6628:     break;
6629:   case MAT_SPD:
6630:     SETERRQ(PetscObjectComm((PetscObject)mat), PETSC_ERR_SUP, "Use MatIsSPDKnown()");
6631:     break;
6632:   case MAT_SYMMETRY_ETERNAL:
6633:     *flg = mat->symmetry_eternal;
6634:     break;
6635:   case MAT_STRUCTURAL_SYMMETRY_ETERNAL:
6636:     *flg = mat->symmetry_eternal;
6637:     break;
6638:   default:
6639:     break;
6640:   }
6641:   PetscFunctionReturn(PETSC_SUCCESS);
6642: }

6644: /*@
6645:   MatZeroEntries - Zeros all entries of a matrix. For sparse matrices
6646:   this routine retains the old nonzero structure.

6648:   Logically Collective

6650:   Input Parameter:
6651: . mat - the matrix

6653:   Level: intermediate

6655:   Note:
6656:   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.
6657:   See the Performance chapter of the users manual for information on preallocating matrices.

6659: .seealso: [](ch_matrices), `Mat`, `MatZeroRows()`, `MatZeroRowsColumns()`
6660: @*/
6661: PetscErrorCode MatZeroEntries(Mat mat)
6662: {
6663:   PetscFunctionBegin;
6666:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
6667:   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");
6668:   MatCheckPreallocated(mat, 1);

6670:   PetscCall(PetscLogEventBegin(MAT_ZeroEntries, mat, 0, 0, 0));
6671:   PetscUseTypeMethod(mat, zeroentries);
6672:   PetscCall(PetscLogEventEnd(MAT_ZeroEntries, mat, 0, 0, 0));
6673:   PetscCall(PetscObjectStateIncrease((PetscObject)mat));
6674:   PetscFunctionReturn(PETSC_SUCCESS);
6675: }

6677: /*@
6678:   MatZeroRowsColumns - Zeros all entries (except possibly the main diagonal)
6679:   of a set of rows and columns of a matrix.

6681:   Collective

6683:   Input Parameters:
6684: + mat     - the matrix
6685: . numRows - the number of rows/columns to zero
6686: . rows    - the global row indices
6687: . diag    - value put in the diagonal of the eliminated rows
6688: . x       - optional vector of the solution for zeroed rows (other entries in vector are not used), these must be set before this call
6689: - b       - optional vector of the right-hand side, that will be adjusted by provided solution entries

6691:   Level: intermediate

6693:   Notes:
6694:   This routine, along with `MatZeroRows()`, is typically used to eliminate known Dirichlet boundary conditions from a linear system.

6696:   For each zeroed row, the value of the corresponding `b` is set to diag times the value of the corresponding `x`.
6697:   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

6699:   If the resulting linear system is to be solved with `KSP` then one can (but does not have to) call `KSPSetInitialGuessNonzero()` to allow the
6700:   Krylov method to take advantage of the known solution on the zeroed rows.

6702:   For the parallel case, all processes that share the matrix (i.e.,
6703:   those in the communicator used for matrix creation) MUST call this
6704:   routine, regardless of whether any rows being zeroed are owned by
6705:   them.

6707:   Unlike `MatZeroRows()`, this ignores the `MAT_KEEP_NONZERO_PATTERN` option value set with `MatSetOption()`, it merely zeros those entries in the matrix, but never
6708:   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
6709:   missing.

6711:   Each process can indicate any rows in the entire matrix to be zeroed (i.e. each process does NOT have to
6712:   list only rows local to itself).

6714:   The option `MAT_NO_OFF_PROC_ZERO_ROWS` does not apply to this routine.

6716: .seealso: [](ch_matrices), `Mat`, `MatZeroRowsIS()`, `MatZeroRows()`, `MatZeroRowsLocalIS()`, `MatZeroRowsStencil()`, `MatZeroEntries()`, `MatZeroRowsLocal()`, `MatSetOption()`,
6717:           `MatZeroRowsColumnsLocal()`, `MatZeroRowsColumnsLocalIS()`, `MatZeroRowsColumnsIS()`, `MatZeroRowsColumnsStencil()`
6718: @*/
6719: PetscErrorCode MatZeroRowsColumns(Mat mat, PetscInt numRows, const PetscInt rows[], PetscScalar diag, Vec x, Vec b)
6720: {
6721:   PetscFunctionBegin;
6724:   if (numRows) PetscAssertPointer(rows, 3);
6725:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
6726:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
6727:   MatCheckPreallocated(mat, 1);

6729:   PetscUseTypeMethod(mat, zerorowscolumns, numRows, rows, diag, x, b);
6730:   PetscCall(MatViewFromOptions(mat, NULL, "-mat_view"));
6731:   PetscCall(PetscObjectStateIncrease((PetscObject)mat));
6732:   PetscFunctionReturn(PETSC_SUCCESS);
6733: }

6735: /*@
6736:   MatZeroRowsColumnsIS - Zeros all entries (except possibly the main diagonal)
6737:   of a set of rows and columns of a matrix.

6739:   Collective

6741:   Input Parameters:
6742: + mat  - the matrix
6743: . is   - the rows to zero
6744: . diag - value put in all diagonals of eliminated rows (0.0 will even eliminate diagonal entry)
6745: . x    - optional vector of solutions for zeroed rows (other entries in vector are not used)
6746: - b    - optional vector of right-hand side, that will be adjusted by provided solution

6748:   Level: intermediate

6750:   Note:
6751:   See `MatZeroRowsColumns()` for details on how this routine operates.

6753: .seealso: [](ch_matrices), `Mat`, `MatZeroRowsIS()`, `MatZeroRowsColumns()`, `MatZeroRowsLocalIS()`, `MatZeroRowsStencil()`, `MatZeroEntries()`, `MatZeroRowsLocal()`, `MatSetOption()`,
6754:           `MatZeroRowsColumnsLocal()`, `MatZeroRowsColumnsLocalIS()`, `MatZeroRows()`, `MatZeroRowsColumnsStencil()`
6755: @*/
6756: PetscErrorCode MatZeroRowsColumnsIS(Mat mat, IS is, PetscScalar diag, Vec x, Vec b)
6757: {
6758:   PetscInt        numRows;
6759:   const PetscInt *rows;

6761:   PetscFunctionBegin;
6766:   PetscCall(ISGetLocalSize(is, &numRows));
6767:   PetscCall(ISGetIndices(is, &rows));
6768:   PetscCall(MatZeroRowsColumns(mat, numRows, rows, diag, x, b));
6769:   PetscCall(ISRestoreIndices(is, &rows));
6770:   PetscFunctionReturn(PETSC_SUCCESS);
6771: }

6773: /*@
6774:   MatZeroRows - Zeros all entries (except possibly the main diagonal)
6775:   of a set of rows of a matrix.

6777:   Collective

6779:   Input Parameters:
6780: + mat     - the matrix
6781: . numRows - the number of rows to zero
6782: . rows    - the global row indices
6783: . diag    - value put in the diagonal of the zeroed rows
6784: . x       - optional vector of solutions for zeroed rows (other entries in vector are not used), these must be set before this call
6785: - b       - optional vector of right-hand side, that will be adjusted by provided solution entries

6787:   Level: intermediate

6789:   Notes:
6790:   This routine, along with `MatZeroRowsColumns()`, is typically used to eliminate known Dirichlet boundary conditions from a linear system.

6792:   For each zeroed row, the value of the corresponding `b` is set to `diag` times the value of the corresponding `x`.

6794:   If the resulting linear system is to be solved with `KSP` then one can (but does not have to) call `KSPSetInitialGuessNonzero()` to allow the
6795:   Krylov method to take advantage of the known solution on the zeroed rows.

6797:   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)
6798:   from the matrix.

6800:   Unlike `MatZeroRowsColumns()` for the `MATAIJ` and `MATBAIJ` matrix formats this removes the old nonzero structure, from the eliminated rows of the matrix
6801:   but does not release memory. Because of this removal matrix-vector products with the adjusted matrix will be a bit faster. For the dense
6802:   formats this does not alter the nonzero structure.

6804:   If the option `MatSetOption`(mat,`MAT_KEEP_NONZERO_PATTERN`,`PETSC_TRUE`) the nonzero structure
6805:   of the matrix is not changed the values are
6806:   merely zeroed.

6808:   The user can set a value in the diagonal entry (or for the `MATAIJ` format
6809:   formats can optionally remove the main diagonal entry from the
6810:   nonzero structure as well, by passing 0.0 as the final argument).

6812:   For the parallel case, all processes that share the matrix (i.e.,
6813:   those in the communicator used for matrix creation) MUST call this
6814:   routine, regardless of whether any rows being zeroed are owned by
6815:   them.

6817:   Each process can indicate any rows in the entire matrix to be zeroed (i.e. each process does NOT have to
6818:   list only rows local to itself).

6820:   You can call `MatSetOption`(mat,`MAT_NO_OFF_PROC_ZERO_ROWS`,`PETSC_TRUE`) if each process indicates only rows it
6821:   owns that are to be zeroed. This saves a global synchronization in the implementation.

6823: .seealso: [](ch_matrices), `Mat`, `MatZeroRowsIS()`, `MatZeroRowsColumns()`, `MatZeroRowsLocalIS()`, `MatZeroRowsStencil()`, `MatZeroEntries()`, `MatZeroRowsLocal()`, `MatSetOption()`,
6824:           `MatZeroRowsColumnsLocal()`, `MatZeroRowsColumnsLocalIS()`, `MatZeroRowsColumnsIS()`, `MatZeroRowsColumnsStencil()`, `PCREDISTRIBUTE`, `MAT_KEEP_NONZERO_PATTERN`
6825: @*/
6826: PetscErrorCode MatZeroRows(Mat mat, PetscInt numRows, const PetscInt rows[], PetscScalar diag, Vec x, Vec b)
6827: {
6828:   PetscFunctionBegin;
6831:   if (numRows) PetscAssertPointer(rows, 3);
6832:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
6833:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
6834:   MatCheckPreallocated(mat, 1);

6836:   PetscUseTypeMethod(mat, zerorows, numRows, rows, diag, x, b);
6837:   PetscCall(MatViewFromOptions(mat, NULL, "-mat_view"));
6838:   PetscCall(PetscObjectStateIncrease((PetscObject)mat));
6839:   PetscFunctionReturn(PETSC_SUCCESS);
6840: }

6842: /*@
6843:   MatZeroRowsIS - Zeros all entries (except possibly the main diagonal)
6844:   of a set of rows of a matrix indicated by an `IS`

6846:   Collective

6848:   Input Parameters:
6849: + mat  - the matrix
6850: . is   - index set, `IS`, of rows to remove (if `NULL` then no row is removed)
6851: . diag - value put in all diagonals of eliminated rows
6852: . x    - optional vector of solutions for zeroed rows (other entries in vector are not used)
6853: - b    - optional vector of right-hand side, that will be adjusted by provided solution

6855:   Level: intermediate

6857:   Note:
6858:   See `MatZeroRows()` for details on how this routine operates.

6860: .seealso: [](ch_matrices), `Mat`, `MatZeroRows()`, `MatZeroRowsColumns()`, `MatZeroRowsLocalIS()`, `MatZeroRowsStencil()`, `MatZeroEntries()`, `MatZeroRowsLocal()`, `MatSetOption()`,
6861:           `MatZeroRowsColumnsLocal()`, `MatZeroRowsColumnsLocalIS()`, `MatZeroRowsColumnsIS()`, `MatZeroRowsColumnsStencil()`, `IS`
6862: @*/
6863: PetscErrorCode MatZeroRowsIS(Mat mat, IS is, PetscScalar diag, Vec x, Vec b)
6864: {
6865:   PetscInt        numRows = 0;
6866:   const PetscInt *rows    = NULL;

6868:   PetscFunctionBegin;
6871:   if (is) {
6873:     PetscCall(ISGetLocalSize(is, &numRows));
6874:     PetscCall(ISGetIndices(is, &rows));
6875:   }
6876:   PetscCall(MatZeroRows(mat, numRows, rows, diag, x, b));
6877:   if (is) PetscCall(ISRestoreIndices(is, &rows));
6878:   PetscFunctionReturn(PETSC_SUCCESS);
6879: }

6881: /*@
6882:   MatZeroRowsStencil - Zeros all entries (except possibly the main diagonal)
6883:   of a set of rows of a matrix indicated by a `MatStencil`. These rows must be local to the process.

6885:   Collective

6887:   Input Parameters:
6888: + mat     - the matrix
6889: . numRows - the number of rows to remove
6890: . rows    - the grid coordinates (and component number when dof > 1) for matrix rows indicated by an array of `MatStencil`
6891: . diag    - value put in all diagonals of eliminated rows (0.0 will even eliminate diagonal entry)
6892: . x       - optional vector of solutions for zeroed rows (other entries in vector are not used)
6893: - b       - optional vector of right-hand side, that will be adjusted by provided solution

6895:   Level: intermediate

6897:   Notes:
6898:   See `MatZeroRows()` for details on how this routine operates.

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

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

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

6910:   Fortran Note:
6911:   `idxm` and `idxn` should be declared as
6912: .vb
6913:     MatStencil idxm(4, m)
6914: .ve
6915:   and the values inserted using
6916: .vb
6917:     idxm(MatStencil_i, 1) = i
6918:     idxm(MatStencil_j, 1) = j
6919:     idxm(MatStencil_k, 1) = k
6920:     idxm(MatStencil_c, 1) = c
6921:    etc
6922: .ve

6924: .seealso: [](ch_matrices), `Mat`, `MatStencil`, `MatZeroRowsIS()`, `MatZeroRowsColumns()`, `MatZeroRowsLocalIS()`, `MatZeroRows()`, `MatZeroEntries()`, `MatZeroRowsLocal()`, `MatSetOption()`,
6925:           `MatZeroRowsColumnsLocal()`, `MatZeroRowsColumnsLocalIS()`, `MatZeroRowsColumnsIS()`, `MatZeroRowsColumnsStencil()`
6926: @*/
6927: PetscErrorCode MatZeroRowsStencil(Mat mat, PetscInt numRows, const MatStencil rows[], PetscScalar diag, Vec x, Vec b)
6928: {
6929:   PetscInt  dim    = mat->stencil.dim;
6930:   PetscInt  sdim   = dim - (1 - (PetscInt)mat->stencil.noc);
6931:   PetscInt *dims   = mat->stencil.dims + 1;
6932:   PetscInt *starts = mat->stencil.starts;
6933:   PetscInt *dxm    = (PetscInt *)rows;
6934:   PetscInt *jdxm, i, j, tmp, numNewRows = 0;

6936:   PetscFunctionBegin;
6939:   if (numRows) PetscAssertPointer(rows, 3);

6941:   PetscCall(PetscMalloc1(numRows, &jdxm));
6942:   for (i = 0; i < numRows; ++i) {
6943:     /* Skip unused dimensions (they are ordered k, j, i, c) */
6944:     for (j = 0; j < 3 - sdim; ++j) dxm++;
6945:     /* Local index in X dir */
6946:     tmp = *dxm++ - starts[0];
6947:     /* Loop over remaining dimensions */
6948:     for (j = 0; j < dim - 1; ++j) {
6949:       /* If nonlocal, set index to be negative */
6950:       if ((*dxm++ - starts[j + 1]) < 0 || tmp < 0) tmp = PETSC_INT_MIN;
6951:       /* Update local index */
6952:       else tmp = tmp * dims[j] + *(dxm - 1) - starts[j + 1];
6953:     }
6954:     /* Skip component slot if necessary */
6955:     if (mat->stencil.noc) dxm++;
6956:     /* Local row number */
6957:     if (tmp >= 0) jdxm[numNewRows++] = tmp;
6958:   }
6959:   PetscCall(MatZeroRowsLocal(mat, numNewRows, jdxm, diag, x, b));
6960:   PetscCall(PetscFree(jdxm));
6961:   PetscFunctionReturn(PETSC_SUCCESS);
6962: }

6964: /*@
6965:   MatZeroRowsColumnsStencil - Zeros all row and column entries (except possibly the main diagonal)
6966:   of a set of rows and columns of a matrix.

6968:   Collective

6970:   Input Parameters:
6971: + mat     - the matrix
6972: . numRows - the number of rows/columns to remove
6973: . rows    - the grid coordinates (and component number when dof > 1) for matrix rows
6974: . diag    - value put in all diagonals of eliminated rows (0.0 will even eliminate diagonal entry)
6975: . x       - optional vector of solutions for zeroed rows (other entries in vector are not used)
6976: - b       - optional vector of right-hand side, that will be adjusted by provided solution

6978:   Level: intermediate

6980:   Notes:
6981:   See `MatZeroRowsColumns()` for details on how this routine operates.

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

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

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

6993:   Fortran Note:
6994:   `idxm` and `idxn` should be declared as
6995: .vb
6996:     MatStencil idxm(4, m)
6997: .ve
6998:   and the values inserted using
6999: .vb
7000:     idxm(MatStencil_i, 1) = i
7001:     idxm(MatStencil_j, 1) = j
7002:     idxm(MatStencil_k, 1) = k
7003:     idxm(MatStencil_c, 1) = c
7004:     etc
7005: .ve

7007: .seealso: [](ch_matrices), `Mat`, `MatZeroRowsIS()`, `MatZeroRowsColumns()`, `MatZeroRowsLocalIS()`, `MatZeroRowsStencil()`, `MatZeroEntries()`, `MatZeroRowsLocal()`, `MatSetOption()`,
7008:           `MatZeroRowsColumnsLocal()`, `MatZeroRowsColumnsLocalIS()`, `MatZeroRowsColumnsIS()`, `MatZeroRows()`
7009: @*/
7010: PetscErrorCode MatZeroRowsColumnsStencil(Mat mat, PetscInt numRows, const MatStencil rows[], PetscScalar diag, Vec x, Vec b)
7011: {
7012:   PetscInt  dim    = mat->stencil.dim;
7013:   PetscInt  sdim   = dim - (1 - (PetscInt)mat->stencil.noc);
7014:   PetscInt *dims   = mat->stencil.dims + 1;
7015:   PetscInt *starts = mat->stencil.starts;
7016:   PetscInt *dxm    = (PetscInt *)rows;
7017:   PetscInt *jdxm, i, j, tmp, numNewRows = 0;

7019:   PetscFunctionBegin;
7022:   if (numRows) PetscAssertPointer(rows, 3);

7024:   PetscCall(PetscMalloc1(numRows, &jdxm));
7025:   for (i = 0; i < numRows; ++i) {
7026:     /* Skip unused dimensions (they are ordered k, j, i, c) */
7027:     for (j = 0; j < 3 - sdim; ++j) dxm++;
7028:     /* Local index in X dir */
7029:     tmp = *dxm++ - starts[0];
7030:     /* Loop over remaining dimensions */
7031:     for (j = 0; j < dim - 1; ++j) {
7032:       /* If nonlocal, set index to be negative */
7033:       if ((*dxm++ - starts[j + 1]) < 0 || tmp < 0) tmp = PETSC_INT_MIN;
7034:       /* Update local index */
7035:       else tmp = tmp * dims[j] + *(dxm - 1) - starts[j + 1];
7036:     }
7037:     /* Skip component slot if necessary */
7038:     if (mat->stencil.noc) dxm++;
7039:     /* Local row number */
7040:     if (tmp >= 0) jdxm[numNewRows++] = tmp;
7041:   }
7042:   PetscCall(MatZeroRowsColumnsLocal(mat, numNewRows, jdxm, diag, x, b));
7043:   PetscCall(PetscFree(jdxm));
7044:   PetscFunctionReturn(PETSC_SUCCESS);
7045: }

7047: /*@
7048:   MatZeroRowsLocal - Zeros all entries (except possibly the main diagonal)
7049:   of a set of rows of a matrix; using local numbering of rows.

7051:   Collective

7053:   Input Parameters:
7054: + mat     - the matrix
7055: . numRows - the number of rows to remove
7056: . rows    - the local row indices
7057: . diag    - value put in all diagonals of eliminated rows
7058: . x       - optional vector of solutions for zeroed rows (other entries in vector are not used)
7059: - b       - optional vector of right-hand side, that will be adjusted by provided solution

7061:   Level: intermediate

7063:   Notes:
7064:   Before calling `MatZeroRowsLocal()`, the user must first set the
7065:   local-to-global mapping by calling MatSetLocalToGlobalMapping(), this is often already set for matrices obtained with `DMCreateMatrix()`.

7067:   See `MatZeroRows()` for details on how this routine operates.

7069: .seealso: [](ch_matrices), `Mat`, `MatZeroRowsIS()`, `MatZeroRowsColumns()`, `MatZeroRowsLocalIS()`, `MatZeroRowsStencil()`, `MatZeroEntries()`, `MatZeroRows()`, `MatSetOption()`,
7070:           `MatZeroRowsColumnsLocal()`, `MatZeroRowsColumnsLocalIS()`, `MatZeroRowsColumnsIS()`, `MatZeroRowsColumnsStencil()`
7071: @*/
7072: PetscErrorCode MatZeroRowsLocal(Mat mat, PetscInt numRows, const PetscInt rows[], PetscScalar diag, Vec x, Vec b)
7073: {
7074:   PetscFunctionBegin;
7077:   if (numRows) PetscAssertPointer(rows, 3);
7078:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
7079:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
7080:   MatCheckPreallocated(mat, 1);

7082:   if (mat->ops->zerorowslocal) {
7083:     PetscUseTypeMethod(mat, zerorowslocal, numRows, rows, diag, x, b);
7084:   } else {
7085:     IS        is, newis;
7086:     PetscInt *newRows, nl = 0;

7088:     PetscCheck(mat->rmap->mapping, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Need to provide local to global mapping to matrix first");
7089:     PetscCall(ISCreateGeneral(PETSC_COMM_SELF, numRows, rows, PETSC_USE_POINTER, &is));
7090:     PetscCall(ISLocalToGlobalMappingApplyIS(mat->rmap->mapping, is, &newis));
7091:     PetscCall(ISGetIndices(newis, (const PetscInt **)&newRows));
7092:     for (PetscInt i = 0; i < numRows; i++)
7093:       if (newRows[i] > -1) newRows[nl++] = newRows[i];
7094:     PetscUseTypeMethod(mat, zerorows, nl, newRows, diag, x, b);
7095:     PetscCall(ISRestoreIndices(newis, (const PetscInt **)&newRows));
7096:     PetscCall(ISDestroy(&newis));
7097:     PetscCall(ISDestroy(&is));
7098:   }
7099:   PetscCall(PetscObjectStateIncrease((PetscObject)mat));
7100:   PetscFunctionReturn(PETSC_SUCCESS);
7101: }

7103: /*@
7104:   MatZeroRowsLocalIS - Zeros all entries (except possibly the main diagonal)
7105:   of a set of rows of a matrix; using local numbering of rows.

7107:   Collective

7109:   Input Parameters:
7110: + mat  - the matrix
7111: . is   - index set of rows to remove
7112: . diag - value put in all diagonals of eliminated rows
7113: . x    - optional vector of solutions for zeroed rows (other entries in vector are not used)
7114: - b    - optional vector of right-hand side, that will be adjusted by provided solution

7116:   Level: intermediate

7118:   Notes:
7119:   Before calling `MatZeroRowsLocalIS()`, the user must first set the
7120:   local-to-global mapping by calling `MatSetLocalToGlobalMapping()`, this is often already set for matrices obtained with `DMCreateMatrix()`.

7122:   See `MatZeroRows()` for details on how this routine operates.

7124: .seealso: [](ch_matrices), `Mat`, `MatZeroRowsIS()`, `MatZeroRowsColumns()`, `MatZeroRows()`, `MatZeroRowsStencil()`, `MatZeroEntries()`, `MatZeroRowsLocal()`, `MatSetOption()`,
7125:           `MatZeroRowsColumnsLocal()`, `MatZeroRowsColumnsLocalIS()`, `MatZeroRowsColumnsIS()`, `MatZeroRowsColumnsStencil()`
7126: @*/
7127: PetscErrorCode MatZeroRowsLocalIS(Mat mat, IS is, PetscScalar diag, Vec x, Vec b)
7128: {
7129:   PetscInt        numRows;
7130:   const PetscInt *rows;

7132:   PetscFunctionBegin;
7136:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
7137:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
7138:   MatCheckPreallocated(mat, 1);

7140:   PetscCall(ISGetLocalSize(is, &numRows));
7141:   PetscCall(ISGetIndices(is, &rows));
7142:   PetscCall(MatZeroRowsLocal(mat, numRows, rows, diag, x, b));
7143:   PetscCall(ISRestoreIndices(is, &rows));
7144:   PetscFunctionReturn(PETSC_SUCCESS);
7145: }

7147: /*@
7148:   MatZeroRowsColumnsLocal - Zeros all entries (except possibly the main diagonal)
7149:   of a set of rows and columns of a matrix; using local numbering of rows.

7151:   Collective

7153:   Input Parameters:
7154: + mat     - the matrix
7155: . numRows - the number of rows to remove
7156: . rows    - the global row indices
7157: . diag    - value put in all diagonals of eliminated rows
7158: . x       - optional vector of solutions for zeroed rows (other entries in vector are not used)
7159: - b       - optional vector of right-hand side, that will be adjusted by provided solution

7161:   Level: intermediate

7163:   Notes:
7164:   Before calling `MatZeroRowsColumnsLocal()`, the user must first set the
7165:   local-to-global mapping by calling `MatSetLocalToGlobalMapping()`, this is often already set for matrices obtained with `DMCreateMatrix()`.

7167:   See `MatZeroRowsColumns()` for details on how this routine operates.

7169: .seealso: [](ch_matrices), `Mat`, `MatZeroRowsIS()`, `MatZeroRowsColumns()`, `MatZeroRowsLocalIS()`, `MatZeroRowsStencil()`, `MatZeroEntries()`, `MatZeroRowsLocal()`, `MatSetOption()`,
7170:           `MatZeroRows()`, `MatZeroRowsColumnsLocalIS()`, `MatZeroRowsColumnsIS()`, `MatZeroRowsColumnsStencil()`
7171: @*/
7172: PetscErrorCode MatZeroRowsColumnsLocal(Mat mat, PetscInt numRows, const PetscInt rows[], PetscScalar diag, Vec x, Vec b)
7173: {
7174:   PetscFunctionBegin;
7177:   if (numRows) PetscAssertPointer(rows, 3);
7178:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
7179:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
7180:   MatCheckPreallocated(mat, 1);

7182:   if (mat->ops->zerorowscolumnslocal) {
7183:     PetscUseTypeMethod(mat, zerorowscolumnslocal, numRows, rows, diag, x, b);
7184:   } else {
7185:     IS        is, newis;
7186:     PetscInt *newRows, nl = 0;

7188:     PetscCheck(mat->rmap->mapping, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Need to provide local to global mapping to matrix first");
7189:     PetscCall(ISCreateGeneral(PETSC_COMM_SELF, numRows, rows, PETSC_USE_POINTER, &is));
7190:     PetscCall(ISLocalToGlobalMappingApplyIS(mat->rmap->mapping, is, &newis));
7191:     PetscCall(ISGetIndices(newis, (const PetscInt **)&newRows));
7192:     for (PetscInt i = 0; i < numRows; i++)
7193:       if (newRows[i] > -1) newRows[nl++] = newRows[i];
7194:     PetscUseTypeMethod(mat, zerorowscolumns, nl, newRows, diag, x, b);
7195:     PetscCall(ISRestoreIndices(newis, (const PetscInt **)&newRows));
7196:     PetscCall(ISDestroy(&newis));
7197:     PetscCall(ISDestroy(&is));
7198:   }
7199:   PetscCall(PetscObjectStateIncrease((PetscObject)mat));
7200:   PetscFunctionReturn(PETSC_SUCCESS);
7201: }

7203: /*@
7204:   MatZeroRowsColumnsLocalIS - Zeros all entries (except possibly the main diagonal)
7205:   of a set of rows and columns of a matrix; using local numbering of rows.

7207:   Collective

7209:   Input Parameters:
7210: + mat  - the matrix
7211: . is   - index set of rows to remove
7212: . diag - value put in all diagonals of eliminated rows
7213: . x    - optional vector of solutions for zeroed rows (other entries in vector are not used)
7214: - b    - optional vector of right-hand side, that will be adjusted by provided solution

7216:   Level: intermediate

7218:   Notes:
7219:   Before calling `MatZeroRowsColumnsLocalIS()`, the user must first set the
7220:   local-to-global mapping by calling `MatSetLocalToGlobalMapping()`, this is often already set for matrices obtained with `DMCreateMatrix()`.

7222:   See `MatZeroRowsColumns()` for details on how this routine operates.

7224: .seealso: [](ch_matrices), `Mat`, `MatZeroRowsIS()`, `MatZeroRowsColumns()`, `MatZeroRowsLocalIS()`, `MatZeroRowsStencil()`, `MatZeroEntries()`, `MatZeroRowsLocal()`, `MatSetOption()`,
7225:           `MatZeroRowsColumnsLocal()`, `MatZeroRows()`, `MatZeroRowsColumnsIS()`, `MatZeroRowsColumnsStencil()`
7226: @*/
7227: PetscErrorCode MatZeroRowsColumnsLocalIS(Mat mat, IS is, PetscScalar diag, Vec x, Vec b)
7228: {
7229:   PetscInt        numRows;
7230:   const PetscInt *rows;

7232:   PetscFunctionBegin;
7236:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
7237:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
7238:   MatCheckPreallocated(mat, 1);

7240:   PetscCall(ISGetLocalSize(is, &numRows));
7241:   PetscCall(ISGetIndices(is, &rows));
7242:   PetscCall(MatZeroRowsColumnsLocal(mat, numRows, rows, diag, x, b));
7243:   PetscCall(ISRestoreIndices(is, &rows));
7244:   PetscFunctionReturn(PETSC_SUCCESS);
7245: }

7247: /*@
7248:   MatGetSize - Returns the numbers of rows and columns in a matrix.

7250:   Not Collective

7252:   Input Parameter:
7253: . mat - the matrix

7255:   Output Parameters:
7256: + m - the number of global rows
7257: - n - the number of global columns

7259:   Level: beginner

7261:   Note:
7262:   Both output parameters can be `NULL` on input.

7264: .seealso: [](ch_matrices), `Mat`, `MatSetSizes()`, `MatGetLocalSize()`
7265: @*/
7266: PetscErrorCode MatGetSize(Mat mat, PetscInt *m, PetscInt *n)
7267: {
7268:   PetscFunctionBegin;
7270:   if (m) *m = mat->rmap->N;
7271:   if (n) *n = mat->cmap->N;
7272:   PetscFunctionReturn(PETSC_SUCCESS);
7273: }

7275: /*@
7276:   MatGetLocalSize - For most matrix formats, excluding `MATELEMENTAL` and `MATSCALAPACK`, Returns the number of local rows and local columns
7277:   of a matrix. For all matrices this is the local size of the left and right vectors as returned by `MatCreateVecs()`.

7279:   Not Collective

7281:   Input Parameter:
7282: . mat - the matrix

7284:   Output Parameters:
7285: + m - the number of local rows, use `NULL` to not obtain this value
7286: - n - the number of local columns, use `NULL` to not obtain this value

7288:   Level: beginner

7290: .seealso: [](ch_matrices), `Mat`, `MatSetSizes()`, `MatGetSize()`
7291: @*/
7292: PetscErrorCode MatGetLocalSize(Mat mat, PetscInt *m, PetscInt *n)
7293: {
7294:   PetscFunctionBegin;
7296:   if (m) PetscAssertPointer(m, 2);
7297:   if (n) PetscAssertPointer(n, 3);
7298:   if (m) *m = mat->rmap->n;
7299:   if (n) *n = mat->cmap->n;
7300:   PetscFunctionReturn(PETSC_SUCCESS);
7301: }

7303: /*@
7304:   MatGetOwnershipRangeColumn - Returns the range of matrix columns associated with rows of a
7305:   vector one multiplies this matrix by that are owned by this process.

7307:   Not Collective, unless matrix has not been allocated, then collective

7309:   Input Parameter:
7310: . mat - the matrix

7312:   Output Parameters:
7313: + m - the global index of the first local column, use `NULL` to not obtain this value
7314: - n - one more than the global index of the last local column, use `NULL` to not obtain this value

7316:   Level: developer

7318:   Notes:
7319:   If the `Mat` was obtained from a `DM` with `DMCreateMatrix()`, then the range values are determined by the specific `DM`.

7321:   If the `Mat` was created directly the range values are determined by the local size passed to `MatSetSizes()` or `MatCreateAIJ()`.
7322:   If `PETSC_DECIDE` was passed as the local size, then the vector uses default values for the range using `PetscSplitOwnership()`.

7324:   For certain `DM`, such as `DMDA`, it is better to use `DM` specific routines, such as `DMDAGetGhostCorners()`, to determine
7325:   the local values in the matrix.

7327:   Returns the columns of the "diagonal block" for most sparse matrix formats. See [Matrix
7328:   Layouts](sec_matlayout) for details on matrix layouts.

7330: .seealso: [](ch_matrices), `Mat`, `MatGetOwnershipRange()`, `MatGetOwnershipRanges()`, `MatGetOwnershipRangesColumn()`, `PetscLayout`,
7331:           `MatSetSizes()`, `MatCreateAIJ()`, `DMDAGetGhostCorners()`, `DM`
7332: @*/
7333: PetscErrorCode MatGetOwnershipRangeColumn(Mat mat, PetscInt *m, PetscInt *n)
7334: {
7335:   PetscFunctionBegin;
7338:   if (m) PetscAssertPointer(m, 2);
7339:   if (n) PetscAssertPointer(n, 3);
7340:   MatCheckPreallocated(mat, 1);
7341:   if (m) *m = mat->cmap->rstart;
7342:   if (n) *n = mat->cmap->rend;
7343:   PetscFunctionReturn(PETSC_SUCCESS);
7344: }

7346: /*@
7347:   MatGetOwnershipRange - For matrices that own values by row, excludes `MATELEMENTAL` and `MATSCALAPACK`, returns the range of matrix rows owned by
7348:   this MPI process.

7350:   Not Collective

7352:   Input Parameter:
7353: . mat - the matrix

7355:   Output Parameters:
7356: + m - the global index of the first local row, use `NULL` to not obtain this value
7357: - n - one more than the global index of the last local row, use `NULL` to not obtain this value

7359:   Level: beginner

7361:   Notes:
7362:   If the `Mat` was obtained from a `DM` with `DMCreateMatrix()`, then the range values are determined by the specific `DM`.

7364:   If the `Mat` was created directly the range values are determined by the local size passed to `MatSetSizes()` or `MatCreateAIJ()`.
7365:   If `PETSC_DECIDE` was passed as the local size, then the vector uses default values for the range using `PetscSplitOwnership()`.

7367:   For certain `DM`, such as `DMDA`, it is better to use `DM` specific routines, such as `DMDAGetGhostCorners()`, to determine
7368:   the local values in the matrix.

7370:   The high argument is one more than the last element stored locally.

7372:   For all matrices  it returns the range of matrix rows associated with rows of a vector that
7373:   would contain the result of a matrix vector product with this matrix. See [Matrix
7374:   Layouts](sec_matlayout) for details on matrix layouts.

7376: .seealso: [](ch_matrices), `Mat`, `MatGetOwnershipRanges()`, `MatGetOwnershipRangeColumn()`, `MatGetOwnershipRangesColumn()`, `PetscSplitOwnership()`,
7377:           `PetscSplitOwnershipBlock()`, `PetscLayout`, `MatSetSizes()`, `MatCreateAIJ()`, `DMDAGetGhostCorners()`, `DM`
7378: @*/
7379: PetscErrorCode MatGetOwnershipRange(Mat mat, PetscInt *m, PetscInt *n)
7380: {
7381:   PetscFunctionBegin;
7384:   if (m) PetscAssertPointer(m, 2);
7385:   if (n) PetscAssertPointer(n, 3);
7386:   MatCheckPreallocated(mat, 1);
7387:   if (m) *m = mat->rmap->rstart;
7388:   if (n) *n = mat->rmap->rend;
7389:   PetscFunctionReturn(PETSC_SUCCESS);
7390: }

7392: /*@
7393:   MatGetOwnershipRanges - For matrices that own values by row, excludes `MATELEMENTAL` and
7394:   `MATSCALAPACK`, returns the range of matrix rows owned by each process.

7396:   Not Collective, unless matrix has not been allocated

7398:   Input Parameter:
7399: . mat - the matrix

7401:   Output Parameter:
7402: . ranges - start of each process's portion plus one more than the total length at the end, of length `size` + 1
7403:            where `size` is the number of MPI processes used by `mat`

7405:   Level: beginner

7407:   Notes:
7408:   If the `Mat` was obtained from a `DM` with `DMCreateMatrix()`, then the range values are determined by the specific `DM`.

7410:   If the `Mat` was created directly the range values are determined by the local size passed to `MatSetSizes()` or `MatCreateAIJ()`.
7411:   If `PETSC_DECIDE` was passed as the local size, then the vector uses default values for the range using `PetscSplitOwnership()`.

7413:   For certain `DM`, such as `DMDA`, it is better to use `DM` specific routines, such as `DMDAGetGhostCorners()`, to determine
7414:   the local values in the matrix.

7416:   For all matrices  it returns the ranges of matrix rows associated with rows of a vector that
7417:   would contain the result of a matrix vector product with this matrix. See [Matrix
7418:   Layouts](sec_matlayout) for details on matrix layouts.

7420: .seealso: [](ch_matrices), `Mat`, `MatGetOwnershipRange()`, `MatGetOwnershipRangeColumn()`, `MatGetOwnershipRangesColumn()`, `PetscLayout`,
7421:           `PetscSplitOwnership()`, `PetscSplitOwnershipBlock()`, `MatSetSizes()`, `MatCreateAIJ()`,
7422:           `DMDAGetGhostCorners()`, `DM`
7423: @*/
7424: PetscErrorCode MatGetOwnershipRanges(Mat mat, const PetscInt *ranges[])
7425: {
7426:   PetscFunctionBegin;
7429:   MatCheckPreallocated(mat, 1);
7430:   PetscCall(PetscLayoutGetRanges(mat->rmap, ranges));
7431:   PetscFunctionReturn(PETSC_SUCCESS);
7432: }

7434: /*@
7435:   MatGetOwnershipRangesColumn - Returns the ranges of matrix columns associated with rows of a
7436:   vector one multiplies this vector by that are owned by each process.

7438:   Not Collective, unless matrix has not been allocated

7440:   Input Parameter:
7441: . mat - the matrix

7443:   Output Parameter:
7444: . ranges - start of each process's portion plus one more than the total length at the end

7446:   Level: beginner

7448:   Notes:
7449:   If the `Mat` was obtained from a `DM` with `DMCreateMatrix()`, then the range values are determined by the specific `DM`.

7451:   If the `Mat` was created directly the range values are determined by the local size passed to `MatSetSizes()` or `MatCreateAIJ()`.
7452:   If `PETSC_DECIDE` was passed as the local size, then the vector uses default values for the range using `PetscSplitOwnership()`.

7454:   For certain `DM`, such as `DMDA`, it is better to use `DM` specific routines, such as `DMDAGetGhostCorners()`, to determine
7455:   the local values in the matrix.

7457:   Returns the columns of the "diagonal blocks", for most sparse matrix formats. See [Matrix
7458:   Layouts](sec_matlayout) for details on matrix layouts.

7460: .seealso: [](ch_matrices), `Mat`, `MatGetOwnershipRange()`, `MatGetOwnershipRangeColumn()`, `MatGetOwnershipRanges()`,
7461:           `PetscSplitOwnership()`, `PetscSplitOwnershipBlock()`, `PetscLayout`, `MatSetSizes()`, `MatCreateAIJ()`,
7462:           `DMDAGetGhostCorners()`, `DM`
7463: @*/
7464: PetscErrorCode MatGetOwnershipRangesColumn(Mat mat, const PetscInt *ranges[])
7465: {
7466:   PetscFunctionBegin;
7469:   MatCheckPreallocated(mat, 1);
7470:   PetscCall(PetscLayoutGetRanges(mat->cmap, ranges));
7471:   PetscFunctionReturn(PETSC_SUCCESS);
7472: }

7474: /*@
7475:   MatGetOwnershipIS - Get row and column ownership of a matrices' values as index sets.

7477:   Not Collective

7479:   Input Parameter:
7480: . A - matrix

7482:   Output Parameters:
7483: + rows - rows in which this process owns elements, , use `NULL` to not obtain this value
7484: - cols - columns in which this process owns elements, use `NULL` to not obtain this value

7486:   Level: intermediate

7488:   Note:
7489:   You should call `ISDestroy()` on the returned `IS`

7491:   For most matrices, excluding `MATELEMENTAL` and `MATSCALAPACK`, this corresponds to values
7492:   returned by `MatGetOwnershipRange()`, `MatGetOwnershipRangeColumn()`. For `MATELEMENTAL` and
7493:   `MATSCALAPACK` the ownership is more complicated. See [Matrix Layouts](sec_matlayout) for
7494:   details on matrix layouts.

7496: .seealso: [](ch_matrices), `IS`, `Mat`, `MatGetOwnershipRanges()`, `MatSetValues()`, `MATELEMENTAL`, `MATSCALAPACK`
7497: @*/
7498: PetscErrorCode MatGetOwnershipIS(Mat A, IS *rows, IS *cols)
7499: {
7500:   PetscErrorCode (*f)(Mat, IS *, IS *);

7502:   PetscFunctionBegin;
7505:   MatCheckPreallocated(A, 1);
7506:   PetscCall(PetscObjectQueryFunction((PetscObject)A, "MatGetOwnershipIS_C", &f));
7507:   if (f) {
7508:     PetscCall((*f)(A, rows, cols));
7509:   } else { /* Create a standard row-based partition, each process is responsible for ALL columns in their row block */
7510:     if (rows) PetscCall(ISCreateStride(PETSC_COMM_SELF, A->rmap->n, A->rmap->rstart, 1, rows));
7511:     if (cols) PetscCall(ISCreateStride(PETSC_COMM_SELF, A->cmap->N, 0, 1, cols));
7512:   }
7513:   PetscFunctionReturn(PETSC_SUCCESS);
7514: }

7516: /*@
7517:   MatILUFactorSymbolic - Performs symbolic ILU factorization of a matrix obtained with `MatGetFactor()`
7518:   Uses levels of fill only, not drop tolerance. Use `MatLUFactorNumeric()`
7519:   to complete the factorization.

7521:   Collective

7523:   Input Parameters:
7524: + fact - the factorized matrix obtained with `MatGetFactor()`
7525: . mat  - the matrix
7526: . row  - row permutation
7527: . col  - column permutation
7528: - info - structure containing
7529: .vb
7530:       levels - number of levels of fill.
7531:       expected fill - as ratio of original fill.
7532:       1 or 0 - indicating force fill on diagonal (improves robustness for matrices
7533:                 missing diagonal entries)
7534: .ve

7536:   Level: developer

7538:   Notes:
7539:   See [Matrix Factorization](sec_matfactor) for additional information.

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

7545:   Uses the definition of level of fill as in Y. Saad, {cite}`saad2003`

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

7550: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatGetFactor()`, `MatLUFactorSymbolic()`, `MatLUFactorNumeric()`, `MatCholeskyFactor()`,
7551:           `MatGetOrdering()`, `MatFactorInfo`
7552: @*/
7553: PetscErrorCode MatILUFactorSymbolic(Mat fact, Mat mat, IS row, IS col, const MatFactorInfo *info)
7554: {
7555:   PetscFunctionBegin;
7560:   PetscAssertPointer(info, 5);
7561:   PetscAssertPointer(fact, 1);
7562:   PetscCheck(info->levels >= 0, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_OUTOFRANGE, "Levels of fill negative %" PetscInt_FMT, (PetscInt)info->levels);
7563:   PetscCheck(info->fill >= 1.0, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_OUTOFRANGE, "Expected fill less than 1.0 %g", (double)info->fill);
7564:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
7565:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
7566:   MatCheckPreallocated(mat, 2);

7568:   if (!fact->trivialsymbolic) PetscCall(PetscLogEventBegin(MAT_ILUFactorSymbolic, mat, row, col, 0));
7569:   PetscUseTypeMethod(fact, ilufactorsymbolic, mat, row, col, info);
7570:   if (!fact->trivialsymbolic) PetscCall(PetscLogEventEnd(MAT_ILUFactorSymbolic, mat, row, col, 0));
7571:   PetscFunctionReturn(PETSC_SUCCESS);
7572: }

7574: /*@
7575:   MatICCFactorSymbolic - Performs symbolic incomplete
7576:   Cholesky factorization for a symmetric matrix. Use
7577:   `MatCholeskyFactorNumeric()` to complete the factorization.

7579:   Collective

7581:   Input Parameters:
7582: + fact - the factorized matrix obtained with `MatGetFactor()`
7583: . mat  - the matrix to be factored
7584: . perm - row and column permutation
7585: - info - structure containing
7586: .vb
7587:       levels - number of levels of fill.
7588:       expected fill - as ratio of original fill.
7589: .ve

7591:   Level: developer

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

7598:   This uses the definition of level of fill as in Y. Saad {cite}`saad2003`

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

7603: .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatCholeskyFactorNumeric()`, `MatCholeskyFactor()`, `MatFactorInfo`
7604: @*/
7605: PetscErrorCode MatICCFactorSymbolic(Mat fact, Mat mat, IS perm, const MatFactorInfo *info)
7606: {
7607:   PetscFunctionBegin;
7611:   PetscAssertPointer(info, 4);
7612:   PetscAssertPointer(fact, 1);
7613:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
7614:   PetscCheck(info->levels >= 0, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_OUTOFRANGE, "Levels negative %" PetscInt_FMT, (PetscInt)info->levels);
7615:   PetscCheck(info->fill >= 1.0, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_OUTOFRANGE, "Expected fill less than 1.0 %g", (double)info->fill);
7616:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
7617:   MatCheckPreallocated(mat, 2);

7619:   if (!fact->trivialsymbolic) PetscCall(PetscLogEventBegin(MAT_ICCFactorSymbolic, mat, perm, 0, 0));
7620:   PetscUseTypeMethod(fact, iccfactorsymbolic, mat, perm, info);
7621:   if (!fact->trivialsymbolic) PetscCall(PetscLogEventEnd(MAT_ICCFactorSymbolic, mat, perm, 0, 0));
7622:   PetscFunctionReturn(PETSC_SUCCESS);
7623: }

7625: /*@
7626:   MatCreateSubMatrices - Extracts several submatrices from a matrix. If submat
7627:   points to an array of valid matrices, they may be reused to store the new
7628:   submatrices.

7630:   Collective

7632:   Input Parameters:
7633: + mat   - the matrix
7634: . n     - the number of submatrixes to be extracted (on this process, may be zero)
7635: . irow  - index set of rows to extract
7636: . icol  - index set of columns to extract
7637: - scall - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`

7639:   Output Parameter:
7640: . submat - the array of submatrices

7642:   Level: advanced

7644:   Notes:
7645:   `MatCreateSubMatrices()` can extract ONLY sequential submatrices
7646:   (from both sequential and parallel matrices). Use `MatCreateSubMatrix()`
7647:   to extract a parallel submatrix.

7649:   Some matrix types place restrictions on the row and column
7650:   indices, such as that they be sorted or that they be equal to each other.
7651:   `MATSEQSBAIJ` inputs may produce `MATSEQBAIJ` submatrices when the row and column index sets do not preserve symmetry.

7653:   The index sets may not have duplicate entries.

7655:   When extracting submatrices from a parallel matrix, each process can
7656:   form a different submatrix by setting the rows and columns of its
7657:   individual index sets according to the local submatrix desired.

7659:   When finished using the submatrices, the user should destroy
7660:   them with `MatDestroySubMatrices()`.

7662:   `MAT_REUSE_MATRIX` can only be used when the nonzero structure of the
7663:   original matrix has not changed from that last call to `MatCreateSubMatrices()`.

7665:   This routine creates the matrices in submat; you should NOT create them before
7666:   calling it. It also allocates the array of matrix pointers submat.

7668:   For `MATBAIJ` matrices the index sets must respect the block structure, that is if they
7669:   request one row/column in a block, they must request all rows/columns that are in
7670:   that block. For example, if the block size is 2 you cannot request just row 0 and
7671:   column 0.

7673:   Fortran Note:
7674: .vb
7675:   Mat, pointer :: submat(:)
7676: .ve

7678: .seealso: [](ch_matrices), `Mat`, `MatDestroySubMatrices()`, `MatCreateSubMatrix()`, `MatGetRow()`, `MatGetDiagonal()`, `MatReuse`
7679: @*/
7680: PetscErrorCode MatCreateSubMatrices(Mat mat, PetscInt n, const IS irow[], const IS icol[], MatReuse scall, Mat *submat[])
7681: {
7682:   PetscInt  i;
7683:   PetscBool eq;

7685:   PetscFunctionBegin;
7688:   if (n) {
7689:     PetscAssertPointer(irow, 3);
7691:     PetscAssertPointer(icol, 4);
7693:   }
7694:   PetscAssertPointer(submat, 6);
7695:   if (n && scall == MAT_REUSE_MATRIX) {
7696:     PetscAssertPointer(*submat, 6);
7698:   }
7699:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
7700:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
7701:   MatCheckPreallocated(mat, 1);
7702:   PetscCall(PetscLogEventBegin(MAT_CreateSubMats, mat, 0, 0, 0));
7703:   PetscUseTypeMethod(mat, createsubmatrices, n, irow, icol, scall, submat);
7704:   PetscCall(PetscLogEventEnd(MAT_CreateSubMats, mat, 0, 0, 0));
7705:   for (i = 0; i < n; i++) {
7706:     (*submat)[i]->factortype = MAT_FACTOR_NONE; /* in case in place factorization was previously done on submatrix */
7707:     PetscCall(ISEqualUnsorted(irow[i], icol[i], &eq));
7708:     if (eq) PetscCall(MatPropagateSymmetryOptions(mat, (*submat)[i]));
7709: #if PetscDefined(HAVE_VIENNACL) || PetscDefined(HAVE_CUDA) || PetscDefined(HAVE_HIP)
7710:     if (mat->boundtocpu && mat->bindingpropagates) {
7711:       PetscCall(MatBindToCPU((*submat)[i], PETSC_TRUE));
7712:       PetscCall(MatSetBindingPropagates((*submat)[i], PETSC_TRUE));
7713:     }
7714: #endif
7715:   }
7716:   PetscFunctionReturn(PETSC_SUCCESS);
7717: }

7719: /*@
7720:   MatCreateSubMatricesMPI - Extracts MPI submatrices across a sub communicator of `mat` (by pairs of `IS` that may live on subcomms).

7722:   Collective

7724:   Input Parameters:
7725: + mat   - the matrix
7726: . n     - the number of submatrixes to be extracted
7727: . irow  - index set of rows to extract
7728: . icol  - index set of columns to extract
7729: - scall - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`

7731:   Output Parameter:
7732: . submat - the array of submatrices

7734:   Level: advanced

7736:   Note:
7737:   This is used by `PCGASM`

7739: .seealso: [](ch_matrices), `Mat`, `PCGASM`, `MatCreateSubMatrices()`, `MatCreateSubMatrix()`, `MatGetRow()`, `MatGetDiagonal()`, `MatReuse`
7740: @*/
7741: PetscErrorCode MatCreateSubMatricesMPI(Mat mat, PetscInt n, const IS irow[], const IS icol[], MatReuse scall, Mat *submat[])
7742: {
7743:   PetscInt  i;
7744:   PetscBool eq;

7746:   PetscFunctionBegin;
7749:   if (n) {
7750:     PetscAssertPointer(irow, 3);
7752:     PetscAssertPointer(icol, 4);
7754:   }
7755:   PetscAssertPointer(submat, 6);
7756:   if (n && scall == MAT_REUSE_MATRIX) {
7757:     PetscAssertPointer(*submat, 6);
7759:   }
7760:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
7761:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
7762:   MatCheckPreallocated(mat, 1);

7764:   PetscCall(PetscLogEventBegin(MAT_CreateSubMats, mat, 0, 0, 0));
7765:   PetscUseTypeMethod(mat, createsubmatricesmpi, n, irow, icol, scall, submat);
7766:   PetscCall(PetscLogEventEnd(MAT_CreateSubMats, mat, 0, 0, 0));
7767:   for (i = 0; i < n; i++) {
7768:     PetscCall(ISEqualUnsorted(irow[i], icol[i], &eq));
7769:     if (eq) PetscCall(MatPropagateSymmetryOptions(mat, (*submat)[i]));
7770:   }
7771:   PetscFunctionReturn(PETSC_SUCCESS);
7772: }

7774: /*@
7775:   MatDestroyMatrices - Destroys an array of matrices

7777:   Collective

7779:   Input Parameters:
7780: + n   - the number of local matrices
7781: - mat - the matrices (this is a pointer to the array of matrices)

7783:   Level: advanced

7785:   Notes:
7786:   Frees not only the matrices, but also the array that contains the matrices

7788:   For matrices obtained with  `MatCreateSubMatrices()` use `MatDestroySubMatrices()`

7790: .seealso: [](ch_matrices), `Mat`, `MatCreateSubMatrices()`, `MatDestroySubMatrices()`
7791: @*/
7792: PetscErrorCode MatDestroyMatrices(PetscInt n, Mat *mat[])
7793: {
7794:   PetscInt i;

7796:   PetscFunctionBegin;
7797:   if (!*mat) PetscFunctionReturn(PETSC_SUCCESS);
7798:   PetscCheck(n >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Trying to destroy negative number of matrices %" PetscInt_FMT, n);
7799:   PetscAssertPointer(mat, 2);

7801:   for (i = 0; i < n; i++) PetscCall(MatDestroy(&(*mat)[i]));

7803:   /* memory is allocated even if n = 0 */
7804:   PetscCall(PetscFree(*mat));
7805:   PetscFunctionReturn(PETSC_SUCCESS);
7806: }

7808: /*@
7809:   MatDestroySubMatrices - Destroys a set of matrices obtained with `MatCreateSubMatrices()`.

7811:   Collective

7813:   Input Parameters:
7814: + n   - the number of local matrices
7815: - mat - the matrices (this is a pointer to the array of matrices, to match the calling sequence of `MatCreateSubMatrices()`)

7817:   Level: advanced

7819:   Note:
7820:   Frees not only the matrices, but also the array that contains the matrices

7822: .seealso: [](ch_matrices), `Mat`, `MatCreateSubMatrices()`, `MatDestroyMatrices()`
7823: @*/
7824: PetscErrorCode MatDestroySubMatrices(PetscInt n, Mat *mat[])
7825: {
7826:   Mat mat0;

7828:   PetscFunctionBegin;
7829:   if (!*mat) PetscFunctionReturn(PETSC_SUCCESS);
7830:   /* mat[] is an array of length n+1, see MatCreateSubMatrices_xxx() */
7831:   PetscCheck(n >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Trying to destroy negative number of matrices %" PetscInt_FMT, n);
7832:   PetscAssertPointer(mat, 2);

7834:   mat0 = (*mat)[0];
7835:   if (mat0 && mat0->ops->destroysubmatrices) {
7836:     PetscCall((*mat0->ops->destroysubmatrices)(n, mat));
7837:   } else {
7838:     PetscCall(MatDestroyMatrices(n, mat));
7839:   }
7840:   PetscFunctionReturn(PETSC_SUCCESS);
7841: }

7843: /*@
7844:   MatGetSeqNonzeroStructure - Extracts the nonzero structure from a matrix and stores it, in its entirety, on each process

7846:   Collective

7848:   Input Parameter:
7849: . mat - the matrix

7851:   Output Parameter:
7852: . matstruct - the sequential matrix with the nonzero structure of `mat`

7854:   Level: developer

7856: .seealso: [](ch_matrices), `Mat`, `MatDestroySeqNonzeroStructure()`, `MatCreateSubMatrices()`, `MatDestroyMatrices()`
7857: @*/
7858: PetscErrorCode MatGetSeqNonzeroStructure(Mat mat, Mat *matstruct)
7859: {
7860:   PetscFunctionBegin;
7862:   PetscAssertPointer(matstruct, 2);

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

7868:   PetscCall(PetscLogEventBegin(MAT_GetSeqNonzeroStructure, mat, 0, 0, 0));
7869:   PetscUseTypeMethod(mat, getseqnonzerostructure, matstruct);
7870:   PetscCall(PetscLogEventEnd(MAT_GetSeqNonzeroStructure, mat, 0, 0, 0));
7871:   PetscFunctionReturn(PETSC_SUCCESS);
7872: }

7874: /*@
7875:   MatDestroySeqNonzeroStructure - Destroys matrix obtained with `MatGetSeqNonzeroStructure()`.

7877:   Collective

7879:   Input Parameter:
7880: . mat - the matrix

7882:   Level: advanced

7884:   Note:
7885:   This is not needed, one can just call `MatDestroy()`

7887: .seealso: [](ch_matrices), `Mat`, `MatGetSeqNonzeroStructure()`
7888: @*/
7889: PetscErrorCode MatDestroySeqNonzeroStructure(Mat *mat)
7890: {
7891:   PetscFunctionBegin;
7892:   PetscAssertPointer(mat, 1);
7893:   PetscCall(MatDestroy(mat));
7894:   PetscFunctionReturn(PETSC_SUCCESS);
7895: }

7897: /*@
7898:   MatIncreaseOverlap - Given a set of submatrices indicated by index sets,
7899:   replaces the index sets by larger ones that represent submatrices with
7900:   additional overlap.

7902:   Collective

7904:   Input Parameters:
7905: + mat - the matrix
7906: . n   - the number of index sets
7907: . is  - the array of index sets (these index sets will changed during the call)
7908: - ov  - the additional overlap requested

7910:   Options Database Key:
7911: . -mat_increase_overlap_scalable - use a scalable algorithm to compute the overlap (supported by MPIAIJ matrix)

7913:   Level: developer

7915:   Note:
7916:   The computed overlap preserves the matrix block sizes when the blocks are square.
7917:   That is: if a matrix nonzero for a given block would increase the overlap all columns associated with
7918:   that block are included in the overlap regardless of whether each specific column would increase the overlap.

7920: .seealso: [](ch_matrices), `Mat`, `PCASM`, `MatSetBlockSize()`, `MatIncreaseOverlapSplit()`, `MatCreateSubMatrices()`
7921: @*/
7922: PetscErrorCode MatIncreaseOverlap(Mat mat, PetscInt n, IS is[], PetscInt ov)
7923: {
7924:   PetscInt i, bs, cbs;

7926:   PetscFunctionBegin;
7930:   PetscCheck(n >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Must have one or more domains, you have %" PetscInt_FMT, n);
7931:   if (n) {
7932:     PetscAssertPointer(is, 3);
7934:   }
7935:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
7936:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
7937:   MatCheckPreallocated(mat, 1);

7939:   if (!ov || !n) PetscFunctionReturn(PETSC_SUCCESS);
7940:   PetscCall(PetscLogEventBegin(MAT_IncreaseOverlap, mat, 0, 0, 0));
7941:   PetscUseTypeMethod(mat, increaseoverlap, n, is, ov);
7942:   PetscCall(PetscLogEventEnd(MAT_IncreaseOverlap, mat, 0, 0, 0));
7943:   PetscCall(MatGetBlockSizes(mat, &bs, &cbs));
7944:   if (bs == cbs) {
7945:     for (i = 0; i < n; i++) PetscCall(ISSetBlockSize(is[i], bs));
7946:   }
7947:   PetscFunctionReturn(PETSC_SUCCESS);
7948: }

7950: PetscErrorCode MatIncreaseOverlapSplit_Single(Mat, IS *, PetscInt);

7952: /*@
7953:   MatIncreaseOverlapSplit - Given a set of submatrices indicated by index sets across
7954:   a sub communicator, replaces the index sets by larger ones that represent submatrices with
7955:   additional overlap.

7957:   Collective

7959:   Input Parameters:
7960: + mat - the matrix
7961: . n   - the number of index sets
7962: . is  - the array of index sets (these index sets will changed during the call)
7963: - ov  - the additional overlap requested

7965:   `   Options Database Key:
7966: . -mat_increase_overlap_scalable - use a scalable algorithm to compute the overlap (supported by MPIAIJ matrix)

7968:   Level: developer

7970: .seealso: [](ch_matrices), `Mat`, `MatCreateSubMatrices()`, `MatIncreaseOverlap()`
7971: @*/
7972: PetscErrorCode MatIncreaseOverlapSplit(Mat mat, PetscInt n, IS is[], PetscInt ov)
7973: {
7974:   PetscInt i;

7976:   PetscFunctionBegin;
7979:   PetscCheck(n >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Must have one or more domains, you have %" PetscInt_FMT, n);
7980:   if (n) {
7981:     PetscAssertPointer(is, 3);
7983:   }
7984:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
7985:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
7986:   MatCheckPreallocated(mat, 1);
7987:   if (!ov) PetscFunctionReturn(PETSC_SUCCESS);
7988:   PetscCall(PetscLogEventBegin(MAT_IncreaseOverlap, mat, 0, 0, 0));
7989:   for (i = 0; i < n; i++) PetscCall(MatIncreaseOverlapSplit_Single(mat, &is[i], ov));
7990:   PetscCall(PetscLogEventEnd(MAT_IncreaseOverlap, mat, 0, 0, 0));
7991:   PetscFunctionReturn(PETSC_SUCCESS);
7992: }

7994: /*@
7995:   MatGetBlockSize - Returns the matrix block size.

7997:   Not Collective

7999:   Input Parameter:
8000: . mat - the matrix

8002:   Output Parameter:
8003: . bs - block size

8005:   Level: intermediate

8007:   Notes:
8008:   Block row formats are `MATBAIJ` and `MATSBAIJ` ALWAYS have square block storage in the matrix.

8010:   If the block size has not been set yet this routine returns 1.

8012: .seealso: [](ch_matrices), `Mat`, `MATBAIJ`, `MATSBAIJ`, `MatCreateSeqBAIJ()`, `MatCreateBAIJ()`, `MatGetBlockSizes()`
8013: @*/
8014: PetscErrorCode MatGetBlockSize(Mat mat, PetscInt *bs)
8015: {
8016:   PetscFunctionBegin;
8018:   PetscAssertPointer(bs, 2);
8019:   *bs = mat->rmap->bs;
8020:   PetscFunctionReturn(PETSC_SUCCESS);
8021: }

8023: /*@
8024:   MatGetBlockSizes - Returns the matrix block row and column sizes.

8026:   Not Collective

8028:   Input Parameter:
8029: . mat - the matrix

8031:   Output Parameters:
8032: + rbs - row block size
8033: - cbs - column block size

8035:   Level: intermediate

8037:   Notes:
8038:   Block row formats are `MATBAIJ` and `MATSBAIJ` ALWAYS have square block storage in the matrix.
8039:   If you pass a different block size for the columns than the rows, the row block size determines the square block storage.

8041:   If a block size has not been set yet this routine returns 1.

8043: .seealso: [](ch_matrices), `Mat`, `MATBAIJ`, `MATSBAIJ`, `MatCreateSeqBAIJ()`, `MatCreateBAIJ()`, `MatGetBlockSize()`, `MatSetBlockSize()`, `MatSetBlockSizes()`
8044: @*/
8045: PetscErrorCode MatGetBlockSizes(Mat mat, PetscInt *rbs, PetscInt *cbs)
8046: {
8047:   PetscFunctionBegin;
8049:   if (rbs) PetscAssertPointer(rbs, 2);
8050:   if (cbs) PetscAssertPointer(cbs, 3);
8051:   if (rbs) *rbs = mat->rmap->bs;
8052:   if (cbs) *cbs = mat->cmap->bs;
8053:   PetscFunctionReturn(PETSC_SUCCESS);
8054: }

8056: /*@
8057:   MatSetBlockSize - Sets the matrix block size.

8059:   Logically Collective

8061:   Input Parameters:
8062: + mat - the matrix
8063: - bs  - block size

8065:   Level: intermediate

8067:   Notes:
8068:   Block row formats are `MATBAIJ` and `MATSBAIJ` formats ALWAYS have square block storage in the matrix.
8069:   This must be called before `MatSetUp()` or MatXXXSetPreallocation() (or will default to 1) and the block size cannot be changed later.

8071:   For `MATAIJ` matrix format, this function can be called at a later stage, provided that the specified block size
8072:   is compatible with the matrix local sizes.

8074: .seealso: [](ch_matrices), `Mat`, `MATBAIJ`, `MATSBAIJ`, `MATAIJ`, `MatCreateSeqBAIJ()`, `MatCreateBAIJ()`, `MatGetBlockSize()`, `MatSetBlockSizes()`, `MatGetBlockSizes()`
8075: @*/
8076: PetscErrorCode MatSetBlockSize(Mat mat, PetscInt bs)
8077: {
8078:   PetscFunctionBegin;
8081:   PetscCall(MatSetBlockSizes(mat, bs, bs));
8082:   PetscFunctionReturn(PETSC_SUCCESS);
8083: }

8085: typedef struct {
8086:   PetscInt         n;
8087:   IS              *is;
8088:   Mat             *mat;
8089:   PetscObjectState nonzerostate;
8090:   Mat              C;
8091: } EnvelopeData;

8093: static PetscErrorCode EnvelopeDataDestroy(PetscCtxRt ptr)
8094: {
8095:   EnvelopeData *edata = *(EnvelopeData **)ptr;

8097:   PetscFunctionBegin;
8098:   for (PetscInt i = 0; i < edata->n; i++) PetscCall(ISDestroy(&edata->is[i]));
8099:   PetscCall(PetscFree(edata->is));
8100:   PetscCall(PetscFree(edata));
8101:   PetscFunctionReturn(PETSC_SUCCESS);
8102: }

8104: /*@
8105:   MatComputeVariableBlockEnvelope - Given a matrix whose nonzeros are in blocks along the diagonal this computes and stores
8106:   the sizes of these blocks in the matrix. An individual block may lie over several processes.

8108:   Collective

8110:   Input Parameter:
8111: . mat - the matrix

8113:   Level: intermediate

8115:   Notes:
8116:   There can be zeros within the blocks

8118:   The blocks can overlap between processes, including laying on more than two processes

8120: .seealso: [](ch_matrices), `Mat`, `MatInvertVariableBlockEnvelope()`, `MatSetVariableBlockSizes()`
8121: @*/
8122: PetscErrorCode MatComputeVariableBlockEnvelope(Mat mat)
8123: {
8124:   PetscInt           n, *sizes, *starts, i = 0, env = 0, tbs = 0, lblocks = 0, rstart, II, ln = 0, cnt = 0, cstart, cend;
8125:   PetscInt          *diag, *odiag, sc;
8126:   VecScatter         scatter;
8127:   PetscScalar       *seqv;
8128:   const PetscScalar *parv;
8129:   const PetscInt    *ia, *ja;
8130:   PetscBool          set, flag, done;
8131:   Mat                AA = mat, A;
8132:   MPI_Comm           comm;
8133:   PetscMPIInt        rank, size, tag;
8134:   MPI_Status         status;
8135:   PetscContainer     container;
8136:   EnvelopeData      *edata;
8137:   Vec                seq, par;
8138:   IS                 isglobal;

8140:   PetscFunctionBegin;
8142:   PetscCall(MatIsSymmetricKnown(mat, &set, &flag));
8143:   if (!set || !flag) {
8144:     /* TODO: only needs nonzero structure of transpose */
8145:     PetscCall(MatTranspose(mat, MAT_INITIAL_MATRIX, &AA));
8146:     PetscCall(MatAXPY(AA, 1.0, mat, DIFFERENT_NONZERO_PATTERN));
8147:   }
8148:   PetscCall(MatAIJGetLocalMat(AA, &A));
8149:   PetscCall(MatGetRowIJ(A, 0, PETSC_FALSE, PETSC_FALSE, &n, &ia, &ja, &done));
8150:   PetscCheck(done, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "Unable to get IJ structure from matrix");

8152:   PetscCall(MatGetLocalSize(mat, &n, NULL));
8153:   PetscCall(PetscObjectGetNewTag((PetscObject)mat, &tag));
8154:   PetscCall(PetscObjectGetComm((PetscObject)mat, &comm));
8155:   PetscCallMPI(MPI_Comm_size(comm, &size));
8156:   PetscCallMPI(MPI_Comm_rank(comm, &rank));

8158:   PetscCall(PetscMalloc2(n, &sizes, n, &starts));

8160:   if (rank > 0) {
8161:     PetscCallMPI(MPI_Recv(&env, 1, MPIU_INT, rank - 1, tag, comm, &status));
8162:     PetscCallMPI(MPI_Recv(&tbs, 1, MPIU_INT, rank - 1, tag, comm, &status));
8163:   }
8164:   PetscCall(MatGetOwnershipRange(mat, &rstart, NULL));
8165:   for (i = 0; i < n; i++) {
8166:     env = PetscMax(env, ja[ia[i + 1] - 1]);
8167:     II  = rstart + i;
8168:     if (env == II) {
8169:       starts[lblocks]  = tbs;
8170:       sizes[lblocks++] = 1 + II - tbs;
8171:       tbs              = 1 + II;
8172:     }
8173:   }
8174:   if (rank < size - 1) {
8175:     PetscCallMPI(MPI_Send(&env, 1, MPIU_INT, rank + 1, tag, comm));
8176:     PetscCallMPI(MPI_Send(&tbs, 1, MPIU_INT, rank + 1, tag, comm));
8177:   }

8179:   PetscCall(MatRestoreRowIJ(A, 0, PETSC_FALSE, PETSC_FALSE, &n, &ia, &ja, &done));
8180:   if (!set || !flag) PetscCall(MatDestroy(&AA));
8181:   PetscCall(MatDestroy(&A));

8183:   PetscCall(PetscNew(&edata));
8184:   PetscCall(MatGetNonzeroState(mat, &edata->nonzerostate));
8185:   edata->n = lblocks;
8186:   /* create IS needed for extracting blocks from the original matrix */
8187:   PetscCall(PetscMalloc1(lblocks, &edata->is));
8188:   for (PetscInt i = 0; i < lblocks; i++) PetscCall(ISCreateStride(PETSC_COMM_SELF, sizes[i], starts[i], 1, &edata->is[i]));

8190:   /* Create the resulting inverse matrix nonzero structure with preallocation information */
8191:   PetscCall(MatCreate(PetscObjectComm((PetscObject)mat), &edata->C));
8192:   PetscCall(MatSetSizes(edata->C, mat->rmap->n, mat->cmap->n, mat->rmap->N, mat->cmap->N));
8193:   PetscCall(MatSetBlockSizesFromMats(edata->C, mat, mat));
8194:   PetscCall(MatSetType(edata->C, MATAIJ));

8196:   /* Communicate the start and end of each row, from each block to the correct rank */
8197:   /* TODO: Use PetscSF instead of VecScatter */
8198:   for (PetscInt i = 0; i < lblocks; i++) ln += sizes[i];
8199:   PetscCall(VecCreateSeq(PETSC_COMM_SELF, 2 * ln, &seq));
8200:   PetscCall(VecGetArrayWrite(seq, &seqv));
8201:   for (PetscInt i = 0; i < lblocks; i++) {
8202:     for (PetscInt j = 0; j < sizes[i]; j++) {
8203:       seqv[cnt]     = starts[i];
8204:       seqv[cnt + 1] = starts[i] + sizes[i];
8205:       cnt += 2;
8206:     }
8207:   }
8208:   PetscCall(VecRestoreArrayWrite(seq, &seqv));
8209:   PetscCallMPI(MPI_Scan(&cnt, &sc, 1, MPIU_INT, MPI_SUM, PetscObjectComm((PetscObject)mat)));
8210:   sc -= cnt;
8211:   PetscCall(VecCreateMPI(PetscObjectComm((PetscObject)mat), 2 * mat->rmap->n, 2 * mat->rmap->N, &par));
8212:   PetscCall(ISCreateStride(PETSC_COMM_SELF, cnt, sc, 1, &isglobal));
8213:   PetscCall(VecScatterCreate(seq, NULL, par, isglobal, &scatter));
8214:   PetscCall(ISDestroy(&isglobal));
8215:   PetscCall(VecScatterBegin(scatter, seq, par, INSERT_VALUES, SCATTER_FORWARD));
8216:   PetscCall(VecScatterEnd(scatter, seq, par, INSERT_VALUES, SCATTER_FORWARD));
8217:   PetscCall(VecScatterDestroy(&scatter));
8218:   PetscCall(VecDestroy(&seq));
8219:   PetscCall(MatGetOwnershipRangeColumn(mat, &cstart, &cend));
8220:   PetscCall(PetscMalloc2(mat->rmap->n, &diag, mat->rmap->n, &odiag));
8221:   PetscCall(VecGetArrayRead(par, &parv));
8222:   cnt = 0;
8223:   PetscCall(MatGetSize(mat, NULL, &n));
8224:   for (PetscInt i = 0; i < mat->rmap->n; i++) {
8225:     PetscInt start, end, d = 0, od = 0;

8227:     start = (PetscInt)PetscRealPart(parv[cnt]);
8228:     end   = (PetscInt)PetscRealPart(parv[cnt + 1]);
8229:     cnt += 2;

8231:     if (start < cstart) {
8232:       od += cstart - start + n - cend;
8233:       d += cend - cstart;
8234:     } else if (start < cend) {
8235:       od += n - cend;
8236:       d += cend - start;
8237:     } else od += n - start;
8238:     if (end <= cstart) {
8239:       od -= cstart - end + n - cend;
8240:       d -= cend - cstart;
8241:     } else if (end < cend) {
8242:       od -= n - cend;
8243:       d -= cend - end;
8244:     } else od -= n - end;

8246:     odiag[i] = od;
8247:     diag[i]  = d;
8248:   }
8249:   PetscCall(VecRestoreArrayRead(par, &parv));
8250:   PetscCall(VecDestroy(&par));
8251:   PetscCall(MatXAIJSetPreallocation(edata->C, mat->rmap->bs, diag, odiag, NULL, NULL));
8252:   PetscCall(PetscFree2(diag, odiag));
8253:   PetscCall(PetscFree2(sizes, starts));

8255:   PetscCall(PetscContainerCreate(PETSC_COMM_SELF, &container));
8256:   PetscCall(PetscContainerSetPointer(container, edata));
8257:   PetscCall(PetscContainerSetCtxDestroy(container, EnvelopeDataDestroy));
8258:   PetscCall(PetscObjectCompose((PetscObject)mat, "EnvelopeData", (PetscObject)container));
8259:   PetscCall(PetscObjectDereference((PetscObject)container));
8260:   PetscFunctionReturn(PETSC_SUCCESS);
8261: }

8263: /*@
8264:   MatInvertVariableBlockEnvelope - set matrix C to be the inverted block diagonal of matrix A

8266:   Collective

8268:   Input Parameters:
8269: + A     - the matrix
8270: - reuse - indicates if the `C` matrix was obtained from a previous call to this routine

8272:   Output Parameter:
8273: . C - matrix with inverted block diagonal of `A`

8275:   Level: advanced

8277:   Note:
8278:   For efficiency the matrix `A` should have all the nonzero entries clustered in smallish blocks along the diagonal.

8280: .seealso: [](ch_matrices), `Mat`, `MatInvertBlockDiagonal()`, `MatComputeBlockDiagonal()`
8281: @*/
8282: PetscErrorCode MatInvertVariableBlockEnvelope(Mat A, MatReuse reuse, Mat *C)
8283: {
8284:   PetscContainer   container;
8285:   EnvelopeData    *edata;
8286:   PetscObjectState nonzerostate;

8288:   PetscFunctionBegin;
8289:   PetscCall(PetscObjectQuery((PetscObject)A, "EnvelopeData", (PetscObject *)&container));
8290:   if (!container) {
8291:     PetscCall(MatComputeVariableBlockEnvelope(A));
8292:     PetscCall(PetscObjectQuery((PetscObject)A, "EnvelopeData", (PetscObject *)&container));
8293:   }
8294:   PetscCall(PetscContainerGetPointer(container, &edata));
8295:   PetscCall(MatGetNonzeroState(A, &nonzerostate));
8296:   PetscCheck(nonzerostate <= edata->nonzerostate, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "Cannot handle changes to matrix nonzero structure");
8297:   PetscCheck(reuse != MAT_REUSE_MATRIX || *C == edata->C, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "C matrix must be the same as previously output");

8299:   PetscCall(MatCreateSubMatrices(A, edata->n, edata->is, edata->is, MAT_INITIAL_MATRIX, &edata->mat));
8300:   *C = edata->C;

8302:   for (PetscInt i = 0; i < edata->n; i++) {
8303:     Mat          D;
8304:     PetscScalar *dvalues;

8306:     PetscCall(MatConvert(edata->mat[i], MATSEQDENSE, MAT_INITIAL_MATRIX, &D));
8307:     PetscCall(MatSetOption(*C, MAT_ROW_ORIENTED, PETSC_FALSE));
8308:     PetscCall(MatSeqDenseInvert(D));
8309:     PetscCall(MatDenseGetArray(D, &dvalues));
8310:     PetscCall(MatSetValuesIS(*C, edata->is[i], edata->is[i], dvalues, INSERT_VALUES));
8311:     PetscCall(MatDestroy(&D));
8312:   }
8313:   PetscCall(MatDestroySubMatrices(edata->n, &edata->mat));
8314:   PetscCall(MatAssemblyBegin(*C, MAT_FINAL_ASSEMBLY));
8315:   PetscCall(MatAssemblyEnd(*C, MAT_FINAL_ASSEMBLY));
8316:   PetscFunctionReturn(PETSC_SUCCESS);
8317: }

8319: /*@
8320:   MatSetVariableBlockSizes - Sets diagonal point-blocks of the matrix that need not be of the same size

8322:   Not Collective

8324:   Input Parameters:
8325: + mat     - the matrix
8326: . nblocks - the number of blocks on this process, each block can only exist on a single process
8327: - bsizes  - the block sizes

8329:   Level: intermediate

8331:   Notes:
8332:   Currently used by `PCVPBJACOBI` for `MATAIJ` matrices

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

8336: .seealso: [](ch_matrices), `Mat`, `MatCreateSeqBAIJ()`, `MatCreateBAIJ()`, `MatGetBlockSize()`, `MatSetBlockSizes()`, `MatGetBlockSizes()`, `MatGetVariableBlockSizes()`,
8337:           `MatComputeVariableBlockEnvelope()`, `PCVPBJACOBI`
8338: @*/
8339: PetscErrorCode MatSetVariableBlockSizes(Mat mat, PetscInt nblocks, const PetscInt bsizes[])
8340: {
8341:   PetscInt ncnt = 0, nlocal;

8343:   PetscFunctionBegin;
8345:   PetscCall(MatGetLocalSize(mat, &nlocal, NULL));
8346:   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);
8347:   for (PetscInt i = 0; i < nblocks; i++) ncnt += bsizes[i];
8348:   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);
8349:   PetscCall(PetscFree(mat->bsizes));
8350:   mat->nblocks = nblocks;
8351:   PetscCall(PetscMalloc1(nblocks, &mat->bsizes));
8352:   PetscCall(PetscArraycpy(mat->bsizes, bsizes, nblocks));
8353:   PetscFunctionReturn(PETSC_SUCCESS);
8354: }

8356: /*@
8357:   MatGetVariableBlockSizes - Gets a diagonal blocks of the matrix that need not be of the same size

8359:   Not Collective; No Fortran Support

8361:   Input Parameter:
8362: . mat - the matrix

8364:   Output Parameters:
8365: + nblocks - the number of blocks on this process
8366: - bsizes  - the block sizes

8368:   Level: intermediate

8370: .seealso: [](ch_matrices), `Mat`, `MatCreateSeqBAIJ()`, `MatCreateBAIJ()`, `MatGetBlockSize()`, `MatSetBlockSizes()`, `MatGetBlockSizes()`, `MatSetVariableBlockSizes()`, `MatComputeVariableBlockEnvelope()`
8371: @*/
8372: PetscErrorCode MatGetVariableBlockSizes(Mat mat, PetscInt *nblocks, const PetscInt *bsizes[])
8373: {
8374:   PetscFunctionBegin;
8376:   if (nblocks) *nblocks = mat->nblocks;
8377:   if (bsizes) *bsizes = mat->bsizes;
8378:   PetscFunctionReturn(PETSC_SUCCESS);
8379: }

8381: /*@
8382:   MatSelectVariableBlockSizes - When creating a submatrix, pass on the variable block sizes

8384:   Not Collective

8386:   Input Parameter:
8387: + subA  - the submatrix
8388: . A     - the original matrix
8389: - isrow - The `IS` of selected rows for the submatrix, must be sorted

8391:   Level: developer

8393:   Notes:
8394:   If the index set is not sorted or contains off-process entries, this function will do nothing.

8396: .seealso: [](ch_matrices), `Mat`, `MatSetVariableBlockSizes()`, `MatComputeVariableBlockEnvelope()`
8397: @*/
8398: PetscErrorCode MatSelectVariableBlockSizes(Mat subA, Mat A, IS isrow)
8399: {
8400:   const PetscInt *rows;
8401:   PetscInt        n, rStart, rEnd, Nb = 0;
8402:   PetscBool       flg = A->bsizes ? PETSC_TRUE : PETSC_FALSE;

8404:   PetscFunctionBegin;
8405:   // The code for block size extraction does not support an unsorted IS
8406:   if (flg) PetscCall(ISSorted(isrow, &flg));
8407:   // We don't support originally off-diagonal blocks
8408:   if (flg) {
8409:     PetscCall(MatGetOwnershipRange(A, &rStart, &rEnd));
8410:     PetscCall(ISGetLocalSize(isrow, &n));
8411:     PetscCall(ISGetIndices(isrow, &rows));
8412:     for (PetscInt i = 0; i < n && flg; ++i) {
8413:       if (rows[i] < rStart || rows[i] >= rEnd) flg = PETSC_FALSE;
8414:     }
8415:     PetscCall(ISRestoreIndices(isrow, &rows));
8416:   }
8417:   // quiet return if we can't extract block size
8418:   PetscCallMPI(MPIU_Allreduce(MPI_IN_PLACE, &flg, 1, MPI_C_BOOL, MPI_LAND, PetscObjectComm((PetscObject)subA)));
8419:   if (!flg) PetscFunctionReturn(PETSC_SUCCESS);

8421:   // extract block sizes
8422:   PetscCall(ISGetIndices(isrow, &rows));
8423:   for (PetscInt b = 0, gr = rStart, i = 0; b < A->nblocks; ++b) {
8424:     PetscBool occupied = PETSC_FALSE;

8426:     for (PetscInt br = 0; br < A->bsizes[b]; ++br) {
8427:       const PetscInt row = gr + br;

8429:       if (i == n) break;
8430:       if (rows[i] == row) {
8431:         occupied = PETSC_TRUE;
8432:         ++i;
8433:       }
8434:       while (i < n && rows[i] < row) ++i;
8435:     }
8436:     gr += A->bsizes[b];
8437:     if (occupied) ++Nb;
8438:   }
8439:   subA->nblocks = Nb;
8440:   PetscCall(PetscFree(subA->bsizes));
8441:   PetscCall(PetscMalloc1(subA->nblocks, &subA->bsizes));
8442:   PetscInt sb = 0;
8443:   for (PetscInt b = 0, gr = rStart, i = 0; b < A->nblocks; ++b) {
8444:     if (sb < subA->nblocks) subA->bsizes[sb] = 0;
8445:     for (PetscInt br = 0; br < A->bsizes[b]; ++br) {
8446:       const PetscInt row = gr + br;

8448:       if (i == n) break;
8449:       if (rows[i] == row) {
8450:         ++subA->bsizes[sb];
8451:         ++i;
8452:       }
8453:       while (i < n && rows[i] < row) ++i;
8454:     }
8455:     gr += A->bsizes[b];
8456:     if (sb < subA->nblocks && subA->bsizes[sb]) ++sb;
8457:   }
8458:   PetscCheck(sb == subA->nblocks, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Invalid number of blocks %" PetscInt_FMT " != %" PetscInt_FMT, sb, subA->nblocks);
8459:   PetscInt nlocal, ncnt = 0;
8460:   PetscCall(MatGetLocalSize(subA, &nlocal, NULL));
8461:   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);
8462:   for (PetscInt i = 0; i < subA->nblocks; i++) ncnt += subA->bsizes[i];
8463:   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);
8464:   PetscCall(ISRestoreIndices(isrow, &rows));
8465:   PetscFunctionReturn(PETSC_SUCCESS);
8466: }

8468: /*@
8469:   MatSetBlockSizes - Sets the matrix block row and column sizes.

8471:   Logically Collective

8473:   Input Parameters:
8474: + mat - the matrix
8475: . rbs - row block size
8476: - cbs - column block size

8478:   Level: intermediate

8480:   Notes:
8481:   Block row formats are `MATBAIJ` and  `MATSBAIJ`. These formats ALWAYS have square block storage in the matrix.
8482:   If you pass a different block size for the columns than the rows, the row block size determines the square block storage.
8483:   This must be called before `MatSetUp()` or MatXXXSetPreallocation() (or will default to 1) and the block size cannot be changed later.

8485:   For `MATAIJ` matrix this function can be called at a later stage, provided that the specified block sizes
8486:   are compatible with the matrix local sizes.

8488:   The row and column block size determine the blocksize of the "row" and "column" vectors returned by `MatCreateVecs()`.

8490: .seealso: [](ch_matrices), `Mat`, `MatCreateSeqBAIJ()`, `MatCreateBAIJ()`, `MatGetBlockSize()`, `MatSetBlockSize()`, `MatGetBlockSizes()`
8491: @*/
8492: PetscErrorCode MatSetBlockSizes(Mat mat, PetscInt rbs, PetscInt cbs)
8493: {
8494:   PetscFunctionBegin;
8498:   PetscTryTypeMethod(mat, setblocksizes, rbs, cbs);
8499:   if (mat->rmap->refcnt) {
8500:     ISLocalToGlobalMapping l2g  = NULL;
8501:     PetscLayout            nmap = NULL;

8503:     PetscCall(PetscLayoutDuplicate(mat->rmap, &nmap));
8504:     if (mat->rmap->mapping) PetscCall(ISLocalToGlobalMappingDuplicate(mat->rmap->mapping, &l2g));
8505:     PetscCall(PetscLayoutDestroy(&mat->rmap));
8506:     mat->rmap          = nmap;
8507:     mat->rmap->mapping = l2g;
8508:   }
8509:   if (mat->cmap->refcnt) {
8510:     ISLocalToGlobalMapping l2g  = NULL;
8511:     PetscLayout            nmap = NULL;

8513:     PetscCall(PetscLayoutDuplicate(mat->cmap, &nmap));
8514:     if (mat->cmap->mapping) PetscCall(ISLocalToGlobalMappingDuplicate(mat->cmap->mapping, &l2g));
8515:     PetscCall(PetscLayoutDestroy(&mat->cmap));
8516:     mat->cmap          = nmap;
8517:     mat->cmap->mapping = l2g;
8518:   }
8519:   PetscCall(PetscLayoutSetBlockSize(mat->rmap, rbs));
8520:   PetscCall(PetscLayoutSetBlockSize(mat->cmap, cbs));
8521:   PetscFunctionReturn(PETSC_SUCCESS);
8522: }

8524: /*@
8525:   MatSetBlockSizesFromMats - Sets the matrix block row and column sizes to match a pair of matrices

8527:   Logically Collective

8529:   Input Parameters:
8530: + mat     - the matrix
8531: . fromRow - matrix from which to copy row block size
8532: - fromCol - matrix from which to copy column block size (can be same as `fromRow`)

8534:   Level: developer

8536: .seealso: [](ch_matrices), `Mat`, `MatCreateSeqBAIJ()`, `MatCreateBAIJ()`, `MatGetBlockSize()`, `MatSetBlockSizes()`
8537: @*/
8538: PetscErrorCode MatSetBlockSizesFromMats(Mat mat, Mat fromRow, Mat fromCol)
8539: {
8540:   PetscFunctionBegin;
8544:   PetscTryTypeMethod(mat, setblocksizes, fromRow->rmap->bs, fromCol->cmap->bs);
8545:   PetscCall(PetscLayoutSetBlockSize(mat->rmap, fromRow->rmap->bs));
8546:   PetscCall(PetscLayoutSetBlockSize(mat->cmap, fromCol->cmap->bs));
8547:   PetscFunctionReturn(PETSC_SUCCESS);
8548: }

8550: /*@
8551:   MatResidual - Default routine to calculate the residual r = b - Ax

8553:   Collective

8555:   Input Parameters:
8556: + mat - the matrix
8557: . b   - the right-hand-side
8558: - x   - the approximate solution

8560:   Output Parameter:
8561: . r - location to store the residual

8563:   Level: developer

8565: .seealso: [](ch_matrices), `Mat`, `MatMult()`, `MatMultAdd()`, `PCMGSetResidual()`
8566: @*/
8567: PetscErrorCode MatResidual(Mat mat, Vec b, Vec x, Vec r)
8568: {
8569:   PetscFunctionBegin;
8575:   MatCheckPreallocated(mat, 1);
8576:   PetscCall(PetscLogEventBegin(MAT_Residual, mat, 0, 0, 0));
8577:   if (!mat->ops->residual) {
8578:     PetscCall(MatMult(mat, x, r));
8579:     PetscCall(VecAYPX(r, -1.0, b));
8580:   } else {
8581:     PetscUseTypeMethod(mat, residual, b, x, r);
8582:   }
8583:   PetscCall(PetscLogEventEnd(MAT_Residual, mat, 0, 0, 0));
8584:   PetscFunctionReturn(PETSC_SUCCESS);
8585: }

8587: /*@
8588:   MatGetRowIJ - Returns the compressed row storage i and j indices for the local rows of a sparse matrix

8590:   Collective

8592:   Input Parameters:
8593: + mat             - the matrix
8594: . shift           - 0 or 1 indicating we want the indices starting at 0 or 1
8595: . symmetric       - `PETSC_TRUE` or `PETSC_FALSE` indicating the matrix data structure should be symmetrized
8596: - inodecompressed - `PETSC_TRUE` or `PETSC_FALSE`  indicating if the nonzero structure of the
8597:                  inodes or the nonzero elements is wanted. For `MATBAIJ` matrices the compressed version is
8598:                  always used.

8600:   Output Parameters:
8601: + n    - number of local rows in the (possibly compressed) matrix, use `NULL` if not needed
8602: . 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
8603: . ja   - the column indices, use `NULL` if not needed
8604: - done - indicates if the routine actually worked and returned appropriate ia[] and ja[] arrays; callers
8605:            are responsible for handling the case when done == `PETSC_FALSE` and ia and ja are not set

8607:   Level: developer

8609:   Notes:
8610:   You CANNOT change any of the ia[] or ja[] values.

8612:   Use `MatRestoreRowIJ()` when you are finished accessing the ia[] and ja[] values.

8614:   Fortran Notes:
8615:   Use
8616: .vb
8617:     PetscInt, pointer :: ia(:),ja(:)
8618:     call MatGetRowIJ(mat,shift,symmetric,inodecompressed,n,ia,ja,done,ierr)
8619:     ! Access the ith and jth entries via ia(i) and ja(j)
8620: .ve

8622: .seealso: [](ch_matrices), `Mat`, `MATAIJ`, `MatGetColumnIJ()`, `MatRestoreRowIJ()`, `MatSeqAIJGetArray()`
8623: @*/
8624: PetscErrorCode MatGetRowIJ(Mat mat, PetscInt shift, PetscBool symmetric, PetscBool inodecompressed, PetscInt *n, const PetscInt *ia[], const PetscInt *ja[], PetscBool *done)
8625: {
8626:   PetscFunctionBegin;
8629:   if (n) PetscAssertPointer(n, 5);
8630:   if (ia) PetscAssertPointer(ia, 6);
8631:   if (ja) PetscAssertPointer(ja, 7);
8632:   if (done) PetscAssertPointer(done, 8);
8633:   MatCheckPreallocated(mat, 1);
8634:   if (!mat->ops->getrowij && done) *done = PETSC_FALSE;
8635:   else {
8636:     if (done) *done = PETSC_TRUE;
8637:     PetscCall(PetscLogEventBegin(MAT_GetRowIJ, mat, 0, 0, 0));
8638:     PetscUseTypeMethod(mat, getrowij, shift, symmetric, inodecompressed, n, ia, ja, done);
8639:     PetscCall(PetscLogEventEnd(MAT_GetRowIJ, mat, 0, 0, 0));
8640:   }
8641:   PetscFunctionReturn(PETSC_SUCCESS);
8642: }

8644: /*@
8645:   MatGetColumnIJ - Returns the compressed column storage i and j indices for sequential matrices.

8647:   Collective

8649:   Input Parameters:
8650: + mat             - the matrix
8651: . shift           - 1 or zero indicating we want the indices starting at 0 or 1
8652: . symmetric       - `PETSC_TRUE` or `PETSC_FALSE` indicating the matrix data structure should be
8653:                 symmetrized
8654: - inodecompressed - `PETSC_TRUE` or `PETSC_FALSE` indicating if the nonzero structure of the
8655:                  inodes or the nonzero elements is wanted. For `MATBAIJ` matrices the compressed version is
8656:                  always used.

8658:   Output Parameters:
8659: + n    - number of columns in the (possibly compressed) matrix
8660: . ia   - the column pointers; that is ia[0] = 0, ia[col] = i[col-1] + number of elements in that col of the matrix
8661: . ja   - the row indices
8662: - done - `PETSC_TRUE` or `PETSC_FALSE`, indicating whether the values have been returned

8664:   Level: developer

8666: .seealso: [](ch_matrices), `Mat`, `MatGetRowIJ()`, `MatRestoreColumnIJ()`
8667: @*/
8668: PetscErrorCode MatGetColumnIJ(Mat mat, PetscInt shift, PetscBool symmetric, PetscBool inodecompressed, PetscInt *n, const PetscInt *ia[], const PetscInt *ja[], PetscBool *done)
8669: {
8670:   PetscFunctionBegin;
8673:   PetscAssertPointer(n, 5);
8674:   if (ia) PetscAssertPointer(ia, 6);
8675:   if (ja) PetscAssertPointer(ja, 7);
8676:   PetscAssertPointer(done, 8);
8677:   MatCheckPreallocated(mat, 1);
8678:   if (!mat->ops->getcolumnij) *done = PETSC_FALSE;
8679:   else {
8680:     *done = PETSC_TRUE;
8681:     PetscUseTypeMethod(mat, getcolumnij, shift, symmetric, inodecompressed, n, ia, ja, done);
8682:   }
8683:   PetscFunctionReturn(PETSC_SUCCESS);
8684: }

8686: /*@
8687:   MatRestoreRowIJ - Call after you are completed with the ia,ja indices obtained with `MatGetRowIJ()`.

8689:   Collective

8691:   Input Parameters:
8692: + mat             - the matrix
8693: . shift           - 1 or zero indicating we want the indices starting at 0 or 1
8694: . symmetric       - `PETSC_TRUE` or `PETSC_FALSE` indicating the matrix data structure should be symmetrized
8695: . inodecompressed - `PETSC_TRUE` or `PETSC_FALSE` indicating if the nonzero structure of the
8696:                     inodes or the nonzero elements is wanted. For `MATBAIJ` matrices the compressed version is
8697:                     always used.
8698: . n               - size of (possibly compressed) matrix
8699: . ia              - the row pointers
8700: - ja              - the column indices

8702:   Output Parameter:
8703: . done - `PETSC_TRUE` or `PETSC_FALSE` indicated that the values have been returned

8705:   Level: developer

8707:   Note:
8708:   This routine zeros out `n`, `ia`, and `ja`. This is to prevent accidental
8709:   us of the array after it has been restored. If you pass `NULL`, it will
8710:   not zero the pointers. Use of ia or ja after `MatRestoreRowIJ()` is invalid.

8712: .seealso: [](ch_matrices), `Mat`, `MatGetRowIJ()`, `MatRestoreColumnIJ()`
8713: @*/
8714: PetscErrorCode MatRestoreRowIJ(Mat mat, PetscInt shift, PetscBool symmetric, PetscBool inodecompressed, PetscInt *n, const PetscInt *ia[], const PetscInt *ja[], PetscBool *done)
8715: {
8716:   PetscFunctionBegin;
8719:   if (ia) PetscAssertPointer(ia, 6);
8720:   if (ja) PetscAssertPointer(ja, 7);
8721:   if (done) PetscAssertPointer(done, 8);
8722:   MatCheckPreallocated(mat, 1);

8724:   if (!mat->ops->restorerowij && done) *done = PETSC_FALSE;
8725:   else {
8726:     if (done) *done = PETSC_TRUE;
8727:     PetscUseTypeMethod(mat, restorerowij, shift, symmetric, inodecompressed, n, ia, ja, done);
8728:     if (n) *n = 0;
8729:     if (ia) *ia = NULL;
8730:     if (ja) *ja = NULL;
8731:   }
8732:   PetscFunctionReturn(PETSC_SUCCESS);
8733: }

8735: /*@
8736:   MatRestoreColumnIJ - Call after you are completed with the ia,ja indices obtained with `MatGetColumnIJ()`.

8738:   Collective

8740:   Input Parameters:
8741: + mat             - the matrix
8742: . shift           - 1 or zero indicating we want the indices starting at 0 or 1
8743: . symmetric       - `PETSC_TRUE` or `PETSC_FALSE` indicating the matrix data structure should be symmetrized
8744: - inodecompressed - `PETSC_TRUE` or `PETSC_FALSE` indicating if the nonzero structure of the
8745:                     inodes or the nonzero elements is wanted. For `MATBAIJ` matrices the compressed version is
8746:                     always used.

8748:   Output Parameters:
8749: + n    - size of (possibly compressed) matrix
8750: . ia   - the column pointers
8751: . ja   - the row indices
8752: - done - `PETSC_TRUE` or `PETSC_FALSE` indicated that the values have been returned

8754:   Level: developer

8756: .seealso: [](ch_matrices), `Mat`, `MatGetColumnIJ()`, `MatRestoreRowIJ()`
8757: @*/
8758: PetscErrorCode MatRestoreColumnIJ(Mat mat, PetscInt shift, PetscBool symmetric, PetscBool inodecompressed, PetscInt *n, const PetscInt *ia[], const PetscInt *ja[], PetscBool *done)
8759: {
8760:   PetscFunctionBegin;
8763:   if (ia) PetscAssertPointer(ia, 6);
8764:   if (ja) PetscAssertPointer(ja, 7);
8765:   PetscAssertPointer(done, 8);
8766:   MatCheckPreallocated(mat, 1);

8768:   if (!mat->ops->restorecolumnij) *done = PETSC_FALSE;
8769:   else {
8770:     *done = PETSC_TRUE;
8771:     PetscUseTypeMethod(mat, restorecolumnij, shift, symmetric, inodecompressed, n, ia, ja, done);
8772:     if (n) *n = 0;
8773:     if (ia) *ia = NULL;
8774:     if (ja) *ja = NULL;
8775:   }
8776:   PetscFunctionReturn(PETSC_SUCCESS);
8777: }

8779: /*@
8780:   MatColoringPatch - Used inside matrix coloring routines that use `MatGetRowIJ()` and/or
8781:   `MatGetColumnIJ()`.

8783:   Collective

8785:   Input Parameters:
8786: + mat        - the matrix
8787: . ncolors    - maximum color value
8788: . n          - number of entries in colorarray
8789: - colorarray - array indicating color for each column

8791:   Output Parameter:
8792: . iscoloring - coloring generated using colorarray information

8794:   Level: developer

8796: .seealso: [](ch_matrices), `Mat`, `MatGetRowIJ()`, `MatGetColumnIJ()`
8797: @*/
8798: PetscErrorCode MatColoringPatch(Mat mat, PetscInt ncolors, PetscInt n, ISColoringValue colorarray[], ISColoring *iscoloring)
8799: {
8800:   PetscFunctionBegin;
8803:   PetscAssertPointer(colorarray, 4);
8804:   PetscAssertPointer(iscoloring, 5);
8805:   MatCheckPreallocated(mat, 1);

8807:   if (!mat->ops->coloringpatch) {
8808:     PetscCall(ISColoringCreate(PetscObjectComm((PetscObject)mat), ncolors, n, colorarray, PETSC_OWN_POINTER, iscoloring));
8809:   } else {
8810:     PetscUseTypeMethod(mat, coloringpatch, ncolors, n, colorarray, iscoloring);
8811:   }
8812:   PetscFunctionReturn(PETSC_SUCCESS);
8813: }

8815: /*@
8816:   MatSetUnfactored - Resets a factored matrix to be treated as unfactored.

8818:   Logically Collective

8820:   Input Parameter:
8821: . mat - the factored matrix to be reset

8823:   Level: developer

8825:   Notes:
8826:   This routine should be used only with factored matrices formed by in-place
8827:   factorization via ILU(0) (or by in-place LU factorization for the `MATSEQDENSE`
8828:   format). This option can save memory, for example, when solving nonlinear
8829:   systems with a matrix-free Newton-Krylov method and a matrix-based, in-place
8830:   ILU(0) preconditioner.

8832:   One can specify in-place ILU(0) factorization by calling
8833: .vb
8834:      PCType(pc,PCILU);
8835:      PCFactorSeUseInPlace(pc);
8836: .ve
8837:   or by using the options -pc_type ilu -pc_factor_in_place

8839:   In-place factorization ILU(0) can also be used as a local
8840:   solver for the blocks within the block Jacobi or additive Schwarz
8841:   methods (runtime option: -sub_pc_factor_in_place). See Users-Manual: ch_pc
8842:   for details on setting local solver options.

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

8848: .seealso: [](ch_matrices), `Mat`, `PCFactorSetUseInPlace()`, `PCFactorGetUseInPlace()`
8849: @*/
8850: PetscErrorCode MatSetUnfactored(Mat mat)
8851: {
8852:   PetscFunctionBegin;
8855:   MatCheckPreallocated(mat, 1);
8856:   mat->factortype = MAT_FACTOR_NONE;
8857:   if (!mat->ops->setunfactored) PetscFunctionReturn(PETSC_SUCCESS);
8858:   PetscUseTypeMethod(mat, setunfactored);
8859:   PetscFunctionReturn(PETSC_SUCCESS);
8860: }

8862: /*@
8863:   MatCreateSubMatrix - Gets a single submatrix on the same number of processes
8864:   as the original matrix.

8866:   Collective

8868:   Input Parameters:
8869: + mat   - the original matrix
8870: . isrow - parallel `IS` containing the rows this process should obtain
8871: . 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.
8872: - cll   - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`

8874:   Output Parameter:
8875: . newmat - the new submatrix, of the same type as the original matrix (except potentially for `MATSEQSBAIJ`)

8877:   Level: advanced

8879:   Notes:
8880:   The submatrix will be able to be multiplied with vectors using the same layout as `iscol`.

8882:   Some matrix types place restrictions on the row and column indices, such
8883:   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;
8884:   for example, if the block size is 3 one cannot select the 0 and 2 rows without selecting the 1 row.
8885:   `MATSEQSBAIJ` inputs may produce a `MATSEQBAIJ` matrix when the row and column index sets do not preserve symmetry.

8887:   The index sets may not have duplicate entries.

8889:   The first time this is called you should use a `cll` of `MAT_INITIAL_MATRIX`,
8890:   the `MatCreateSubMatrix()` routine will create the newmat for you. Any additional calls
8891:   to this routine with a mat of the same nonzero structure and with a call of `MAT_REUSE_MATRIX`
8892:   will reuse the matrix generated the first time. You should call `MatDestroy()` on `newmat` when
8893:   you are finished using it.

8895:   The communicator of the newly obtained matrix is ALWAYS the same as the communicator of
8896:   the input matrix.

8898:   If `iscol` is `NULL` then all columns are obtained (not supported in Fortran).

8900:   If `isrow` and `iscol` have a nontrivial block-size, then the resulting matrix has this block-size as well. This feature
8901:   is used by `PCFIELDSPLIT` to allow easy nesting of its use.

8903:   Example usage:
8904:   Consider the following 8x8 matrix with 34 non-zero values, that is
8905:   assembled across 3 processes. Let's assume that proc0 owns 3 rows,
8906:   proc1 owns 3 rows, proc2 owns 2 rows. This division can be shown
8907:   as follows
8908: .vb
8909:             1  2  0  |  0  3  0  |  0  4
8910:     Proc0   0  5  6  |  7  0  0  |  8  0
8911:             9  0 10  | 11  0  0  | 12  0
8912:     -------------------------------------
8913:            13  0 14  | 15 16 17  |  0  0
8914:     Proc1   0 18  0  | 19 20 21  |  0  0
8915:             0  0  0  | 22 23  0  | 24  0
8916:     -------------------------------------
8917:     Proc2  25 26 27  |  0  0 28  | 29  0
8918:            30  0  0  | 31 32 33  |  0 34
8919: .ve

8921:   Suppose `isrow` = [0 1 | 4 | 6 7] and `iscol` = [1 2 | 3 4 5 | 6]. The resulting submatrix is

8923: .vb
8924:             2  0  |  0  3  0  |  0
8925:     Proc0   5  6  |  7  0  0  |  8
8926:     -------------------------------
8927:     Proc1  18  0  | 19 20 21  |  0
8928:     -------------------------------
8929:     Proc2  26 27  |  0  0 28  | 29
8930:             0  0  | 31 32 33  |  0
8931: .ve

8933: .seealso: [](ch_matrices), `Mat`, `MatCreateSubMatrices()`, `MatCreateSubMatricesMPI()`, `MatCreateSubMatrixVirtual()`, `MatSubMatrixVirtualUpdate()`
8934: @*/
8935: PetscErrorCode MatCreateSubMatrix(Mat mat, IS isrow, IS iscol, MatReuse cll, Mat *newmat)
8936: {
8937:   PetscMPIInt size;
8938:   Mat        *local;
8939:   IS          iscoltmp;
8940:   PetscBool   flg;

8942:   PetscFunctionBegin;
8946:   PetscAssertPointer(newmat, 5);
8949:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
8950:   PetscCheck(cll != MAT_IGNORE_MATRIX, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Cannot use MAT_IGNORE_MATRIX");
8951:   PetscCheck(cll != MAT_INPLACE_MATRIX, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Cannot use MAT_INPLACE_MATRIX");

8953:   MatCheckPreallocated(mat, 1);
8954:   PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)mat), &size));

8956:   if (!iscol || isrow == iscol) {
8957:     PetscBool   stride;
8958:     PetscMPIInt grab = 0;
8959:     PetscCall(PetscObjectTypeCompare((PetscObject)isrow, ISSTRIDE, &stride));
8960:     if (stride) {
8961:       PetscInt first, step, n, rstart, rend;
8962:       PetscCall(ISStrideGetInfo(isrow, &first, &step));
8963:       if (step == 1) {
8964:         PetscCall(MatGetOwnershipRange(mat, &rstart, &rend));
8965:         if (rstart == first) {
8966:           PetscCall(ISGetLocalSize(isrow, &n));
8967:           if (n == rend - rstart) grab = 1;
8968:         }
8969:       }
8970:     }
8971:     PetscCallMPI(MPIU_Allreduce(MPI_IN_PLACE, &grab, 1, MPI_INT, MPI_MIN, PetscObjectComm((PetscObject)mat)));
8972:     if (grab) {
8973:       PetscCall(PetscInfo(mat, "Getting entire matrix as submatrix\n"));
8974:       if (cll == MAT_INITIAL_MATRIX) {
8975:         *newmat = mat;
8976:         PetscCall(PetscObjectReference((PetscObject)mat));
8977:       }
8978:       PetscFunctionReturn(PETSC_SUCCESS);
8979:     }
8980:   }

8982:   if (!iscol) {
8983:     PetscCall(ISCreateStride(PetscObjectComm((PetscObject)mat), mat->cmap->n, mat->cmap->rstart, 1, &iscoltmp));
8984:   } else {
8985:     iscoltmp = iscol;
8986:   }

8988:   /* if original matrix is on just one process then use submatrix generated */
8989:   if (mat->ops->createsubmatrices && !mat->ops->createsubmatrix && size == 1 && cll == MAT_REUSE_MATRIX) {
8990:     PetscCall(MatCreateSubMatrices(mat, 1, &isrow, &iscoltmp, MAT_REUSE_MATRIX, &newmat));
8991:     goto setproperties;
8992:   } else if (mat->ops->createsubmatrices && !mat->ops->createsubmatrix && size == 1) {
8993:     PetscCall(MatCreateSubMatrices(mat, 1, &isrow, &iscoltmp, MAT_INITIAL_MATRIX, &local));
8994:     *newmat = *local;
8995:     PetscCall(PetscFree(local));
8996:     goto setproperties;
8997:   } else if (!mat->ops->createsubmatrix) {
8998:     /* Create a new matrix type that implements the operation using the full matrix */
8999:     PetscCall(PetscLogEventBegin(MAT_CreateSubMat, mat, 0, 0, 0));
9000:     switch (cll) {
9001:     case MAT_INITIAL_MATRIX:
9002:       PetscCall(MatCreateSubMatrixVirtual(mat, isrow, iscoltmp, newmat));
9003:       break;
9004:     case MAT_REUSE_MATRIX:
9005:       PetscCall(MatSubMatrixVirtualUpdate(*newmat, mat, isrow, iscoltmp));
9006:       break;
9007:     default:
9008:       SETERRQ(PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_OUTOFRANGE, "Invalid MatReuse, must be either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX");
9009:     }
9010:     PetscCall(PetscLogEventEnd(MAT_CreateSubMat, mat, 0, 0, 0));
9011:     goto setproperties;
9012:   }

9014:   PetscCall(PetscLogEventBegin(MAT_CreateSubMat, mat, 0, 0, 0));
9015:   PetscUseTypeMethod(mat, createsubmatrix, isrow, iscoltmp, cll, newmat);
9016:   PetscCall(PetscLogEventEnd(MAT_CreateSubMat, mat, 0, 0, 0));

9018: setproperties:
9019:   if ((*newmat)->symmetric == PETSC_BOOL3_UNKNOWN && (*newmat)->structurally_symmetric == PETSC_BOOL3_UNKNOWN && (*newmat)->spd == PETSC_BOOL3_UNKNOWN && (*newmat)->hermitian == PETSC_BOOL3_UNKNOWN) {
9020:     PetscCall(ISEqualUnsorted(isrow, iscoltmp, &flg));
9021:     if (flg) PetscCall(MatPropagateSymmetryOptions(mat, *newmat));
9022:   }
9023:   if (!iscol) PetscCall(ISDestroy(&iscoltmp));
9024:   if (*newmat && cll == MAT_INITIAL_MATRIX) PetscCall(PetscObjectStateIncrease((PetscObject)*newmat));
9025:   if (!iscol || isrow == iscol) PetscCall(MatSelectVariableBlockSizes(*newmat, mat, isrow));
9026:   PetscFunctionReturn(PETSC_SUCCESS);
9027: }

9029: /*@
9030:   MatPropagateSymmetryOptions - Propagates symmetry options set on a matrix to another matrix

9032:   Not Collective

9034:   Input Parameters:
9035: + A - the matrix we wish to propagate options from
9036: - B - the matrix we wish to propagate options to

9038:   Level: beginner

9040:   Note:
9041:   Propagates the options associated to `MAT_SYMMETRY_ETERNAL`, `MAT_STRUCTURALLY_SYMMETRIC`, `MAT_HERMITIAN`, `MAT_SPD`, `MAT_SYMMETRIC`, and `MAT_STRUCTURAL_SYMMETRY_ETERNAL`

9043: .seealso: [](ch_matrices), `Mat`, `MatSetOption()`, `MatIsSymmetricKnown()`, `MatIsSPDKnown()`, `MatIsHermitianKnown()`, `MatIsStructurallySymmetricKnown()`
9044: @*/
9045: PetscErrorCode MatPropagateSymmetryOptions(Mat A, Mat B)
9046: {
9047:   PetscFunctionBegin;
9050:   B->symmetry_eternal            = A->symmetry_eternal;
9051:   B->structural_symmetry_eternal = A->structural_symmetry_eternal;
9052:   B->symmetric                   = A->symmetric;
9053:   B->structurally_symmetric      = A->structurally_symmetric;
9054:   B->spd                         = A->spd;
9055:   B->hermitian                   = A->hermitian;
9056:   PetscFunctionReturn(PETSC_SUCCESS);
9057: }

9059: /*@
9060:   MatStashSetInitialSize - sets the sizes of the matrix stash, that is
9061:   used during the assembly process to store values that belong to
9062:   other processes.

9064:   Not Collective

9066:   Input Parameters:
9067: + mat   - the matrix
9068: . size  - the initial size of the stash.
9069: - bsize - the initial size of the block-stash(if used).

9071:   Options Database Keys:
9072: + -matstash_initial_size size or size0,size1,...,sizep-1            - set initial size
9073: - -matstash_block_initial_size bsize  or bsize0,bsize1,...,bsizep-1 - set initial block size

9075:   Level: intermediate

9077:   Notes:
9078:   The block-stash is used for values set with `MatSetValuesBlocked()` while
9079:   the stash is used for values set with `MatSetValues()`

9081:   Run with the option -info and look for output of the form
9082:   MatAssemblyBegin_MPIXXX:Stash has MM entries, uses nn mallocs.
9083:   to determine the appropriate value, MM, to use for size and
9084:   MatAssemblyBegin_MPIXXX:Block-Stash has BMM entries, uses nn mallocs.
9085:   to determine the value, BMM to use for bsize

9087: .seealso: [](ch_matrices), `MatAssemblyBegin()`, `MatAssemblyEnd()`, `Mat`, `MatStashGetInfo()`
9088: @*/
9089: PetscErrorCode MatStashSetInitialSize(Mat mat, PetscInt size, PetscInt bsize)
9090: {
9091:   PetscFunctionBegin;
9094:   PetscCall(MatStashSetInitialSize_Private(&mat->stash, size));
9095:   PetscCall(MatStashSetInitialSize_Private(&mat->bstash, bsize));
9096:   PetscFunctionReturn(PETSC_SUCCESS);
9097: }

9099: /*@
9100:   MatInterpolateAdd - $w = y + A*x$ or $A^T*x$ depending on the shape of
9101:   the matrix

9103:   Neighbor-wise Collective

9105:   Input Parameters:
9106: + A - the matrix
9107: . x - the vector to be multiplied by the interpolation operator
9108: - y - the vector to be added to the result

9110:   Output Parameter:
9111: . w - the resulting vector

9113:   Level: intermediate

9115:   Notes:
9116:   `w` may be the same vector as `y`.

9118:   This allows one to use either the restriction or interpolation (its transpose)
9119:   matrix to do the interpolation

9121: .seealso: [](ch_matrices), `Mat`, `MatMultAdd()`, `MatMultTransposeAdd()`, `MatRestrict()`, `PCMG`
9122: @*/
9123: PetscErrorCode MatInterpolateAdd(Mat A, Vec x, Vec y, Vec w)
9124: {
9125:   PetscInt M, N, Ny;

9127:   PetscFunctionBegin;
9132:   PetscCall(MatGetSize(A, &M, &N));
9133:   PetscCall(VecGetSize(y, &Ny));
9134:   if (M == Ny) PetscCall(MatMultAdd(A, x, y, w));
9135:   else PetscCall(MatMultTransposeAdd(A, x, y, w));
9136:   PetscFunctionReturn(PETSC_SUCCESS);
9137: }

9139: /*@
9140:   MatInterpolate - $y = A*x$ or $A^T*x$ depending on the shape of
9141:   the matrix

9143:   Neighbor-wise Collective

9145:   Input Parameters:
9146: + A - the matrix
9147: - x - the vector to be interpolated

9149:   Output Parameter:
9150: . y - the resulting vector

9152:   Level: intermediate

9154:   Note:
9155:   This allows one to use either the restriction or interpolation (its transpose)
9156:   matrix to do the interpolation

9158: .seealso: [](ch_matrices), `Mat`, `MatMultAdd()`, `MatMultTransposeAdd()`, `MatRestrict()`, `PCMG`
9159: @*/
9160: PetscErrorCode MatInterpolate(Mat A, Vec x, Vec y)
9161: {
9162:   PetscInt M, N, Ny;

9164:   PetscFunctionBegin;
9168:   PetscCall(MatGetSize(A, &M, &N));
9169:   PetscCall(VecGetSize(y, &Ny));
9170:   if (M == Ny) PetscCall(MatMult(A, x, y));
9171:   else PetscCall(MatMultTranspose(A, x, y));
9172:   PetscFunctionReturn(PETSC_SUCCESS);
9173: }

9175: /*@
9176:   MatRestrict - $y = A*x$ or $A^T*x$

9178:   Neighbor-wise Collective

9180:   Input Parameters:
9181: + A - the matrix
9182: - x - the vector to be restricted

9184:   Output Parameter:
9185: . y - the resulting vector

9187:   Level: intermediate

9189:   Note:
9190:   This allows one to use either the restriction or interpolation (its transpose)
9191:   matrix to do the restriction

9193: .seealso: [](ch_matrices), `Mat`, `MatMultAdd()`, `MatMultTransposeAdd()`, `MatInterpolate()`, `PCMG`
9194: @*/
9195: PetscErrorCode MatRestrict(Mat A, Vec x, Vec y)
9196: {
9197:   PetscInt M, N, Nx;

9199:   PetscFunctionBegin;
9203:   PetscCall(MatGetSize(A, &M, &N));
9204:   PetscCall(VecGetSize(x, &Nx));
9205:   if (M == Nx) PetscCall(MatMultTranspose(A, x, y));
9206:   else PetscCall(MatMult(A, x, y));
9207:   PetscFunctionReturn(PETSC_SUCCESS);
9208: }

9210: /*@
9211:   MatMatInterpolateAdd - $Y = W + A*X$ or $W + A^T*X$ depending on the shape of `A`

9213:   Neighbor-wise Collective

9215:   Input Parameters:
9216: + A - the matrix
9217: . x - the input dense matrix to be multiplied
9218: - w - the input dense matrix to be added to the result

9220:   Output Parameter:
9221: . y - the output dense matrix

9223:   Level: intermediate

9225:   Note:
9226:   This allows one to use either the restriction or interpolation (its transpose)
9227:   matrix to do the interpolation. `y` matrix can be reused if already created with the proper sizes,
9228:   otherwise it will be recreated. `y` must be initialized to `NULL` if not supplied.

9230: .seealso: [](ch_matrices), `Mat`, `MatInterpolateAdd()`, `MatMatInterpolate()`, `MatMatRestrict()`, `PCMG`
9231: @*/
9232: PetscErrorCode MatMatInterpolateAdd(Mat A, Mat x, Mat w, Mat *y)
9233: {
9234:   PetscInt  M, N, Mx, Nx, Mo, My = 0, Ny = 0;
9235:   PetscBool trans = PETSC_TRUE;
9236:   MatReuse  reuse = MAT_INITIAL_MATRIX;

9238:   PetscFunctionBegin;
9244:   PetscCall(MatGetSize(A, &M, &N));
9245:   PetscCall(MatGetSize(x, &Mx, &Nx));
9246:   if (N == Mx) trans = PETSC_FALSE;
9247:   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);
9248:   Mo = trans ? N : M;
9249:   if (*y) {
9250:     PetscCall(MatGetSize(*y, &My, &Ny));
9251:     if (Mo == My && Nx == Ny) reuse = MAT_REUSE_MATRIX;
9252:     else {
9253:       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);
9254:       PetscCall(MatDestroy(y));
9255:     }
9256:   }

9258:   if (w && *y == w) { /* this is to minimize changes in PCMG */
9259:     PetscBool flg;

9261:     PetscCall(PetscObjectQuery((PetscObject)*y, "__MatMatIntAdd_w", (PetscObject *)&w));
9262:     if (w) {
9263:       PetscInt My, Ny, Mw, Nw;

9265:       PetscCall(PetscObjectTypeCompare((PetscObject)*y, ((PetscObject)w)->type_name, &flg));
9266:       PetscCall(MatGetSize(*y, &My, &Ny));
9267:       PetscCall(MatGetSize(w, &Mw, &Nw));
9268:       if (!flg || My != Mw || Ny != Nw) w = NULL;
9269:     }
9270:     if (!w) {
9271:       PetscCall(MatDuplicate(*y, MAT_COPY_VALUES, &w));
9272:       PetscCall(PetscObjectCompose((PetscObject)*y, "__MatMatIntAdd_w", (PetscObject)w));
9273:       PetscCall(PetscObjectDereference((PetscObject)w));
9274:     } else PetscCall(MatCopy(*y, w, UNKNOWN_NONZERO_PATTERN));
9275:   }
9276:   if (!trans) PetscCall(MatMatMult(A, x, reuse, PETSC_DETERMINE, y));
9277:   else PetscCall(MatTransposeMatMult(A, x, reuse, PETSC_DETERMINE, y));
9278:   if (w) PetscCall(MatAXPY(*y, 1.0, w, UNKNOWN_NONZERO_PATTERN));
9279:   PetscFunctionReturn(PETSC_SUCCESS);
9280: }

9282: /*@
9283:   MatMatInterpolate - $Y = A*X$ or $A^T*X$ depending on the shape of `A`

9285:   Neighbor-wise Collective

9287:   Input Parameters:
9288: + A - the matrix
9289: - x - the input dense matrix

9291:   Output Parameter:
9292: . y - the output dense matrix

9294:   Level: intermediate

9296:   Note:
9297:   This allows one to use either the restriction or interpolation (its transpose)
9298:   matrix to do the interpolation. `y` matrix can be reused if already created with the proper sizes,
9299:   otherwise it will be recreated. `y` must be initialized to `NULL` if not supplied.

9301: .seealso: [](ch_matrices), `Mat`, `MatInterpolate()`, `MatRestrict()`, `MatMatRestrict()`, `PCMG`
9302: @*/
9303: PetscErrorCode MatMatInterpolate(Mat A, Mat x, Mat *y)
9304: {
9305:   PetscFunctionBegin;
9306:   PetscCall(MatMatInterpolateAdd(A, x, NULL, y));
9307:   PetscFunctionReturn(PETSC_SUCCESS);
9308: }

9310: /*@
9311:   MatMatRestrict - $Y = A*X$ or $A^T*X$ depending on the shape of `A`

9313:   Neighbor-wise Collective

9315:   Input Parameters:
9316: + A - the matrix
9317: - x - the input dense matrix

9319:   Output Parameter:
9320: . y - the output dense matrix

9322:   Level: intermediate

9324:   Note:
9325:   This allows one to use either the restriction or interpolation (its transpose)
9326:   matrix to do the restriction. `y` matrix can be reused if already created with the proper sizes,
9327:   otherwise it will be recreated. `y` must be initialized to `NULL` if not supplied.

9329: .seealso: [](ch_matrices), `Mat`, `MatRestrict()`, `MatInterpolate()`, `MatMatInterpolate()`, `PCMG`
9330: @*/
9331: PetscErrorCode MatMatRestrict(Mat A, Mat x, Mat *y)
9332: {
9333:   PetscFunctionBegin;
9334:   PetscCall(MatMatInterpolateAdd(A, x, NULL, y));
9335:   PetscFunctionReturn(PETSC_SUCCESS);
9336: }

9338: /*@
9339:   MatGetNullSpace - retrieves the null space of a matrix.

9341:   Logically Collective

9343:   Input Parameters:
9344: + mat    - the matrix
9345: - nullsp - the null space object

9347:   Level: developer

9349: .seealso: [](ch_matrices), `Mat`, `MatCreate()`, `MatNullSpaceCreate()`, `MatSetNearNullSpace()`, `MatSetNullSpace()`, `MatNullSpace`
9350: @*/
9351: PetscErrorCode MatGetNullSpace(Mat mat, MatNullSpace *nullsp)
9352: {
9353:   PetscFunctionBegin;
9355:   PetscAssertPointer(nullsp, 2);
9356:   *nullsp = (mat->symmetric == PETSC_BOOL3_TRUE && !mat->nullsp) ? mat->transnullsp : mat->nullsp;
9357:   PetscFunctionReturn(PETSC_SUCCESS);
9358: }

9360: /*@
9361:   MatGetNullSpaces - gets the null spaces, transpose null spaces, and near null spaces from an array of matrices

9363:   Logically Collective

9365:   Input Parameters:
9366: + n   - the number of matrices
9367: - mat - the array of matrices

9369:   Output Parameters:
9370: . nullsp - an array of null spaces, `NULL` for each matrix that does not have a null space, length 3 * `n`

9372:   Level: developer

9374:   Note:
9375:   Call `MatRestoreNullspaces()` to provide these to another array of matrices

9377: .seealso: [](ch_matrices), `Mat`, `MatCreate()`, `MatNullSpaceCreate()`, `MatSetNearNullSpace()`, `MatGetNullSpace()`, `MatSetTransposeNullSpace()`, `MatGetTransposeNullSpace()`,
9378:           `MatNullSpaceRemove()`, `MatRestoreNullSpaces()`
9379: @*/
9380: PetscErrorCode MatGetNullSpaces(PetscInt n, Mat mat[], MatNullSpace *nullsp[])
9381: {
9382:   PetscFunctionBegin;
9383:   PetscCheck(n >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Number of matrices %" PetscInt_FMT " must be non-negative", n);
9384:   PetscAssertPointer(mat, 2);
9385:   PetscAssertPointer(nullsp, 3);

9387:   PetscCall(PetscCalloc1(3 * n, nullsp));
9388:   for (PetscInt i = 0; i < n; i++) {
9390:     (*nullsp)[i] = mat[i]->nullsp;
9391:     PetscCall(PetscObjectReference((PetscObject)(*nullsp)[i]));
9392:     (*nullsp)[n + i] = mat[i]->nearnullsp;
9393:     PetscCall(PetscObjectReference((PetscObject)(*nullsp)[n + i]));
9394:     (*nullsp)[2 * n + i] = mat[i]->transnullsp;
9395:     PetscCall(PetscObjectReference((PetscObject)(*nullsp)[2 * n + i]));
9396:   }
9397:   PetscFunctionReturn(PETSC_SUCCESS);
9398: }

9400: /*@
9401:   MatRestoreNullSpaces - sets the null spaces, transpose null spaces, and near null spaces obtained with `MatGetNullSpaces()` for an array of matrices

9403:   Logically Collective

9405:   Input Parameters:
9406: + n      - the number of matrices
9407: . mat    - the array of matrices
9408: - nullsp - an array of null spaces

9410:   Level: developer

9412:   Note:
9413:   Call `MatGetNullSpaces()` to create `nullsp`

9415: .seealso: [](ch_matrices), `Mat`, `MatCreate()`, `MatNullSpaceCreate()`, `MatSetNearNullSpace()`, `MatGetNullSpace()`, `MatSetTransposeNullSpace()`, `MatGetTransposeNullSpace()`,
9416:           `MatNullSpaceRemove()`, `MatGetNullSpaces()`
9417: @*/
9418: PetscErrorCode MatRestoreNullSpaces(PetscInt n, Mat mat[], MatNullSpace *nullsp[])
9419: {
9420:   PetscFunctionBegin;
9421:   PetscCheck(n >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Number of matrices %" PetscInt_FMT " must be non-negative", n);
9422:   PetscAssertPointer(mat, 2);
9423:   PetscAssertPointer(nullsp, 3);
9424:   PetscAssertPointer(*nullsp, 3);

9426:   for (PetscInt i = 0; i < n; i++) {
9428:     PetscCall(MatSetNullSpace(mat[i], (*nullsp)[i]));
9429:     PetscCall(PetscObjectDereference((PetscObject)(*nullsp)[i]));
9430:     PetscCall(MatSetNearNullSpace(mat[i], (*nullsp)[n + i]));
9431:     PetscCall(PetscObjectDereference((PetscObject)(*nullsp)[n + i]));
9432:     PetscCall(MatSetTransposeNullSpace(mat[i], (*nullsp)[2 * n + i]));
9433:     PetscCall(PetscObjectDereference((PetscObject)(*nullsp)[2 * n + i]));
9434:   }
9435:   PetscCall(PetscFree(*nullsp));
9436:   PetscFunctionReturn(PETSC_SUCCESS);
9437: }

9439: /*@
9440:   MatSetNullSpace - attaches a null space to a matrix.

9442:   Logically Collective

9444:   Input Parameters:
9445: + mat    - the matrix
9446: - nullsp - the null space object

9448:   Level: advanced

9450:   Notes:
9451:   This null space is used by the `KSP` linear solvers to solve singular systems.

9453:   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`

9455:   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
9456:   to zero but the linear system will still be solved in a least squares sense.

9458:   The fundamental theorem of linear algebra (Gilbert Strang, Introduction to Applied Mathematics, page 72) states that
9459:   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)$.
9460:   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
9461:   $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
9462:   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)$.
9463:   This  $\hat{b}$ can be obtained by calling `MatNullSpaceRemove()` with the null space of the transpose of the matrix.

9465:   If the matrix is known to be symmetric because it is an `MATSBAIJ` matrix or one has called
9466:   `MatSetOption`(mat,`MAT_SYMMETRIC` or possibly `MAT_SYMMETRY_ETERNAL`,`PETSC_TRUE`); this
9467:   routine also automatically calls `MatSetTransposeNullSpace()`.

9469:   The user should call `MatNullSpaceDestroy()`.

9471: .seealso: [](ch_matrices), `Mat`, `MatCreate()`, `MatNullSpaceCreate()`, `MatSetNearNullSpace()`, `MatGetNullSpace()`, `MatSetTransposeNullSpace()`, `MatGetTransposeNullSpace()`, `MatNullSpaceRemove()`,
9472:           `KSPSetPCSide()`
9473: @*/
9474: PetscErrorCode MatSetNullSpace(Mat mat, MatNullSpace nullsp)
9475: {
9476:   PetscFunctionBegin;
9479:   PetscCall(PetscObjectReference((PetscObject)nullsp));
9480:   PetscCall(MatNullSpaceDestroy(&mat->nullsp));
9481:   mat->nullsp = nullsp;
9482:   if (mat->symmetric == PETSC_BOOL3_TRUE) PetscCall(MatSetTransposeNullSpace(mat, nullsp));
9483:   PetscFunctionReturn(PETSC_SUCCESS);
9484: }

9486: /*@
9487:   MatGetTransposeNullSpace - retrieves the null space of the transpose of a matrix.

9489:   Logically Collective

9491:   Input Parameters:
9492: + mat    - the matrix
9493: - nullsp - the null space object

9495:   Level: developer

9497: .seealso: [](ch_matrices), `Mat`, `MatNullSpace`, `MatCreate()`, `MatNullSpaceCreate()`, `MatSetNearNullSpace()`, `MatSetTransposeNullSpace()`, `MatSetNullSpace()`, `MatGetNullSpace()`
9498: @*/
9499: PetscErrorCode MatGetTransposeNullSpace(Mat mat, MatNullSpace *nullsp)
9500: {
9501:   PetscFunctionBegin;
9504:   PetscAssertPointer(nullsp, 2);
9505:   *nullsp = (mat->symmetric == PETSC_BOOL3_TRUE && !mat->transnullsp) ? mat->nullsp : mat->transnullsp;
9506:   PetscFunctionReturn(PETSC_SUCCESS);
9507: }

9509: /*@
9510:   MatSetTransposeNullSpace - attaches the null space of a transpose of a matrix to the matrix

9512:   Logically Collective

9514:   Input Parameters:
9515: + mat    - the matrix
9516: - nullsp - the null space object

9518:   Level: advanced

9520:   Notes:
9521:   This allows solving singular linear systems defined by the transpose of the matrix using `KSP` solvers with left preconditioning.

9523:   See `MatSetNullSpace()`

9525: .seealso: [](ch_matrices), `Mat`, `MatNullSpace`, `MatCreate()`, `MatNullSpaceCreate()`, `MatSetNearNullSpace()`, `MatGetNullSpace()`, `MatSetNullSpace()`, `MatGetTransposeNullSpace()`, `MatNullSpaceRemove()`, `KSPSetPCSide()`
9526: @*/
9527: PetscErrorCode MatSetTransposeNullSpace(Mat mat, MatNullSpace nullsp)
9528: {
9529:   PetscFunctionBegin;
9532:   PetscCall(PetscObjectReference((PetscObject)nullsp));
9533:   PetscCall(MatNullSpaceDestroy(&mat->transnullsp));
9534:   mat->transnullsp = nullsp;
9535:   PetscFunctionReturn(PETSC_SUCCESS);
9536: }

9538: /*@
9539:   MatSetNearNullSpace - attaches a null space to a matrix, which is often the null space (rigid body modes) of the operator without boundary conditions
9540:   This null space will be used to provide near null space vectors to a multigrid preconditioner built from this matrix.

9542:   Logically Collective

9544:   Input Parameters:
9545: + mat    - the matrix
9546: - nullsp - the null space object

9548:   Level: advanced

9550:   Notes:
9551:   Overwrites any previous near null space that may have been attached

9553:   You can remove the null space by calling this routine with an `nullsp` of `NULL`

9555: .seealso: [](ch_matrices), `Mat`, `MatNullSpace`, `MatCreate()`, `MatNullSpaceCreate()`, `MatSetNullSpace()`, `MatNullSpaceCreateRigidBody()`, `MatGetNearNullSpace()`
9556: @*/
9557: PetscErrorCode MatSetNearNullSpace(Mat mat, MatNullSpace nullsp)
9558: {
9559:   PetscFunctionBegin;
9563:   MatCheckPreallocated(mat, 1);
9564:   PetscCall(PetscObjectReference((PetscObject)nullsp));
9565:   PetscCall(MatNullSpaceDestroy(&mat->nearnullsp));
9566:   mat->nearnullsp = nullsp;
9567:   PetscFunctionReturn(PETSC_SUCCESS);
9568: }

9570: /*@
9571:   MatGetNearNullSpace - Get null space attached with `MatSetNearNullSpace()`

9573:   Not Collective

9575:   Input Parameter:
9576: . mat - the matrix

9578:   Output Parameter:
9579: . nullsp - the null space object, `NULL` if not set

9581:   Level: advanced

9583: .seealso: [](ch_matrices), `Mat`, `MatNullSpace`, `MatSetNearNullSpace()`, `MatGetNullSpace()`, `MatNullSpaceCreate()`
9584: @*/
9585: PetscErrorCode MatGetNearNullSpace(Mat mat, MatNullSpace *nullsp)
9586: {
9587:   PetscFunctionBegin;
9590:   PetscAssertPointer(nullsp, 2);
9591:   MatCheckPreallocated(mat, 1);
9592:   *nullsp = mat->nearnullsp;
9593:   PetscFunctionReturn(PETSC_SUCCESS);
9594: }

9596: /*@
9597:   MatICCFactor - Performs in-place incomplete Cholesky factorization of matrix.

9599:   Collective

9601:   Input Parameters:
9602: + mat  - the matrix
9603: . row  - row/column permutation
9604: - info - information on desired factorization process

9606:   Level: developer

9608:   Notes:
9609:   Probably really in-place only when level of fill is zero, otherwise allocates
9610:   new space to store factored matrix and deletes previous memory.

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

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

9619: .seealso: [](ch_matrices), `Mat`, `MatFactorInfo`, `MatGetFactor()`, `MatICCFactorSymbolic()`, `MatLUFactorNumeric()`, `MatCholeskyFactor()`
9620: @*/
9621: PetscErrorCode MatICCFactor(Mat mat, IS row, const MatFactorInfo *info)
9622: {
9623:   PetscFunctionBegin;
9627:   PetscAssertPointer(info, 3);
9628:   PetscCheck(mat->rmap->N == mat->cmap->N, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONG, "matrix must be square");
9629:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
9630:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
9631:   MatCheckPreallocated(mat, 1);
9632:   PetscUseTypeMethod(mat, iccfactor, row, info);
9633:   PetscCall(PetscObjectStateIncrease((PetscObject)mat));
9634:   PetscFunctionReturn(PETSC_SUCCESS);
9635: }

9637: /*@
9638:   MatDiagonalScaleLocal - Scales columns of a matrix given the scaling values including the
9639:   ghosted ones.

9641:   Not Collective

9643:   Input Parameters:
9644: + mat  - the matrix
9645: - diag - the diagonal values, including ghost ones

9647:   Level: developer

9649:   Notes:
9650:   Works only for `MATMPIAIJ` and `MATMPIBAIJ` matrices

9652:   This allows one to avoid during communication to perform the scaling that must be done with `MatDiagonalScale()`

9654: .seealso: [](ch_matrices), `Mat`, `MatDiagonalScale()`
9655: @*/
9656: PetscErrorCode MatDiagonalScaleLocal(Mat mat, Vec diag)
9657: {
9658:   PetscMPIInt size;

9660:   PetscFunctionBegin;

9665:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Matrix must be already assembled");
9666:   PetscCall(PetscLogEventBegin(MAT_Scale, mat, 0, 0, 0));
9667:   PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)mat), &size));
9668:   if (size == 1) {
9669:     PetscInt n, m;
9670:     PetscCall(VecGetSize(diag, &n));
9671:     PetscCall(MatGetSize(mat, NULL, &m));
9672:     PetscCheck(m == n, PETSC_COMM_SELF, PETSC_ERR_SUP, "Only supported for sequential matrices when no ghost points/periodic conditions");
9673:     PetscCall(MatDiagonalScale(mat, NULL, diag));
9674:   } else PetscUseMethod(mat, "MatDiagonalScaleLocal_C", (Mat, Vec), (mat, diag));
9675:   PetscCall(PetscLogEventEnd(MAT_Scale, mat, 0, 0, 0));
9676:   PetscCall(PetscObjectStateIncrease((PetscObject)mat));
9677:   PetscFunctionReturn(PETSC_SUCCESS);
9678: }

9680: /*@
9681:   MatGetInertia - Gets the inertia from a factored matrix

9683:   Collective

9685:   Input Parameter:
9686: . mat - the matrix

9688:   Output Parameters:
9689: + nneg  - number of negative eigenvalues
9690: . nzero - number of zero eigenvalues
9691: - npos  - number of positive eigenvalues

9693:   Level: advanced

9695:   Note:
9696:   Matrix must have been factored by `MatCholeskyFactor()`

9698: .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatCholeskyFactor()`
9699: @*/
9700: PetscErrorCode MatGetInertia(Mat mat, PetscInt *nneg, PetscInt *nzero, PetscInt *npos)
9701: {
9702:   PetscFunctionBegin;
9705:   PetscCheck(mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Unfactored matrix");
9706:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Numeric factor mat is not assembled");
9707:   PetscUseTypeMethod(mat, getinertia, nneg, nzero, npos);
9708:   PetscFunctionReturn(PETSC_SUCCESS);
9709: }

9711: /*@
9712:   MatSolves - Solves $A x = b$, given a factored matrix, for a collection of vectors

9714:   Neighbor-wise Collective

9716:   Input Parameters:
9717: + mat - the factored matrix obtained with `MatGetFactor()`
9718: - b   - the right-hand-side vectors

9720:   Output Parameter:
9721: . x - the result vectors

9723:   Level: developer

9725:   Note:
9726:   The vectors `b` and `x` cannot be the same. I.e., one cannot
9727:   call `MatSolves`(A,x,x).

9729: .seealso: [](ch_matrices), `Mat`, `Vecs`, `MatSolveAdd()`, `MatSolveTranspose()`, `MatSolveTransposeAdd()`, `MatSolve()`
9730: @*/
9731: PetscErrorCode MatSolves(Mat mat, Vecs b, Vecs x)
9732: {
9733:   PetscFunctionBegin;
9736:   PetscCheck(x != b, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_IDN, "x and b must be different vectors");
9737:   PetscCheck(mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Unfactored matrix");
9738:   if (!mat->rmap->N && !mat->cmap->N) PetscFunctionReturn(PETSC_SUCCESS);

9740:   MatCheckPreallocated(mat, 1);
9741:   PetscCall(PetscLogEventBegin(MAT_Solves, mat, 0, 0, 0));
9742:   PetscUseTypeMethod(mat, solves, b, x);
9743:   PetscCall(PetscLogEventEnd(MAT_Solves, mat, 0, 0, 0));
9744:   PetscFunctionReturn(PETSC_SUCCESS);
9745: }

9747: /*@
9748:   MatIsSymmetric - Test whether a matrix is symmetric

9750:   Collective

9752:   Input Parameters:
9753: + A   - the matrix to test
9754: - tol - difference between value and its transpose less than this amount counts as equal (use 0.0 for exact transpose)

9756:   Output Parameter:
9757: . flg - the result

9759:   Level: intermediate

9761:   Notes:
9762:   For real numbers `MatIsSymmetric()` and `MatIsHermitian()` return identical results

9764:   If the matrix does not yet know if it is symmetric or not this can be an expensive operation, also available `MatIsSymmetricKnown()`

9766:   One can declare that a matrix is symmetric with `MatSetOption`(mat,`MAT_SYMMETRIC`,`PETSC_TRUE`) and if it is known to remain symmetric
9767:   after changes to the matrices values one can call `MatSetOption`(mat,`MAT_SYMMETRY_ETERNAL`,`PETSC_TRUE`)

9769: .seealso: [](ch_matrices), `Mat`, `MatTranspose()`, `MatIsTranspose()`, `MatIsHermitian()`, `MatIsStructurallySymmetric()`, `MatSetOption()`, `MatIsSymmetricKnown()`,
9770:           `MAT_SYMMETRIC`, `MAT_SYMMETRY_ETERNAL`
9771: @*/
9772: PetscErrorCode MatIsSymmetric(Mat A, PetscReal tol, PetscBool *flg)
9773: {
9774:   PetscFunctionBegin;
9776:   PetscAssertPointer(flg, 3);
9777:   if (A->symmetric != PETSC_BOOL3_UNKNOWN && !tol) *flg = PetscBool3ToBool(A->symmetric);
9778:   else {
9779:     if (A->ops->issymmetric) PetscUseTypeMethod(A, issymmetric, tol, flg);
9780:     else PetscCall(MatIsTranspose(A, A, tol, flg));
9781:     if (!tol) PetscCall(MatSetOption(A, MAT_SYMMETRIC, *flg));
9782:   }
9783:   PetscFunctionReturn(PETSC_SUCCESS);
9784: }

9786: /*@
9787:   MatIsHermitian - Test whether a matrix is Hermitian

9789:   Collective

9791:   Input Parameters:
9792: + A   - the matrix to test
9793: - tol - difference between value and its transpose less than this amount counts as equal (use 0.0 for exact Hermitian)

9795:   Output Parameter:
9796: . flg - the result

9798:   Level: intermediate

9800:   Notes:
9801:   For real numbers `MatIsSymmetric()` and `MatIsHermitian()` return identical results

9803:   If the matrix does not yet know if it is Hermitian or not this can be an expensive operation, also available `MatIsHermitianKnown()`

9805:   One can declare that a matrix is Hermitian with `MatSetOption`(mat,`MAT_HERMITIAN`,`PETSC_TRUE`) and if it is known to remain Hermitian
9806:   after changes to the matrices values one can call `MatSetOption`(mat,`MAT_SYMEMTRY_ETERNAL`,`PETSC_TRUE`)

9808: .seealso: [](ch_matrices), `Mat`, `MatTranspose()`, `MatIsTranspose()`, `MatIsHermitianKnown()`, `MatIsStructurallySymmetric()`, `MatSetOption()`,
9809:           `MatIsSymmetricKnown()`, `MatIsSymmetric()`, `MAT_HERMITIAN`, `MAT_SYMMETRY_ETERNAL`
9810: @*/
9811: PetscErrorCode MatIsHermitian(Mat A, PetscReal tol, PetscBool *flg)
9812: {
9813:   PetscFunctionBegin;
9815:   PetscAssertPointer(flg, 3);
9816:   if (A->hermitian != PETSC_BOOL3_UNKNOWN && !tol) *flg = PetscBool3ToBool(A->hermitian);
9817:   else {
9818:     if (A->ops->ishermitian) PetscUseTypeMethod(A, ishermitian, tol, flg);
9819:     else PetscCall(MatIsHermitianTranspose(A, A, tol, flg));
9820:     if (!tol) PetscCall(MatSetOption(A, MAT_HERMITIAN, *flg));
9821:   }
9822:   PetscFunctionReturn(PETSC_SUCCESS);
9823: }

9825: /*@
9826:   MatIsSymmetricKnown - Checks if a matrix knows if it is symmetric or not and its symmetric state

9828:   Not Collective

9830:   Input Parameter:
9831: . A - the matrix to check

9833:   Output Parameters:
9834: + set - `PETSC_TRUE` if the matrix knows its symmetry state (this tells you if the next flag is valid)
9835: - flg - the result (only valid if set is `PETSC_TRUE`)

9837:   Level: advanced

9839:   Notes:
9840:   Does not check the matrix values directly, so this may return unknown (set = `PETSC_FALSE`). Use `MatIsSymmetric()`
9841:   if you want it explicitly checked

9843:   One can declare that a matrix is symmetric with `MatSetOption`(mat,`MAT_SYMMETRIC`,`PETSC_TRUE`) and if it is known to remain symmetric
9844:   after changes to the matrices values one can call `MatSetOption`(mat,`MAT_SYMMETRY_ETERNAL`,`PETSC_TRUE`)

9846: .seealso: [](ch_matrices), `Mat`, `MAT_SYMMETRY_ETERNAL`, `MatTranspose()`, `MatIsTranspose()`, `MatIsHermitian()`, `MatIsStructurallySymmetric()`, `MatSetOption()`, `MatIsSymmetric()`, `MatIsHermitianKnown()`
9847: @*/
9848: PetscErrorCode MatIsSymmetricKnown(Mat A, PetscBool *set, PetscBool *flg)
9849: {
9850:   PetscFunctionBegin;
9852:   PetscAssertPointer(set, 2);
9853:   PetscAssertPointer(flg, 3);
9854:   if (A->symmetric != PETSC_BOOL3_UNKNOWN) {
9855:     *set = PETSC_TRUE;
9856:     *flg = PetscBool3ToBool(A->symmetric);
9857:   } else *set = PETSC_FALSE;
9858:   PetscFunctionReturn(PETSC_SUCCESS);
9859: }

9861: /*@
9862:   MatIsSPDKnown - Checks if a matrix knows if it is symmetric positive definite or not and its symmetric positive definite state

9864:   Not Collective

9866:   Input Parameter:
9867: . A - the matrix to check

9869:   Output Parameters:
9870: + set - `PETSC_TRUE` if the matrix knows its symmetric positive definite state (this tells you if the next flag is valid)
9871: - flg - the result (only valid if set is `PETSC_TRUE`)

9873:   Level: advanced

9875:   Notes:
9876:   Does not check the matrix values directly, so this may return unknown (set = `PETSC_FALSE`).

9878:   One can declare that a matrix is SPD with `MatSetOption`(mat,`MAT_SPD`,`PETSC_TRUE`) and if it is known to remain SPD
9879:   after changes to the matrices values one can call `MatSetOption`(mat,`MAT_SPD_ETERNAL`,`PETSC_TRUE`)

9881: .seealso: [](ch_matrices), `Mat`, `MAT_SPD_ETERNAL`, `MAT_SPD`, `MatTranspose()`, `MatIsTranspose()`, `MatIsHermitian()`, `MatIsStructurallySymmetric()`, `MatSetOption()`, `MatIsSymmetric()`, `MatIsHermitianKnown()`
9882: @*/
9883: PetscErrorCode MatIsSPDKnown(Mat A, PetscBool *set, PetscBool *flg)
9884: {
9885:   PetscFunctionBegin;
9887:   PetscAssertPointer(set, 2);
9888:   PetscAssertPointer(flg, 3);
9889:   if (A->spd != PETSC_BOOL3_UNKNOWN) {
9890:     *set = PETSC_TRUE;
9891:     *flg = PetscBool3ToBool(A->spd);
9892:   } else *set = PETSC_FALSE;
9893:   PetscFunctionReturn(PETSC_SUCCESS);
9894: }

9896: /*@
9897:   MatIsHermitianKnown - Checks if a matrix knows if it is Hermitian or not and its Hermitian state

9899:   Not Collective

9901:   Input Parameter:
9902: . A - the matrix to check

9904:   Output Parameters:
9905: + set - `PETSC_TRUE` if the matrix knows its Hermitian state (this tells you if the next flag is valid)
9906: - flg - the result (only valid if set is `PETSC_TRUE`)

9908:   Level: advanced

9910:   Notes:
9911:   Does not check the matrix values directly, so this may return unknown (set = `PETSC_FALSE`). Use `MatIsHermitian()`
9912:   if you want it explicitly checked

9914:   One can declare that a matrix is Hermitian with `MatSetOption`(mat,`MAT_HERMITIAN`,`PETSC_TRUE`) and if it is known to remain Hermitian
9915:   after changes to the matrices values one can call `MatSetOption`(mat,`MAT_SYMMETRY_ETERNAL`,`PETSC_TRUE`)

9917: .seealso: [](ch_matrices), `Mat`, `MAT_SYMMETRY_ETERNAL`, `MAT_HERMITIAN`, `MatTranspose()`, `MatIsTranspose()`, `MatIsHermitian()`, `MatIsStructurallySymmetric()`, `MatSetOption()`, `MatIsSymmetric()`
9918: @*/
9919: PetscErrorCode MatIsHermitianKnown(Mat A, PetscBool *set, PetscBool *flg)
9920: {
9921:   PetscFunctionBegin;
9923:   PetscAssertPointer(set, 2);
9924:   PetscAssertPointer(flg, 3);
9925:   if (A->hermitian != PETSC_BOOL3_UNKNOWN) {
9926:     *set = PETSC_TRUE;
9927:     *flg = PetscBool3ToBool(A->hermitian);
9928:   } else *set = PETSC_FALSE;
9929:   PetscFunctionReturn(PETSC_SUCCESS);
9930: }

9932: /*@
9933:   MatIsStructurallySymmetric - Test whether a matrix is structurally symmetric

9935:   Collective

9937:   Input Parameter:
9938: . A - the matrix to test

9940:   Output Parameter:
9941: . flg - the result

9943:   Level: intermediate

9945:   Notes:
9946:   If the matrix does yet know it is structurally symmetric this can be an expensive operation, also available `MatIsStructurallySymmetricKnown()`

9948:   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
9949:   symmetric after changes to the matrices values one can call `MatSetOption`(mat,`MAT_STRUCTURAL_SYMMETRY_ETERNAL`,`PETSC_TRUE`)

9951: .seealso: [](ch_matrices), `Mat`, `MAT_STRUCTURALLY_SYMMETRIC`, `MAT_STRUCTURAL_SYMMETRY_ETERNAL`, `MatTranspose()`, `MatIsTranspose()`, `MatIsHermitian()`, `MatIsSymmetric()`, `MatSetOption()`, `MatIsStructurallySymmetricKnown()`
9952: @*/
9953: PetscErrorCode MatIsStructurallySymmetric(Mat A, PetscBool *flg)
9954: {
9955:   PetscFunctionBegin;
9957:   PetscAssertPointer(flg, 2);
9958:   if (A->structurally_symmetric != PETSC_BOOL3_UNKNOWN) *flg = PetscBool3ToBool(A->structurally_symmetric);
9959:   else {
9960:     PetscUseTypeMethod(A, isstructurallysymmetric, flg);
9961:     PetscCall(MatSetOption(A, MAT_STRUCTURALLY_SYMMETRIC, *flg));
9962:   }
9963:   PetscFunctionReturn(PETSC_SUCCESS);
9964: }

9966: /*@
9967:   MatIsStructurallySymmetricKnown - Checks if a matrix knows if it is structurally symmetric or not and its structurally symmetric state

9969:   Not Collective

9971:   Input Parameter:
9972: . A - the matrix to check

9974:   Output Parameters:
9975: + set - PETSC_TRUE if the matrix knows its structurally symmetric state (this tells you if the next flag is valid)
9976: - flg - the result (only valid if set is PETSC_TRUE)

9978:   Level: advanced

9980:   Notes:
9981:   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
9982:   symmetric after changes to the matrices values one can call `MatSetOption`(mat,`MAT_STRUCTURAL_SYMMETRY_ETERNAL`,`PETSC_TRUE`)

9984:   Use `MatIsStructurallySymmetric()` to explicitly check if a matrix is structurally symmetric (this is an expensive operation)

9986: .seealso: [](ch_matrices), `Mat`, `MAT_STRUCTURALLY_SYMMETRIC`, `MatTranspose()`, `MatIsTranspose()`, `MatIsHermitian()`, `MatIsStructurallySymmetric()`, `MatSetOption()`, `MatIsSymmetric()`, `MatIsHermitianKnown()`
9987: @*/
9988: PetscErrorCode MatIsStructurallySymmetricKnown(Mat A, PetscBool *set, PetscBool *flg)
9989: {
9990:   PetscFunctionBegin;
9992:   PetscAssertPointer(set, 2);
9993:   PetscAssertPointer(flg, 3);
9994:   if (A->structurally_symmetric != PETSC_BOOL3_UNKNOWN) {
9995:     *set = PETSC_TRUE;
9996:     *flg = PetscBool3ToBool(A->structurally_symmetric);
9997:   } else *set = PETSC_FALSE;
9998:   PetscFunctionReturn(PETSC_SUCCESS);
9999: }

10001: /*@
10002:   MatStashGetInfo - Gets how many values are currently in the matrix stash, i.e. need
10003:   to be communicated to other processes during the `MatAssemblyBegin()`/`MatAssemblyEnd()` process

10005:   Not Collective

10007:   Input Parameter:
10008: . mat - the matrix

10010:   Output Parameters:
10011: + nstash    - the size of the stash
10012: . reallocs  - the number of additional mallocs incurred.
10013: . bnstash   - the size of the block stash
10014: - breallocs - the number of additional mallocs incurred.in the block stash

10016:   Level: advanced

10018: .seealso: [](ch_matrices), `MatAssemblyBegin()`, `MatAssemblyEnd()`, `Mat`, `MatStashSetInitialSize()`
10019: @*/
10020: PetscErrorCode MatStashGetInfo(Mat mat, PetscInt *nstash, PetscInt *reallocs, PetscInt *bnstash, PetscInt *breallocs)
10021: {
10022:   PetscFunctionBegin;
10023:   PetscCall(MatStashGetInfo_Private(&mat->stash, nstash, reallocs));
10024:   PetscCall(MatStashGetInfo_Private(&mat->bstash, bnstash, breallocs));
10025:   PetscFunctionReturn(PETSC_SUCCESS);
10026: }

10028: /*@
10029:   MatCreateVecs - Get vector(s) compatible with the matrix, i.e. with the same
10030:   parallel layout, `PetscLayout` for rows and columns

10032:   Collective

10034:   Input Parameter:
10035: . mat - the matrix

10037:   Output Parameters:
10038: + right - (optional) vector that the matrix can be multiplied against
10039: - left  - (optional) vector that the matrix vector product can be stored in

10041:   Options Database Key:
10042: . -mat_vec_type type - set the `VecType` of the created vectors during `MatSetFromOptions()`

10044:   Level: advanced

10046:   Notes:
10047:   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()`.

10049:   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`.

10051:   These are new vectors which are not owned by the `mat`, they should be destroyed with `VecDestroy()` when no longer needed.

10053:   PETSc `Vec` always have all zero entries when created with `MatCreateVecs()` until routines such as `VecSet()` or `VecSetValues()`
10054:   are used to change the values. There is no reason to call `VecZeroEntries()` after creation.

10056: .seealso: [](ch_matrices), `Mat`, `Vec`, `VecCreate()`, `VecDestroy()`, `DMCreateGlobalVector()`, `MatSetVecType()`
10057: @*/
10058: PetscErrorCode MatCreateVecs(Mat mat, Vec *right, Vec *left)
10059: {
10060:   PetscFunctionBegin;
10063:   if (mat->ops->getvecs) {
10064:     PetscUseTypeMethod(mat, getvecs, right, left);
10065:   } else {
10066:     if (right) {
10067:       PetscCheck(mat->cmap->n >= 0, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "PetscLayout for columns not yet setup");
10068:       PetscCall(VecCreateWithLayout_Private(mat->cmap, right));
10069:       PetscCall(VecSetType(*right, mat->defaultvectype));
10070: #if PetscDefined(HAVE_VIENNACL) || PetscDefined(HAVE_CUDA) || PetscDefined(HAVE_HIP)
10071:       if (mat->boundtocpu && mat->bindingpropagates) {
10072:         PetscCall(VecSetBindingPropagates(*right, PETSC_TRUE));
10073:         PetscCall(VecBindToCPU(*right, PETSC_TRUE));
10074:       }
10075: #endif
10076:     }
10077:     if (left) {
10078:       PetscCheck(mat->rmap->n >= 0, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "PetscLayout for rows not yet setup");
10079:       PetscCall(VecCreateWithLayout_Private(mat->rmap, left));
10080:       PetscCall(VecSetType(*left, mat->defaultvectype));
10081: #if PetscDefined(HAVE_VIENNACL) || PetscDefined(HAVE_CUDA) || PetscDefined(HAVE_HIP)
10082:       if (mat->boundtocpu && mat->bindingpropagates) {
10083:         PetscCall(VecSetBindingPropagates(*left, PETSC_TRUE));
10084:         PetscCall(VecBindToCPU(*left, PETSC_TRUE));
10085:       }
10086: #endif
10087:     }
10088:   }
10089:   PetscFunctionReturn(PETSC_SUCCESS);
10090: }

10092: /*@
10093:   MatFactorInfoInitialize - Initializes a `MatFactorInfo` data structure
10094:   with default values.

10096:   Not Collective

10098:   Input Parameter:
10099: . info - the `MatFactorInfo` data structure

10101:   Level: developer

10103:   Notes:
10104:   The solvers are generally used through the `KSP` and `PC` objects, for example
10105:   `PCLU`, `PCILU`, `PCCHOLESKY`, `PCICC`

10107:   Once the data structure is initialized one may change certain entries as desired for the particular factorization to be performed

10109: .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatFactorInfo`
10110: @*/
10111: PetscErrorCode MatFactorInfoInitialize(MatFactorInfo *info)
10112: {
10113:   PetscFunctionBegin;
10114:   PetscCall(PetscMemzero(info, sizeof(MatFactorInfo)));
10115:   PetscFunctionReturn(PETSC_SUCCESS);
10116: }

10118: /*@
10119:   MatFactorSetSchurIS - Set indices corresponding to the Schur complement you wish to have computed

10121:   Collective

10123:   Input Parameters:
10124: + mat - the factored matrix
10125: - is  - the index set defining the Schur indices (0-based)

10127:   Level: advanced

10129:   Notes:
10130:   Call `MatFactorSolveSchurComplement()` or `MatFactorSolveSchurComplementTranspose()` after this call to solve a Schur complement system.

10132:   You can call `MatFactorGetSchurComplement()` or `MatFactorCreateSchurComplement()` after this call.

10134:   This functionality is only supported for `MATSOLVERMUMPS` and `MATSOLVERMKL_PARDISO`

10136: .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatFactorGetSchurComplement()`, `MatFactorRestoreSchurComplement()`, `MatFactorCreateSchurComplement()`, `MatFactorSolveSchurComplement()`,
10137:           `MatFactorSolveSchurComplementTranspose()`, `MATSOLVERMUMPS`, `MATSOLVERMKL_PARDISO`
10138: @*/
10139: PetscErrorCode MatFactorSetSchurIS(Mat mat, IS is)
10140: {
10141:   PetscErrorCode (*f)(Mat, IS);

10143:   PetscFunctionBegin;
10148:   PetscCheckSameComm(mat, 1, is, 2);
10149:   PetscCheck(mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Only for factored matrix");
10150:   PetscCall(PetscObjectQueryFunction((PetscObject)mat, "MatFactorSetSchurIS_C", &f));
10151:   PetscCheck(f, PetscObjectComm((PetscObject)mat), PETSC_ERR_SUP, "The selected MatSolverType does not support Schur complement computation. You should use MATSOLVERMUMPS or MATSOLVERMKL_PARDISO");
10152:   PetscCall((*f)(mat, is));
10153:   PetscCheck(mat->schur, PetscObjectComm((PetscObject)mat), PETSC_ERR_PLIB, "Schur complement has not been created");
10154:   PetscFunctionReturn(PETSC_SUCCESS);
10155: }

10157: /*@
10158:   MatFactorCreateSchurComplement - Create a Schur complement matrix object using Schur data computed during the factorization step

10160:   Logically Collective

10162:   Input Parameters:
10163: + F      - the factored matrix obtained by calling `MatGetFactor()`
10164: . S      - location where to return the Schur complement, can be `NULL`
10165: - status - the status of the Schur complement matrix, can be `NULL`

10167:   Level: advanced

10169:   Notes:
10170:   You must call `MatFactorSetSchurIS()` before calling this routine.

10172:   This functionality is only supported for `MATSOLVERMUMPS` and `MATSOLVERMKL_PARDISO`

10174:   The routine provides a copy of the Schur matrix stored within the solver data structures.
10175:   The caller must destroy the object when it is no longer needed.
10176:   If `MatFactorInvertSchurComplement()` has been called, the routine gets back the inverse.

10178:   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)

10180:   See `MatCreateSchurComplement()` or `MatGetSchurComplement()` for ways to create virtual or approximate Schur complements.

10182:   Developer Note:
10183:   The reason this routine exists is because the representation of the Schur complement within the factor matrix may be different than a standard PETSc
10184:   matrix representation and we normally do not want to use the time or memory to make a copy as a regular PETSc matrix.

10186: .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatFactorSetSchurIS()`, `MatFactorGetSchurComplement()`, `MatFactorSchurStatus`, `MATSOLVERMUMPS`, `MATSOLVERMKL_PARDISO`
10187: @*/
10188: PetscErrorCode MatFactorCreateSchurComplement(Mat F, Mat *S, MatFactorSchurStatus *status)
10189: {
10190:   PetscFunctionBegin;
10192:   if (S) PetscAssertPointer(S, 2);
10193:   if (status) PetscAssertPointer(status, 3);
10194:   if (S) {
10195:     PetscErrorCode (*f)(Mat, Mat *);

10197:     PetscCall(PetscObjectQueryFunction((PetscObject)F, "MatFactorCreateSchurComplement_C", &f));
10198:     if (f) PetscCall((*f)(F, S));
10199:     else PetscCall(MatDuplicate(F->schur, MAT_COPY_VALUES, S));
10200:   }
10201:   if (status) *status = F->schur_status;
10202:   PetscFunctionReturn(PETSC_SUCCESS);
10203: }

10205: /*@
10206:   MatFactorGetSchurComplement - Gets access to a Schur complement matrix using the current Schur data within a factored matrix

10208:   Logically Collective

10210:   Input Parameters:
10211: + F      - the factored matrix obtained by calling `MatGetFactor()`
10212: . S      - location where to return the Schur complement, can be `NULL`
10213: - status - the status of the Schur complement matrix, can be `NULL`

10215:   Level: advanced

10217:   Notes:
10218:   You must call `MatFactorSetSchurIS()` before calling this routine.

10220:   Schur complement mode is currently implemented for sequential matrices with factor type of `MATSOLVERMUMPS`

10222:   The routine returns a the Schur Complement stored within the data structures of the solver.

10224:   If `MatFactorInvertSchurComplement()` has previously been called, the returned matrix is actually the inverse of the Schur complement.

10226:   The returned matrix should not be destroyed; the caller should call `MatFactorRestoreSchurComplement()` when the object is no longer needed.

10228:   Use `MatFactorCreateSchurComplement()` to create a copy of the Schur complement matrix that is within a factored matrix

10230:   See `MatCreateSchurComplement()` or `MatGetSchurComplement()` for ways to create virtual or approximate Schur complements.

10232: .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatFactorSetSchurIS()`, `MatFactorRestoreSchurComplement()`, `MatFactorCreateSchurComplement()`, `MatFactorSchurStatus`
10233: @*/
10234: PetscErrorCode MatFactorGetSchurComplement(Mat F, Mat *S, MatFactorSchurStatus *status)
10235: {
10236:   PetscFunctionBegin;
10238:   if (S) {
10239:     PetscAssertPointer(S, 2);
10240:     *S = F->schur;
10241:   }
10242:   if (status) {
10243:     PetscAssertPointer(status, 3);
10244:     *status = F->schur_status;
10245:   }
10246:   PetscFunctionReturn(PETSC_SUCCESS);
10247: }

10249: static PetscErrorCode MatFactorUpdateSchurStatus_Private(Mat F)
10250: {
10251:   Mat S = F->schur;

10253:   PetscFunctionBegin;
10254:   switch (F->schur_status) {
10255:   case MAT_FACTOR_SCHUR_UNFACTORED: // fall-through
10256:   case MAT_FACTOR_SCHUR_INVERTED:
10257:     if (S) {
10258:       S->ops->solve             = NULL;
10259:       S->ops->matsolve          = NULL;
10260:       S->ops->solvetranspose    = NULL;
10261:       S->ops->matsolvetranspose = NULL;
10262:       S->ops->solveadd          = NULL;
10263:       S->ops->solvetransposeadd = NULL;
10264:       S->factortype             = MAT_FACTOR_NONE;
10265:       PetscCall(PetscFree(S->solvertype));
10266:     }
10267:   case MAT_FACTOR_SCHUR_FACTORED: // fall-through
10268:     break;
10269:   default:
10270:     SETERRQ(PetscObjectComm((PetscObject)F), PETSC_ERR_SUP, "Unhandled MatFactorSchurStatus %d", F->schur_status);
10271:   }
10272:   PetscFunctionReturn(PETSC_SUCCESS);
10273: }

10275: /*@
10276:   MatFactorRestoreSchurComplement - Restore the Schur complement matrix object obtained from a call to `MatFactorGetSchurComplement()`

10278:   Logically Collective

10280:   Input Parameters:
10281: + F      - the factored matrix obtained by calling `MatGetFactor()`
10282: . S      - location where the Schur complement is stored
10283: - status - the status of the Schur complement matrix (see `MatFactorSchurStatus`)

10285:   Level: advanced

10287: .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatFactorSetSchurIS()`, `MatFactorCreateSchurComplement()`, `MatFactorSchurStatus`
10288: @*/
10289: PetscErrorCode MatFactorRestoreSchurComplement(Mat F, Mat *S, MatFactorSchurStatus status)
10290: {
10291:   PetscFunctionBegin;
10293:   if (S) {
10295:     *S = NULL;
10296:   }
10297:   F->schur_status = status;
10298:   PetscCall(MatFactorUpdateSchurStatus_Private(F));
10299:   PetscFunctionReturn(PETSC_SUCCESS);
10300: }

10302: /*@
10303:   MatFactorSolveSchurComplementTranspose - Solve the transpose of the Schur complement system computed during the factorization step

10305:   Logically Collective

10307:   Input Parameters:
10308: + F   - the factored matrix obtained by calling `MatGetFactor()`
10309: . rhs - location where the right-hand side of the Schur complement system is stored
10310: - sol - location where the solution of the Schur complement system has to be returned

10312:   Level: advanced

10314:   Notes:
10315:   The sizes of the vectors should match the size of the Schur complement

10317:   Must be called after `MatFactorSetSchurIS()`

10319: .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatFactorSetSchurIS()`, `MatFactorSolveSchurComplement()`
10320: @*/
10321: PetscErrorCode MatFactorSolveSchurComplementTranspose(Mat F, Vec rhs, Vec sol)
10322: {
10323:   PetscFunctionBegin;
10330:   PetscCheckSameComm(F, 1, rhs, 2);
10331:   PetscCheckSameComm(F, 1, sol, 3);
10332:   PetscCall(MatFactorFactorizeSchurComplement(F));
10333:   switch (F->schur_status) {
10334:   case MAT_FACTOR_SCHUR_FACTORED:
10335:     PetscCall(MatSolveTranspose(F->schur, rhs, sol));
10336:     break;
10337:   case MAT_FACTOR_SCHUR_INVERTED:
10338:     PetscCall(MatMultTranspose(F->schur, rhs, sol));
10339:     break;
10340:   default:
10341:     SETERRQ(PetscObjectComm((PetscObject)F), PETSC_ERR_SUP, "Unhandled MatFactorSchurStatus %d", F->schur_status);
10342:   }
10343:   PetscFunctionReturn(PETSC_SUCCESS);
10344: }

10346: /*@
10347:   MatFactorSolveSchurComplement - Solve the Schur complement system computed during the factorization step

10349:   Logically Collective

10351:   Input Parameters:
10352: + F   - the factored matrix obtained by calling `MatGetFactor()`
10353: . rhs - location where the right-hand side of the Schur complement system is stored
10354: - sol - location where the solution of the Schur complement system has to be returned

10356:   Level: advanced

10358:   Notes:
10359:   The sizes of the vectors should match the size of the Schur complement

10361:   Must be called after `MatFactorSetSchurIS()`

10363: .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatFactorSetSchurIS()`, `MatFactorSolveSchurComplementTranspose()`
10364: @*/
10365: PetscErrorCode MatFactorSolveSchurComplement(Mat F, Vec rhs, Vec sol)
10366: {
10367:   PetscFunctionBegin;
10374:   PetscCheckSameComm(F, 1, rhs, 2);
10375:   PetscCheckSameComm(F, 1, sol, 3);
10376:   PetscCall(MatFactorFactorizeSchurComplement(F));
10377:   switch (F->schur_status) {
10378:   case MAT_FACTOR_SCHUR_FACTORED:
10379:     PetscCall(MatSolve(F->schur, rhs, sol));
10380:     break;
10381:   case MAT_FACTOR_SCHUR_INVERTED:
10382:     PetscCall(MatMult(F->schur, rhs, sol));
10383:     break;
10384:   default:
10385:     SETERRQ(PetscObjectComm((PetscObject)F), PETSC_ERR_SUP, "Unhandled MatFactorSchurStatus %d", F->schur_status);
10386:   }
10387:   PetscFunctionReturn(PETSC_SUCCESS);
10388: }

10390: PETSC_SINGLE_LIBRARY_INTERN PetscErrorCode MatSeqDenseInvertFactors_Private(Mat);
10391: #if PetscDefined(HAVE_CUDA)
10392: PETSC_SINGLE_LIBRARY_INTERN PetscErrorCode MatSeqDenseCUDAInvertFactors_Internal(Mat);
10393: #endif

10395: /* Schur status updated in the interface */
10396: static PetscErrorCode MatFactorInvertSchurComplement_Private(Mat F)
10397: {
10398:   Mat S = F->schur;

10400:   PetscFunctionBegin;
10401:   if (S) {
10402:     PetscMPIInt size;
10403:     PetscBool   isdense, isdensecuda;

10405:     PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)S), &size));
10406:     PetscCheck(size <= 1, PetscObjectComm((PetscObject)S), PETSC_ERR_SUP, "Not yet implemented");
10407:     PetscCall(PetscObjectTypeCompare((PetscObject)S, MATSEQDENSE, &isdense));
10408:     PetscCall(PetscObjectTypeCompare((PetscObject)S, MATSEQDENSECUDA, &isdensecuda));
10409:     PetscCheck(isdense || isdensecuda, PetscObjectComm((PetscObject)S), PETSC_ERR_SUP, "Not implemented for type %s", ((PetscObject)S)->type_name);
10410:     PetscCall(PetscLogEventBegin(MAT_FactorInvS, F, 0, 0, 0));
10411:     if (isdense) {
10412:       PetscCall(MatSeqDenseInvertFactors_Private(S));
10413:     } else if (isdensecuda) {
10414: #if PetscDefined(HAVE_CUDA)
10415:       PetscCall(MatSeqDenseCUDAInvertFactors_Internal(S));
10416: #endif
10417:     }
10418:     // HIP??????????????
10419:     PetscCall(PetscLogEventEnd(MAT_FactorInvS, F, 0, 0, 0));
10420:   }
10421:   PetscFunctionReturn(PETSC_SUCCESS);
10422: }

10424: /*@
10425:   MatFactorInvertSchurComplement - Invert the Schur complement matrix computed during the factorization step

10427:   Logically Collective

10429:   Input Parameter:
10430: . F - the factored matrix obtained by calling `MatGetFactor()`

10432:   Level: advanced

10434:   Notes:
10435:   Must be called after `MatFactorSetSchurIS()`.

10437:   Call `MatFactorGetSchurComplement()` or  `MatFactorCreateSchurComplement()` AFTER this call to actually compute the inverse and get access to it.

10439: .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatFactorSetSchurIS()`, `MatFactorGetSchurComplement()`, `MatFactorCreateSchurComplement()`
10440: @*/
10441: PetscErrorCode MatFactorInvertSchurComplement(Mat F)
10442: {
10443:   PetscFunctionBegin;
10446:   if (F->schur_status == MAT_FACTOR_SCHUR_INVERTED) PetscFunctionReturn(PETSC_SUCCESS);
10447:   PetscCall(MatFactorFactorizeSchurComplement(F));
10448:   PetscCall(MatFactorInvertSchurComplement_Private(F));
10449:   F->schur_status = MAT_FACTOR_SCHUR_INVERTED;
10450:   PetscFunctionReturn(PETSC_SUCCESS);
10451: }

10453: /*@
10454:   MatFactorFactorizeSchurComplement - Factorize the Schur complement matrix computed during the factorization step

10456:   Logically Collective

10458:   Input Parameter:
10459: . F - the factored matrix obtained by calling `MatGetFactor()`

10461:   Level: advanced

10463:   Note:
10464:   Must be called after `MatFactorSetSchurIS()`

10466: .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatFactorSetSchurIS()`, `MatFactorInvertSchurComplement()`
10467: @*/
10468: PetscErrorCode MatFactorFactorizeSchurComplement(Mat F)
10469: {
10470:   MatFactorInfo info;

10472:   PetscFunctionBegin;
10475:   if (F->schur_status == MAT_FACTOR_SCHUR_INVERTED || F->schur_status == MAT_FACTOR_SCHUR_FACTORED) PetscFunctionReturn(PETSC_SUCCESS);
10476:   PetscCall(PetscLogEventBegin(MAT_FactorFactS, F, 0, 0, 0));
10477:   PetscCall(PetscMemzero(&info, sizeof(MatFactorInfo)));
10478:   if (F->factortype == MAT_FACTOR_CHOLESKY) { /* LDL^t regarded as Cholesky */
10479:     PetscCall(MatCholeskyFactor(F->schur, NULL, &info));
10480:   } else {
10481:     PetscCall(MatLUFactor(F->schur, NULL, NULL, &info));
10482:   }
10483:   PetscCall(PetscLogEventEnd(MAT_FactorFactS, F, 0, 0, 0));
10484:   F->schur_status = MAT_FACTOR_SCHUR_FACTORED;
10485:   PetscFunctionReturn(PETSC_SUCCESS);
10486: }

10488: /*@
10489:   MatPtAP - Creates the matrix product $C = P^T * A * P$

10491:   Neighbor-wise Collective

10493:   Input Parameters:
10494: + A     - the matrix
10495: . P     - the projection matrix
10496: . scall - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`
10497: - 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
10498:           if the result is a dense matrix this is irrelevant

10500:   Output Parameter:
10501: . C - the product matrix

10503:   Level: intermediate

10505:   Notes:
10506:   `C` will be created and must be destroyed by the user with `MatDestroy()`.

10508:   This is a convenience routine that wraps the use of the `MatProductCreate()` with a `MatProductType` of `MATPRODUCT_PtAP`
10509:   functionality into a single function call. For more involved matrix-matrix operations see `MatProductCreate()`.

10511:   The deprecated `PETSC_DEFAULT` in `fill` also means use the current value

10513:   Developer Note:
10514:   For matrix types without special implementation the function fallbacks to `MatMatMult()` followed by `MatTransposeMatMult()`.

10516: .seealso: [](ch_matrices), `Mat`, `MatProductCreate()`, `MatMatMult()`, `MatRARt()`
10517: @*/
10518: PetscErrorCode MatPtAP(Mat A, Mat P, MatReuse scall, PetscReal fill, Mat *C)
10519: {
10520:   PetscFunctionBegin;
10521:   if (scall == MAT_REUSE_MATRIX) MatCheckProduct(*C, 5);
10522:   PetscCheck(scall != MAT_INPLACE_MATRIX, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "Inplace product not supported");

10524:   if (scall == MAT_INITIAL_MATRIX) {
10525:     PetscCall(MatProductCreate(A, P, NULL, C));
10526:     PetscCall(MatProductSetType(*C, MATPRODUCT_PtAP));
10527:     PetscCall(MatProductSetAlgorithm(*C, "default"));
10528:     PetscCall(MatProductSetFill(*C, fill));

10530:     (*C)->product->api_user = PETSC_TRUE;
10531:     PetscCall(MatProductSetFromOptions(*C));
10532:     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);
10533:     PetscCall(MatProductSymbolic(*C));
10534:   } else { /* scall == MAT_REUSE_MATRIX */
10535:     PetscCall(MatProductReplaceMats(A, P, NULL, *C));
10536:   }

10538:   PetscCall(MatProductNumeric(*C));
10539:   if (A->symmetric == PETSC_BOOL3_TRUE) {
10540:     PetscCall(MatSetOption(*C, MAT_SYMMETRIC, PETSC_TRUE));
10541:     (*C)->spd = A->spd;
10542:   }
10543:   PetscFunctionReturn(PETSC_SUCCESS);
10544: }

10546: /*@
10547:   MatRARt - Creates the matrix product $C = R * A * R^T$

10549:   Neighbor-wise Collective

10551:   Input Parameters:
10552: + A     - the matrix
10553: . R     - the projection matrix
10554: . scall - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`
10555: - fill  - expected fill as ratio of nnz(C)/nnz(A), use `PETSC_DETERMINE` or `PETSC_CURRENT` if you do not have a good estimate
10556:           if the result is a dense matrix this is irrelevant

10558:   Output Parameter:
10559: . C - the product matrix

10561:   Level: intermediate

10563:   Notes:
10564:   `C` will be created and must be destroyed by the user with `MatDestroy()`.

10566:   This is a convenience routine that wraps the use of the `MatProductCreate()` with a `MatProductType` of `MATPRODUCT_RARt`
10567:   functionality into a single function call. For more involved matrix-matrix operations see `MatProductCreate()`.

10569:   This routine is currently only implemented for pairs of `MATAIJ` matrices and classes
10570:   which inherit from `MATAIJ`. Due to PETSc sparse matrix block row distribution among processes,
10571:   the parallel `MatRARt()` is implemented computing the explicit transpose of `R`, which can be very expensive.
10572:   We recommend using `MatPtAP()` when possible.

10574:   The deprecated `PETSC_DEFAULT` in `fill` also means use the current value

10576: .seealso: [](ch_matrices), `Mat`, `MatProductCreate()`, `MatMatMult()`, `MatPtAP()`
10577: @*/
10578: PetscErrorCode MatRARt(Mat A, Mat R, MatReuse scall, PetscReal fill, Mat *C)
10579: {
10580:   PetscFunctionBegin;
10581:   if (scall == MAT_REUSE_MATRIX) MatCheckProduct(*C, 5);
10582:   PetscCheck(scall != MAT_INPLACE_MATRIX, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "Inplace product not supported");

10584:   if (scall == MAT_INITIAL_MATRIX) {
10585:     PetscCall(MatProductCreate(A, R, NULL, C));
10586:     PetscCall(MatProductSetType(*C, MATPRODUCT_RARt));
10587:     PetscCall(MatProductSetAlgorithm(*C, "default"));
10588:     PetscCall(MatProductSetFill(*C, fill));

10590:     (*C)->product->api_user = PETSC_TRUE;
10591:     PetscCall(MatProductSetFromOptions(*C));
10592:     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);
10593:     PetscCall(MatProductSymbolic(*C));
10594:   } else { /* scall == MAT_REUSE_MATRIX */
10595:     PetscCall(MatProductReplaceMats(A, R, NULL, *C));
10596:   }

10598:   PetscCall(MatProductNumeric(*C));
10599:   if (A->symmetric == PETSC_BOOL3_TRUE) PetscCall(MatSetOption(*C, MAT_SYMMETRIC, PETSC_TRUE));
10600:   PetscFunctionReturn(PETSC_SUCCESS);
10601: }

10603: static PetscErrorCode MatProduct_Private(Mat A, Mat B, MatReuse scall, PetscReal fill, MatProductType ptype, Mat *C)
10604: {
10605:   PetscBool flg = PETSC_TRUE;

10607:   PetscFunctionBegin;
10608:   PetscCheck(scall != MAT_INPLACE_MATRIX, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "MAT_INPLACE_MATRIX product not supported");
10609:   if (scall == MAT_INITIAL_MATRIX) {
10610:     PetscCall(PetscInfo(A, "Calling MatProduct API with MAT_INITIAL_MATRIX and product type %s\n", MatProductTypes[ptype]));
10611:     PetscCall(MatProductCreate(A, B, NULL, C));
10612:     PetscCall(MatProductSetAlgorithm(*C, MATPRODUCTALGORITHMDEFAULT));
10613:     PetscCall(MatProductSetFill(*C, fill));
10614:   } else { /* scall == MAT_REUSE_MATRIX */
10615:     Mat_Product *product = (*C)->product;

10617:     PetscCall(PetscObjectBaseTypeCompareAny((PetscObject)*C, &flg, MATSEQDENSE, MATMPIDENSE, ""));
10618:     if (flg && product && product->type != ptype) {
10619:       PetscCall(MatProductClear(*C));
10620:       product = NULL;
10621:     }
10622:     PetscCall(PetscInfo(A, "Calling MatProduct API with MAT_REUSE_MATRIX %s product present and product type %s\n", product ? "with" : "without", MatProductTypes[ptype]));
10623:     if (!product) { /* user provide the dense matrix *C without calling MatProductCreate() or reusing it from previous calls */
10624:       PetscCheck(flg, PetscObjectComm((PetscObject)*C), PETSC_ERR_SUP, "Call MatProductCreate() first");
10625:       PetscCall(MatProductCreate_Private(A, B, NULL, *C));
10626:       product        = (*C)->product;
10627:       product->fill  = fill;
10628:       product->clear = PETSC_TRUE;
10629:     } else { /* user may change input matrices A or B when MAT_REUSE_MATRIX */
10630:       flg = PETSC_FALSE;
10631:       PetscCall(MatProductReplaceMats(A, B, NULL, *C));
10632:     }
10633:   }
10634:   if (flg) {
10635:     (*C)->product->api_user = PETSC_TRUE;
10636:     PetscCall(MatProductSetType(*C, ptype));
10637:     PetscCall(MatProductSetFromOptions(*C));
10638:     PetscCall(MatProductSymbolic(*C));
10639:   }
10640:   PetscCall(MatProductNumeric(*C));
10641:   PetscFunctionReturn(PETSC_SUCCESS);
10642: }

10644: /*@
10645:   MatMatMult - Performs matrix-matrix multiplication $ C=A*B $.

10647:   Neighbor-wise Collective

10649:   Input Parameters:
10650: + A     - the left matrix
10651: . B     - the right matrix
10652: . scall - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`
10653: - 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
10654:           if the result is a dense matrix this is irrelevant

10656:   Output Parameter:
10657: . C - the product matrix

10659:   Notes:
10660:   Unless scall is `MAT_REUSE_MATRIX` C will be created.

10662:   `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
10663:   call to this function with `MAT_INITIAL_MATRIX`.

10665:   To determine the correct fill value, run with `-info` and search for the string "Fill ratio" to see the value actually needed.

10667:   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`,
10668:   rather than first having `MatMatMult()` create it for you. You can NEVER do this if the matrix `C` is sparse.

10670:   The deprecated `PETSC_DEFAULT` in `fill` also means use the current value

10672:   This is a convenience routine that wraps the use of the `MatProductCreate()` with a `MatProductType` of `MATPRODUCT_AB`
10673:   functionality into a single function call. For more involved matrix-matrix operations see `MatProductCreate()`.

10675:   Example of Usage:
10676: .vb
10677:      MatProductCreate(A,B,NULL,&C);
10678:      MatProductSetType(C,MATPRODUCT_AB);
10679:      MatProductSymbolic(C);
10680:      MatProductNumeric(C); // compute C=A * B
10681:      MatProductReplaceMats(A1,B1,NULL,C); // compute C=A1 * B1
10682:      MatProductNumeric(C);
10683:      MatProductReplaceMats(A2,NULL,NULL,C); // compute C=A2 * B1
10684:      MatProductNumeric(C);
10685: .ve

10687:   Level: intermediate

10689: .seealso: [](ch_matrices), `Mat`, `MatProductType`, `MATPRODUCT_AB`, `MatTransposeMatMult()`, `MatMatTransposeMult()`, `MatPtAP()`, `MatProductCreate()`, `MatProductSymbolic()`, `MatProductReplaceMats()`, `MatProductNumeric()`
10690: @*/
10691: PetscErrorCode MatMatMult(Mat A, Mat B, MatReuse scall, PetscReal fill, Mat *C)
10692: {
10693:   PetscFunctionBegin;
10694:   PetscCall(MatProduct_Private(A, B, scall, fill, MATPRODUCT_AB, C));
10695:   PetscFunctionReturn(PETSC_SUCCESS);
10696: }

10698: /*@
10699:   MatMatTransposeMult - Performs matrix-matrix multiplication $C = A*B^T$.

10701:   Neighbor-wise Collective

10703:   Input Parameters:
10704: + A     - the left matrix
10705: . B     - the right matrix
10706: . scall - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`
10707: - fill  - expected fill as ratio of nnz(C)/(nnz(A) + nnz(B)), use `PETSC_DETERMINE` or `PETSC_CURRENT` if not known

10709:   Output Parameter:
10710: . C - the product matrix

10712:   Options Database Key:
10713: . -matmattransmult_mpidense_mpidense_via {allgatherv,cyclic} - Choose between algorithms for `MATMPIDENSE` matrices: the
10714:               first redundantly copies the transposed `B` matrix on each process and requires O(log P) communication complexity;
10715:               the second never stores more than one portion of the `B` matrix at a time but requires O(P) communication complexity.

10717:   Level: intermediate

10719:   Notes:
10720:   C will be created if `MAT_INITIAL_MATRIX` and must be destroyed by the user with `MatDestroy()`.

10722:   `MAT_REUSE_MATRIX` can only be used if the matrices A and B have the same nonzero pattern as in the previous call

10724:   To determine the correct fill value, run with -info and search for the string "Fill ratio" to see the value
10725:   actually needed.

10727:   This routine is currently only implemented for pairs of `MATSEQAIJ` matrices, for the `MATSEQDENSE` class,
10728:   and for pairs of `MATMPIDENSE` matrices.

10730:   This is a convenience routine that wraps the use of the `MatProductCreate()` with a `MatProductType` of `MATPRODUCT_ABt`
10731:   functionality into a single function call. For more involved matrix-matrix operations see `MatProductCreate()`.

10733:   The deprecated `PETSC_DEFAULT` in `fill` also means use the current value

10735: .seealso: [](ch_matrices), `Mat`, `MatProductCreate()`, `MATPRODUCT_ABt`, `MatMatMult()`, `MatTransposeMatMult()`, `MatPtAP()`, `MatProductAlgorithm`, `MatProductType`
10736: @*/
10737: PetscErrorCode MatMatTransposeMult(Mat A, Mat B, MatReuse scall, PetscReal fill, Mat *C)
10738: {
10739:   PetscFunctionBegin;
10740:   PetscCall(MatProduct_Private(A, B, scall, fill, MATPRODUCT_ABt, C));
10741:   if (A == B) PetscCall(MatSetOption(*C, MAT_SYMMETRIC, PETSC_TRUE));
10742:   PetscFunctionReturn(PETSC_SUCCESS);
10743: }

10745: /*@
10746:   MatTransposeMatMult - Performs matrix-matrix multiplication $C = A^T*B$.

10748:   Neighbor-wise Collective

10750:   Input Parameters:
10751: + A     - the left matrix
10752: . B     - the right matrix
10753: . scall - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`
10754: - fill  - expected fill as ratio of nnz(C)/(nnz(A) + nnz(B)), use `PETSC_DETERMINE` or `PETSC_CURRENT` if not known

10756:   Output Parameter:
10757: . C - the product matrix

10759:   Level: intermediate

10761:   Notes:
10762:   `C` will be created if `MAT_INITIAL_MATRIX` and must be destroyed by the user with `MatDestroy()`.

10764:   `MAT_REUSE_MATRIX` can only be used if `A` and `B` have the same nonzero pattern as in the previous call.

10766:   This is a convenience routine that wraps the use of `MatProductCreate()` with a `MatProductType` of `MATPRODUCT_AtB`
10767:   functionality into a single function call. For more involved matrix-matrix operations see `MatProductCreate()`.

10769:   To determine the correct fill value, run with -info and search for the string "Fill ratio" to see the value
10770:   actually needed.

10772:   This routine is currently implemented for pairs of `MATAIJ` matrices and pairs of `MATSEQDENSE` matrices and classes
10773:   which inherit from `MATSEQAIJ`. `C` will be of the same type as the input matrices.

10775:   The deprecated `PETSC_DEFAULT` in `fill` also means use the current value

10777: .seealso: [](ch_matrices), `Mat`, `MatProductCreate()`, `MATPRODUCT_AtB`, `MatMatMult()`, `MatMatTransposeMult()`, `MatPtAP()`
10778: @*/
10779: PetscErrorCode MatTransposeMatMult(Mat A, Mat B, MatReuse scall, PetscReal fill, Mat *C)
10780: {
10781:   PetscFunctionBegin;
10782:   PetscCall(MatProduct_Private(A, B, scall, fill, MATPRODUCT_AtB, C));
10783:   PetscFunctionReturn(PETSC_SUCCESS);
10784: }

10786: /*@
10787:   MatMatMatMult - Performs matrix-matrix-matrix multiplication D=A*B*C.

10789:   Neighbor-wise Collective

10791:   Input Parameters:
10792: + A     - the left matrix
10793: . B     - the middle matrix
10794: . C     - the right matrix
10795: . scall - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`
10796: - 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
10797:           if the result is a dense matrix this is irrelevant

10799:   Output Parameter:
10800: . D - the product matrix

10802:   Level: intermediate

10804:   Notes:
10805:   Unless `scall` is `MAT_REUSE_MATRIX` `D` will be created.

10807:   `MAT_REUSE_MATRIX` can only be used if the matrices `A`, `B`, and `C` have the same nonzero pattern as in the previous call

10809:   This is a convenience routine that wraps the use of the `MatProductCreate()` with a `MatProductType` of `MATPRODUCT_ABC`
10810:   functionality into a single function call. For more involved matrix-matrix operations see `MatProductCreate()`.

10812:   To determine the correct fill value, run with `-info` and search for the string "Fill ratio" to see the value
10813:   actually needed.

10815:   If you have many matrices with the same non-zero structure to multiply, you
10816:   should use `MAT_REUSE_MATRIX` in all calls but the first

10818:   The deprecated `PETSC_DEFAULT` in `fill` also means use the current value

10820: .seealso: [](ch_matrices), `Mat`, `MatProductCreate()`, `MATPRODUCT_ABC`, `MatMatMult`, `MatPtAP()`, `MatMatTransposeMult()`, `MatTransposeMatMult()`
10821: @*/
10822: PetscErrorCode MatMatMatMult(Mat A, Mat B, Mat C, MatReuse scall, PetscReal fill, Mat *D)
10823: {
10824:   PetscFunctionBegin;
10825:   if (scall == MAT_REUSE_MATRIX) MatCheckProduct(*D, 6);
10826:   PetscCheck(scall != MAT_INPLACE_MATRIX, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "Inplace product not supported");

10828:   if (scall == MAT_INITIAL_MATRIX) {
10829:     PetscCall(MatProductCreate(A, B, C, D));
10830:     PetscCall(MatProductSetType(*D, MATPRODUCT_ABC));
10831:     PetscCall(MatProductSetAlgorithm(*D, "default"));
10832:     PetscCall(MatProductSetFill(*D, fill));

10834:     (*D)->product->api_user = PETSC_TRUE;
10835:     PetscCall(MatProductSetFromOptions(*D));
10836:     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,
10837:                ((PetscObject)C)->type_name);
10838:     PetscCall(MatProductSymbolic(*D));
10839:   } else { /* user may change input matrices when REUSE */
10840:     PetscCall(MatProductReplaceMats(A, B, C, *D));
10841:   }
10842:   PetscCall(MatProductNumeric(*D));
10843:   PetscFunctionReturn(PETSC_SUCCESS);
10844: }

10846: /*@
10847:   MatCreateRedundantMatrix - Create redundant matrices and put them into processes of subcommunicators.

10849:   Collective

10851:   Input Parameters:
10852: + mat      - the matrix
10853: . nsubcomm - the number of subcommunicators (= number of redundant parallel or sequential matrices)
10854: . subcomm  - MPI communicator split from the communicator where mat resides in (or `MPI_COMM_NULL` if nsubcomm is used)
10855: - reuse    - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`

10857:   Output Parameter:
10858: . matredundant - redundant matrix

10860:   Level: advanced

10862:   Notes:
10863:   `MAT_REUSE_MATRIX` can only be used when the nonzero structure of the
10864:   original matrix has not changed from that last call to `MatCreateRedundantMatrix()`.

10866:   This routine creates the duplicated matrices in the subcommunicators; you should NOT create them before
10867:   calling it.

10869:   `PetscSubcommCreate()` can be used to manage the creation of the subcomm but need not be.

10871: .seealso: [](ch_matrices), `Mat`, `MatDestroy()`, `PetscSubcommCreate()`, `PetscSubcomm`
10872: @*/
10873: PetscErrorCode MatCreateRedundantMatrix(Mat mat, PetscInt nsubcomm, MPI_Comm subcomm, MatReuse reuse, Mat *matredundant)
10874: {
10875:   MPI_Comm       comm;
10876:   PetscMPIInt    size;
10877:   PetscInt       mloc_sub, nloc_sub, rstart, rend, M = mat->rmap->N, N = mat->cmap->N, bs = mat->rmap->bs;
10878:   Mat_Redundant *redund     = NULL;
10879:   PetscSubcomm   psubcomm   = NULL;
10880:   MPI_Comm       subcomm_in = subcomm;
10881:   Mat           *matseq;
10882:   IS             isrow, iscol;
10883:   PetscBool      newsubcomm = PETSC_FALSE;

10885:   PetscFunctionBegin;
10887:   if (nsubcomm && reuse == MAT_REUSE_MATRIX) {
10888:     PetscAssertPointer(*matredundant, 5);
10890:   }

10892:   PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)mat), &size));
10893:   if (size == 1 || nsubcomm == 1) {
10894:     if (reuse == MAT_INITIAL_MATRIX) {
10895:       PetscCall(MatDuplicate(mat, MAT_COPY_VALUES, matredundant));
10896:     } else {
10897:       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");
10898:       PetscCall(MatCopy(mat, *matredundant, SAME_NONZERO_PATTERN));
10899:     }
10900:     PetscFunctionReturn(PETSC_SUCCESS);
10901:   }

10903:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
10904:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
10905:   MatCheckPreallocated(mat, 1);

10907:   PetscCall(PetscLogEventBegin(MAT_RedundantMat, mat, 0, 0, 0));
10908:   if (subcomm_in == MPI_COMM_NULL && reuse == MAT_INITIAL_MATRIX) { /* get subcomm if user does not provide subcomm */
10909:     /* create psubcomm, then get subcomm */
10910:     PetscCall(PetscObjectGetComm((PetscObject)mat, &comm));
10911:     PetscCallMPI(MPI_Comm_size(comm, &size));
10912:     PetscCheck(nsubcomm >= 1 && nsubcomm <= size, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "nsubcomm must between 1 and %d", size);

10914:     PetscCall(PetscSubcommCreate(comm, &psubcomm));
10915:     PetscCall(PetscSubcommSetNumber(psubcomm, nsubcomm));
10916:     PetscCall(PetscSubcommSetType(psubcomm, PETSC_SUBCOMM_CONTIGUOUS));
10917:     PetscCall(PetscSubcommSetFromOptions(psubcomm));
10918:     PetscCall(PetscCommDuplicate(PetscSubcommChild(psubcomm), &subcomm, NULL));
10919:     newsubcomm = PETSC_TRUE;
10920:     PetscCall(PetscSubcommDestroy(&psubcomm));
10921:   }

10923:   /* get isrow, iscol and a local sequential matrix matseq[0] */
10924:   if (reuse == MAT_INITIAL_MATRIX) {
10925:     mloc_sub = PETSC_DECIDE;
10926:     nloc_sub = PETSC_DECIDE;
10927:     if (bs < 1) {
10928:       PetscCall(PetscSplitOwnership(subcomm, &mloc_sub, &M));
10929:       PetscCall(PetscSplitOwnership(subcomm, &nloc_sub, &N));
10930:     } else {
10931:       PetscCall(PetscSplitOwnershipBlock(subcomm, bs, &mloc_sub, &M));
10932:       PetscCall(PetscSplitOwnershipBlock(subcomm, bs, &nloc_sub, &N));
10933:     }
10934:     PetscCallMPI(MPI_Scan(&mloc_sub, &rend, 1, MPIU_INT, MPI_SUM, subcomm));
10935:     rstart = rend - mloc_sub;
10936:     PetscCall(ISCreateStride(PETSC_COMM_SELF, mloc_sub, rstart, 1, &isrow));
10937:     PetscCall(ISCreateStride(PETSC_COMM_SELF, N, 0, 1, &iscol));
10938:     PetscCall(ISSetIdentity(iscol));
10939:   } else { /* reuse == MAT_REUSE_MATRIX */
10940:     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");
10941:     /* retrieve subcomm */
10942:     PetscCall(PetscObjectGetComm((PetscObject)*matredundant, &subcomm));
10943:     redund = (*matredundant)->redundant;
10944:     isrow  = redund->isrow;
10945:     iscol  = redund->iscol;
10946:     matseq = redund->matseq;
10947:   }
10948:   PetscCall(MatCreateSubMatrices(mat, 1, &isrow, &iscol, reuse, &matseq));

10950:   /* get matredundant over subcomm */
10951:   if (reuse == MAT_INITIAL_MATRIX) {
10952:     PetscCall(MatCreateMPIMatConcatenateSeqMat(subcomm, matseq[0], nloc_sub, reuse, matredundant));

10954:     /* create a supporting struct and attach it to C for reuse */
10955:     PetscCall(PetscNew(&redund));
10956:     (*matredundant)->redundant = redund;
10957:     redund->isrow              = isrow;
10958:     redund->iscol              = iscol;
10959:     redund->matseq             = matseq;
10960:     if (newsubcomm) {
10961:       redund->subcomm = subcomm;
10962:     } else {
10963:       redund->subcomm = MPI_COMM_NULL;
10964:     }
10965:   } else {
10966:     PetscCall(MatCreateMPIMatConcatenateSeqMat(subcomm, matseq[0], PETSC_DECIDE, reuse, matredundant));
10967:   }
10968: #if PetscDefined(HAVE_VIENNACL) || PetscDefined(HAVE_CUDA) || PetscDefined(HAVE_HIP)
10969:   if (matseq[0]->boundtocpu && matseq[0]->bindingpropagates) {
10970:     PetscCall(MatBindToCPU(*matredundant, PETSC_TRUE));
10971:     PetscCall(MatSetBindingPropagates(*matredundant, PETSC_TRUE));
10972:   }
10973: #endif
10974:   PetscCall(PetscLogEventEnd(MAT_RedundantMat, mat, 0, 0, 0));
10975:   PetscFunctionReturn(PETSC_SUCCESS);
10976: }

10978: /*@
10979:   MatGetMultiProcBlock - Create multiple 'parallel submatrices' from
10980:   a given `Mat`. Each submatrix can span multiple procs.

10982:   Collective

10984:   Input Parameters:
10985: + mat     - the matrix
10986: . subComm - the sub communicator obtained as if by `MPI_Comm_split(PetscObjectComm((PetscObject)mat))`
10987: - scall   - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`

10989:   Output Parameter:
10990: . subMat - parallel sub-matrices each spanning a given `subcomm`

10992:   Level: advanced

10994:   Notes:
10995:   The submatrix partition across processes is dictated by `subComm` a
10996:   communicator obtained by `MPI_comm_split()` or via `PetscSubcommCreate()`. The `subComm`
10997:   is not restricted to be grouped with consecutive original MPI processes.

10999:   Due the `MPI_Comm_split()` usage, the parallel layout of the submatrices
11000:   map directly to the layout of the original matrix [wrt the local
11001:   row,col partitioning]. So the original 'DiagonalMat' naturally maps
11002:   into the 'DiagonalMat' of the `subMat`, hence it is used directly from
11003:   the `subMat`. However the offDiagMat looses some columns - and this is
11004:   reconstructed with `MatSetValues()`

11006:   This is used by `PCBJACOBI` when a single block spans multiple MPI processes.

11008: .seealso: [](ch_matrices), `Mat`, `MatCreateRedundantMatrix()`, `MatCreateSubMatrices()`, `PCBJACOBI`
11009: @*/
11010: PetscErrorCode MatGetMultiProcBlock(Mat mat, MPI_Comm subComm, MatReuse scall, Mat *subMat)
11011: {
11012:   PetscMPIInt commsize, subCommSize;

11014:   PetscFunctionBegin;
11015:   PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)mat), &commsize));
11016:   PetscCallMPI(MPI_Comm_size(subComm, &subCommSize));
11017:   PetscCheck(subCommSize <= commsize, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_OUTOFRANGE, "CommSize %d < SubCommZize %d", commsize, subCommSize);

11019:   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");
11020:   PetscCall(PetscLogEventBegin(MAT_GetMultiProcBlock, mat, 0, 0, 0));
11021:   PetscUseTypeMethod(mat, getmultiprocblock, subComm, scall, subMat);
11022:   PetscCall(PetscLogEventEnd(MAT_GetMultiProcBlock, mat, 0, 0, 0));
11023:   PetscFunctionReturn(PETSC_SUCCESS);
11024: }

11026: /*@
11027:   MatGetLocalSubMatrix - Gets a reference to a submatrix specified in local numbering

11029:   Not Collective

11031:   Input Parameters:
11032: + mat   - matrix to extract local submatrix from
11033: . isrow - local row indices for submatrix
11034: - iscol - local column indices for submatrix

11036:   Output Parameter:
11037: . submat - the submatrix

11039:   Level: intermediate

11041:   Notes:
11042:   `submat` should be disposed of with `MatRestoreLocalSubMatrix()`.

11044:   Depending on the format of `mat`, the returned `submat` may not implement `MatMult()`. Its communicator may be
11045:   the same as `mat`, it may be `PETSC_COMM_SELF`, or some other sub-communictor of `mat`'s.

11047:   `submat` always implements `MatSetValuesLocal()`. If `isrow` and `iscol` have the same block size, then
11048:   `MatSetValuesBlockedLocal()` will also be implemented.

11050:   `mat` must have had a `ISLocalToGlobalMapping` provided to it with `MatSetLocalToGlobalMapping()`.
11051:   Matrices obtained with `DMCreateMatrix()` generally already have the local to global mapping provided.

11053: .seealso: [](ch_matrices), `Mat`, `MatRestoreLocalSubMatrix()`, `MatCreateLocalRef()`, `MatSetLocalToGlobalMapping()`
11054: @*/
11055: PetscErrorCode MatGetLocalSubMatrix(Mat mat, IS isrow, IS iscol, Mat *submat)
11056: {
11057:   PetscFunctionBegin;
11061:   PetscCheckSameComm(isrow, 2, iscol, 3);
11062:   PetscAssertPointer(submat, 4);
11063:   PetscCheck(mat->rmap->mapping, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Matrix must have local to global mapping provided before this call");

11065:   if (mat->ops->getlocalsubmatrix) {
11066:     PetscUseTypeMethod(mat, getlocalsubmatrix, isrow, iscol, submat);
11067:   } else {
11068:     PetscCall(MatCreateLocalRef(mat, isrow, iscol, submat));
11069:   }
11070:   (*submat)->assembled = mat->assembled;
11071:   PetscFunctionReturn(PETSC_SUCCESS);
11072: }

11074: /*@
11075:   MatRestoreLocalSubMatrix - Restores a reference to a submatrix specified in local numbering obtained with `MatGetLocalSubMatrix()`

11077:   Not Collective

11079:   Input Parameters:
11080: + mat    - matrix to extract local submatrix from
11081: . isrow  - local row indices for submatrix
11082: . iscol  - local column indices for submatrix
11083: - submat - the submatrix

11085:   Level: intermediate

11087: .seealso: [](ch_matrices), `Mat`, `MatGetLocalSubMatrix()`
11088: @*/
11089: PetscErrorCode MatRestoreLocalSubMatrix(Mat mat, IS isrow, IS iscol, Mat *submat)
11090: {
11091:   PetscFunctionBegin;
11095:   PetscCheckSameComm(isrow, 2, iscol, 3);
11096:   PetscAssertPointer(submat, 4);

11099:   if (mat->ops->restorelocalsubmatrix) {
11100:     PetscUseTypeMethod(mat, restorelocalsubmatrix, isrow, iscol, submat);
11101:   } else {
11102:     PetscCall(MatDestroy(submat));
11103:   }
11104:   *submat = NULL;
11105:   PetscFunctionReturn(PETSC_SUCCESS);
11106: }

11108: /*@
11109:   MatFindZeroDiagonals - Finds all the rows of a matrix that have zero or no diagonal entry in the matrix

11111:   Collective

11113:   Input Parameter:
11114: . mat - the matrix

11116:   Output Parameter:
11117: . is - if any rows have zero diagonals this contains the list of them

11119:   Level: developer

11121: .seealso: [](ch_matrices), `Mat`, `MatMultTranspose()`, `MatMultAdd()`, `MatMultTransposeAdd()`
11122: @*/
11123: PetscErrorCode MatFindZeroDiagonals(Mat mat, IS *is)
11124: {
11125:   PetscFunctionBegin;
11128:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
11129:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");

11131:   if (!mat->ops->findzerodiagonals) {
11132:     Vec                diag;
11133:     const PetscScalar *a;
11134:     PetscInt          *rows;
11135:     PetscInt           rStart, rEnd, r, nrow = 0;

11137:     PetscCall(MatCreateVecs(mat, &diag, NULL));
11138:     PetscCall(MatGetDiagonal(mat, diag));
11139:     PetscCall(MatGetOwnershipRange(mat, &rStart, &rEnd));
11140:     PetscCall(VecGetArrayRead(diag, &a));
11141:     for (r = 0; r < rEnd - rStart; ++r)
11142:       if (a[r] == 0.0) ++nrow;
11143:     PetscCall(PetscMalloc1(nrow, &rows));
11144:     nrow = 0;
11145:     for (r = 0; r < rEnd - rStart; ++r)
11146:       if (a[r] == 0.0) rows[nrow++] = r + rStart;
11147:     PetscCall(VecRestoreArrayRead(diag, &a));
11148:     PetscCall(VecDestroy(&diag));
11149:     PetscCall(ISCreateGeneral(PetscObjectComm((PetscObject)mat), nrow, rows, PETSC_OWN_POINTER, is));
11150:   } else {
11151:     PetscUseTypeMethod(mat, findzerodiagonals, is);
11152:   }
11153:   PetscFunctionReturn(PETSC_SUCCESS);
11154: }

11156: /*@
11157:   MatFindOffBlockDiagonalEntries - Finds all the rows of a matrix that have entries outside of the main diagonal block (defined by the matrix block size)

11159:   Collective

11161:   Input Parameter:
11162: . mat - the matrix

11164:   Output Parameter:
11165: . is - contains the list of rows with off block diagonal entries

11167:   Level: developer

11169: .seealso: [](ch_matrices), `Mat`, `MatMultTranspose()`, `MatMultAdd()`, `MatMultTransposeAdd()`
11170: @*/
11171: PetscErrorCode MatFindOffBlockDiagonalEntries(Mat mat, IS *is)
11172: {
11173:   PetscFunctionBegin;
11176:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
11177:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");

11179:   PetscUseTypeMethod(mat, findoffblockdiagonalentries, is);
11180:   PetscFunctionReturn(PETSC_SUCCESS);
11181: }

11183: /*@
11184:   MatInvertBlockDiagonal - Inverts the block diagonal entries.

11186:   Collective; No Fortran Support

11188:   Input Parameter:
11189: . mat - the matrix

11191:   Output Parameter:
11192: . values - the block inverses in column major order (FORTRAN-like)

11194:   Level: advanced

11196:   Notes:
11197:   The size of the blocks is determined by the block size of the matrix.

11199:   The blocks never overlap between two MPI processes, use `MatInvertVariableBlockEnvelope()` for that case

11201:   The blocks all have the same size, use `MatInvertVariableBlockDiagonal()` for variable block size

11203: .seealso: [](ch_matrices), `Mat`, `MatInvertVariableBlockEnvelope()`, `MatInvertBlockDiagonalMat()`
11204: @*/
11205: PetscErrorCode MatInvertBlockDiagonal(Mat mat, const PetscScalar *values[])
11206: {
11207:   PetscFunctionBegin;
11209:   PetscCheck(mat->assembled, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
11210:   PetscCheck(!mat->factortype, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
11211:   PetscUseTypeMethod(mat, invertblockdiagonal, values);
11212:   PetscFunctionReturn(PETSC_SUCCESS);
11213: }

11215: /*@
11216:   MatInvertVariableBlockDiagonal - Inverts the point block diagonal entries.

11218:   Collective; No Fortran Support

11220:   Input Parameters:
11221: + mat     - the matrix
11222: . nblocks - the number of blocks on the process, set with `MatSetVariableBlockSizes()`
11223: - bsizes  - the size of each block on the process, set with `MatSetVariableBlockSizes()`

11225:   Output Parameter:
11226: . values - the block inverses in column major order (FORTRAN-like)

11228:   Level: advanced

11230:   Notes:
11231:   Use `MatInvertBlockDiagonal()` if all blocks have the same size

11233:   The blocks never overlap between two MPI processes, use `MatInvertVariableBlockEnvelope()` for that case

11235: .seealso: [](ch_matrices), `Mat`, `MatInvertBlockDiagonal()`, `MatSetVariableBlockSizes()`, `MatInvertVariableBlockEnvelope()`
11236: @*/
11237: PetscErrorCode MatInvertVariableBlockDiagonal(Mat mat, PetscInt nblocks, const PetscInt bsizes[], PetscScalar values[])
11238: {
11239:   PetscFunctionBegin;
11241:   PetscCheck(mat->assembled, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
11242:   PetscCheck(!mat->factortype, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
11243:   PetscUseTypeMethod(mat, invertvariableblockdiagonal, nblocks, bsizes, values);
11244:   PetscFunctionReturn(PETSC_SUCCESS);
11245: }

11247: /*@
11248:   MatInvertBlockDiagonalMat - set the values of matrix C to be the inverted block diagonal of matrix A

11250:   Collective

11252:   Input Parameters:
11253: + A - the matrix
11254: - C - matrix with inverted block diagonal of `A`. This matrix should be created and may have its type set.

11256:   Level: advanced

11258:   Note:
11259:   The blocksize of the matrix is used to determine the blocks on the diagonal of `C`

11261: .seealso: [](ch_matrices), `Mat`, `MatInvertBlockDiagonal()`
11262: @*/
11263: PetscErrorCode MatInvertBlockDiagonalMat(Mat A, Mat C)
11264: {
11265:   const PetscScalar *vals;
11266:   PetscInt          *dnnz;
11267:   PetscInt           m, rstart, rend, bs, i, j;

11269:   PetscFunctionBegin;
11270:   PetscCall(MatInvertBlockDiagonal(A, &vals));
11271:   PetscCall(MatGetBlockSize(A, &bs));
11272:   PetscCall(MatGetLocalSize(A, &m, NULL));
11273:   PetscCall(MatSetLayouts(C, A->rmap, A->cmap));
11274:   PetscCall(MatSetBlockSizes(C, A->rmap->bs, A->cmap->bs));
11275:   PetscCall(PetscMalloc1(m / bs, &dnnz));
11276:   for (j = 0; j < m / bs; j++) dnnz[j] = 1;
11277:   PetscCall(MatXAIJSetPreallocation(C, bs, dnnz, NULL, NULL, NULL));
11278:   PetscCall(PetscFree(dnnz));
11279:   PetscCall(MatGetOwnershipRange(C, &rstart, &rend));
11280:   PetscCall(MatSetOption(C, MAT_ROW_ORIENTED, PETSC_FALSE));
11281:   for (i = rstart / bs; i < rend / bs; i++) PetscCall(MatSetValuesBlocked(C, 1, &i, 1, &i, &vals[(i - rstart / bs) * bs * bs], INSERT_VALUES));
11282:   PetscCall(MatSetOption(C, MAT_NO_OFF_PROC_ENTRIES, PETSC_TRUE));
11283:   PetscCall(MatAssemblyBegin(C, MAT_FINAL_ASSEMBLY));
11284:   PetscCall(MatAssemblyEnd(C, MAT_FINAL_ASSEMBLY));
11285:   PetscCall(MatSetOption(C, MAT_NO_OFF_PROC_ENTRIES, PETSC_FALSE));
11286:   PetscCall(MatSetOption(C, MAT_ROW_ORIENTED, PETSC_TRUE));
11287:   PetscFunctionReturn(PETSC_SUCCESS);
11288: }

11290: /*@
11291:   MatTransposeColoringDestroy - Destroys a coloring context for matrix product $C = A*B^T$ that was created
11292:   via `MatTransposeColoringCreate()`.

11294:   Collective

11296:   Input Parameter:
11297: . c - coloring context

11299:   Level: intermediate

11301: .seealso: [](ch_matrices), `Mat`, `MatTransposeColoringCreate()`
11302: @*/
11303: PetscErrorCode MatTransposeColoringDestroy(MatTransposeColoring *c)
11304: {
11305:   MatTransposeColoring matcolor = *c;

11307:   PetscFunctionBegin;
11308:   if (!matcolor) PetscFunctionReturn(PETSC_SUCCESS);
11309:   if (--((PetscObject)matcolor)->refct > 0) {
11310:     matcolor = NULL;
11311:     PetscFunctionReturn(PETSC_SUCCESS);
11312:   }

11314:   PetscCall(PetscFree3(matcolor->ncolumns, matcolor->nrows, matcolor->colorforrow));
11315:   PetscCall(PetscFree(matcolor->rows));
11316:   PetscCall(PetscFree(matcolor->den2sp));
11317:   PetscCall(PetscFree(matcolor->colorforcol));
11318:   PetscCall(PetscFree(matcolor->columns));
11319:   if (matcolor->brows > 0) PetscCall(PetscFree(matcolor->lstart));
11320:   PetscCall(PetscHeaderDestroy(c));
11321:   PetscFunctionReturn(PETSC_SUCCESS);
11322: }

11324: /*@
11325:   MatTransColoringApplySpToDen - Given a symbolic matrix product $C = A*B^T$ for which
11326:   a `MatTransposeColoring` context has been created, computes a dense $B^T$ by applying
11327:   `MatTransposeColoring` to sparse `B`.

11329:   Collective

11331:   Input Parameters:
11332: + coloring - coloring context created with `MatTransposeColoringCreate()`
11333: - B        - sparse matrix

11335:   Output Parameter:
11336: . Btdense - dense matrix $B^T$

11338:   Level: developer

11340:   Note:
11341:   These are used internally for some implementations of `MatRARt()`

11343: .seealso: [](ch_matrices), `Mat`, `MatTransposeColoringCreate()`, `MatTransposeColoringDestroy()`, `MatTransColoringApplyDenToSp()`
11344: @*/
11345: PetscErrorCode MatTransColoringApplySpToDen(MatTransposeColoring coloring, Mat B, Mat Btdense)
11346: {
11347:   PetscFunctionBegin;

11352:   PetscCall((*B->ops->transcoloringapplysptoden)(coloring, B, Btdense));
11353:   PetscFunctionReturn(PETSC_SUCCESS);
11354: }

11356: /*@
11357:   MatTransColoringApplyDenToSp - Given a symbolic matrix product $C_{sp} = A*B^T$ for which
11358:   a `MatTransposeColoring` context has been created and a dense matrix $C_{den} = A*B^T_{dense}$
11359:   in which `B^T_{dens}` is obtained from `MatTransColoringApplySpToDen()`, recover sparse matrix
11360:   $C_{sp}$ from $C_{den}$.

11362:   Collective

11364:   Input Parameters:
11365: + matcoloring - coloring context created with `MatTransposeColoringCreate()`
11366: - Cden        - matrix product of a sparse matrix and a dense matrix Btdense

11368:   Output Parameter:
11369: . Csp - sparse matrix

11371:   Level: developer

11373:   Note:
11374:   These are used internally for some implementations of `MatRARt()`

11376: .seealso: [](ch_matrices), `Mat`, `MatTransposeColoringCreate()`, `MatTransposeColoringDestroy()`, `MatTransColoringApplySpToDen()`
11377: @*/
11378: PetscErrorCode MatTransColoringApplyDenToSp(MatTransposeColoring matcoloring, Mat Cden, Mat Csp)
11379: {
11380:   PetscFunctionBegin;

11385:   PetscCall((*Csp->ops->transcoloringapplydentosp)(matcoloring, Cden, Csp));
11386:   PetscCall(MatAssemblyBegin(Csp, MAT_FINAL_ASSEMBLY));
11387:   PetscCall(MatAssemblyEnd(Csp, MAT_FINAL_ASSEMBLY));
11388:   PetscFunctionReturn(PETSC_SUCCESS);
11389: }

11391: /*@
11392:   MatTransposeColoringCreate - Creates a matrix coloring context for the matrix product $C = A*B^T$.

11394:   Collective

11396:   Input Parameters:
11397: + mat        - the matrix product C
11398: - iscoloring - the coloring of the matrix; usually obtained with `MatColoringCreate()` or `DMCreateColoring()`

11400:   Output Parameter:
11401: . color - the new coloring context

11403:   Level: intermediate

11405: .seealso: [](ch_matrices), `Mat`, `MatTransposeColoringDestroy()`, `MatTransColoringApplySpToDen()`,
11406:           `MatTransColoringApplyDenToSp()`
11407: @*/
11408: PetscErrorCode MatTransposeColoringCreate(Mat mat, ISColoring iscoloring, MatTransposeColoring *color)
11409: {
11410:   MatTransposeColoring c;
11411:   MPI_Comm             comm;

11413:   PetscFunctionBegin;
11414:   PetscAssertPointer(color, 3);

11416:   PetscCall(PetscLogEventBegin(MAT_TransposeColoringCreate, mat, 0, 0, 0));
11417:   PetscCall(PetscObjectGetComm((PetscObject)mat, &comm));
11418:   PetscCall(PetscHeaderCreate(c, MAT_TRANSPOSECOLORING_CLASSID, "MatTransposeColoring", "Matrix product C=A*B^T via coloring", "Mat", comm, MatTransposeColoringDestroy, NULL));
11419:   c->ctype = iscoloring->ctype;
11420:   PetscUseTypeMethod(mat, transposecoloringcreate, iscoloring, c);
11421:   *color = c;
11422:   PetscCall(PetscLogEventEnd(MAT_TransposeColoringCreate, mat, 0, 0, 0));
11423:   PetscFunctionReturn(PETSC_SUCCESS);
11424: }

11426: /*@
11427:   MatGetNonzeroState - Returns a 64-bit integer representing the current state of nonzeros in the matrix. If the
11428:   matrix has had new nonzero locations added to (or removed from) the matrix since the previous call, the value will be larger.

11430:   Not Collective

11432:   Input Parameter:
11433: . mat - the matrix

11435:   Output Parameter:
11436: . state - the current state

11438:   Level: intermediate

11440:   Notes:
11441:   You can only compare states from two different calls to the SAME matrix, you cannot compare calls between
11442:   different matrices

11444:   Use `PetscObjectStateGet()` to check for changes to the numerical values in a matrix

11446:   Use the result of `PetscObjectGetId()` to compare if a previously checked matrix is the same as the current matrix, do not compare object pointers.

11448: .seealso: [](ch_matrices), `Mat`, `PetscObjectStateGet()`, `PetscObjectGetId()`
11449: @*/
11450: PetscErrorCode MatGetNonzeroState(Mat mat, PetscObjectState *state)
11451: {
11452:   PetscFunctionBegin;
11454:   *state = mat->nonzerostate;
11455:   PetscFunctionReturn(PETSC_SUCCESS);
11456: }

11458: /*@
11459:   MatCreateMPIMatConcatenateSeqMat - Creates a single large PETSc matrix by concatenating sequential
11460:   matrices from each process

11462:   Collective

11464:   Input Parameters:
11465: + comm   - the communicators the parallel matrix will live on
11466: . seqmat - the input sequential matrices
11467: . n      - number of local columns (or `PETSC_DECIDE`)
11468: - reuse  - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`

11470:   Output Parameter:
11471: . mpimat - the parallel matrix generated

11473:   Level: developer

11475:   Note:
11476:   The number of columns of the matrix in EACH process MUST be the same.

11478: .seealso: [](ch_matrices), `Mat`
11479: @*/
11480: PetscErrorCode MatCreateMPIMatConcatenateSeqMat(MPI_Comm comm, Mat seqmat, PetscInt n, MatReuse reuse, Mat *mpimat)
11481: {
11482:   PetscMPIInt size;

11484:   PetscFunctionBegin;
11485:   PetscCallMPI(MPI_Comm_size(comm, &size));
11486:   if (size == 1) {
11487:     if (reuse == MAT_INITIAL_MATRIX) {
11488:       PetscCall(MatDuplicate(seqmat, MAT_COPY_VALUES, mpimat));
11489:     } else {
11490:       PetscCall(MatCopy(seqmat, *mpimat, SAME_NONZERO_PATTERN));
11491:     }
11492:     PetscFunctionReturn(PETSC_SUCCESS);
11493:   }

11495:   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");

11497:   PetscCall(PetscLogEventBegin(MAT_Merge, seqmat, 0, 0, 0));
11498:   PetscCall((*seqmat->ops->creatempimatconcatenateseqmat)(comm, seqmat, n, reuse, mpimat));
11499:   PetscCall(PetscLogEventEnd(MAT_Merge, seqmat, 0, 0, 0));
11500:   PetscFunctionReturn(PETSC_SUCCESS);
11501: }

11503: /*@
11504:   MatSubdomainsCreateCoalesce - Creates index subdomains by coalescing adjacent MPI processes' ownership ranges.

11506:   Collective

11508:   Input Parameters:
11509: + A - the matrix to create subdomains from
11510: - N - requested number of subdomains

11512:   Output Parameters:
11513: + n   - number of subdomains resulting on this MPI process
11514: - iss - `IS` list with indices of subdomains on this MPI process

11516:   Level: advanced

11518:   Note:
11519:   The number of subdomains must be smaller than the communicator size

11521: .seealso: [](ch_matrices), `Mat`, `IS`
11522: @*/
11523: PetscErrorCode MatSubdomainsCreateCoalesce(Mat A, PetscInt N, PetscInt *n, IS *iss[])
11524: {
11525:   MPI_Comm    comm, subcomm;
11526:   PetscMPIInt size, rank, color;
11527:   PetscInt    rstart, rend, k;

11529:   PetscFunctionBegin;
11530:   PetscCall(PetscObjectGetComm((PetscObject)A, &comm));
11531:   PetscCallMPI(MPI_Comm_size(comm, &size));
11532:   PetscCallMPI(MPI_Comm_rank(comm, &rank));
11533:   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);
11534:   *n    = 1;
11535:   k     = size / N + (size % N > 0); /* There are up to k ranks to a color */
11536:   color = rank / k;
11537:   PetscCallMPI(MPI_Comm_split(comm, color, rank, &subcomm));
11538:   PetscCall(PetscMalloc1(1, iss));
11539:   PetscCall(MatGetOwnershipRange(A, &rstart, &rend));
11540:   PetscCall(ISCreateStride(subcomm, rend - rstart, rstart, 1, iss[0]));
11541:   PetscCallMPI(MPI_Comm_free(&subcomm));
11542:   PetscFunctionReturn(PETSC_SUCCESS);
11543: }

11545: /*@
11546:   MatGalerkin - Constructs the coarse grid problem matrix via Galerkin projection.

11548:   If the interpolation and restriction operators are the same, uses `MatPtAP()`.
11549:   If they are not the same, uses `MatMatMatMult()`.

11551:   Once the coarse grid problem is constructed, correct for interpolation operators
11552:   that are not of full rank, which can legitimately happen in the case of non-nested
11553:   geometric multigrid.

11555:   Input Parameters:
11556: + restrct     - restriction operator
11557: . dA          - fine grid matrix
11558: . interpolate - interpolation operator
11559: . reuse       - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`
11560: - fill        - expected fill, use `PETSC_DETERMINE` or `PETSC_DETERMINE` if you do not have a good estimate

11562:   Output Parameter:
11563: . A - the Galerkin coarse matrix

11565:   Options Database Key:
11566: . -pc_mg_galerkin (both|pmat|mat|none) - for what matrices the Galerkin process should be used

11568:   Level: developer

11570:   Note:
11571:   The deprecated `PETSC_DEFAULT` in `fill` also means use the current value

11573: .seealso: [](ch_matrices), `Mat`, `MatPtAP()`, `MatMatMatMult()`
11574: @*/
11575: PetscErrorCode MatGalerkin(Mat restrct, Mat dA, Mat interpolate, MatReuse reuse, PetscReal fill, Mat *A)
11576: {
11577:   IS  zerorows;
11578:   Vec diag;

11580:   PetscFunctionBegin;
11581:   PetscCheck(reuse != MAT_INPLACE_MATRIX, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "Inplace product not supported");
11582:   /* Construct the coarse grid matrix */
11583:   if (interpolate == restrct) {
11584:     PetscCall(MatPtAP(dA, interpolate, reuse, fill, A));
11585:   } else {
11586:     PetscCall(MatMatMatMult(restrct, dA, interpolate, reuse, fill, A));
11587:   }

11589:   /* If the interpolation matrix is not of full rank, A will have zero rows.
11590:      This can legitimately happen in the case of non-nested geometric multigrid.
11591:      In that event, we set the rows of the matrix to the rows of the identity,
11592:      ignoring the equations (as the RHS will also be zero). */

11594:   PetscCall(MatFindZeroRows(*A, &zerorows));

11596:   if (zerorows != NULL) { /* if there are any zero rows */
11597:     PetscCall(MatCreateVecs(*A, &diag, NULL));
11598:     PetscCall(MatGetDiagonal(*A, diag));
11599:     PetscCall(VecISSet(diag, zerorows, 1.0));
11600:     PetscCall(MatDiagonalSet(*A, diag, INSERT_VALUES));
11601:     PetscCall(VecDestroy(&diag));
11602:     PetscCall(ISDestroy(&zerorows));
11603:   }
11604:   PetscFunctionReturn(PETSC_SUCCESS);
11605: }

11607: /*@
11608:   MatSetOperation - Allows user to set a matrix operation for any matrix type

11610:   Logically Collective

11612:   Input Parameters:
11613: + mat - the matrix
11614: . op  - the name of the operation
11615: - f   - the function that provides the operation

11617:   Level: developer

11619:   Example Usage:
11620: .vb
11621:   extern PetscErrorCode usermult(Mat, Vec, Vec);

11623:   PetscCall(MatCreateXXX(comm, ..., &A));
11624:   PetscCall(MatSetOperation(A, MATOP_MULT, (PetscErrorCodeFn *)usermult));
11625: .ve

11627:   Notes:
11628:   See the file `include/petscmat.h` for a complete list of matrix
11629:   operations, which all have the form MATOP_<OPERATION>, where
11630:   <OPERATION> is the name (in all capital letters) of the
11631:   user interface routine (e.g., `MatMult()` -> `MATOP_MULT`).

11633:   All user-provided functions (except for `MATOP_DESTROY`) should have the same calling
11634:   sequence as the usual matrix interface routines, since they
11635:   are intended to be accessed via the usual matrix interface
11636:   routines, e.g.,
11637: .vb
11638:   MatMult(Mat, Vec, Vec) -> usermult(Mat, Vec, Vec)
11639: .ve

11641:   In particular each function MUST return `PETSC_SUCCESS` on success and
11642:   nonzero on failure.

11644:   This routine is distinct from `MatShellSetOperation()` in that it can be called on any matrix type.

11646: .seealso: [](ch_matrices), `Mat`, `MatGetOperation()`, `MatCreateShell()`, `MatShellSetContext()`, `MatShellSetOperation()`
11647: @*/
11648: PetscErrorCode MatSetOperation(Mat mat, MatOperation op, PetscErrorCodeFn *f)
11649: {
11650:   PetscFunctionBegin;
11653:   if (op == MATOP_VIEW && !mat->ops->viewnative && f != (PetscErrorCodeFn *)mat->ops->view) mat->ops->viewnative = mat->ops->view;
11654: #if !PetscDefined(USE_COMPLEX)
11655:   if (op == MATOP_MULT_HERMITIAN_TRANSPOSE) op = MATOP_MULT_TRANSPOSE;
11656:   else if (op == MATOP_MULT_HERMITIAN_TRANS_ADD) op = MATOP_MULT_TRANSPOSE_ADD;
11657:   else if (op == MATOP_HERMITIAN_TRANSPOSE) op = MATOP_TRANSPOSE;
11658: #endif
11659:   (((PetscErrorCodeFn **)mat->ops)[op]) = f;
11660:   PetscFunctionReturn(PETSC_SUCCESS);
11661: }

11663: /*@
11664:   MatGetOperation - Gets a matrix operation for any matrix type.

11666:   Not Collective

11668:   Input Parameters:
11669: + mat - the matrix
11670: - op  - the name of the operation

11672:   Output Parameter:
11673: . f - the function that provides the operation

11675:   Level: developer

11677:   Example Usage:
11678: .vb
11679:   PetscErrorCode (*usermult)(Mat, Vec, Vec);

11681:   MatGetOperation(A, MATOP_MULT, (PetscErrorCodeFn **)&usermult);
11682: .ve

11684:   Notes:
11685:   See the file `include/petscmat.h` for a complete list of matrix
11686:   operations, which all have the form MATOP_<OPERATION>, where
11687:   <OPERATION> is the name (in all capital letters) of the
11688:   user interface routine (e.g., `MatMult()` -> `MATOP_MULT`).

11690:   This routine is distinct from `MatShellGetOperation()` in that it can be called on any matrix type.

11692: .seealso: [](ch_matrices), `Mat`, `MatSetOperation()`, `MatCreateShell()`, `MatShellGetContext()`, `MatShellGetOperation()`
11693: @*/
11694: PetscErrorCode MatGetOperation(Mat mat, MatOperation op, PetscErrorCodeFn **f)
11695: {
11696:   PetscFunctionBegin;
11698:   PetscAssertPointer(f, 3);
11699: #if !PetscDefined(USE_COMPLEX)
11700:   if (op == MATOP_MULT_HERMITIAN_TRANSPOSE) op = MATOP_MULT_TRANSPOSE;
11701:   else if (op == MATOP_MULT_HERMITIAN_TRANS_ADD) op = MATOP_MULT_TRANSPOSE_ADD;
11702:   else if (op == MATOP_HERMITIAN_TRANSPOSE) op = MATOP_TRANSPOSE;
11703: #endif
11704:   *f = (((PetscErrorCodeFn **)mat->ops)[op]);
11705:   PetscFunctionReturn(PETSC_SUCCESS);
11706: }

11708: /*@
11709:   MatHasOperation - Determines whether the given matrix supports the particular operation.

11711:   Not Collective

11713:   Input Parameters:
11714: + mat - the matrix
11715: - op  - the operation, for example, `MATOP_GET_DIAGONAL`

11717:   Output Parameter:
11718: . has - either `PETSC_TRUE` or `PETSC_FALSE`

11720:   Level: advanced

11722:   Note:
11723:   See `MatSetOperation()` for additional discussion on naming convention and usage of `op`.

11725: .seealso: [](ch_matrices), `Mat`, `MatCreateShell()`, `MatGetOperation()`, `MatSetOperation()`
11726: @*/
11727: PetscErrorCode MatHasOperation(Mat mat, MatOperation op, PetscBool *has)
11728: {
11729:   PetscFunctionBegin;
11731:   PetscAssertPointer(has, 3);
11732: #if !PetscDefined(USE_COMPLEX)
11733:   if (op == MATOP_MULT_HERMITIAN_TRANSPOSE) op = MATOP_MULT_TRANSPOSE;
11734:   else if (op == MATOP_MULT_HERMITIAN_TRANS_ADD) op = MATOP_MULT_TRANSPOSE_ADD;
11735:   else if (op == MATOP_HERMITIAN_TRANSPOSE) op = MATOP_TRANSPOSE;
11736: #endif
11737:   if (mat->ops->hasoperation) {
11738:     PetscUseTypeMethod(mat, hasoperation, op, has);
11739:   } else {
11740:     if (((void **)mat->ops)[op]) *has = PETSC_TRUE;
11741:     else {
11742:       *has = PETSC_FALSE;
11743:       if (op == MATOP_CREATE_SUBMATRIX) {
11744:         PetscMPIInt size;

11746:         PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)mat), &size));
11747:         if (size == 1) PetscCall(MatHasOperation(mat, MATOP_CREATE_SUBMATRICES, has));
11748:       }
11749:     }
11750:   }
11751:   PetscFunctionReturn(PETSC_SUCCESS);
11752: }

11754: /*@
11755:   MatHasCongruentLayouts - Determines whether the rows and columns layouts of the matrix are congruent

11757:   Collective

11759:   Input Parameter:
11760: . mat - the matrix

11762:   Output Parameter:
11763: . cong - either `PETSC_TRUE` or `PETSC_FALSE`

11765:   Level: beginner

11767: .seealso: [](ch_matrices), `Mat`, `MatCreate()`, `MatSetSizes()`, `PetscLayout`
11768: @*/
11769: PetscErrorCode MatHasCongruentLayouts(Mat mat, PetscBool *cong)
11770: {
11771:   PetscFunctionBegin;
11774:   PetscAssertPointer(cong, 2);
11775:   if (!mat->rmap || !mat->cmap) {
11776:     *cong = mat->rmap == mat->cmap ? PETSC_TRUE : PETSC_FALSE;
11777:     PetscFunctionReturn(PETSC_SUCCESS);
11778:   }
11779:   if (mat->congruentlayouts == PETSC_DECIDE) { /* first time we compare rows and cols layouts */
11780:     PetscCall(PetscLayoutSetUp(mat->rmap));
11781:     PetscCall(PetscLayoutSetUp(mat->cmap));
11782:     PetscCall(PetscLayoutCompare(mat->rmap, mat->cmap, cong));
11783:     if (*cong) mat->congruentlayouts = 1;
11784:     else mat->congruentlayouts = 0;
11785:   } else *cong = mat->congruentlayouts ? PETSC_TRUE : PETSC_FALSE;
11786:   PetscFunctionReturn(PETSC_SUCCESS);
11787: }

11789: /*@
11790:   MatSetInf - Set every entry (of a given nonzero pattern) of a matrix to positive infinity.

11792:   Logically Collective

11794:   Input Parameter:
11795: . A - the matrix

11797:   Level: developer

11799: .seealso: `Mat`, `MatZeroEntries()`, `MatSetValues()`
11800: @*/
11801: PetscErrorCode MatSetInf(Mat A)
11802: {
11803:   PetscFunctionBegin;
11804:   PetscUseTypeMethod(A, setinf);
11805:   PetscFunctionReturn(PETSC_SUCCESS);
11806: }

11808: /*@
11809:   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
11810:   and possibly removes small values from the graph structure.

11812:   Collective

11814:   Input Parameters:
11815: + A       - the matrix
11816: . sym     - `PETSC_TRUE` indicates that the graph should be symmetrized
11817: . scale   - `PETSC_TRUE` indicates that the graph edge weights should be symmetrically scaled with the diagonal entry
11818: . filter  - filter value - < 0: does nothing; == 0: removes only 0.0 entries; otherwise: removes entries with abs(entries) <= value
11819: . num_idx - size of `index` array
11820: - index   - array of block indices to use for graph strength of connection weight

11822:   Output Parameter:
11823: . graph - the resulting graph

11825:   Level: advanced

11827: .seealso: [](ch_matrices), `Mat`, `MatCreate()`, `PCGAMG`
11828: @*/
11829: PetscErrorCode MatCreateGraph(Mat A, PetscBool sym, PetscBool scale, PetscReal filter, PetscInt num_idx, PetscInt index[], Mat *graph)
11830: {
11831:   PetscFunctionBegin;
11835:   PetscAssertPointer(graph, 7);
11836:   PetscCall(PetscLogEventBegin(MAT_CreateGraph, A, 0, 0, 0));
11837:   PetscUseTypeMethod(A, creategraph, sym, scale, filter, num_idx, index, graph);
11838:   PetscCall(PetscLogEventEnd(MAT_CreateGraph, A, 0, 0, 0));
11839:   PetscFunctionReturn(PETSC_SUCCESS);
11840: }

11842: /*@
11843:   MatEliminateZeros - eliminate the nondiagonal zero entries in place from the nonzero structure of a sparse `Mat` in place,
11844:   meaning the same memory is used for the matrix, and no new memory is allocated.

11846:   Collective

11848:   Input Parameters:
11849: + A    - the matrix
11850: - 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

11852:   Level: intermediate

11854:   Developer Note:
11855:   The entries in the sparse matrix data structure are shifted to fill in the unneeded locations in the data. Thus the end
11856:   of the arrays in the data structure are unneeded.

11858: .seealso: [](ch_matrices), `Mat`, `MatCreate()`, `MatCreateGraph()`, `MatFilter()`
11859: @*/
11860: PetscErrorCode MatEliminateZeros(Mat A, PetscBool keep)
11861: {
11862:   PetscFunctionBegin;
11864:   PetscUseTypeMethod(A, eliminatezeros, keep);
11865:   PetscFunctionReturn(PETSC_SUCCESS);
11866: }

11868: /*@
11869:   MatGetCurrentMemType - Get the memory location of the matrix

11871:   Not Collective, but the result will be the same on all MPI processes

11873:   Input Parameter:
11874: . A - the matrix whose memory type we are checking

11876:   Output Parameter:
11877: . m - the memory type

11879:   Level: intermediate

11881: .seealso: [](ch_matrices), `Mat`, `MatBoundToCPU()`, `PetscMemType`
11882: @*/
11883: PetscErrorCode MatGetCurrentMemType(Mat A, PetscMemType *m)
11884: {
11885:   PetscFunctionBegin;
11887:   PetscAssertPointer(m, 2);
11888:   if (A->ops->getcurrentmemtype) PetscUseTypeMethod(A, getcurrentmemtype, m);
11889:   else *m = PETSC_MEMTYPE_HOST;
11890:   PetscFunctionReturn(PETSC_SUCCESS);
11891: }