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

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

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

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

297:   Level: intermediate

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

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

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

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

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

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

330:   Level: intermediate

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

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

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

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

363:   Not Collective

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

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

371:   Level: advanced

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

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

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

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

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

401:   Collective

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

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

409:   Level: advanced

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

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

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

430:   Logically Collective

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

435:   Level: advanced

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

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

454:   Collective

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

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

463:   Level: advanced

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

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

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

488:   Logically Collective

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

493:   Level: advanced

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

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

515:   Not Collective

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

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

526:   Level: advanced

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

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

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

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

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

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

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

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

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

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

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

583:   Logically Collective

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

588:   Level: advanced

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

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

607:   Not Collective

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

616:   Level: advanced

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

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

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

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

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

650:   Not Collective

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

655:   Level: advanced

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

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

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

677:   Not Collective

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

682:   Level: advanced

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

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

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

705:   Logically Collective

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

711:   Level: advanced

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

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

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

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

736:   Logically Collective

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

742:   Level: developer

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

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

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

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

772:   Logically Collective

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

778:   Level: developer

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

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

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

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

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

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

816:   Logically Collective

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

822:   Level: advanced

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

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

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

843:   Not Collective

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

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

851:   Level: advanced

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

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

867:   Not Collective

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

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

875:   Level: advanced

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

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

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

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

898:   Collective

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

903:   Level: beginner

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

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

912:   Currently only supported for  `MATAIJ` matrices.

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

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

928:   Collective

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

933:   Level: intermediate

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

938:   Currently only supported for `MATAIJ` matrices.

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

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

961:   Collective

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

966:   Level: advanced

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

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

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

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

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

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

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

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

1009:   Collective

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

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

1019:   Level: intermediate

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

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

1037:   Collective on viewer

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

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

1057:   Level: beginner

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

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

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

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

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

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

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

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

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

1112:   PetscFunctionBegin;
1115:   if (!viewer) PetscCall(PetscViewerASCIIGetStdout(PetscObjectComm((PetscObject)mat), &viewer));

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

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

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

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

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

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

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

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

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

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

1250:   Collective

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

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

1260:   Level: beginner

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1369:   PetscFunctionBegin;

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

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

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

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

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

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

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

1421:   Collective

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

1426:   Level: beginner

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

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

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

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

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

1476:   Not Collective

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

1488:   Level: beginner

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

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

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

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

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

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

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

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

1531:   if (PetscDefined(USE_DEBUG)) {
1532:     PetscInt i, j;

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

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

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

1567:   Not Collective

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

1577:   Level: beginner

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

1582:   Calls to `MatSetValues()` with the `INSERT_VALUES` and `ADD_VALUES`
1583:   options cannot be mixed without intervening calls to the assembly
1584:   routines.

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

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

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

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

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

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

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

1624: /*@
1625:   MatSetValuesRowLocal - Inserts a row of nonzero values into a matrix

1627:   Not Collective

1629:   Input Parameters:
1630: + mat - the matrix
1631: . row - the row to set
1632: - v   - a one-dimensional array that contains the values

1634:   Level: intermediate

1636:   Notes:
1637:   Currently only supported for `MATAIJ`.

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

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

1643:   `row` must belong to this MPI process

1645: .seealso: [](ch_matrices), `Mat`, `MatSetOption()`, `MatAssemblyBegin()`, `MatAssemblyEnd()`, `MatSetValuesBlocked()`, `MatSetValuesLocal()`,
1646:           `InsertMode`, `INSERT_VALUES`, `ADD_VALUES`, `MatSetValues()`, `MatSetValuesRow()`, `MatSetLocalToGlobalMapping()`, `MATAIJ`
1647: @*/
1648: PetscErrorCode MatSetValuesRowLocal(Mat mat, PetscInt row, const PetscScalar v[])
1649: {
1650:   PetscInt globalrow;

1652:   PetscFunctionBegin;
1655:   PetscAssertPointer(v, 3);
1656:   PetscCall(ISLocalToGlobalMappingApply(mat->rmap->mapping, 1, &row, &globalrow));
1657:   PetscCall(MatSetValuesRow(mat, globalrow, v));
1658:   PetscFunctionReturn(PETSC_SUCCESS);
1659: }

1661: /*@
1662:   MatSetValuesRow - Inserts a row of nonzero values into a matrix

1664:   Not Collective

1666:   Input Parameters:
1667: + mat - the matrix
1668: . row - the row to set
1669: - v   - a one dimensional array of values

1671:   Level: advanced

1673:   Notes:
1674:   Currently only supported for `MATAIJ`.

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

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

1680:   `row` must belong to this process

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

1696:   if (mat->assembled) {
1697:     mat->was_assembled = PETSC_TRUE;
1698:     mat->assembled     = PETSC_FALSE;
1699:   }
1700:   PetscCall(PetscLogEventBegin(MAT_SetValues, mat, 0, 0, 0));
1701:   PetscUseTypeMethod(mat, setvaluesrow, row, v);
1702:   PetscCall(PetscLogEventEnd(MAT_SetValues, mat, 0, 0, 0));
1703:   PetscFunctionReturn(PETSC_SUCCESS);
1704: }

1706: // PetscClangLinter pragma disable: -fdoc-section-header-unknown
1707: /*@
1708:   MatSetValuesStencil - Inserts or adds a block of values into a matrix.
1709:   Using structured grid indexing

1711:   Not Collective

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

1723:   Level: beginner

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

1728:   Calls to `MatSetValuesStencil()` with the `INSERT_VALUES` and `ADD_VALUES`
1729:   options cannot be mixed without intervening calls to the assembly
1730:   routines.

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

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

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

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

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

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

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

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

1759:   Fortran Notes:
1760:   If any of `idxm`, `idxn`, and `v` are scalars pass them using, for example,
1761: .vb
1762:   call MatSetValuesStencil(mat, one, [idxm], one, [idxn], [v], INSERT_VALUES, ierr)
1763: .ve

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

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

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

1781:   PetscFunctionBegin;
1782:   if (!m || !n) PetscFunctionReturn(PETSC_SUCCESS); /* no values to insert */
1785:   PetscAssertPointer(idxm, 3);
1786:   PetscAssertPointer(idxn, 5);

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

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

1825:   Not Collective

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

1837:   Level: beginner

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

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

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

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

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

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

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

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

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

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

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

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

1890:   PetscFunctionBegin;
1891:   if (!m || !n) PetscFunctionReturn(PETSC_SUCCESS); /* no values to insert */
1894:   PetscAssertPointer(idxm, 3);
1895:   PetscAssertPointer(idxn, 5);
1896:   PetscAssertPointer(v, 6);

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

1931: /*@
1932:   MatSetStencil - Sets the grid information for setting values into a matrix via
1933:   `MatSetValuesStencil()`

1935:   Not Collective

1937:   Input Parameters:
1938: + mat    - the matrix
1939: . dim    - dimension of the grid 1, 2, or 3
1940: . dims   - number of grid points in x, y, and z direction, including ghost points on your processor
1941: . starts - starting point of ghost nodes on your processor in x, y, and z direction
1942: - dof    - number of degrees of freedom per node

1944:   Level: beginner

1946:   Notes:
1947:   Inspired by the structured grid interface to the HYPRE package
1948:   (www.llnl.gov/CASC/hyper)

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

1953: .seealso: [](ch_matrices), `Mat`, `MatStencil`, `MatSetOption()`, `MatAssemblyBegin()`, `MatAssemblyEnd()`, `MatSetValuesBlocked()`, `MatSetValuesLocal()`,
1954:           `MatSetValues()`, `MatSetValuesBlockedStencil()`, `MatSetValuesStencil()`
1955: @*/
1956: PetscErrorCode MatSetStencil(Mat mat, PetscInt dim, const PetscInt dims[], const PetscInt starts[], PetscInt dof)
1957: {
1958:   PetscFunctionBegin;
1960:   PetscAssertPointer(dims, 3);
1961:   PetscAssertPointer(starts, 4);

1963:   mat->stencil.dim = dim + (dof > 1);
1964:   for (PetscInt i = 0; i < dim; i++) {
1965:     mat->stencil.dims[i]   = dims[dim - i - 1]; /* copy the values in backwards */
1966:     mat->stencil.starts[i] = starts[dim - i - 1];
1967:   }
1968:   mat->stencil.dims[dim]   = dof;
1969:   mat->stencil.starts[dim] = 0;
1970:   mat->stencil.noc         = (PetscBool)(dof == 1);
1971:   PetscFunctionReturn(PETSC_SUCCESS);
1972: }

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

1977:   Not Collective

1979:   Input Parameters:
1980: + mat  - the matrix
1981: . m    - the number of block rows
1982: . idxm - the global block indices
1983: . n    - the number of block columns
1984: . idxn - the global block indices
1985: . v    - a one-dimensional array that contains the values implicitly stored as a two-dimensional array, by default in row-major order.
1986:          See `MAT_ROW_ORIENTED` in `MatSetOption()` for how to use column-major order.
1987: - addv - either `ADD_VALUES` to add values to any existing entries, or `INSERT_VALUES` replaces existing entries with new values

1989:   Level: intermediate

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

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

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

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

2006:   Calls to `MatSetValuesBlocked()` with the `INSERT_VALUES` and `ADD_VALUES`
2007:   options cannot be mixed without intervening calls to the assembly
2008:   routines.

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

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

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

2024:   Example:
2025: .vb
2026:    Suppose m=n=2 and block size(bs) = 2 The array is

2028:    1  2  | 3  4
2029:    5  6  | 7  8
2030:    - - - | - - -
2031:    9  10 | 11 12
2032:    13 14 | 15 16

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

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

2041:   Fortran Notes:
2042:   If any of `idmx`, `idxn`, and `v` are scalars pass them using, for example,
2043: .vb
2044:   call MatSetValuesBlocked(mat, one, [idxm], one, [idxn], [v], INSERT_VALUES, ierr)
2045: .ve

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

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

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

2109: /*@
2110:   MatGetValues - Gets a block of local values from a matrix.

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

2114:   Input Parameters:
2115: + mat  - the matrix
2116: . v    - a logically two-dimensional array for storing the values
2117: . m    - the number of rows
2118: . idxm - the  global indices of the rows
2119: . n    - the number of columns
2120: - idxn - the global indices of the columns

2122:   Level: advanced

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

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

2132:   `MatGetValues()` requires that the matrix has been assembled
2133:   with `MatAssemblyBegin()`/`MatAssemblyEnd()`.  Thus, calls to
2134:   `MatSetValues()` and `MatGetValues()` CANNOT be made in succession
2135:   without intermediate matrix assembly.

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

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

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

2159:   PetscCall(PetscLogEventBegin(MAT_GetValues, mat, 0, 0, 0));
2160:   PetscUseTypeMethod(mat, getvalues, m, idxm, n, idxn, v);
2161:   PetscCall(PetscLogEventEnd(MAT_GetValues, mat, 0, 0, 0));
2162:   PetscFunctionReturn(PETSC_SUCCESS);
2163: }

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

2169:   Not Collective

2171:   Input Parameters:
2172: + mat  - the matrix
2173: . nrow - number of rows
2174: . irow - the row local indices
2175: . ncol - number of columns
2176: - icol - the column local indices

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

2182:   Level: advanced

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

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

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

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

2236:   Not Collective

2238:   Input Parameters:
2239: + mat  - the matrix
2240: . nb   - the number of blocks
2241: . bs   - the number of rows (and columns) in each block
2242: . rows - a concatenation of the rows for each block
2243: - v    - a concatenation of logically two-dimensional arrays of values

2245:   Level: advanced

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

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

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

2264:   PetscCall(PetscLogEventBegin(MAT_SetValuesBatch, mat, 0, 0, 0));
2265:   if (mat->ops->setvaluesbatch) PetscUseTypeMethod(mat, setvaluesbatch, nb, bs, rows, v);
2266:   else {
2267:     for (PetscInt b = 0; b < nb; ++b) PetscCall(MatSetValues(mat, bs, &rows[b * bs], bs, &rows[b * bs], &v[b * bs * bs], ADD_VALUES));
2268:   }
2269:   PetscCall(PetscLogEventEnd(MAT_SetValuesBatch, mat, 0, 0, 0));
2270:   PetscFunctionReturn(PETSC_SUCCESS);
2271: }

2273: /*@
2274:   MatSetLocalToGlobalMapping - Sets a local-to-global numbering for use by
2275:   the routine `MatSetValuesLocal()` to allow users to insert matrix entries
2276:   using a local (per-processor) numbering.

2278:   Not Collective

2280:   Input Parameters:
2281: + x        - the matrix
2282: . rmapping - row mapping created with `ISLocalToGlobalMappingCreate()` or `ISLocalToGlobalMappingCreateIS()`
2283: - cmapping - column mapping

2285:   Level: intermediate

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

2290: .seealso: [](ch_matrices), `Mat`, `DM`, `DMCreateMatrix()`, `MatGetLocalToGlobalMapping()`, `MatAssemblyBegin()`, `MatAssemblyEnd()`, `MatSetValues()`, `MatSetValuesLocal()`, `MatGetValuesLocal()`
2291: @*/
2292: PetscErrorCode MatSetLocalToGlobalMapping(Mat x, ISLocalToGlobalMapping rmapping, ISLocalToGlobalMapping cmapping)
2293: {
2294:   PetscFunctionBegin;
2299:   if (x->ops->setlocaltoglobalmapping) PetscUseTypeMethod(x, setlocaltoglobalmapping, rmapping, cmapping);
2300:   else {
2301:     PetscCall(PetscLayoutSetISLocalToGlobalMapping(x->rmap, rmapping));
2302:     PetscCall(PetscLayoutSetISLocalToGlobalMapping(x->cmap, cmapping));
2303:   }
2304:   PetscFunctionReturn(PETSC_SUCCESS);
2305: }

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

2310:   Not Collective

2312:   Input Parameter:
2313: . A - the matrix

2315:   Output Parameters:
2316: + rmapping - row mapping
2317: - cmapping - column mapping

2319:   Level: advanced

2321: .seealso: [](ch_matrices), `Mat`, `MatSetLocalToGlobalMapping()`, `MatSetValuesLocal()`
2322: @*/
2323: PetscErrorCode MatGetLocalToGlobalMapping(Mat A, ISLocalToGlobalMapping *rmapping, ISLocalToGlobalMapping *cmapping)
2324: {
2325:   PetscFunctionBegin;
2328:   if (rmapping) {
2329:     PetscAssertPointer(rmapping, 2);
2330:     *rmapping = A->rmap->mapping;
2331:   }
2332:   if (cmapping) {
2333:     PetscAssertPointer(cmapping, 3);
2334:     *cmapping = A->cmap->mapping;
2335:   }
2336:   PetscFunctionReturn(PETSC_SUCCESS);
2337: }

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

2342:   Logically Collective

2344:   Input Parameters:
2345: + A    - the matrix
2346: . rmap - row layout
2347: - cmap - column layout

2349:   Level: advanced

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

2354: .seealso: [](ch_matrices), `Mat`, `PetscLayout`, `MatCreateVecs()`, `MatGetLocalToGlobalMapping()`, `MatGetLayouts()`
2355: @*/
2356: PetscErrorCode MatSetLayouts(Mat A, PetscLayout rmap, PetscLayout cmap)
2357: {
2358:   PetscFunctionBegin;
2360:   PetscCall(PetscLayoutReference(rmap, &A->rmap));
2361:   PetscCall(PetscLayoutReference(cmap, &A->cmap));
2362:   PetscFunctionReturn(PETSC_SUCCESS);
2363: }

2365: /*@
2366:   MatGetLayouts - Gets the `PetscLayout` objects for rows and columns

2368:   Not Collective

2370:   Input Parameter:
2371: . A - the matrix

2373:   Output Parameters:
2374: + rmap - row layout
2375: - cmap - column layout

2377:   Level: advanced

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

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

2401:   Not Collective

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

2413:   Level: intermediate

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

2418:   Calls to `MatSetValuesLocal()` with the `INSERT_VALUES` and `ADD_VALUES`
2419:   options cannot be mixed without intervening calls to the assembly
2420:   routines.

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

2425:   Fortran Notes:
2426:   If any of `irow`, `icol`, and `v` are scalars pass them using, for example,
2427: .vb
2428:   call MatSetValuesLocal(mat, one, [irow], one, [icol], [v], INSERT_VALUES, ierr)
2429: .ve

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

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

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

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

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

2490:   Not Collective

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

2502:   Level: intermediate

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

2508:   Calls to `MatSetValuesBlockedLocal()` with the `INSERT_VALUES` and `ADD_VALUES`
2509:   options cannot be mixed without intervening calls to the assembly
2510:   routines.

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

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

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

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

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

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

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

2591:   Collective

2593:   Input Parameters:
2594: + mat - the matrix
2595: - x   - the vector to be multiplied

2597:   Output Parameter:
2598: . y - the result

2600:   Level: developer

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

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

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

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

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

2629:   Neighbor-wise Collective

2631:   Input Parameters:
2632: + mat - the matrix
2633: - x   - the vector to be multiplied

2635:   Output Parameter:
2636: . y - the result

2638:   Level: beginner

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

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

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

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

2677:   Neighbor-wise Collective

2679:   Input Parameters:
2680: + mat - the matrix
2681: - x   - the vector to be multiplied

2683:   Output Parameter:
2684: . y - the result

2686:   Level: beginner

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

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

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

2701:   PetscFunctionBegin;
2705:   VecCheckAssembled(x);

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

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

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

2735:   Neighbor-wise Collective

2737:   Input Parameters:
2738: + mat - the matrix
2739: - x   - the vector to be multiplied

2741:   Output Parameter:
2742: . y - the result

2744:   Level: beginner

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

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

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

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

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

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

2797: /*@
2798:   MatMultAdd -  Computes $v3 = v2 + A * v1$.

2800:   Neighbor-wise Collective

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

2807:   Output Parameter:
2808: . v3 - the result

2810:   Level: beginner

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

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

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

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

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

2849:   Neighbor-wise Collective

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

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

2859:   Level: beginner

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

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

2871:   PetscFunctionBegin;

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

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

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

2899:   Neighbor-wise Collective

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

2906:   Output Parameter:
2907: . v3 - the result

2909:   Level: beginner

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

2915: .seealso: [](ch_matrices), `Mat`, `MatMultHermitianTranspose()`, `MatMultTranspose()`, `MatMultAdd()`, `MatMult()`
2916: @*/
2917: PetscErrorCode MatMultHermitianTransposeAdd(Mat mat, Vec v1, Vec v2, Vec v3)
2918: {
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(v1 != v3, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_IDN, "v1 and v3 must be different vectors");
2929:   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);
2930:   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);
2931:   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);
2932:   MatCheckPreallocated(mat, 1);

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

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

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

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

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

2981:   Collective

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

2988:   Output Parameter:
2989: . val - the dot product with respect to `A`

2991:   Level: intermediate

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

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

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

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

3039:   Collective

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

3045:   Output Parameter:
3046: . val - the norm with respect to `A`

3048:   Level: intermediate

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

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

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

3085: /*@
3086:   MatGetFactorType - gets the type of factorization a matrix is

3088:   Not Collective

3090:   Input Parameter:
3091: . mat - the matrix

3093:   Output Parameter:
3094: . 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`

3096:   Level: intermediate

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

3111: /*@
3112:   MatSetFactorType - sets the type of factorization a matrix is

3114:   Logically Collective

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

3120:   Level: intermediate

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

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

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

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

3144:   Output Parameter:
3145: . info - matrix information context

3147:   Options Database Key:
3148: . -mat_view ::ascii_info - print matrix info to `PETSC_STDOUT`

3150:   Level: intermediate

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

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

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

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

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

3196: /*@
3197:   MatLUFactor - Performs in-place LU factorization of matrix.

3199:   Collective

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

3212:   Level: developer

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

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

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

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

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

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

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

3256: /*@
3257:   MatILUFactor - Performs in-place ILU factorization of matrix.

3259:   Collective

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

3273:   Level: developer

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

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

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

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

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

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

3313:   Collective

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

3326:   Level: developer

3328:   Notes:
3329:   See [Matrix Factorization](sec_matfactor) for additional information about factorizations

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

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

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

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

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

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

3371:   Collective

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

3378:   Level: developer

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

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

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

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

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

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

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

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

3426:   Collective

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

3433:   Level: developer

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

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

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

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

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

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

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

3478:   Collective

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

3491:   Level: developer

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

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

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

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

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

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

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

3539:   Collective

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

3546:   Level: developer

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

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

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

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

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

3586: /*@
3587:   MatQRFactor - Performs in-place QR factorization of matrix.

3589:   Collective

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

3601:   Level: developer

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

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

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

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

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

3638:   Collective

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

3651:   Level: developer

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

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

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

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

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

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

3693:   Collective

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

3700:   Level: developer

3702:   Notes:
3703:   See `MatQRFactor()` for in-place factorization.

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

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

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

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

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

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

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

3746:   Neighbor-wise Collective

3748:   Input Parameters:
3749: + mat - the factored matrix
3750: - b   - the right-hand-side vector

3752:   Output Parameter:
3753: . x - the result vector

3755:   Level: developer

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

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

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

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

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

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

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

3835:   Neighbor-wise Collective

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

3841:   Output Parameter:
3842: . X - the result matrix (dense matrix)

3844:   Level: developer

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

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

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

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

3880:   Neighbor-wise Collective

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

3886:   Output Parameter:
3887: . X - the result matrix (dense matrix)

3889:   Level: developer

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

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

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

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

3927:   Neighbor-wise Collective

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

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

3936:   Level: developer

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

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

3954:   PetscCheck(X != Bt, 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 == 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);
3957:   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");
3958:   if (!A->rmap->N && !A->cmap->N) PetscFunctionReturn(PETSC_SUCCESS);
3959:   PetscCheck(A->factortype, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_WRONGSTATE, "Unfactored matrix");
3960:   MatCheckPreallocated(A, 1);

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

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

3973:   Neighbor-wise Collective

3975:   Input Parameters:
3976: + mat - the factored matrix
3977: - b   - the right-hand-side vector

3979:   Output Parameter:
3980: . x - the result vector

3982:   Level: developer

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

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

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

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

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

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

4026:   Neighbor-wise Collective

4028:   Input Parameters:
4029: + mat - the factored matrix
4030: - b   - the right-hand-side vector

4032:   Output Parameter:
4033: . x - the result vector

4035:   Level: developer

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

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

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

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

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

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

4078:   Neighbor-wise Collective

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

4085:   Output Parameter:
4086: . x - the result vector

4088:   Level: developer

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

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

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

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

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

4146:   Neighbor-wise Collective

4148:   Input Parameters:
4149: + mat - the factored matrix
4150: - b   - the right-hand-side vector

4152:   Output Parameter:
4153: . x - the result vector

4155:   Level: developer

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

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

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

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

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

4200:   Neighbor-wise Collective

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

4207:   Output Parameter:
4208: . x - the result vector

4210:   Level: developer

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

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

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

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

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

4269:   Neighbor-wise Collective

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

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

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

4294:   Level: developer

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

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

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

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

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

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

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

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

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

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

4370: /*@
4371:   MatCopy - Copies a matrix to another matrix.

4373:   Collective

4375:   Input Parameters:
4376: + A   - the matrix
4377: - str - `SAME_NONZERO_PATTERN` or `DIFFERENT_NONZERO_PATTERN`

4379:   Output Parameter:
4380: . B - where the copy is put

4382:   Level: intermediate

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

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

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

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

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

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

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

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

4431:   Collective

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

4441:   Output Parameter:
4442: . M - pointer to place new matrix

4444:   Level: intermediate

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

4609: /*@
4610:   MatFactorGetSolverType - Returns name of the package providing the factorization routines

4612:   Not Collective

4614:   Input Parameter:
4615: . mat - the matrix, must be a factored matrix

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

4620:   Level: intermediate

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

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

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

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

4654: static MatSolverTypeHolder MatSolverTypeHolders = NULL;

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

4659:   Logically Collective, No Fortran Support

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

4667:   Level: developer

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

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

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

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

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

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

4736:   Level: developer

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

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

4752:   PetscFunctionBegin;
4753:   if (foundtype) *foundtype = PETSC_FALSE;
4754:   if (foundmtype) *foundmtype = PETSC_FALSE;
4755:   if (createfactor) *createfactor = NULL;

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

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

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

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

4836:   Logically Collective

4838:   Input Parameter:
4839: . mat - the matrix

4841:   Output Parameter:
4842: . flg - `PETSC_TRUE` if uses the ordering

4844:   Level: developer

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

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

4859: /*@
4860:   MatFactorGetPreferredOrdering - The preferred ordering for a particular matrix factor object

4862:   Logically Collective

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

4868:   Output Parameter:
4869: . otype - the preferred ordering type

4871:   Level: developer

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

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

4887:   Collective

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

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

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

4903:   Level: intermediate

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

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

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

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

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

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

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

4939:   PetscFunctionBegin;

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

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

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

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

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

4973:   Not Collective

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

4980:   Output Parameter:
4981: . flg - PETSC_TRUE if the factorization is available

4983:   Level: intermediate

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

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

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

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

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

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

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

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

5016: /*@
5017:   MatDuplicate - Duplicates a matrix including the non-zero structure.

5019:   Collective

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

5026:   Output Parameter:
5027: . M - pointer to place new matrix

5029:   Level: intermediate

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

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

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

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

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

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

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

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

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

5077:   B->nooffproczerorows = mat->nooffproczerorows;
5078:   B->nooffprocentries  = mat->nooffprocentries;

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

5091: /*@
5092:   MatGetDiagonal - Gets the diagonal of a matrix as a `Vec`

5094:   Logically Collective

5096:   Input Parameter:
5097: . mat - the matrix

5099:   Output Parameter:
5100: . v - the diagonal of the matrix

5102:   Level: intermediate

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

5109:   Currently only correct in parallel for square matrices.

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

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

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

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

5139:   Logically Collective

5141:   Input Parameter:
5142: . mat - the matrix

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

5148:   Level: intermediate

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

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

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

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

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

5185:   Logically Collective

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

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

5194:   Level: intermediate

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

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

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

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

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

5232:   Logically Collective

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

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

5241:   Level: intermediate

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

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

5249: .seealso: [](ch_matrices), `Mat`, `MatGetDiagonal()`, `MatCreateSubMatrices()`, `MatCreateSubMatrix()`, `MatGetRowMaxAbs()`, `MatGetRowMin()`, `MatGetRowMinAbs()`
5250: @*/
5251: PetscErrorCode MatGetRowMax(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_MIN_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:     PetscUseTypeMethod(mat, getrowmax, v, idx);
5268:   }
5269:   PetscCall(PetscObjectStateIncrease((PetscObject)v));
5270:   PetscFunctionReturn(PETSC_SUCCESS);
5271: }

5273: /*@
5274:   MatGetRowMaxAbs - Gets the maximum 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 maximums
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()`, `MatGetRowSum()`, `MatGetRowMin()`, `MatGetRowMinAbs()`
5295: @*/
5296: PetscErrorCode MatGetRowMaxAbs(Mat mat, Vec v, PetscInt idx[])
5297: {
5298:   PetscFunctionBegin;
5302:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");

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

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

5322:   Logically Collective

5324:   Input Parameter:
5325: . mat - the matrix

5327:   Output Parameter:
5328: . v - the vector for storing the sum

5330:   Level: intermediate

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

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

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

5353: /*@
5354:   MatGetRowSum - Gets the sum of each row of the matrix

5356:   Logically or Neighborhood Collective

5358:   Input Parameter:
5359: . mat - the matrix

5361:   Output Parameter:
5362: . v - the vector for storing the sum of rows

5364:   Level: intermediate

5366:   Note:
5367:   This code is slow since it is not currently specialized for different formats

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

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

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

5392:   Collective

5394:   Input Parameter:
5395: . mat - the matrix to provide the transpose

5397:   Output Parameter:
5398: . 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

5400:   Level: advanced

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

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

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

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

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

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

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

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

5470:   Collective

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

5476:   Output Parameter:
5477: . B - the transpose of the matrix

5479:   Level: intermediate

5481:   Notes:
5482:   If you use `MAT_INPLACE_MATRIX` then you must pass in `&mat` for `B`

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

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

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

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

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

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

5506: /*@
5507:   MatTransposeSymbolic - Computes the symbolic part of the transpose of a matrix.

5509:   Collective

5511:   Input Parameter:
5512: . A - the matrix to transpose

5514:   Output Parameter:
5515: . 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
5516:       numerical portion.

5518:   Level: intermediate

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

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

5536:   PetscCall(MatTransposeSetPrecursor(A, *B));
5537:   PetscFunctionReturn(PETSC_SUCCESS);
5538: }

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

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

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

5562:   Collective

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

5569:   Output Parameter:
5570: . flg - the result

5572:   Level: intermediate

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

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

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

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

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

5606:   Collective

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

5612:   Output Parameter:
5613: . B - the Hermitian transpose

5615:   Level: intermediate

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

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

5629:   Collective

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

5636:   Output Parameter:
5637: . flg - the result

5639:   Level: intermediate

5641:   Notes:
5642:   Only available for `MATAIJ` matrices.

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

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

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

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

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

5676:   Collective

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

5683:   Output Parameter:
5684: . B - the permuted matrix

5686:   Level: advanced

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

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

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

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

5723: /*@
5724:   MatEqual - Compares two matrices.

5726:   Collective

5728:   Input Parameters:
5729: + A - the first matrix
5730: - B - the second matrix

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

5735:   Level: intermediate

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

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

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

5768:   Collective

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

5775:   Level: intermediate

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

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

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

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

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

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

5844:   Logically Collective

5846:   Input Parameters:
5847: + mat - the matrix to be scaled
5848: - a   - the scaling value

5850:   Level: intermediate

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

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

5873: /*@
5874:   MatNorm - Calculates various norms of a matrix.

5876:   Collective

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

5882:   Output Parameter:
5883: . nrm - the resulting norm

5885:   Level: intermediate

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

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

5900:   PetscUseTypeMethod(mat, norm, type, nrm);
5901:   PetscFunctionReturn(PETSC_SUCCESS);
5902: }

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

5913:   Collective

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

5919:   Level: beginner

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

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

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

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

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

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

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

5963:   Not Collective

5965:   Input Parameter:
5966: . mat - the matrix

5968:   Output Parameter:
5969: . assembled - `PETSC_TRUE` or `PETSC_FALSE`

5971:   Level: advanced

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

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

5988:   Collective

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

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

5997:   Level: beginner

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

6007:   PetscFunctionBegin;

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

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

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

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

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

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

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

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

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

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

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

6089:    When (re)assembling a matrix, we can restrict the input for
6090:    efficiency/debugging purposes.  These options include
6091: . `MAT_NEW_NONZERO_LOCATIONS`       - additional insertions will be allowed if they generate a new nonzero (slow)
6092: . `MAT_FORCE_DIAGONAL_ENTRIES`      - forces diagonal entries to be allocated
6093: . `MAT_IGNORE_OFF_PROC_ENTRIES`     - drops off-processor entries
6094: . `MAT_NEW_NONZERO_LOCATION_ERR`    - generates an error for new matrix entry
6095: . `MAT_USE_HASH_TABLE`              - uses a hash table to speed up matrix assembly
6096: . `MAT_NO_OFF_PROC_ENTRIES`         - you know each process will only set values for its own rows, will generate an error if
6097:         any process sets values for another process. This avoids all reductions in the MatAssembly routines and thus improves
6098:         performance for very large process counts.
6099: - `MAT_SUBSET_OFF_PROC_ENTRIES`     - you know that the first assembly after setting this flag will set a superset
6100:         of the off-process entries required for all subsequent assemblies. This avoids a rendezvous step in the MatAssembly
6101:         functions, instead sending only neighbor messages.

6103:   Level: intermediate

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

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

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

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

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

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

6133:   `MAT_IGNORE_OFF_PROC_ENTRIES` set to `PETSC_TRUE` indicates entries destined for
6134:   other processors should be dropped, rather than stashed.
6135:   This is useful if you know that the "owning" processor is also
6136:   always generating the correct matrix entries, so that PETSc need
6137:   not transfer duplicate entries generated on another processor.

6139:   `MAT_USE_HASH_TABLE` indicates that a hash table be used to improve the
6140:   searches during matrix assembly. When this flag is set, the hash table
6141:   is created during the first matrix assembly. This hash table is
6142:   used the next time through, during `MatSetValues()`/`MatSetValuesBlocked()`
6143:   to improve the searching of indices. `MAT_NEW_NONZERO_LOCATIONS` flag
6144:   should be used with `MAT_USE_HASH_TABLE` flag. This option is currently
6145:   supported by `MATMPIBAIJ` format only.

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

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

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

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

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

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

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

6171: .seealso: [](ch_matrices), `MatOption`, `Mat`, `MatGetOption()`
6172: @*/
6173: PetscErrorCode MatSetOption(Mat mat, MatOption op, PetscBool flg)
6174: {
6175:   PetscFunctionBegin;
6177:   if (op > 0) {
6180:   }

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

6184:   switch (op) {
6185:   case MAT_FORCE_DIAGONAL_ENTRIES:
6186:     mat->force_diagonals = flg;
6187:     PetscFunctionReturn(PETSC_SUCCESS);
6188:   case MAT_NO_OFF_PROC_ENTRIES:
6189:     mat->nooffprocentries = flg;
6190:     PetscFunctionReturn(PETSC_SUCCESS);
6191:   case MAT_SUBSET_OFF_PROC_ENTRIES:
6192:     mat->assembly_subset = flg;
6193:     if (!mat->assembly_subset) { /* See the same logic in VecAssembly wrt VEC_SUBSET_OFF_PROC_ENTRIES */
6194: #if !defined(PETSC_HAVE_MPIUNI)
6195:       PetscCall(MatStashScatterDestroy_BTS(&mat->stash));
6196: #endif
6197:       mat->stash.first_assembly_done = PETSC_FALSE;
6198:     }
6199:     PetscFunctionReturn(PETSC_SUCCESS);
6200:   case MAT_NO_OFF_PROC_ZERO_ROWS:
6201:     mat->nooffproczerorows = flg;
6202:     PetscFunctionReturn(PETSC_SUCCESS);
6203:   case MAT_SPD:
6204:     if (flg) {
6205:       mat->spd                    = PETSC_BOOL3_TRUE;
6206:       mat->symmetric              = PETSC_BOOL3_TRUE;
6207:       mat->structurally_symmetric = PETSC_BOOL3_TRUE;
6208: #if !defined(PETSC_USE_COMPLEX)
6209:       mat->hermitian = PETSC_BOOL3_TRUE;
6210: #endif
6211:     } else {
6212:       mat->spd = PETSC_BOOL3_FALSE;
6213:     }
6214:     break;
6215:   case MAT_SYMMETRIC:
6216:     mat->symmetric = PetscBoolToBool3(flg);
6217:     if (flg) mat->structurally_symmetric = PETSC_BOOL3_TRUE;
6218: #if !defined(PETSC_USE_COMPLEX)
6219:     mat->hermitian = PetscBoolToBool3(flg);
6220: #endif
6221:     break;
6222:   case MAT_HERMITIAN:
6223:     mat->hermitian = PetscBoolToBool3(flg);
6224:     if (flg) mat->structurally_symmetric = PETSC_BOOL3_TRUE;
6225: #if !defined(PETSC_USE_COMPLEX)
6226:     mat->symmetric = PetscBoolToBool3(flg);
6227: #endif
6228:     break;
6229:   case MAT_STRUCTURALLY_SYMMETRIC:
6230:     mat->structurally_symmetric = PetscBoolToBool3(flg);
6231:     break;
6232:   case MAT_SYMMETRY_ETERNAL:
6233:     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");
6234:     mat->symmetry_eternal = flg;
6235:     if (flg) mat->structural_symmetry_eternal = PETSC_TRUE;
6236:     break;
6237:   case MAT_STRUCTURAL_SYMMETRY_ETERNAL:
6238:     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");
6239:     mat->structural_symmetry_eternal = flg;
6240:     break;
6241:   case MAT_SPD_ETERNAL:
6242:     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");
6243:     mat->spd_eternal = flg;
6244:     if (flg) {
6245:       mat->structural_symmetry_eternal = PETSC_TRUE;
6246:       mat->symmetry_eternal            = PETSC_TRUE;
6247:     }
6248:     break;
6249:   case MAT_STRUCTURE_ONLY:
6250:     mat->structure_only = flg;
6251:     break;
6252:   case MAT_SORTED_FULL:
6253:     mat->sortedfull = flg;
6254:     break;
6255:   default:
6256:     break;
6257:   }
6258:   PetscTryTypeMethod(mat, setoption, op, flg);
6259:   PetscFunctionReturn(PETSC_SUCCESS);
6260: }

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

6265:   Logically Collective

6267:   Input Parameters:
6268: + mat - the matrix
6269: - op  - the option, this only responds to certain options, check the code for which ones

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

6274:   Level: intermediate

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

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

6282: .seealso: [](ch_matrices), `Mat`, `MatOption`, `MatSetOption()`, `MatIsSymmetric()`, `MatIsHermitian()`, `MatIsStructurallySymmetric()`,
6283:     `MatIsSymmetricKnown()`, `MatIsHermitianKnown()`, `MatIsStructurallySymmetricKnown()`
6284: @*/
6285: PetscErrorCode MatGetOption(Mat mat, MatOption op, PetscBool *flg)
6286: {
6287:   PetscFunctionBegin;

6291:   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);
6292:   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()");

6294:   switch (op) {
6295:   case MAT_NO_OFF_PROC_ENTRIES:
6296:     *flg = mat->nooffprocentries;
6297:     break;
6298:   case MAT_NO_OFF_PROC_ZERO_ROWS:
6299:     *flg = mat->nooffproczerorows;
6300:     break;
6301:   case MAT_SYMMETRIC:
6302:     SETERRQ(PetscObjectComm((PetscObject)mat), PETSC_ERR_SUP, "Use MatIsSymmetric() or MatIsSymmetricKnown()");
6303:     break;
6304:   case MAT_HERMITIAN:
6305:     SETERRQ(PetscObjectComm((PetscObject)mat), PETSC_ERR_SUP, "Use MatIsHermitian() or MatIsHermitianKnown()");
6306:     break;
6307:   case MAT_STRUCTURALLY_SYMMETRIC:
6308:     SETERRQ(PetscObjectComm((PetscObject)mat), PETSC_ERR_SUP, "Use MatIsStructurallySymmetric() or MatIsStructurallySymmetricKnown()");
6309:     break;
6310:   case MAT_SPD:
6311:     SETERRQ(PetscObjectComm((PetscObject)mat), PETSC_ERR_SUP, "Use MatIsSPDKnown()");
6312:     break;
6313:   case MAT_SYMMETRY_ETERNAL:
6314:     *flg = mat->symmetry_eternal;
6315:     break;
6316:   case MAT_STRUCTURAL_SYMMETRY_ETERNAL:
6317:     *flg = mat->symmetry_eternal;
6318:     break;
6319:   default:
6320:     break;
6321:   }
6322:   PetscFunctionReturn(PETSC_SUCCESS);
6323: }

6325: /*@
6326:   MatZeroEntries - Zeros all entries of a matrix.  For sparse matrices
6327:   this routine retains the old nonzero structure.

6329:   Logically Collective

6331:   Input Parameter:
6332: . mat - the matrix

6334:   Level: intermediate

6336:   Note:
6337:   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.
6338:   See the Performance chapter of the users manual for information on preallocating matrices.

6340: .seealso: [](ch_matrices), `Mat`, `MatZeroRows()`, `MatZeroRowsColumns()`
6341: @*/
6342: PetscErrorCode MatZeroEntries(Mat mat)
6343: {
6344:   PetscFunctionBegin;
6347:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
6348:   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");
6349:   MatCheckPreallocated(mat, 1);

6351:   PetscCall(PetscLogEventBegin(MAT_ZeroEntries, mat, 0, 0, 0));
6352:   PetscUseTypeMethod(mat, zeroentries);
6353:   PetscCall(PetscLogEventEnd(MAT_ZeroEntries, mat, 0, 0, 0));
6354:   PetscCall(PetscObjectStateIncrease((PetscObject)mat));
6355:   PetscFunctionReturn(PETSC_SUCCESS);
6356: }

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

6362:   Collective

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

6372:   Level: intermediate

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

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

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

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

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

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

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

6397: .seealso: [](ch_matrices), `Mat`, `MatZeroRowsIS()`, `MatZeroRows()`, `MatZeroRowsLocalIS()`, `MatZeroRowsStencil()`, `MatZeroEntries()`, `MatZeroRowsLocal()`, `MatSetOption()`,
6398:           `MatZeroRowsColumnsLocal()`, `MatZeroRowsColumnsLocalIS()`, `MatZeroRowsColumnsIS()`, `MatZeroRowsColumnsStencil()`
6399: @*/
6400: PetscErrorCode MatZeroRowsColumns(Mat mat, PetscInt numRows, const PetscInt rows[], PetscScalar diag, Vec x, Vec b)
6401: {
6402:   PetscFunctionBegin;
6405:   if (numRows) PetscAssertPointer(rows, 3);
6406:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
6407:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
6408:   MatCheckPreallocated(mat, 1);

6410:   PetscUseTypeMethod(mat, zerorowscolumns, numRows, rows, diag, x, b);
6411:   PetscCall(MatViewFromOptions(mat, NULL, "-mat_view"));
6412:   PetscCall(PetscObjectStateIncrease((PetscObject)mat));
6413:   PetscFunctionReturn(PETSC_SUCCESS);
6414: }

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

6420:   Collective

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

6429:   Level: intermediate

6431:   Note:
6432:   See `MatZeroRowsColumns()` for details on how this routine operates.

6434: .seealso: [](ch_matrices), `Mat`, `MatZeroRowsIS()`, `MatZeroRowsColumns()`, `MatZeroRowsLocalIS()`, `MatZeroRowsStencil()`, `MatZeroEntries()`, `MatZeroRowsLocal()`, `MatSetOption()`,
6435:           `MatZeroRowsColumnsLocal()`, `MatZeroRowsColumnsLocalIS()`, `MatZeroRows()`, `MatZeroRowsColumnsStencil()`
6436: @*/
6437: PetscErrorCode MatZeroRowsColumnsIS(Mat mat, IS is, PetscScalar diag, Vec x, Vec b)
6438: {
6439:   PetscInt        numRows;
6440:   const PetscInt *rows;

6442:   PetscFunctionBegin;
6447:   PetscCall(ISGetLocalSize(is, &numRows));
6448:   PetscCall(ISGetIndices(is, &rows));
6449:   PetscCall(MatZeroRowsColumns(mat, numRows, rows, diag, x, b));
6450:   PetscCall(ISRestoreIndices(is, &rows));
6451:   PetscFunctionReturn(PETSC_SUCCESS);
6452: }

6454: /*@
6455:   MatZeroRows - Zeros all entries (except possibly the main diagonal)
6456:   of a set of rows of a matrix.

6458:   Collective

6460:   Input Parameters:
6461: + mat     - the matrix
6462: . numRows - the number of rows to zero
6463: . rows    - the global row indices
6464: . diag    - value put in the diagonal of the zeroed rows
6465: . x       - optional vector of solutions for zeroed rows (other entries in vector are not used), these must be set before this call
6466: - b       - optional vector of right-hand side, that will be adjusted by provided solution entries

6468:   Level: intermediate

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

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

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

6478:   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)
6479:   from the matrix.

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

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

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

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

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

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

6504: .seealso: [](ch_matrices), `Mat`, `MatZeroRowsIS()`, `MatZeroRowsColumns()`, `MatZeroRowsLocalIS()`, `MatZeroRowsStencil()`, `MatZeroEntries()`, `MatZeroRowsLocal()`, `MatSetOption()`,
6505:           `MatZeroRowsColumnsLocal()`, `MatZeroRowsColumnsLocalIS()`, `MatZeroRowsColumnsIS()`, `MatZeroRowsColumnsStencil()`, `PCREDISTRIBUTE`, `MAT_KEEP_NONZERO_PATTERN`
6506: @*/
6507: PetscErrorCode MatZeroRows(Mat mat, PetscInt numRows, const PetscInt rows[], PetscScalar diag, Vec x, Vec b)
6508: {
6509:   PetscFunctionBegin;
6512:   if (numRows) PetscAssertPointer(rows, 3);
6513:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
6514:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
6515:   MatCheckPreallocated(mat, 1);

6517:   PetscUseTypeMethod(mat, zerorows, numRows, rows, diag, x, b);
6518:   PetscCall(MatViewFromOptions(mat, NULL, "-mat_view"));
6519:   PetscCall(PetscObjectStateIncrease((PetscObject)mat));
6520:   PetscFunctionReturn(PETSC_SUCCESS);
6521: }

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

6527:   Collective

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

6536:   Level: intermediate

6538:   Note:
6539:   See `MatZeroRows()` for details on how this routine operates.

6541: .seealso: [](ch_matrices), `Mat`, `MatZeroRows()`, `MatZeroRowsColumns()`, `MatZeroRowsLocalIS()`, `MatZeroRowsStencil()`, `MatZeroEntries()`, `MatZeroRowsLocal()`, `MatSetOption()`,
6542:           `MatZeroRowsColumnsLocal()`, `MatZeroRowsColumnsLocalIS()`, `MatZeroRowsColumnsIS()`, `MatZeroRowsColumnsStencil()`, `IS`
6543: @*/
6544: PetscErrorCode MatZeroRowsIS(Mat mat, IS is, PetscScalar diag, Vec x, Vec b)
6545: {
6546:   PetscInt        numRows = 0;
6547:   const PetscInt *rows    = NULL;

6549:   PetscFunctionBegin;
6552:   if (is) {
6554:     PetscCall(ISGetLocalSize(is, &numRows));
6555:     PetscCall(ISGetIndices(is, &rows));
6556:   }
6557:   PetscCall(MatZeroRows(mat, numRows, rows, diag, x, b));
6558:   if (is) PetscCall(ISRestoreIndices(is, &rows));
6559:   PetscFunctionReturn(PETSC_SUCCESS);
6560: }

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

6566:   Collective

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

6576:   Level: intermediate

6578:   Notes:
6579:   See `MatZeroRows()` for details on how this routine operates.

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

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

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

6591:   Fortran Note:
6592:   `idxm` and `idxn` should be declared as
6593: .vb
6594:     MatStencil idxm(4, m)
6595: .ve
6596:   and the values inserted using
6597: .vb
6598:     idxm(MatStencil_i, 1) = i
6599:     idxm(MatStencil_j, 1) = j
6600:     idxm(MatStencil_k, 1) = k
6601:     idxm(MatStencil_c, 1) = c
6602:    etc
6603: .ve

6605: .seealso: [](ch_matrices), `Mat`, `MatStencil`, `MatZeroRowsIS()`, `MatZeroRowsColumns()`, `MatZeroRowsLocalIS()`, `MatZeroRows()`, `MatZeroEntries()`, `MatZeroRowsLocal()`, `MatSetOption()`,
6606:           `MatZeroRowsColumnsLocal()`, `MatZeroRowsColumnsLocalIS()`, `MatZeroRowsColumnsIS()`, `MatZeroRowsColumnsStencil()`
6607: @*/
6608: PetscErrorCode MatZeroRowsStencil(Mat mat, PetscInt numRows, const MatStencil rows[], PetscScalar diag, Vec x, Vec b)
6609: {
6610:   PetscInt  dim    = mat->stencil.dim;
6611:   PetscInt  sdim   = dim - (1 - (PetscInt)mat->stencil.noc);
6612:   PetscInt *dims   = mat->stencil.dims + 1;
6613:   PetscInt *starts = mat->stencil.starts;
6614:   PetscInt *dxm    = (PetscInt *)rows;
6615:   PetscInt *jdxm, i, j, tmp, numNewRows = 0;

6617:   PetscFunctionBegin;
6620:   if (numRows) PetscAssertPointer(rows, 3);

6622:   PetscCall(PetscMalloc1(numRows, &jdxm));
6623:   for (i = 0; i < numRows; ++i) {
6624:     /* Skip unused dimensions (they are ordered k, j, i, c) */
6625:     for (j = 0; j < 3 - sdim; ++j) dxm++;
6626:     /* Local index in X dir */
6627:     tmp = *dxm++ - starts[0];
6628:     /* Loop over remaining dimensions */
6629:     for (j = 0; j < dim - 1; ++j) {
6630:       /* If nonlocal, set index to be negative */
6631:       if ((*dxm++ - starts[j + 1]) < 0 || tmp < 0) tmp = PETSC_INT_MIN;
6632:       /* Update local index */
6633:       else tmp = tmp * dims[j] + *(dxm - 1) - starts[j + 1];
6634:     }
6635:     /* Skip component slot if necessary */
6636:     if (mat->stencil.noc) dxm++;
6637:     /* Local row number */
6638:     if (tmp >= 0) jdxm[numNewRows++] = tmp;
6639:   }
6640:   PetscCall(MatZeroRowsLocal(mat, numNewRows, jdxm, diag, x, b));
6641:   PetscCall(PetscFree(jdxm));
6642:   PetscFunctionReturn(PETSC_SUCCESS);
6643: }

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

6649:   Collective

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

6659:   Level: intermediate

6661:   Notes:
6662:   See `MatZeroRowsColumns()` for details on how this routine operates.

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

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

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

6674:   Fortran Note:
6675:   `idxm` and `idxn` should be declared as
6676: .vb
6677:     MatStencil idxm(4, m)
6678: .ve
6679:   and the values inserted using
6680: .vb
6681:     idxm(MatStencil_i, 1) = i
6682:     idxm(MatStencil_j, 1) = j
6683:     idxm(MatStencil_k, 1) = k
6684:     idxm(MatStencil_c, 1) = c
6685:     etc
6686: .ve

6688: .seealso: [](ch_matrices), `Mat`, `MatZeroRowsIS()`, `MatZeroRowsColumns()`, `MatZeroRowsLocalIS()`, `MatZeroRowsStencil()`, `MatZeroEntries()`, `MatZeroRowsLocal()`, `MatSetOption()`,
6689:           `MatZeroRowsColumnsLocal()`, `MatZeroRowsColumnsLocalIS()`, `MatZeroRowsColumnsIS()`, `MatZeroRows()`
6690: @*/
6691: PetscErrorCode MatZeroRowsColumnsStencil(Mat mat, PetscInt numRows, const MatStencil rows[], PetscScalar diag, Vec x, Vec b)
6692: {
6693:   PetscInt  dim    = mat->stencil.dim;
6694:   PetscInt  sdim   = dim - (1 - (PetscInt)mat->stencil.noc);
6695:   PetscInt *dims   = mat->stencil.dims + 1;
6696:   PetscInt *starts = mat->stencil.starts;
6697:   PetscInt *dxm    = (PetscInt *)rows;
6698:   PetscInt *jdxm, i, j, tmp, numNewRows = 0;

6700:   PetscFunctionBegin;
6703:   if (numRows) PetscAssertPointer(rows, 3);

6705:   PetscCall(PetscMalloc1(numRows, &jdxm));
6706:   for (i = 0; i < numRows; ++i) {
6707:     /* Skip unused dimensions (they are ordered k, j, i, c) */
6708:     for (j = 0; j < 3 - sdim; ++j) dxm++;
6709:     /* Local index in X dir */
6710:     tmp = *dxm++ - starts[0];
6711:     /* Loop over remaining dimensions */
6712:     for (j = 0; j < dim - 1; ++j) {
6713:       /* If nonlocal, set index to be negative */
6714:       if ((*dxm++ - starts[j + 1]) < 0 || tmp < 0) tmp = PETSC_INT_MIN;
6715:       /* Update local index */
6716:       else tmp = tmp * dims[j] + *(dxm - 1) - starts[j + 1];
6717:     }
6718:     /* Skip component slot if necessary */
6719:     if (mat->stencil.noc) dxm++;
6720:     /* Local row number */
6721:     if (tmp >= 0) jdxm[numNewRows++] = tmp;
6722:   }
6723:   PetscCall(MatZeroRowsColumnsLocal(mat, numNewRows, jdxm, diag, x, b));
6724:   PetscCall(PetscFree(jdxm));
6725:   PetscFunctionReturn(PETSC_SUCCESS);
6726: }

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

6732:   Collective

6734:   Input Parameters:
6735: + mat     - the matrix
6736: . numRows - the number of rows to remove
6737: . rows    - the local row indices
6738: . diag    - value put in all diagonals of eliminated rows
6739: . x       - optional vector of solutions for zeroed rows (other entries in vector are not used)
6740: - b       - optional vector of right-hand side, that will be adjusted by provided solution

6742:   Level: intermediate

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

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

6750: .seealso: [](ch_matrices), `Mat`, `MatZeroRowsIS()`, `MatZeroRowsColumns()`, `MatZeroRowsLocalIS()`, `MatZeroRowsStencil()`, `MatZeroEntries()`, `MatZeroRows()`, `MatSetOption()`,
6751:           `MatZeroRowsColumnsLocal()`, `MatZeroRowsColumnsLocalIS()`, `MatZeroRowsColumnsIS()`, `MatZeroRowsColumnsStencil()`
6752: @*/
6753: PetscErrorCode MatZeroRowsLocal(Mat mat, PetscInt numRows, const PetscInt rows[], PetscScalar diag, Vec x, Vec b)
6754: {
6755:   PetscFunctionBegin;
6758:   if (numRows) PetscAssertPointer(rows, 3);
6759:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
6760:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
6761:   MatCheckPreallocated(mat, 1);

6763:   if (mat->ops->zerorowslocal) {
6764:     PetscUseTypeMethod(mat, zerorowslocal, numRows, rows, diag, x, b);
6765:   } else {
6766:     IS        is, newis;
6767:     PetscInt *newRows, nl = 0;

6769:     PetscCheck(mat->rmap->mapping, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Need to provide local to global mapping to matrix first");
6770:     PetscCall(ISCreateGeneral(PETSC_COMM_SELF, numRows, rows, PETSC_USE_POINTER, &is));
6771:     PetscCall(ISLocalToGlobalMappingApplyIS(mat->rmap->mapping, is, &newis));
6772:     PetscCall(ISGetIndices(newis, (const PetscInt **)&newRows));
6773:     for (PetscInt i = 0; i < numRows; i++)
6774:       if (newRows[i] > -1) newRows[nl++] = newRows[i];
6775:     PetscUseTypeMethod(mat, zerorows, nl, newRows, diag, x, b);
6776:     PetscCall(ISRestoreIndices(newis, (const PetscInt **)&newRows));
6777:     PetscCall(ISDestroy(&newis));
6778:     PetscCall(ISDestroy(&is));
6779:   }
6780:   PetscCall(PetscObjectStateIncrease((PetscObject)mat));
6781:   PetscFunctionReturn(PETSC_SUCCESS);
6782: }

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

6788:   Collective

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

6797:   Level: intermediate

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

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

6805: .seealso: [](ch_matrices), `Mat`, `MatZeroRowsIS()`, `MatZeroRowsColumns()`, `MatZeroRows()`, `MatZeroRowsStencil()`, `MatZeroEntries()`, `MatZeroRowsLocal()`, `MatSetOption()`,
6806:           `MatZeroRowsColumnsLocal()`, `MatZeroRowsColumnsLocalIS()`, `MatZeroRowsColumnsIS()`, `MatZeroRowsColumnsStencil()`
6807: @*/
6808: PetscErrorCode MatZeroRowsLocalIS(Mat mat, IS is, PetscScalar diag, Vec x, Vec b)
6809: {
6810:   PetscInt        numRows;
6811:   const PetscInt *rows;

6813:   PetscFunctionBegin;
6817:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
6818:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
6819:   MatCheckPreallocated(mat, 1);

6821:   PetscCall(ISGetLocalSize(is, &numRows));
6822:   PetscCall(ISGetIndices(is, &rows));
6823:   PetscCall(MatZeroRowsLocal(mat, numRows, rows, diag, x, b));
6824:   PetscCall(ISRestoreIndices(is, &rows));
6825:   PetscFunctionReturn(PETSC_SUCCESS);
6826: }

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

6832:   Collective

6834:   Input Parameters:
6835: + mat     - the matrix
6836: . numRows - the number of rows to remove
6837: . rows    - the global row indices
6838: . diag    - value put in all diagonals of eliminated rows
6839: . x       - optional vector of solutions for zeroed rows (other entries in vector are not used)
6840: - b       - optional vector of right-hand side, that will be adjusted by provided solution

6842:   Level: intermediate

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

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

6850: .seealso: [](ch_matrices), `Mat`, `MatZeroRowsIS()`, `MatZeroRowsColumns()`, `MatZeroRowsLocalIS()`, `MatZeroRowsStencil()`, `MatZeroEntries()`, `MatZeroRowsLocal()`, `MatSetOption()`,
6851:           `MatZeroRows()`, `MatZeroRowsColumnsLocalIS()`, `MatZeroRowsColumnsIS()`, `MatZeroRowsColumnsStencil()`
6852: @*/
6853: PetscErrorCode MatZeroRowsColumnsLocal(Mat mat, PetscInt numRows, const PetscInt rows[], PetscScalar diag, Vec x, Vec b)
6854: {
6855:   PetscFunctionBegin;
6858:   if (numRows) PetscAssertPointer(rows, 3);
6859:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
6860:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
6861:   MatCheckPreallocated(mat, 1);

6863:   if (mat->ops->zerorowscolumnslocal) {
6864:     PetscUseTypeMethod(mat, zerorowscolumnslocal, numRows, rows, diag, x, b);
6865:   } else {
6866:     IS        is, newis;
6867:     PetscInt *newRows, nl = 0;

6869:     PetscCheck(mat->rmap->mapping, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Need to provide local to global mapping to matrix first");
6870:     PetscCall(ISCreateGeneral(PETSC_COMM_SELF, numRows, rows, PETSC_USE_POINTER, &is));
6871:     PetscCall(ISLocalToGlobalMappingApplyIS(mat->rmap->mapping, is, &newis));
6872:     PetscCall(ISGetIndices(newis, (const PetscInt **)&newRows));
6873:     for (PetscInt i = 0; i < numRows; i++)
6874:       if (newRows[i] > -1) newRows[nl++] = newRows[i];
6875:     PetscUseTypeMethod(mat, zerorowscolumns, nl, newRows, diag, x, b);
6876:     PetscCall(ISRestoreIndices(newis, (const PetscInt **)&newRows));
6877:     PetscCall(ISDestroy(&newis));
6878:     PetscCall(ISDestroy(&is));
6879:   }
6880:   PetscCall(PetscObjectStateIncrease((PetscObject)mat));
6881:   PetscFunctionReturn(PETSC_SUCCESS);
6882: }

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

6888:   Collective

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

6897:   Level: intermediate

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

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

6905: .seealso: [](ch_matrices), `Mat`, `MatZeroRowsIS()`, `MatZeroRowsColumns()`, `MatZeroRowsLocalIS()`, `MatZeroRowsStencil()`, `MatZeroEntries()`, `MatZeroRowsLocal()`, `MatSetOption()`,
6906:           `MatZeroRowsColumnsLocal()`, `MatZeroRows()`, `MatZeroRowsColumnsIS()`, `MatZeroRowsColumnsStencil()`
6907: @*/
6908: PetscErrorCode MatZeroRowsColumnsLocalIS(Mat mat, IS is, PetscScalar diag, Vec x, Vec b)
6909: {
6910:   PetscInt        numRows;
6911:   const PetscInt *rows;

6913:   PetscFunctionBegin;
6917:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
6918:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
6919:   MatCheckPreallocated(mat, 1);

6921:   PetscCall(ISGetLocalSize(is, &numRows));
6922:   PetscCall(ISGetIndices(is, &rows));
6923:   PetscCall(MatZeroRowsColumnsLocal(mat, numRows, rows, diag, x, b));
6924:   PetscCall(ISRestoreIndices(is, &rows));
6925:   PetscFunctionReturn(PETSC_SUCCESS);
6926: }

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

6931:   Not Collective

6933:   Input Parameter:
6934: . mat - the matrix

6936:   Output Parameters:
6937: + m - the number of global rows
6938: - n - the number of global columns

6940:   Level: beginner

6942:   Note:
6943:   Both output parameters can be `NULL` on input.

6945: .seealso: [](ch_matrices), `Mat`, `MatSetSizes()`, `MatGetLocalSize()`
6946: @*/
6947: PetscErrorCode MatGetSize(Mat mat, PetscInt *m, PetscInt *n)
6948: {
6949:   PetscFunctionBegin;
6951:   if (m) *m = mat->rmap->N;
6952:   if (n) *n = mat->cmap->N;
6953:   PetscFunctionReturn(PETSC_SUCCESS);
6954: }

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

6960:   Not Collective

6962:   Input Parameter:
6963: . mat - the matrix

6965:   Output Parameters:
6966: + m - the number of local rows, use `NULL` to not obtain this value
6967: - n - the number of local columns, use `NULL` to not obtain this value

6969:   Level: beginner

6971: .seealso: [](ch_matrices), `Mat`, `MatSetSizes()`, `MatGetSize()`
6972: @*/
6973: PetscErrorCode MatGetLocalSize(Mat mat, PetscInt *m, PetscInt *n)
6974: {
6975:   PetscFunctionBegin;
6977:   if (m) PetscAssertPointer(m, 2);
6978:   if (n) PetscAssertPointer(n, 3);
6979:   if (m) *m = mat->rmap->n;
6980:   if (n) *n = mat->cmap->n;
6981:   PetscFunctionReturn(PETSC_SUCCESS);
6982: }

6984: /*@
6985:   MatGetOwnershipRangeColumn - Returns the range of matrix columns associated with rows of a
6986:   vector one multiplies this matrix by that are owned by this processor.

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

6990:   Input Parameter:
6991: . mat - the matrix

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

6997:   Level: developer

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

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

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

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

7011: .seealso: [](ch_matrices), `Mat`, `MatGetOwnershipRange()`, `MatGetOwnershipRanges()`, `MatGetOwnershipRangesColumn()`, `PetscLayout`,
7012:           `MatSetSizes()`, `MatCreateAIJ()`, `DMDAGetGhostCorners()`, `DM`
7013: @*/
7014: PetscErrorCode MatGetOwnershipRangeColumn(Mat mat, PetscInt *m, PetscInt *n)
7015: {
7016:   PetscFunctionBegin;
7019:   if (m) PetscAssertPointer(m, 2);
7020:   if (n) PetscAssertPointer(n, 3);
7021:   MatCheckPreallocated(mat, 1);
7022:   if (m) *m = mat->cmap->rstart;
7023:   if (n) *n = mat->cmap->rend;
7024:   PetscFunctionReturn(PETSC_SUCCESS);
7025: }

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

7031:   Not Collective

7033:   Input Parameter:
7034: . mat - the matrix

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

7040:   Level: beginner

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

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

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

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

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

7057: .seealso: [](ch_matrices), `Mat`, `MatGetOwnershipRanges()`, `MatGetOwnershipRangeColumn()`, `MatGetOwnershipRangesColumn()`, `PetscSplitOwnership()`,
7058:           `PetscSplitOwnershipBlock()`, `PetscLayout`, `MatSetSizes()`, `MatCreateAIJ()`, `DMDAGetGhostCorners()`, `DM`
7059: @*/
7060: PetscErrorCode MatGetOwnershipRange(Mat mat, PetscInt *m, PetscInt *n)
7061: {
7062:   PetscFunctionBegin;
7065:   if (m) PetscAssertPointer(m, 2);
7066:   if (n) PetscAssertPointer(n, 3);
7067:   MatCheckPreallocated(mat, 1);
7068:   if (m) *m = mat->rmap->rstart;
7069:   if (n) *n = mat->rmap->rend;
7070:   PetscFunctionReturn(PETSC_SUCCESS);
7071: }

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

7077:   Not Collective, unless matrix has not been allocated

7079:   Input Parameter:
7080: . mat - the matrix

7082:   Output Parameter:
7083: . ranges - start of each processors portion plus one more than the total length at the end, of length `size` + 1
7084:            where `size` is the number of MPI processes used by `mat`

7086:   Level: beginner

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

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

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

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

7101: .seealso: [](ch_matrices), `Mat`, `MatGetOwnershipRange()`, `MatGetOwnershipRangeColumn()`, `MatGetOwnershipRangesColumn()`, `PetscLayout`,
7102:           `PetscSplitOwnership()`, `PetscSplitOwnershipBlock()`, `MatSetSizes()`, `MatCreateAIJ()`,
7103:           `DMDAGetGhostCorners()`, `DM`
7104: @*/
7105: PetscErrorCode MatGetOwnershipRanges(Mat mat, const PetscInt *ranges[])
7106: {
7107:   PetscFunctionBegin;
7110:   MatCheckPreallocated(mat, 1);
7111:   PetscCall(PetscLayoutGetRanges(mat->rmap, ranges));
7112:   PetscFunctionReturn(PETSC_SUCCESS);
7113: }

7115: /*@C
7116:   MatGetOwnershipRangesColumn - Returns the ranges of matrix columns associated with rows of a
7117:   vector one multiplies this vector by that are owned by each processor.

7119:   Not Collective, unless matrix has not been allocated

7121:   Input Parameter:
7122: . mat - the matrix

7124:   Output Parameter:
7125: . ranges - start of each processors portion plus one more than the total length at the end

7127:   Level: beginner

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

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

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

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

7141: .seealso: [](ch_matrices), `Mat`, `MatGetOwnershipRange()`, `MatGetOwnershipRangeColumn()`, `MatGetOwnershipRanges()`,
7142:           `PetscSplitOwnership()`, `PetscSplitOwnershipBlock()`, `PetscLayout`, `MatSetSizes()`, `MatCreateAIJ()`,
7143:           `DMDAGetGhostCorners()`, `DM`
7144: @*/
7145: PetscErrorCode MatGetOwnershipRangesColumn(Mat mat, const PetscInt *ranges[])
7146: {
7147:   PetscFunctionBegin;
7150:   MatCheckPreallocated(mat, 1);
7151:   PetscCall(PetscLayoutGetRanges(mat->cmap, ranges));
7152:   PetscFunctionReturn(PETSC_SUCCESS);
7153: }

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

7158:   Not Collective

7160:   Input Parameter:
7161: . A - matrix

7163:   Output Parameters:
7164: + rows - rows in which this process owns elements, , use `NULL` to not obtain this value
7165: - cols - columns in which this process owns elements, use `NULL` to not obtain this value

7167:   Level: intermediate

7169:   Note:
7170:   You should call `ISDestroy()` on the returned `IS`

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

7177: .seealso: [](ch_matrices), `IS`, `Mat`, `MatGetOwnershipRanges()`, `MatSetValues()`, `MATELEMENTAL`, `MATSCALAPACK`
7178: @*/
7179: PetscErrorCode MatGetOwnershipIS(Mat A, IS *rows, IS *cols)
7180: {
7181:   PetscErrorCode (*f)(Mat, IS *, IS *);

7183:   PetscFunctionBegin;
7186:   MatCheckPreallocated(A, 1);
7187:   PetscCall(PetscObjectQueryFunction((PetscObject)A, "MatGetOwnershipIS_C", &f));
7188:   if (f) {
7189:     PetscCall((*f)(A, rows, cols));
7190:   } else { /* Create a standard row-based partition, each process is responsible for ALL columns in their row block */
7191:     if (rows) PetscCall(ISCreateStride(PETSC_COMM_SELF, A->rmap->n, A->rmap->rstart, 1, rows));
7192:     if (cols) PetscCall(ISCreateStride(PETSC_COMM_SELF, A->cmap->N, 0, 1, cols));
7193:   }
7194:   PetscFunctionReturn(PETSC_SUCCESS);
7195: }

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

7202:   Collective

7204:   Input Parameters:
7205: + fact - the factorized matrix obtained with `MatGetFactor()`
7206: . mat  - the matrix
7207: . row  - row permutation
7208: . col  - column permutation
7209: - info - structure containing
7210: .vb
7211:       levels - number of levels of fill.
7212:       expected fill - as ratio of original fill.
7213:       1 or 0 - indicating force fill on diagonal (improves robustness for matrices
7214:                 missing diagonal entries)
7215: .ve

7217:   Level: developer

7219:   Notes:
7220:   See [Matrix Factorization](sec_matfactor) for additional information.

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

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

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

7231: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatGetFactor()`, `MatLUFactorSymbolic()`, `MatLUFactorNumeric()`, `MatCholeskyFactor()`,
7232:           `MatGetOrdering()`, `MatFactorInfo`
7233: @*/
7234: PetscErrorCode MatILUFactorSymbolic(Mat fact, Mat mat, IS row, IS col, const MatFactorInfo *info)
7235: {
7236:   PetscFunctionBegin;
7241:   PetscAssertPointer(info, 5);
7242:   PetscAssertPointer(fact, 1);
7243:   PetscCheck(info->levels >= 0, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_OUTOFRANGE, "Levels of fill negative %" PetscInt_FMT, (PetscInt)info->levels);
7244:   PetscCheck(info->fill >= 1.0, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_OUTOFRANGE, "Expected fill less than 1.0 %g", (double)info->fill);
7245:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
7246:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
7247:   MatCheckPreallocated(mat, 2);

7249:   if (!fact->trivialsymbolic) PetscCall(PetscLogEventBegin(MAT_ILUFactorSymbolic, mat, row, col, 0));
7250:   PetscUseTypeMethod(fact, ilufactorsymbolic, mat, row, col, info);
7251:   if (!fact->trivialsymbolic) PetscCall(PetscLogEventEnd(MAT_ILUFactorSymbolic, mat, row, col, 0));
7252:   PetscFunctionReturn(PETSC_SUCCESS);
7253: }

7255: /*@
7256:   MatICCFactorSymbolic - Performs symbolic incomplete
7257:   Cholesky factorization for a symmetric matrix.  Use
7258:   `MatCholeskyFactorNumeric()` to complete the factorization.

7260:   Collective

7262:   Input Parameters:
7263: + fact - the factorized matrix obtained with `MatGetFactor()`
7264: . mat  - the matrix to be factored
7265: . perm - row and column permutation
7266: - info - structure containing
7267: .vb
7268:       levels - number of levels of fill.
7269:       expected fill - as ratio of original fill.
7270: .ve

7272:   Level: developer

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

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

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

7284: .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatCholeskyFactorNumeric()`, `MatCholeskyFactor()`, `MatFactorInfo`
7285: @*/
7286: PetscErrorCode MatICCFactorSymbolic(Mat fact, Mat mat, IS perm, const MatFactorInfo *info)
7287: {
7288:   PetscFunctionBegin;
7292:   PetscAssertPointer(info, 4);
7293:   PetscAssertPointer(fact, 1);
7294:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
7295:   PetscCheck(info->levels >= 0, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_OUTOFRANGE, "Levels negative %" PetscInt_FMT, (PetscInt)info->levels);
7296:   PetscCheck(info->fill >= 1.0, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_OUTOFRANGE, "Expected fill less than 1.0 %g", (double)info->fill);
7297:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
7298:   MatCheckPreallocated(mat, 2);

7300:   if (!fact->trivialsymbolic) PetscCall(PetscLogEventBegin(MAT_ICCFactorSymbolic, mat, perm, 0, 0));
7301:   PetscUseTypeMethod(fact, iccfactorsymbolic, mat, perm, info);
7302:   if (!fact->trivialsymbolic) PetscCall(PetscLogEventEnd(MAT_ICCFactorSymbolic, mat, perm, 0, 0));
7303:   PetscFunctionReturn(PETSC_SUCCESS);
7304: }

7306: /*@C
7307:   MatCreateSubMatrices - Extracts several submatrices from a matrix. If submat
7308:   points to an array of valid matrices, they may be reused to store the new
7309:   submatrices.

7311:   Collective

7313:   Input Parameters:
7314: + mat   - the matrix
7315: . n     - the number of submatrixes to be extracted (on this processor, may be zero)
7316: . irow  - index set of rows to extract
7317: . icol  - index set of columns to extract
7318: - scall - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`

7320:   Output Parameter:
7321: . submat - the array of submatrices

7323:   Level: advanced

7325:   Notes:
7326:   `MatCreateSubMatrices()` can extract ONLY sequential submatrices
7327:   (from both sequential and parallel matrices). Use `MatCreateSubMatrix()`
7328:   to extract a parallel submatrix.

7330:   Some matrix types place restrictions on the row and column
7331:   indices, such as that they be sorted or that they be equal to each other.

7333:   The index sets may not have duplicate entries.

7335:   When extracting submatrices from a parallel matrix, each processor can
7336:   form a different submatrix by setting the rows and columns of its
7337:   individual index sets according to the local submatrix desired.

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

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

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

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

7353:   Fortran Note:
7354: .vb
7355:   Mat, pointer :: submat(:)
7356: .ve

7358: .seealso: [](ch_matrices), `Mat`, `MatDestroySubMatrices()`, `MatCreateSubMatrix()`, `MatGetRow()`, `MatGetDiagonal()`, `MatReuse`
7359: @*/
7360: PetscErrorCode MatCreateSubMatrices(Mat mat, PetscInt n, const IS irow[], const IS icol[], MatReuse scall, Mat *submat[])
7361: {
7362:   PetscInt  i;
7363:   PetscBool eq;

7365:   PetscFunctionBegin;
7368:   if (n) {
7369:     PetscAssertPointer(irow, 3);
7371:     PetscAssertPointer(icol, 4);
7373:   }
7374:   PetscAssertPointer(submat, 6);
7375:   if (n && scall == MAT_REUSE_MATRIX) {
7376:     PetscAssertPointer(*submat, 6);
7378:   }
7379:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
7380:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
7381:   MatCheckPreallocated(mat, 1);
7382:   PetscCall(PetscLogEventBegin(MAT_CreateSubMats, mat, 0, 0, 0));
7383:   PetscUseTypeMethod(mat, createsubmatrices, n, irow, icol, scall, submat);
7384:   PetscCall(PetscLogEventEnd(MAT_CreateSubMats, mat, 0, 0, 0));
7385:   for (i = 0; i < n; i++) {
7386:     (*submat)[i]->factortype = MAT_FACTOR_NONE; /* in case in place factorization was previously done on submatrix */
7387:     PetscCall(ISEqualUnsorted(irow[i], icol[i], &eq));
7388:     if (eq) PetscCall(MatPropagateSymmetryOptions(mat, (*submat)[i]));
7389: #if defined(PETSC_HAVE_VIENNACL) || defined(PETSC_HAVE_CUDA) || defined(PETSC_HAVE_HIP)
7390:     if (mat->boundtocpu && mat->bindingpropagates) {
7391:       PetscCall(MatBindToCPU((*submat)[i], PETSC_TRUE));
7392:       PetscCall(MatSetBindingPropagates((*submat)[i], PETSC_TRUE));
7393:     }
7394: #endif
7395:   }
7396:   PetscFunctionReturn(PETSC_SUCCESS);
7397: }

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

7402:   Collective

7404:   Input Parameters:
7405: + mat   - the matrix
7406: . n     - the number of submatrixes to be extracted
7407: . irow  - index set of rows to extract
7408: . icol  - index set of columns to extract
7409: - scall - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`

7411:   Output Parameter:
7412: . submat - the array of submatrices

7414:   Level: advanced

7416:   Note:
7417:   This is used by `PCGASM`

7419: .seealso: [](ch_matrices), `Mat`, `PCGASM`, `MatCreateSubMatrices()`, `MatCreateSubMatrix()`, `MatGetRow()`, `MatGetDiagonal()`, `MatReuse`
7420: @*/
7421: PetscErrorCode MatCreateSubMatricesMPI(Mat mat, PetscInt n, const IS irow[], const IS icol[], MatReuse scall, Mat *submat[])
7422: {
7423:   PetscInt  i;
7424:   PetscBool eq;

7426:   PetscFunctionBegin;
7429:   if (n) {
7430:     PetscAssertPointer(irow, 3);
7432:     PetscAssertPointer(icol, 4);
7434:   }
7435:   PetscAssertPointer(submat, 6);
7436:   if (n && scall == MAT_REUSE_MATRIX) {
7437:     PetscAssertPointer(*submat, 6);
7439:   }
7440:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
7441:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
7442:   MatCheckPreallocated(mat, 1);

7444:   PetscCall(PetscLogEventBegin(MAT_CreateSubMats, mat, 0, 0, 0));
7445:   PetscUseTypeMethod(mat, createsubmatricesmpi, n, irow, icol, scall, submat);
7446:   PetscCall(PetscLogEventEnd(MAT_CreateSubMats, mat, 0, 0, 0));
7447:   for (i = 0; i < n; i++) {
7448:     PetscCall(ISEqualUnsorted(irow[i], icol[i], &eq));
7449:     if (eq) PetscCall(MatPropagateSymmetryOptions(mat, (*submat)[i]));
7450:   }
7451:   PetscFunctionReturn(PETSC_SUCCESS);
7452: }

7454: /*@C
7455:   MatDestroyMatrices - Destroys an array of matrices

7457:   Collective

7459:   Input Parameters:
7460: + n   - the number of local matrices
7461: - mat - the matrices (this is a pointer to the array of matrices)

7463:   Level: advanced

7465:   Notes:
7466:   Frees not only the matrices, but also the array that contains the matrices

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

7470: .seealso: [](ch_matrices), `Mat`, `MatCreateSubMatrices()`, `MatDestroySubMatrices()`
7471: @*/
7472: PetscErrorCode MatDestroyMatrices(PetscInt n, Mat *mat[])
7473: {
7474:   PetscInt i;

7476:   PetscFunctionBegin;
7477:   if (!*mat) PetscFunctionReturn(PETSC_SUCCESS);
7478:   PetscCheck(n >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Trying to destroy negative number of matrices %" PetscInt_FMT, n);
7479:   PetscAssertPointer(mat, 2);

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

7483:   /* memory is allocated even if n = 0 */
7484:   PetscCall(PetscFree(*mat));
7485:   PetscFunctionReturn(PETSC_SUCCESS);
7486: }

7488: /*@C
7489:   MatDestroySubMatrices - Destroys a set of matrices obtained with `MatCreateSubMatrices()`.

7491:   Collective

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

7497:   Level: advanced

7499:   Note:
7500:   Frees not only the matrices, but also the array that contains the matrices

7502: .seealso: [](ch_matrices), `Mat`, `MatCreateSubMatrices()`, `MatDestroyMatrices()`
7503: @*/
7504: PetscErrorCode MatDestroySubMatrices(PetscInt n, Mat *mat[])
7505: {
7506:   Mat mat0;

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

7514:   mat0 = (*mat)[0];
7515:   if (mat0 && mat0->ops->destroysubmatrices) {
7516:     PetscCall((*mat0->ops->destroysubmatrices)(n, mat));
7517:   } else {
7518:     PetscCall(MatDestroyMatrices(n, mat));
7519:   }
7520:   PetscFunctionReturn(PETSC_SUCCESS);
7521: }

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

7526:   Collective

7528:   Input Parameter:
7529: . mat - the matrix

7531:   Output Parameter:
7532: . matstruct - the sequential matrix with the nonzero structure of `mat`

7534:   Level: developer

7536: .seealso: [](ch_matrices), `Mat`, `MatDestroySeqNonzeroStructure()`, `MatCreateSubMatrices()`, `MatDestroyMatrices()`
7537: @*/
7538: PetscErrorCode MatGetSeqNonzeroStructure(Mat mat, Mat *matstruct)
7539: {
7540:   PetscFunctionBegin;
7542:   PetscAssertPointer(matstruct, 2);

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

7548:   PetscCall(PetscLogEventBegin(MAT_GetSeqNonzeroStructure, mat, 0, 0, 0));
7549:   PetscUseTypeMethod(mat, getseqnonzerostructure, matstruct);
7550:   PetscCall(PetscLogEventEnd(MAT_GetSeqNonzeroStructure, mat, 0, 0, 0));
7551:   PetscFunctionReturn(PETSC_SUCCESS);
7552: }

7554: /*@C
7555:   MatDestroySeqNonzeroStructure - Destroys matrix obtained with `MatGetSeqNonzeroStructure()`.

7557:   Collective

7559:   Input Parameter:
7560: . mat - the matrix

7562:   Level: advanced

7564:   Note:
7565:   This is not needed, one can just call `MatDestroy()`

7567: .seealso: [](ch_matrices), `Mat`, `MatGetSeqNonzeroStructure()`
7568: @*/
7569: PetscErrorCode MatDestroySeqNonzeroStructure(Mat *mat)
7570: {
7571:   PetscFunctionBegin;
7572:   PetscAssertPointer(mat, 1);
7573:   PetscCall(MatDestroy(mat));
7574:   PetscFunctionReturn(PETSC_SUCCESS);
7575: }

7577: /*@
7578:   MatIncreaseOverlap - Given a set of submatrices indicated by index sets,
7579:   replaces the index sets by larger ones that represent submatrices with
7580:   additional overlap.

7582:   Collective

7584:   Input Parameters:
7585: + mat - the matrix
7586: . n   - the number of index sets
7587: . is  - the array of index sets (these index sets will changed during the call)
7588: - ov  - the additional overlap requested

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

7593:   Level: developer

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

7600: .seealso: [](ch_matrices), `Mat`, `PCASM`, `MatSetBlockSize()`, `MatIncreaseOverlapSplit()`, `MatCreateSubMatrices()`
7601: @*/
7602: PetscErrorCode MatIncreaseOverlap(Mat mat, PetscInt n, IS is[], PetscInt ov)
7603: {
7604:   PetscInt i, bs, cbs;

7606:   PetscFunctionBegin;
7610:   PetscCheck(n >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Must have one or more domains, you have %" PetscInt_FMT, n);
7611:   if (n) {
7612:     PetscAssertPointer(is, 3);
7614:   }
7615:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
7616:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
7617:   MatCheckPreallocated(mat, 1);

7619:   if (!ov || !n) PetscFunctionReturn(PETSC_SUCCESS);
7620:   PetscCall(PetscLogEventBegin(MAT_IncreaseOverlap, mat, 0, 0, 0));
7621:   PetscUseTypeMethod(mat, increaseoverlap, n, is, ov);
7622:   PetscCall(PetscLogEventEnd(MAT_IncreaseOverlap, mat, 0, 0, 0));
7623:   PetscCall(MatGetBlockSizes(mat, &bs, &cbs));
7624:   if (bs == cbs) {
7625:     for (i = 0; i < n; i++) PetscCall(ISSetBlockSize(is[i], bs));
7626:   }
7627:   PetscFunctionReturn(PETSC_SUCCESS);
7628: }

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

7632: /*@
7633:   MatIncreaseOverlapSplit - Given a set of submatrices indicated by index sets across
7634:   a sub communicator, replaces the index sets by larger ones that represent submatrices with
7635:   additional overlap.

7637:   Collective

7639:   Input Parameters:
7640: + mat - the matrix
7641: . n   - the number of index sets
7642: . is  - the array of index sets (these index sets will changed during the call)
7643: - ov  - the additional overlap requested

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

7648:   Level: developer

7650: .seealso: [](ch_matrices), `Mat`, `MatCreateSubMatrices()`, `MatIncreaseOverlap()`
7651: @*/
7652: PetscErrorCode MatIncreaseOverlapSplit(Mat mat, PetscInt n, IS is[], PetscInt ov)
7653: {
7654:   PetscInt i;

7656:   PetscFunctionBegin;
7659:   PetscCheck(n >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Must have one or more domains, you have %" PetscInt_FMT, n);
7660:   if (n) {
7661:     PetscAssertPointer(is, 3);
7663:   }
7664:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
7665:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
7666:   MatCheckPreallocated(mat, 1);
7667:   if (!ov) PetscFunctionReturn(PETSC_SUCCESS);
7668:   PetscCall(PetscLogEventBegin(MAT_IncreaseOverlap, mat, 0, 0, 0));
7669:   for (i = 0; i < n; i++) PetscCall(MatIncreaseOverlapSplit_Single(mat, &is[i], ov));
7670:   PetscCall(PetscLogEventEnd(MAT_IncreaseOverlap, mat, 0, 0, 0));
7671:   PetscFunctionReturn(PETSC_SUCCESS);
7672: }

7674: /*@
7675:   MatGetBlockSize - Returns the matrix block size.

7677:   Not Collective

7679:   Input Parameter:
7680: . mat - the matrix

7682:   Output Parameter:
7683: . bs - block size

7685:   Level: intermediate

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

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

7692: .seealso: [](ch_matrices), `Mat`, `MATBAIJ`, `MATSBAIJ`, `MatCreateSeqBAIJ()`, `MatCreateBAIJ()`, `MatGetBlockSizes()`
7693: @*/
7694: PetscErrorCode MatGetBlockSize(Mat mat, PetscInt *bs)
7695: {
7696:   PetscFunctionBegin;
7698:   PetscAssertPointer(bs, 2);
7699:   *bs = mat->rmap->bs;
7700:   PetscFunctionReturn(PETSC_SUCCESS);
7701: }

7703: /*@
7704:   MatGetBlockSizes - Returns the matrix block row and column sizes.

7706:   Not Collective

7708:   Input Parameter:
7709: . mat - the matrix

7711:   Output Parameters:
7712: + rbs - row block size
7713: - cbs - column block size

7715:   Level: intermediate

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

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

7723: .seealso: [](ch_matrices), `Mat`, `MATBAIJ`, `MATSBAIJ`, `MatCreateSeqBAIJ()`, `MatCreateBAIJ()`, `MatGetBlockSize()`, `MatSetBlockSize()`, `MatSetBlockSizes()`
7724: @*/
7725: PetscErrorCode MatGetBlockSizes(Mat mat, PetscInt *rbs, PetscInt *cbs)
7726: {
7727:   PetscFunctionBegin;
7729:   if (rbs) PetscAssertPointer(rbs, 2);
7730:   if (cbs) PetscAssertPointer(cbs, 3);
7731:   if (rbs) *rbs = mat->rmap->bs;
7732:   if (cbs) *cbs = mat->cmap->bs;
7733:   PetscFunctionReturn(PETSC_SUCCESS);
7734: }

7736: /*@
7737:   MatSetBlockSize - Sets the matrix block size.

7739:   Logically Collective

7741:   Input Parameters:
7742: + mat - the matrix
7743: - bs  - block size

7745:   Level: intermediate

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

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

7754: .seealso: [](ch_matrices), `Mat`, `MATBAIJ`, `MATSBAIJ`, `MATAIJ`, `MatCreateSeqBAIJ()`, `MatCreateBAIJ()`, `MatGetBlockSize()`, `MatSetBlockSizes()`, `MatGetBlockSizes()`
7755: @*/
7756: PetscErrorCode MatSetBlockSize(Mat mat, PetscInt bs)
7757: {
7758:   PetscFunctionBegin;
7761:   PetscCall(MatSetBlockSizes(mat, bs, bs));
7762:   PetscFunctionReturn(PETSC_SUCCESS);
7763: }

7765: typedef struct {
7766:   PetscInt         n;
7767:   IS              *is;
7768:   Mat             *mat;
7769:   PetscObjectState nonzerostate;
7770:   Mat              C;
7771: } EnvelopeData;

7773: static PetscErrorCode EnvelopeDataDestroy(PetscCtxRt ptr)
7774: {
7775:   EnvelopeData *edata = *(EnvelopeData **)ptr;

7777:   PetscFunctionBegin;
7778:   for (PetscInt i = 0; i < edata->n; i++) PetscCall(ISDestroy(&edata->is[i]));
7779:   PetscCall(PetscFree(edata->is));
7780:   PetscCall(PetscFree(edata));
7781:   PetscFunctionReturn(PETSC_SUCCESS);
7782: }

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

7788:   Collective

7790:   Input Parameter:
7791: . mat - the matrix

7793:   Level: intermediate

7795:   Notes:
7796:   There can be zeros within the blocks

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

7800: .seealso: [](ch_matrices), `Mat`, `MatInvertVariableBlockEnvelope()`, `MatSetVariableBlockSizes()`
7801: @*/
7802: PetscErrorCode MatComputeVariableBlockEnvelope(Mat mat)
7803: {
7804:   PetscInt           n, *sizes, *starts, i = 0, env = 0, tbs = 0, lblocks = 0, rstart, II, ln = 0, cnt = 0, cstart, cend;
7805:   PetscInt          *diag, *odiag, sc;
7806:   VecScatter         scatter;
7807:   PetscScalar       *seqv;
7808:   const PetscScalar *parv;
7809:   const PetscInt    *ia, *ja;
7810:   PetscBool          set, flag, done;
7811:   Mat                AA = mat, A;
7812:   MPI_Comm           comm;
7813:   PetscMPIInt        rank, size, tag;
7814:   MPI_Status         status;
7815:   PetscContainer     container;
7816:   EnvelopeData      *edata;
7817:   Vec                seq, par;
7818:   IS                 isglobal;

7820:   PetscFunctionBegin;
7822:   PetscCall(MatIsSymmetricKnown(mat, &set, &flag));
7823:   if (!set || !flag) {
7824:     /* TODO: only needs nonzero structure of transpose */
7825:     PetscCall(MatTranspose(mat, MAT_INITIAL_MATRIX, &AA));
7826:     PetscCall(MatAXPY(AA, 1.0, mat, DIFFERENT_NONZERO_PATTERN));
7827:   }
7828:   PetscCall(MatAIJGetLocalMat(AA, &A));
7829:   PetscCall(MatGetRowIJ(A, 0, PETSC_FALSE, PETSC_FALSE, &n, &ia, &ja, &done));
7830:   PetscCheck(done, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "Unable to get IJ structure from matrix");

7832:   PetscCall(MatGetLocalSize(mat, &n, NULL));
7833:   PetscCall(PetscObjectGetNewTag((PetscObject)mat, &tag));
7834:   PetscCall(PetscObjectGetComm((PetscObject)mat, &comm));
7835:   PetscCallMPI(MPI_Comm_size(comm, &size));
7836:   PetscCallMPI(MPI_Comm_rank(comm, &rank));

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

7840:   if (rank > 0) {
7841:     PetscCallMPI(MPI_Recv(&env, 1, MPIU_INT, rank - 1, tag, comm, &status));
7842:     PetscCallMPI(MPI_Recv(&tbs, 1, MPIU_INT, rank - 1, tag, comm, &status));
7843:   }
7844:   PetscCall(MatGetOwnershipRange(mat, &rstart, NULL));
7845:   for (i = 0; i < n; i++) {
7846:     env = PetscMax(env, ja[ia[i + 1] - 1]);
7847:     II  = rstart + i;
7848:     if (env == II) {
7849:       starts[lblocks]  = tbs;
7850:       sizes[lblocks++] = 1 + II - tbs;
7851:       tbs              = 1 + II;
7852:     }
7853:   }
7854:   if (rank < size - 1) {
7855:     PetscCallMPI(MPI_Send(&env, 1, MPIU_INT, rank + 1, tag, comm));
7856:     PetscCallMPI(MPI_Send(&tbs, 1, MPIU_INT, rank + 1, tag, comm));
7857:   }

7859:   PetscCall(MatRestoreRowIJ(A, 0, PETSC_FALSE, PETSC_FALSE, &n, &ia, &ja, &done));
7860:   if (!set || !flag) PetscCall(MatDestroy(&AA));
7861:   PetscCall(MatDestroy(&A));

7863:   PetscCall(PetscNew(&edata));
7864:   PetscCall(MatGetNonzeroState(mat, &edata->nonzerostate));
7865:   edata->n = lblocks;
7866:   /* create IS needed for extracting blocks from the original matrix */
7867:   PetscCall(PetscMalloc1(lblocks, &edata->is));
7868:   for (PetscInt i = 0; i < lblocks; i++) PetscCall(ISCreateStride(PETSC_COMM_SELF, sizes[i], starts[i], 1, &edata->is[i]));

7870:   /* Create the resulting inverse matrix nonzero structure with preallocation information */
7871:   PetscCall(MatCreate(PetscObjectComm((PetscObject)mat), &edata->C));
7872:   PetscCall(MatSetSizes(edata->C, mat->rmap->n, mat->cmap->n, mat->rmap->N, mat->cmap->N));
7873:   PetscCall(MatSetBlockSizesFromMats(edata->C, mat, mat));
7874:   PetscCall(MatSetType(edata->C, MATAIJ));

7876:   /* Communicate the start and end of each row, from each block to the correct rank */
7877:   /* TODO: Use PetscSF instead of VecScatter */
7878:   for (PetscInt i = 0; i < lblocks; i++) ln += sizes[i];
7879:   PetscCall(VecCreateSeq(PETSC_COMM_SELF, 2 * ln, &seq));
7880:   PetscCall(VecGetArrayWrite(seq, &seqv));
7881:   for (PetscInt i = 0; i < lblocks; i++) {
7882:     for (PetscInt j = 0; j < sizes[i]; j++) {
7883:       seqv[cnt]     = starts[i];
7884:       seqv[cnt + 1] = starts[i] + sizes[i];
7885:       cnt += 2;
7886:     }
7887:   }
7888:   PetscCall(VecRestoreArrayWrite(seq, &seqv));
7889:   PetscCallMPI(MPI_Scan(&cnt, &sc, 1, MPIU_INT, MPI_SUM, PetscObjectComm((PetscObject)mat)));
7890:   sc -= cnt;
7891:   PetscCall(VecCreateMPI(PetscObjectComm((PetscObject)mat), 2 * mat->rmap->n, 2 * mat->rmap->N, &par));
7892:   PetscCall(ISCreateStride(PETSC_COMM_SELF, cnt, sc, 1, &isglobal));
7893:   PetscCall(VecScatterCreate(seq, NULL, par, isglobal, &scatter));
7894:   PetscCall(ISDestroy(&isglobal));
7895:   PetscCall(VecScatterBegin(scatter, seq, par, INSERT_VALUES, SCATTER_FORWARD));
7896:   PetscCall(VecScatterEnd(scatter, seq, par, INSERT_VALUES, SCATTER_FORWARD));
7897:   PetscCall(VecScatterDestroy(&scatter));
7898:   PetscCall(VecDestroy(&seq));
7899:   PetscCall(MatGetOwnershipRangeColumn(mat, &cstart, &cend));
7900:   PetscCall(PetscMalloc2(mat->rmap->n, &diag, mat->rmap->n, &odiag));
7901:   PetscCall(VecGetArrayRead(par, &parv));
7902:   cnt = 0;
7903:   PetscCall(MatGetSize(mat, NULL, &n));
7904:   for (PetscInt i = 0; i < mat->rmap->n; i++) {
7905:     PetscInt start, end, d = 0, od = 0;

7907:     start = (PetscInt)PetscRealPart(parv[cnt]);
7908:     end   = (PetscInt)PetscRealPart(parv[cnt + 1]);
7909:     cnt += 2;

7911:     if (start < cstart) {
7912:       od += cstart - start + n - cend;
7913:       d += cend - cstart;
7914:     } else if (start < cend) {
7915:       od += n - cend;
7916:       d += cend - start;
7917:     } else od += n - start;
7918:     if (end <= cstart) {
7919:       od -= cstart - end + n - cend;
7920:       d -= cend - cstart;
7921:     } else if (end < cend) {
7922:       od -= n - cend;
7923:       d -= cend - end;
7924:     } else od -= n - end;

7926:     odiag[i] = od;
7927:     diag[i]  = d;
7928:   }
7929:   PetscCall(VecRestoreArrayRead(par, &parv));
7930:   PetscCall(VecDestroy(&par));
7931:   PetscCall(MatXAIJSetPreallocation(edata->C, mat->rmap->bs, diag, odiag, NULL, NULL));
7932:   PetscCall(PetscFree2(diag, odiag));
7933:   PetscCall(PetscFree2(sizes, starts));

7935:   PetscCall(PetscContainerCreate(PETSC_COMM_SELF, &container));
7936:   PetscCall(PetscContainerSetPointer(container, edata));
7937:   PetscCall(PetscContainerSetCtxDestroy(container, EnvelopeDataDestroy));
7938:   PetscCall(PetscObjectCompose((PetscObject)mat, "EnvelopeData", (PetscObject)container));
7939:   PetscCall(PetscObjectDereference((PetscObject)container));
7940:   PetscFunctionReturn(PETSC_SUCCESS);
7941: }

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

7946:   Collective

7948:   Input Parameters:
7949: + A     - the matrix
7950: - reuse - indicates if the `C` matrix was obtained from a previous call to this routine

7952:   Output Parameter:
7953: . C - matrix with inverted block diagonal of `A`

7955:   Level: advanced

7957:   Note:
7958:   For efficiency the matrix `A` should have all the nonzero entries clustered in smallish blocks along the diagonal.

7960: .seealso: [](ch_matrices), `Mat`, `MatInvertBlockDiagonal()`, `MatComputeBlockDiagonal()`
7961: @*/
7962: PetscErrorCode MatInvertVariableBlockEnvelope(Mat A, MatReuse reuse, Mat *C)
7963: {
7964:   PetscContainer   container;
7965:   EnvelopeData    *edata;
7966:   PetscObjectState nonzerostate;

7968:   PetscFunctionBegin;
7969:   PetscCall(PetscObjectQuery((PetscObject)A, "EnvelopeData", (PetscObject *)&container));
7970:   if (!container) {
7971:     PetscCall(MatComputeVariableBlockEnvelope(A));
7972:     PetscCall(PetscObjectQuery((PetscObject)A, "EnvelopeData", (PetscObject *)&container));
7973:   }
7974:   PetscCall(PetscContainerGetPointer(container, &edata));
7975:   PetscCall(MatGetNonzeroState(A, &nonzerostate));
7976:   PetscCheck(nonzerostate <= edata->nonzerostate, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "Cannot handle changes to matrix nonzero structure");
7977:   PetscCheck(reuse != MAT_REUSE_MATRIX || *C == edata->C, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "C matrix must be the same as previously output");

7979:   PetscCall(MatCreateSubMatrices(A, edata->n, edata->is, edata->is, MAT_INITIAL_MATRIX, &edata->mat));
7980:   *C = edata->C;

7982:   for (PetscInt i = 0; i < edata->n; i++) {
7983:     Mat          D;
7984:     PetscScalar *dvalues;

7986:     PetscCall(MatConvert(edata->mat[i], MATSEQDENSE, MAT_INITIAL_MATRIX, &D));
7987:     PetscCall(MatSetOption(*C, MAT_ROW_ORIENTED, PETSC_FALSE));
7988:     PetscCall(MatSeqDenseInvert(D));
7989:     PetscCall(MatDenseGetArray(D, &dvalues));
7990:     PetscCall(MatSetValuesIS(*C, edata->is[i], edata->is[i], dvalues, INSERT_VALUES));
7991:     PetscCall(MatDestroy(&D));
7992:   }
7993:   PetscCall(MatDestroySubMatrices(edata->n, &edata->mat));
7994:   PetscCall(MatAssemblyBegin(*C, MAT_FINAL_ASSEMBLY));
7995:   PetscCall(MatAssemblyEnd(*C, MAT_FINAL_ASSEMBLY));
7996:   PetscFunctionReturn(PETSC_SUCCESS);
7997: }

7999: /*@
8000:   MatSetVariableBlockSizes - Sets diagonal point-blocks of the matrix that need not be of the same size

8002:   Not Collective

8004:   Input Parameters:
8005: + mat     - the matrix
8006: . nblocks - the number of blocks on this process, each block can only exist on a single process
8007: - bsizes  - the block sizes

8009:   Level: intermediate

8011:   Notes:
8012:   Currently used by `PCVPBJACOBI` for `MATAIJ` matrices

8014:   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.

8016: .seealso: [](ch_matrices), `Mat`, `MatCreateSeqBAIJ()`, `MatCreateBAIJ()`, `MatGetBlockSize()`, `MatSetBlockSizes()`, `MatGetBlockSizes()`, `MatGetVariableBlockSizes()`,
8017:           `MatComputeVariableBlockEnvelope()`, `PCVPBJACOBI`
8018: @*/
8019: PetscErrorCode MatSetVariableBlockSizes(Mat mat, PetscInt nblocks, const PetscInt bsizes[])
8020: {
8021:   PetscInt ncnt = 0, nlocal;

8023:   PetscFunctionBegin;
8025:   PetscCall(MatGetLocalSize(mat, &nlocal, NULL));
8026:   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);
8027:   for (PetscInt i = 0; i < nblocks; i++) ncnt += bsizes[i];
8028:   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);
8029:   PetscCall(PetscFree(mat->bsizes));
8030:   mat->nblocks = nblocks;
8031:   PetscCall(PetscMalloc1(nblocks, &mat->bsizes));
8032:   PetscCall(PetscArraycpy(mat->bsizes, bsizes, nblocks));
8033:   PetscFunctionReturn(PETSC_SUCCESS);
8034: }

8036: /*@C
8037:   MatGetVariableBlockSizes - Gets a diagonal blocks of the matrix that need not be of the same size

8039:   Not Collective; No Fortran Support

8041:   Input Parameter:
8042: . mat - the matrix

8044:   Output Parameters:
8045: + nblocks - the number of blocks on this process
8046: - bsizes  - the block sizes

8048:   Level: intermediate

8050: .seealso: [](ch_matrices), `Mat`, `MatCreateSeqBAIJ()`, `MatCreateBAIJ()`, `MatGetBlockSize()`, `MatSetBlockSizes()`, `MatGetBlockSizes()`, `MatSetVariableBlockSizes()`, `MatComputeVariableBlockEnvelope()`
8051: @*/
8052: PetscErrorCode MatGetVariableBlockSizes(Mat mat, PetscInt *nblocks, const PetscInt *bsizes[])
8053: {
8054:   PetscFunctionBegin;
8056:   if (nblocks) *nblocks = mat->nblocks;
8057:   if (bsizes) *bsizes = mat->bsizes;
8058:   PetscFunctionReturn(PETSC_SUCCESS);
8059: }

8061: /*@
8062:   MatSelectVariableBlockSizes - When creating a submatrix, pass on the variable block sizes

8064:   Not Collective

8066:   Input Parameter:
8067: + subA  - the submatrix
8068: . A     - the original matrix
8069: - isrow - The `IS` of selected rows for the submatrix, must be sorted

8071:   Level: developer

8073:   Notes:
8074:   If the index set is not sorted or contains off-process entries, this function will do nothing.

8076: .seealso: [](ch_matrices), `Mat`, `MatSetVariableBlockSizes()`, `MatComputeVariableBlockEnvelope()`
8077: @*/
8078: PetscErrorCode MatSelectVariableBlockSizes(Mat subA, Mat A, IS isrow)
8079: {
8080:   const PetscInt *rows;
8081:   PetscInt        n, rStart, rEnd, Nb = 0;
8082:   PetscBool       flg = A->bsizes ? PETSC_TRUE : PETSC_FALSE;

8084:   PetscFunctionBegin;
8085:   // The code for block size extraction does not support an unsorted IS
8086:   if (flg) PetscCall(ISSorted(isrow, &flg));
8087:   // We don't support originally off-diagonal blocks
8088:   if (flg) {
8089:     PetscCall(MatGetOwnershipRange(A, &rStart, &rEnd));
8090:     PetscCall(ISGetLocalSize(isrow, &n));
8091:     PetscCall(ISGetIndices(isrow, &rows));
8092:     for (PetscInt i = 0; i < n && flg; ++i) {
8093:       if (rows[i] < rStart || rows[i] >= rEnd) flg = PETSC_FALSE;
8094:     }
8095:     PetscCall(ISRestoreIndices(isrow, &rows));
8096:   }
8097:   // quiet return if we can't extract block size
8098:   PetscCallMPI(MPIU_Allreduce(MPI_IN_PLACE, &flg, 1, MPI_C_BOOL, MPI_LAND, PetscObjectComm((PetscObject)subA)));
8099:   if (!flg) PetscFunctionReturn(PETSC_SUCCESS);

8101:   // extract block sizes
8102:   PetscCall(ISGetIndices(isrow, &rows));
8103:   for (PetscInt b = 0, gr = rStart, i = 0; b < A->nblocks; ++b) {
8104:     PetscBool occupied = PETSC_FALSE;

8106:     for (PetscInt br = 0; br < A->bsizes[b]; ++br) {
8107:       const PetscInt row = gr + br;

8109:       if (i == n) break;
8110:       if (rows[i] == row) {
8111:         occupied = PETSC_TRUE;
8112:         ++i;
8113:       }
8114:       while (i < n && rows[i] < row) ++i;
8115:     }
8116:     gr += A->bsizes[b];
8117:     if (occupied) ++Nb;
8118:   }
8119:   subA->nblocks = Nb;
8120:   PetscCall(PetscFree(subA->bsizes));
8121:   PetscCall(PetscMalloc1(subA->nblocks, &subA->bsizes));
8122:   PetscInt sb = 0;
8123:   for (PetscInt b = 0, gr = rStart, i = 0; b < A->nblocks; ++b) {
8124:     if (sb < subA->nblocks) subA->bsizes[sb] = 0;
8125:     for (PetscInt br = 0; br < A->bsizes[b]; ++br) {
8126:       const PetscInt row = gr + br;

8128:       if (i == n) break;
8129:       if (rows[i] == row) {
8130:         ++subA->bsizes[sb];
8131:         ++i;
8132:       }
8133:       while (i < n && rows[i] < row) ++i;
8134:     }
8135:     gr += A->bsizes[b];
8136:     if (sb < subA->nblocks && subA->bsizes[sb]) ++sb;
8137:   }
8138:   PetscCheck(sb == subA->nblocks, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Invalid number of blocks %" PetscInt_FMT " != %" PetscInt_FMT, sb, subA->nblocks);
8139:   PetscInt nlocal, ncnt = 0;
8140:   PetscCall(MatGetLocalSize(subA, &nlocal, NULL));
8141:   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);
8142:   for (PetscInt i = 0; i < subA->nblocks; i++) ncnt += subA->bsizes[i];
8143:   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);
8144:   PetscCall(ISRestoreIndices(isrow, &rows));
8145:   PetscFunctionReturn(PETSC_SUCCESS);
8146: }

8148: /*@
8149:   MatSetBlockSizes - Sets the matrix block row and column sizes.

8151:   Logically Collective

8153:   Input Parameters:
8154: + mat - the matrix
8155: . rbs - row block size
8156: - cbs - column block size

8158:   Level: intermediate

8160:   Notes:
8161:   Block row formats are `MATBAIJ` and  `MATSBAIJ`. These formats ALWAYS have square block storage in the matrix.
8162:   If you pass a different block size for the columns than the rows, the row block size determines the square block storage.
8163:   This must be called before `MatSetUp()` or MatXXXSetPreallocation() (or will default to 1) and the block size cannot be changed later.

8165:   For `MATAIJ` matrix this function can be called at a later stage, provided that the specified block sizes
8166:   are compatible with the matrix local sizes.

8168:   The row and column block size determine the blocksize of the "row" and "column" vectors returned by `MatCreateVecs()`.

8170: .seealso: [](ch_matrices), `Mat`, `MatCreateSeqBAIJ()`, `MatCreateBAIJ()`, `MatGetBlockSize()`, `MatSetBlockSize()`, `MatGetBlockSizes()`
8171: @*/
8172: PetscErrorCode MatSetBlockSizes(Mat mat, PetscInt rbs, PetscInt cbs)
8173: {
8174:   PetscFunctionBegin;
8178:   PetscTryTypeMethod(mat, setblocksizes, rbs, cbs);
8179:   if (mat->rmap->refcnt) {
8180:     ISLocalToGlobalMapping l2g  = NULL;
8181:     PetscLayout            nmap = NULL;

8183:     PetscCall(PetscLayoutDuplicate(mat->rmap, &nmap));
8184:     if (mat->rmap->mapping) PetscCall(ISLocalToGlobalMappingDuplicate(mat->rmap->mapping, &l2g));
8185:     PetscCall(PetscLayoutDestroy(&mat->rmap));
8186:     mat->rmap          = nmap;
8187:     mat->rmap->mapping = l2g;
8188:   }
8189:   if (mat->cmap->refcnt) {
8190:     ISLocalToGlobalMapping l2g  = NULL;
8191:     PetscLayout            nmap = NULL;

8193:     PetscCall(PetscLayoutDuplicate(mat->cmap, &nmap));
8194:     if (mat->cmap->mapping) PetscCall(ISLocalToGlobalMappingDuplicate(mat->cmap->mapping, &l2g));
8195:     PetscCall(PetscLayoutDestroy(&mat->cmap));
8196:     mat->cmap          = nmap;
8197:     mat->cmap->mapping = l2g;
8198:   }
8199:   PetscCall(PetscLayoutSetBlockSize(mat->rmap, rbs));
8200:   PetscCall(PetscLayoutSetBlockSize(mat->cmap, cbs));
8201:   PetscFunctionReturn(PETSC_SUCCESS);
8202: }

8204: /*@
8205:   MatSetBlockSizesFromMats - Sets the matrix block row and column sizes to match a pair of matrices

8207:   Logically Collective

8209:   Input Parameters:
8210: + mat     - the matrix
8211: . fromRow - matrix from which to copy row block size
8212: - fromCol - matrix from which to copy column block size (can be same as `fromRow`)

8214:   Level: developer

8216: .seealso: [](ch_matrices), `Mat`, `MatCreateSeqBAIJ()`, `MatCreateBAIJ()`, `MatGetBlockSize()`, `MatSetBlockSizes()`
8217: @*/
8218: PetscErrorCode MatSetBlockSizesFromMats(Mat mat, Mat fromRow, Mat fromCol)
8219: {
8220:   PetscFunctionBegin;
8224:   PetscTryTypeMethod(mat, setblocksizes, fromRow->rmap->bs, fromCol->cmap->bs);
8225:   PetscCall(PetscLayoutSetBlockSize(mat->rmap, fromRow->rmap->bs));
8226:   PetscCall(PetscLayoutSetBlockSize(mat->cmap, fromCol->cmap->bs));
8227:   PetscFunctionReturn(PETSC_SUCCESS);
8228: }

8230: /*@
8231:   MatResidual - Default routine to calculate the residual r = b - Ax

8233:   Collective

8235:   Input Parameters:
8236: + mat - the matrix
8237: . b   - the right-hand-side
8238: - x   - the approximate solution

8240:   Output Parameter:
8241: . r - location to store the residual

8243:   Level: developer

8245: .seealso: [](ch_matrices), `Mat`, `MatMult()`, `MatMultAdd()`, `PCMGSetResidual()`
8246: @*/
8247: PetscErrorCode MatResidual(Mat mat, Vec b, Vec x, Vec r)
8248: {
8249:   PetscFunctionBegin;
8255:   MatCheckPreallocated(mat, 1);
8256:   PetscCall(PetscLogEventBegin(MAT_Residual, mat, 0, 0, 0));
8257:   if (!mat->ops->residual) {
8258:     PetscCall(MatMult(mat, x, r));
8259:     PetscCall(VecAYPX(r, -1.0, b));
8260:   } else {
8261:     PetscUseTypeMethod(mat, residual, b, x, r);
8262:   }
8263:   PetscCall(PetscLogEventEnd(MAT_Residual, mat, 0, 0, 0));
8264:   PetscFunctionReturn(PETSC_SUCCESS);
8265: }

8267: /*@C
8268:   MatGetRowIJ - Returns the compressed row storage i and j indices for the local rows of a sparse matrix

8270:   Collective

8272:   Input Parameters:
8273: + mat             - the matrix
8274: . shift           - 0 or 1 indicating we want the indices starting at 0 or 1
8275: . symmetric       - `PETSC_TRUE` or `PETSC_FALSE` indicating the matrix data structure should be symmetrized
8276: - inodecompressed - `PETSC_TRUE` or `PETSC_FALSE`  indicating if the nonzero structure of the
8277:                  inodes or the nonzero elements is wanted. For `MATBAIJ` matrices the compressed version is
8278:                  always used.

8280:   Output Parameters:
8281: + n    - number of local rows in the (possibly compressed) matrix, use `NULL` if not needed
8282: . 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
8283: . ja   - the column indices, use `NULL` if not needed
8284: - done - indicates if the routine actually worked and returned appropriate ia[] and ja[] arrays; callers
8285:            are responsible for handling the case when done == `PETSC_FALSE` and ia and ja are not set

8287:   Level: developer

8289:   Notes:
8290:   You CANNOT change any of the ia[] or ja[] values.

8292:   Use `MatRestoreRowIJ()` when you are finished accessing the ia[] and ja[] values.

8294:   Fortran Notes:
8295:   Use
8296: .vb
8297:     PetscInt, pointer :: ia(:),ja(:)
8298:     call MatGetRowIJ(mat,shift,symmetric,inodecompressed,n,ia,ja,done,ierr)
8299:     ! Access the ith and jth entries via ia(i) and ja(j)
8300: .ve

8302: .seealso: [](ch_matrices), `Mat`, `MATAIJ`, `MatGetColumnIJ()`, `MatRestoreRowIJ()`, `MatSeqAIJGetArray()`
8303: @*/
8304: PetscErrorCode MatGetRowIJ(Mat mat, PetscInt shift, PetscBool symmetric, PetscBool inodecompressed, PetscInt *n, const PetscInt *ia[], const PetscInt *ja[], PetscBool *done)
8305: {
8306:   PetscFunctionBegin;
8309:   if (n) PetscAssertPointer(n, 5);
8310:   if (ia) PetscAssertPointer(ia, 6);
8311:   if (ja) PetscAssertPointer(ja, 7);
8312:   if (done) PetscAssertPointer(done, 8);
8313:   MatCheckPreallocated(mat, 1);
8314:   if (!mat->ops->getrowij && done) *done = PETSC_FALSE;
8315:   else {
8316:     if (done) *done = PETSC_TRUE;
8317:     PetscCall(PetscLogEventBegin(MAT_GetRowIJ, mat, 0, 0, 0));
8318:     PetscUseTypeMethod(mat, getrowij, shift, symmetric, inodecompressed, n, ia, ja, done);
8319:     PetscCall(PetscLogEventEnd(MAT_GetRowIJ, mat, 0, 0, 0));
8320:   }
8321:   PetscFunctionReturn(PETSC_SUCCESS);
8322: }

8324: /*@C
8325:   MatGetColumnIJ - Returns the compressed column storage i and j indices for sequential matrices.

8327:   Collective

8329:   Input Parameters:
8330: + mat             - the matrix
8331: . shift           - 1 or zero indicating we want the indices starting at 0 or 1
8332: . symmetric       - `PETSC_TRUE` or `PETSC_FALSE` indicating the matrix data structure should be
8333:                 symmetrized
8334: - inodecompressed - `PETSC_TRUE` or `PETSC_FALSE` indicating if the nonzero structure of the
8335:                  inodes or the nonzero elements is wanted. For `MATBAIJ` matrices the compressed version is
8336:                  always used.

8338:   Output Parameters:
8339: + n    - number of columns in the (possibly compressed) matrix
8340: . ia   - the column pointers; that is ia[0] = 0, ia[col] = i[col-1] + number of elements in that col of the matrix
8341: . ja   - the row indices
8342: - done - `PETSC_TRUE` or `PETSC_FALSE`, indicating whether the values have been returned

8344:   Level: developer

8346: .seealso: [](ch_matrices), `Mat`, `MatGetRowIJ()`, `MatRestoreColumnIJ()`
8347: @*/
8348: PetscErrorCode MatGetColumnIJ(Mat mat, PetscInt shift, PetscBool symmetric, PetscBool inodecompressed, PetscInt *n, const PetscInt *ia[], const PetscInt *ja[], PetscBool *done)
8349: {
8350:   PetscFunctionBegin;
8353:   PetscAssertPointer(n, 5);
8354:   if (ia) PetscAssertPointer(ia, 6);
8355:   if (ja) PetscAssertPointer(ja, 7);
8356:   PetscAssertPointer(done, 8);
8357:   MatCheckPreallocated(mat, 1);
8358:   if (!mat->ops->getcolumnij) *done = PETSC_FALSE;
8359:   else {
8360:     *done = PETSC_TRUE;
8361:     PetscUseTypeMethod(mat, getcolumnij, shift, symmetric, inodecompressed, n, ia, ja, done);
8362:   }
8363:   PetscFunctionReturn(PETSC_SUCCESS);
8364: }

8366: /*@C
8367:   MatRestoreRowIJ - Call after you are completed with the ia,ja indices obtained with `MatGetRowIJ()`.

8369:   Collective

8371:   Input Parameters:
8372: + mat             - the matrix
8373: . shift           - 1 or zero indicating we want the indices starting at 0 or 1
8374: . symmetric       - `PETSC_TRUE` or `PETSC_FALSE` indicating the matrix data structure should be symmetrized
8375: . inodecompressed - `PETSC_TRUE` or `PETSC_FALSE` indicating if the nonzero structure of the
8376:                     inodes or the nonzero elements is wanted. For `MATBAIJ` matrices the compressed version is
8377:                     always used.
8378: . n               - size of (possibly compressed) matrix
8379: . ia              - the row pointers
8380: - ja              - the column indices

8382:   Output Parameter:
8383: . done - `PETSC_TRUE` or `PETSC_FALSE` indicated that the values have been returned

8385:   Level: developer

8387:   Note:
8388:   This routine zeros out `n`, `ia`, and `ja`. This is to prevent accidental
8389:   us of the array after it has been restored. If you pass `NULL`, it will
8390:   not zero the pointers.  Use of ia or ja after `MatRestoreRowIJ()` is invalid.

8392: .seealso: [](ch_matrices), `Mat`, `MatGetRowIJ()`, `MatRestoreColumnIJ()`
8393: @*/
8394: PetscErrorCode MatRestoreRowIJ(Mat mat, PetscInt shift, PetscBool symmetric, PetscBool inodecompressed, PetscInt *n, const PetscInt *ia[], const PetscInt *ja[], PetscBool *done)
8395: {
8396:   PetscFunctionBegin;
8399:   if (ia) PetscAssertPointer(ia, 6);
8400:   if (ja) PetscAssertPointer(ja, 7);
8401:   if (done) PetscAssertPointer(done, 8);
8402:   MatCheckPreallocated(mat, 1);

8404:   if (!mat->ops->restorerowij && done) *done = PETSC_FALSE;
8405:   else {
8406:     if (done) *done = PETSC_TRUE;
8407:     PetscUseTypeMethod(mat, restorerowij, shift, symmetric, inodecompressed, n, ia, ja, done);
8408:     if (n) *n = 0;
8409:     if (ia) *ia = NULL;
8410:     if (ja) *ja = NULL;
8411:   }
8412:   PetscFunctionReturn(PETSC_SUCCESS);
8413: }

8415: /*@C
8416:   MatRestoreColumnIJ - Call after you are completed with the ia,ja indices obtained with `MatGetColumnIJ()`.

8418:   Collective

8420:   Input Parameters:
8421: + mat             - the matrix
8422: . shift           - 1 or zero indicating we want the indices starting at 0 or 1
8423: . symmetric       - `PETSC_TRUE` or `PETSC_FALSE` indicating the matrix data structure should be symmetrized
8424: - inodecompressed - `PETSC_TRUE` or `PETSC_FALSE` indicating if the nonzero structure of the
8425:                     inodes or the nonzero elements is wanted. For `MATBAIJ` matrices the compressed version is
8426:                     always used.

8428:   Output Parameters:
8429: + n    - size of (possibly compressed) matrix
8430: . ia   - the column pointers
8431: . ja   - the row indices
8432: - done - `PETSC_TRUE` or `PETSC_FALSE` indicated that the values have been returned

8434:   Level: developer

8436: .seealso: [](ch_matrices), `Mat`, `MatGetColumnIJ()`, `MatRestoreRowIJ()`
8437: @*/
8438: PetscErrorCode MatRestoreColumnIJ(Mat mat, PetscInt shift, PetscBool symmetric, PetscBool inodecompressed, PetscInt *n, const PetscInt *ia[], const PetscInt *ja[], PetscBool *done)
8439: {
8440:   PetscFunctionBegin;
8443:   if (ia) PetscAssertPointer(ia, 6);
8444:   if (ja) PetscAssertPointer(ja, 7);
8445:   PetscAssertPointer(done, 8);
8446:   MatCheckPreallocated(mat, 1);

8448:   if (!mat->ops->restorecolumnij) *done = PETSC_FALSE;
8449:   else {
8450:     *done = PETSC_TRUE;
8451:     PetscUseTypeMethod(mat, restorecolumnij, shift, symmetric, inodecompressed, n, ia, ja, done);
8452:     if (n) *n = 0;
8453:     if (ia) *ia = NULL;
8454:     if (ja) *ja = NULL;
8455:   }
8456:   PetscFunctionReturn(PETSC_SUCCESS);
8457: }

8459: /*@
8460:   MatColoringPatch - Used inside matrix coloring routines that use `MatGetRowIJ()` and/or
8461:   `MatGetColumnIJ()`.

8463:   Collective

8465:   Input Parameters:
8466: + mat        - the matrix
8467: . ncolors    - maximum color value
8468: . n          - number of entries in colorarray
8469: - colorarray - array indicating color for each column

8471:   Output Parameter:
8472: . iscoloring - coloring generated using colorarray information

8474:   Level: developer

8476: .seealso: [](ch_matrices), `Mat`, `MatGetRowIJ()`, `MatGetColumnIJ()`
8477: @*/
8478: PetscErrorCode MatColoringPatch(Mat mat, PetscInt ncolors, PetscInt n, ISColoringValue colorarray[], ISColoring *iscoloring)
8479: {
8480:   PetscFunctionBegin;
8483:   PetscAssertPointer(colorarray, 4);
8484:   PetscAssertPointer(iscoloring, 5);
8485:   MatCheckPreallocated(mat, 1);

8487:   if (!mat->ops->coloringpatch) {
8488:     PetscCall(ISColoringCreate(PetscObjectComm((PetscObject)mat), ncolors, n, colorarray, PETSC_OWN_POINTER, iscoloring));
8489:   } else {
8490:     PetscUseTypeMethod(mat, coloringpatch, ncolors, n, colorarray, iscoloring);
8491:   }
8492:   PetscFunctionReturn(PETSC_SUCCESS);
8493: }

8495: /*@
8496:   MatSetUnfactored - Resets a factored matrix to be treated as unfactored.

8498:   Logically Collective

8500:   Input Parameter:
8501: . mat - the factored matrix to be reset

8503:   Level: developer

8505:   Notes:
8506:   This routine should be used only with factored matrices formed by in-place
8507:   factorization via ILU(0) (or by in-place LU factorization for the `MATSEQDENSE`
8508:   format).  This option can save memory, for example, when solving nonlinear
8509:   systems with a matrix-free Newton-Krylov method and a matrix-based, in-place
8510:   ILU(0) preconditioner.

8512:   One can specify in-place ILU(0) factorization by calling
8513: .vb
8514:      PCType(pc,PCILU);
8515:      PCFactorSeUseInPlace(pc);
8516: .ve
8517:   or by using the options -pc_type ilu -pc_factor_in_place

8519:   In-place factorization ILU(0) can also be used as a local
8520:   solver for the blocks within the block Jacobi or additive Schwarz
8521:   methods (runtime option: -sub_pc_factor_in_place).  See Users-Manual: ch_pc
8522:   for details on setting local solver options.

8524:   Most users should employ the `KSP` interface for linear solvers
8525:   instead of working directly with matrix algebra routines such as this.
8526:   See, e.g., `KSPCreate()`.

8528: .seealso: [](ch_matrices), `Mat`, `PCFactorSetUseInPlace()`, `PCFactorGetUseInPlace()`
8529: @*/
8530: PetscErrorCode MatSetUnfactored(Mat mat)
8531: {
8532:   PetscFunctionBegin;
8535:   MatCheckPreallocated(mat, 1);
8536:   mat->factortype = MAT_FACTOR_NONE;
8537:   if (!mat->ops->setunfactored) PetscFunctionReturn(PETSC_SUCCESS);
8538:   PetscUseTypeMethod(mat, setunfactored);
8539:   PetscFunctionReturn(PETSC_SUCCESS);
8540: }

8542: /*@
8543:   MatCreateSubMatrix - Gets a single submatrix on the same number of processors
8544:   as the original matrix.

8546:   Collective

8548:   Input Parameters:
8549: + mat   - the original matrix
8550: . isrow - parallel `IS` containing the rows this processor should obtain
8551: . 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.
8552: - cll   - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`

8554:   Output Parameter:
8555: . newmat - the new submatrix, of the same type as the original matrix

8557:   Level: advanced

8559:   Notes:
8560:   The submatrix will be able to be multiplied with vectors using the same layout as `iscol`.

8562:   Some matrix types place restrictions on the row and column indices, such
8563:   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;
8564:   for example, if the block size is 3 one cannot select the 0 and 2 rows without selecting the 1 row.

8566:   The index sets may not have duplicate entries.

8568:   The first time this is called you should use a cll of `MAT_INITIAL_MATRIX`,
8569:   the `MatCreateSubMatrix()` routine will create the newmat for you. Any additional calls
8570:   to this routine with a mat of the same nonzero structure and with a call of `MAT_REUSE_MATRIX`
8571:   will reuse the matrix generated the first time.  You should call `MatDestroy()` on `newmat` when
8572:   you are finished using it.

8574:   The communicator of the newly obtained matrix is ALWAYS the same as the communicator of
8575:   the input matrix.

8577:   If `iscol` is `NULL` then all columns are obtained (not supported in Fortran).

8579:   If `isrow` and `iscol` have a nontrivial block-size, then the resulting matrix has this block-size as well. This feature
8580:   is used by `PCFIELDSPLIT` to allow easy nesting of its use.

8582:   Example usage:
8583:   Consider the following 8x8 matrix with 34 non-zero values, that is
8584:   assembled across 3 processors. Let's assume that proc0 owns 3 rows,
8585:   proc1 owns 3 rows, proc2 owns 2 rows. This division can be shown
8586:   as follows
8587: .vb
8588:             1  2  0  |  0  3  0  |  0  4
8589:     Proc0   0  5  6  |  7  0  0  |  8  0
8590:             9  0 10  | 11  0  0  | 12  0
8591:     -------------------------------------
8592:            13  0 14  | 15 16 17  |  0  0
8593:     Proc1   0 18  0  | 19 20 21  |  0  0
8594:             0  0  0  | 22 23  0  | 24  0
8595:     -------------------------------------
8596:     Proc2  25 26 27  |  0  0 28  | 29  0
8597:            30  0  0  | 31 32 33  |  0 34
8598: .ve

8600:   Suppose `isrow` = [0 1 | 4 | 6 7] and `iscol` = [1 2 | 3 4 5 | 6].  The resulting submatrix is

8602: .vb
8603:             2  0  |  0  3  0  |  0
8604:     Proc0   5  6  |  7  0  0  |  8
8605:     -------------------------------
8606:     Proc1  18  0  | 19 20 21  |  0
8607:     -------------------------------
8608:     Proc2  26 27  |  0  0 28  | 29
8609:             0  0  | 31 32 33  |  0
8610: .ve

8612: .seealso: [](ch_matrices), `Mat`, `MatCreateSubMatrices()`, `MatCreateSubMatricesMPI()`, `MatCreateSubMatrixVirtual()`, `MatSubMatrixVirtualUpdate()`
8613: @*/
8614: PetscErrorCode MatCreateSubMatrix(Mat mat, IS isrow, IS iscol, MatReuse cll, Mat *newmat)
8615: {
8616:   PetscMPIInt size;
8617:   Mat        *local;
8618:   IS          iscoltmp;
8619:   PetscBool   flg;

8621:   PetscFunctionBegin;
8625:   PetscAssertPointer(newmat, 5);
8628:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
8629:   PetscCheck(cll != MAT_IGNORE_MATRIX, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Cannot use MAT_IGNORE_MATRIX");
8630:   PetscCheck(cll != MAT_INPLACE_MATRIX, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Cannot use MAT_INPLACE_MATRIX");

8632:   MatCheckPreallocated(mat, 1);
8633:   PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)mat), &size));

8635:   if (!iscol || isrow == iscol) {
8636:     PetscBool   stride;
8637:     PetscMPIInt grabentirematrix = 0, grab;
8638:     PetscCall(PetscObjectTypeCompare((PetscObject)isrow, ISSTRIDE, &stride));
8639:     if (stride) {
8640:       PetscInt first, step, n, rstart, rend;
8641:       PetscCall(ISStrideGetInfo(isrow, &first, &step));
8642:       if (step == 1) {
8643:         PetscCall(MatGetOwnershipRange(mat, &rstart, &rend));
8644:         if (rstart == first) {
8645:           PetscCall(ISGetLocalSize(isrow, &n));
8646:           if (n == rend - rstart) grabentirematrix = 1;
8647:         }
8648:       }
8649:     }
8650:     PetscCallMPI(MPIU_Allreduce(&grabentirematrix, &grab, 1, MPI_INT, MPI_MIN, PetscObjectComm((PetscObject)mat)));
8651:     if (grab) {
8652:       PetscCall(PetscInfo(mat, "Getting entire matrix as submatrix\n"));
8653:       if (cll == MAT_INITIAL_MATRIX) {
8654:         *newmat = mat;
8655:         PetscCall(PetscObjectReference((PetscObject)mat));
8656:       }
8657:       PetscFunctionReturn(PETSC_SUCCESS);
8658:     }
8659:   }

8661:   if (!iscol) {
8662:     PetscCall(ISCreateStride(PetscObjectComm((PetscObject)mat), mat->cmap->n, mat->cmap->rstart, 1, &iscoltmp));
8663:   } else {
8664:     iscoltmp = iscol;
8665:   }

8667:   /* if original matrix is on just one processor then use submatrix generated */
8668:   if (mat->ops->createsubmatrices && !mat->ops->createsubmatrix && size == 1 && cll == MAT_REUSE_MATRIX) {
8669:     PetscCall(MatCreateSubMatrices(mat, 1, &isrow, &iscoltmp, MAT_REUSE_MATRIX, &newmat));
8670:     goto setproperties;
8671:   } else if (mat->ops->createsubmatrices && !mat->ops->createsubmatrix && size == 1) {
8672:     PetscCall(MatCreateSubMatrices(mat, 1, &isrow, &iscoltmp, MAT_INITIAL_MATRIX, &local));
8673:     *newmat = *local;
8674:     PetscCall(PetscFree(local));
8675:     goto setproperties;
8676:   } else if (!mat->ops->createsubmatrix) {
8677:     /* Create a new matrix type that implements the operation using the full matrix */
8678:     PetscCall(PetscLogEventBegin(MAT_CreateSubMat, mat, 0, 0, 0));
8679:     switch (cll) {
8680:     case MAT_INITIAL_MATRIX:
8681:       PetscCall(MatCreateSubMatrixVirtual(mat, isrow, iscoltmp, newmat));
8682:       break;
8683:     case MAT_REUSE_MATRIX:
8684:       PetscCall(MatSubMatrixVirtualUpdate(*newmat, mat, isrow, iscoltmp));
8685:       break;
8686:     default:
8687:       SETERRQ(PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_OUTOFRANGE, "Invalid MatReuse, must be either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX");
8688:     }
8689:     PetscCall(PetscLogEventEnd(MAT_CreateSubMat, mat, 0, 0, 0));
8690:     goto setproperties;
8691:   }

8693:   PetscCall(PetscLogEventBegin(MAT_CreateSubMat, mat, 0, 0, 0));
8694:   PetscUseTypeMethod(mat, createsubmatrix, isrow, iscoltmp, cll, newmat);
8695:   PetscCall(PetscLogEventEnd(MAT_CreateSubMat, mat, 0, 0, 0));

8697: setproperties:
8698:   if ((*newmat)->symmetric == PETSC_BOOL3_UNKNOWN && (*newmat)->structurally_symmetric == PETSC_BOOL3_UNKNOWN && (*newmat)->spd == PETSC_BOOL3_UNKNOWN && (*newmat)->hermitian == PETSC_BOOL3_UNKNOWN) {
8699:     PetscCall(ISEqualUnsorted(isrow, iscoltmp, &flg));
8700:     if (flg) PetscCall(MatPropagateSymmetryOptions(mat, *newmat));
8701:   }
8702:   if (!iscol) PetscCall(ISDestroy(&iscoltmp));
8703:   if (*newmat && cll == MAT_INITIAL_MATRIX) PetscCall(PetscObjectStateIncrease((PetscObject)*newmat));
8704:   if (!iscol || isrow == iscol) PetscCall(MatSelectVariableBlockSizes(*newmat, mat, isrow));
8705:   PetscFunctionReturn(PETSC_SUCCESS);
8706: }

8708: /*@
8709:   MatPropagateSymmetryOptions - Propagates symmetry options set on a matrix to another matrix

8711:   Not Collective

8713:   Input Parameters:
8714: + A - the matrix we wish to propagate options from
8715: - B - the matrix we wish to propagate options to

8717:   Level: beginner

8719:   Note:
8720:   Propagates the options associated to `MAT_SYMMETRY_ETERNAL`, `MAT_STRUCTURALLY_SYMMETRIC`, `MAT_HERMITIAN`, `MAT_SPD`, `MAT_SYMMETRIC`, and `MAT_STRUCTURAL_SYMMETRY_ETERNAL`

8722: .seealso: [](ch_matrices), `Mat`, `MatSetOption()`, `MatIsSymmetricKnown()`, `MatIsSPDKnown()`, `MatIsHermitianKnown()`, `MatIsStructurallySymmetricKnown()`
8723: @*/
8724: PetscErrorCode MatPropagateSymmetryOptions(Mat A, Mat B)
8725: {
8726:   PetscFunctionBegin;
8729:   B->symmetry_eternal            = A->symmetry_eternal;
8730:   B->structural_symmetry_eternal = A->structural_symmetry_eternal;
8731:   B->symmetric                   = A->symmetric;
8732:   B->structurally_symmetric      = A->structurally_symmetric;
8733:   B->spd                         = A->spd;
8734:   B->hermitian                   = A->hermitian;
8735:   PetscFunctionReturn(PETSC_SUCCESS);
8736: }

8738: /*@
8739:   MatStashSetInitialSize - sets the sizes of the matrix stash, that is
8740:   used during the assembly process to store values that belong to
8741:   other processors.

8743:   Not Collective

8745:   Input Parameters:
8746: + mat   - the matrix
8747: . size  - the initial size of the stash.
8748: - bsize - the initial size of the block-stash(if used).

8750:   Options Database Keys:
8751: + -matstash_initial_size size or size0,size1,...,sizep-1            - set initial size
8752: - -matstash_block_initial_size bsize  or bsize0,bsize1,...,bsizep-1 - set initial block size

8754:   Level: intermediate

8756:   Notes:
8757:   The block-stash is used for values set with `MatSetValuesBlocked()` while
8758:   the stash is used for values set with `MatSetValues()`

8760:   Run with the option -info and look for output of the form
8761:   MatAssemblyBegin_MPIXXX:Stash has MM entries, uses nn mallocs.
8762:   to determine the appropriate value, MM, to use for size and
8763:   MatAssemblyBegin_MPIXXX:Block-Stash has BMM entries, uses nn mallocs.
8764:   to determine the value, BMM to use for bsize

8766: .seealso: [](ch_matrices), `MatAssemblyBegin()`, `MatAssemblyEnd()`, `Mat`, `MatStashGetInfo()`
8767: @*/
8768: PetscErrorCode MatStashSetInitialSize(Mat mat, PetscInt size, PetscInt bsize)
8769: {
8770:   PetscFunctionBegin;
8773:   PetscCall(MatStashSetInitialSize_Private(&mat->stash, size));
8774:   PetscCall(MatStashSetInitialSize_Private(&mat->bstash, bsize));
8775:   PetscFunctionReturn(PETSC_SUCCESS);
8776: }

8778: /*@
8779:   MatInterpolateAdd - $w = y + A*x$ or $A^T*x$ depending on the shape of
8780:   the matrix

8782:   Neighbor-wise Collective

8784:   Input Parameters:
8785: + A - the matrix
8786: . x - the vector to be multiplied by the interpolation operator
8787: - y - the vector to be added to the result

8789:   Output Parameter:
8790: . w - the resulting vector

8792:   Level: intermediate

8794:   Notes:
8795:   `w` may be the same vector as `y`.

8797:   This allows one to use either the restriction or interpolation (its transpose)
8798:   matrix to do the interpolation

8800: .seealso: [](ch_matrices), `Mat`, `MatMultAdd()`, `MatMultTransposeAdd()`, `MatRestrict()`, `PCMG`
8801: @*/
8802: PetscErrorCode MatInterpolateAdd(Mat A, Vec x, Vec y, Vec w)
8803: {
8804:   PetscInt M, N, Ny;

8806:   PetscFunctionBegin;
8811:   PetscCall(MatGetSize(A, &M, &N));
8812:   PetscCall(VecGetSize(y, &Ny));
8813:   if (M == Ny) PetscCall(MatMultAdd(A, x, y, w));
8814:   else PetscCall(MatMultTransposeAdd(A, x, y, w));
8815:   PetscFunctionReturn(PETSC_SUCCESS);
8816: }

8818: /*@
8819:   MatInterpolate - $y = A*x$ or $A^T*x$ depending on the shape of
8820:   the matrix

8822:   Neighbor-wise Collective

8824:   Input Parameters:
8825: + A - the matrix
8826: - x - the vector to be interpolated

8828:   Output Parameter:
8829: . y - the resulting vector

8831:   Level: intermediate

8833:   Note:
8834:   This allows one to use either the restriction or interpolation (its transpose)
8835:   matrix to do the interpolation

8837: .seealso: [](ch_matrices), `Mat`, `MatMultAdd()`, `MatMultTransposeAdd()`, `MatRestrict()`, `PCMG`
8838: @*/
8839: PetscErrorCode MatInterpolate(Mat A, Vec x, Vec y)
8840: {
8841:   PetscInt M, N, Ny;

8843:   PetscFunctionBegin;
8847:   PetscCall(MatGetSize(A, &M, &N));
8848:   PetscCall(VecGetSize(y, &Ny));
8849:   if (M == Ny) PetscCall(MatMult(A, x, y));
8850:   else PetscCall(MatMultTranspose(A, x, y));
8851:   PetscFunctionReturn(PETSC_SUCCESS);
8852: }

8854: /*@
8855:   MatRestrict - $y = A*x$ or $A^T*x$

8857:   Neighbor-wise Collective

8859:   Input Parameters:
8860: + A - the matrix
8861: - x - the vector to be restricted

8863:   Output Parameter:
8864: . y - the resulting vector

8866:   Level: intermediate

8868:   Note:
8869:   This allows one to use either the restriction or interpolation (its transpose)
8870:   matrix to do the restriction

8872: .seealso: [](ch_matrices), `Mat`, `MatMultAdd()`, `MatMultTransposeAdd()`, `MatInterpolate()`, `PCMG`
8873: @*/
8874: PetscErrorCode MatRestrict(Mat A, Vec x, Vec y)
8875: {
8876:   PetscInt M, N, Nx;

8878:   PetscFunctionBegin;
8882:   PetscCall(MatGetSize(A, &M, &N));
8883:   PetscCall(VecGetSize(x, &Nx));
8884:   if (M == Nx) PetscCall(MatMultTranspose(A, x, y));
8885:   else PetscCall(MatMult(A, x, y));
8886:   PetscFunctionReturn(PETSC_SUCCESS);
8887: }

8889: /*@
8890:   MatMatInterpolateAdd - $Y = W + A*X$ or $W + A^T*X$ depending on the shape of `A`

8892:   Neighbor-wise Collective

8894:   Input Parameters:
8895: + A - the matrix
8896: . x - the input dense matrix to be multiplied
8897: - w - the input dense matrix to be added to the result

8899:   Output Parameter:
8900: . y - the output dense matrix

8902:   Level: intermediate

8904:   Note:
8905:   This allows one to use either the restriction or interpolation (its transpose)
8906:   matrix to do the interpolation. `y` matrix can be reused if already created with the proper sizes,
8907:   otherwise it will be recreated. `y` must be initialized to `NULL` if not supplied.

8909: .seealso: [](ch_matrices), `Mat`, `MatInterpolateAdd()`, `MatMatInterpolate()`, `MatMatRestrict()`, `PCMG`
8910: @*/
8911: PetscErrorCode MatMatInterpolateAdd(Mat A, Mat x, Mat w, Mat *y)
8912: {
8913:   PetscInt  M, N, Mx, Nx, Mo, My = 0, Ny = 0;
8914:   PetscBool trans = PETSC_TRUE;
8915:   MatReuse  reuse = MAT_INITIAL_MATRIX;

8917:   PetscFunctionBegin;
8923:   PetscCall(MatGetSize(A, &M, &N));
8924:   PetscCall(MatGetSize(x, &Mx, &Nx));
8925:   if (N == Mx) trans = PETSC_FALSE;
8926:   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);
8927:   Mo = trans ? N : M;
8928:   if (*y) {
8929:     PetscCall(MatGetSize(*y, &My, &Ny));
8930:     if (Mo == My && Nx == Ny) reuse = MAT_REUSE_MATRIX;
8931:     else {
8932:       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);
8933:       PetscCall(MatDestroy(y));
8934:     }
8935:   }

8937:   if (w && *y == w) { /* this is to minimize changes in PCMG */
8938:     PetscBool flg;

8940:     PetscCall(PetscObjectQuery((PetscObject)*y, "__MatMatIntAdd_w", (PetscObject *)&w));
8941:     if (w) {
8942:       PetscInt My, Ny, Mw, Nw;

8944:       PetscCall(PetscObjectTypeCompare((PetscObject)*y, ((PetscObject)w)->type_name, &flg));
8945:       PetscCall(MatGetSize(*y, &My, &Ny));
8946:       PetscCall(MatGetSize(w, &Mw, &Nw));
8947:       if (!flg || My != Mw || Ny != Nw) w = NULL;
8948:     }
8949:     if (!w) {
8950:       PetscCall(MatDuplicate(*y, MAT_COPY_VALUES, &w));
8951:       PetscCall(PetscObjectCompose((PetscObject)*y, "__MatMatIntAdd_w", (PetscObject)w));
8952:       PetscCall(PetscObjectDereference((PetscObject)w));
8953:     } else PetscCall(MatCopy(*y, w, UNKNOWN_NONZERO_PATTERN));
8954:   }
8955:   if (!trans) PetscCall(MatMatMult(A, x, reuse, PETSC_DETERMINE, y));
8956:   else PetscCall(MatTransposeMatMult(A, x, reuse, PETSC_DETERMINE, y));
8957:   if (w) PetscCall(MatAXPY(*y, 1.0, w, UNKNOWN_NONZERO_PATTERN));
8958:   PetscFunctionReturn(PETSC_SUCCESS);
8959: }

8961: /*@
8962:   MatMatInterpolate - $Y = A*X$ or $A^T*X$ depending on the shape of `A`

8964:   Neighbor-wise Collective

8966:   Input Parameters:
8967: + A - the matrix
8968: - x - the input dense matrix

8970:   Output Parameter:
8971: . y - the output dense matrix

8973:   Level: intermediate

8975:   Note:
8976:   This allows one to use either the restriction or interpolation (its transpose)
8977:   matrix to do the interpolation. `y` matrix can be reused if already created with the proper sizes,
8978:   otherwise it will be recreated. `y` must be initialized to `NULL` if not supplied.

8980: .seealso: [](ch_matrices), `Mat`, `MatInterpolate()`, `MatRestrict()`, `MatMatRestrict()`, `PCMG`
8981: @*/
8982: PetscErrorCode MatMatInterpolate(Mat A, Mat x, Mat *y)
8983: {
8984:   PetscFunctionBegin;
8985:   PetscCall(MatMatInterpolateAdd(A, x, NULL, y));
8986:   PetscFunctionReturn(PETSC_SUCCESS);
8987: }

8989: /*@
8990:   MatMatRestrict - $Y = A*X$ or $A^T*X$ depending on the shape of `A`

8992:   Neighbor-wise Collective

8994:   Input Parameters:
8995: + A - the matrix
8996: - x - the input dense matrix

8998:   Output Parameter:
8999: . y - the output dense matrix

9001:   Level: intermediate

9003:   Note:
9004:   This allows one to use either the restriction or interpolation (its transpose)
9005:   matrix to do the restriction. `y` matrix can be reused if already created with the proper sizes,
9006:   otherwise it will be recreated. `y` must be initialized to `NULL` if not supplied.

9008: .seealso: [](ch_matrices), `Mat`, `MatRestrict()`, `MatInterpolate()`, `MatMatInterpolate()`, `PCMG`
9009: @*/
9010: PetscErrorCode MatMatRestrict(Mat A, Mat x, Mat *y)
9011: {
9012:   PetscFunctionBegin;
9013:   PetscCall(MatMatInterpolateAdd(A, x, NULL, y));
9014:   PetscFunctionReturn(PETSC_SUCCESS);
9015: }

9017: /*@
9018:   MatGetNullSpace - retrieves the null space of a matrix.

9020:   Logically Collective

9022:   Input Parameters:
9023: + mat    - the matrix
9024: - nullsp - the null space object

9026:   Level: developer

9028: .seealso: [](ch_matrices), `Mat`, `MatCreate()`, `MatNullSpaceCreate()`, `MatSetNearNullSpace()`, `MatSetNullSpace()`, `MatNullSpace`
9029: @*/
9030: PetscErrorCode MatGetNullSpace(Mat mat, MatNullSpace *nullsp)
9031: {
9032:   PetscFunctionBegin;
9034:   PetscAssertPointer(nullsp, 2);
9035:   *nullsp = (mat->symmetric == PETSC_BOOL3_TRUE && !mat->nullsp) ? mat->transnullsp : mat->nullsp;
9036:   PetscFunctionReturn(PETSC_SUCCESS);
9037: }

9039: /*@C
9040:   MatGetNullSpaces - gets the null spaces, transpose null spaces, and near null spaces from an array of matrices

9042:   Logically Collective

9044:   Input Parameters:
9045: + n   - the number of matrices
9046: - mat - the array of matrices

9048:   Output Parameters:
9049: . nullsp - an array of null spaces, `NULL` for each matrix that does not have a null space, length 3 * `n`

9051:   Level: developer

9053:   Note:
9054:   Call `MatRestoreNullspaces()` to provide these to another array of matrices

9056: .seealso: [](ch_matrices), `Mat`, `MatCreate()`, `MatNullSpaceCreate()`, `MatSetNearNullSpace()`, `MatGetNullSpace()`, `MatSetTransposeNullSpace()`, `MatGetTransposeNullSpace()`,
9057:           `MatNullSpaceRemove()`, `MatRestoreNullSpaces()`
9058: @*/
9059: PetscErrorCode MatGetNullSpaces(PetscInt n, Mat mat[], MatNullSpace *nullsp[])
9060: {
9061:   PetscFunctionBegin;
9062:   PetscCheck(n >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Number of matrices %" PetscInt_FMT " must be non-negative", n);
9063:   PetscAssertPointer(mat, 2);
9064:   PetscAssertPointer(nullsp, 3);

9066:   PetscCall(PetscCalloc1(3 * n, nullsp));
9067:   for (PetscInt i = 0; i < n; i++) {
9069:     (*nullsp)[i] = mat[i]->nullsp;
9070:     PetscCall(PetscObjectReference((PetscObject)(*nullsp)[i]));
9071:     (*nullsp)[n + i] = mat[i]->nearnullsp;
9072:     PetscCall(PetscObjectReference((PetscObject)(*nullsp)[n + i]));
9073:     (*nullsp)[2 * n + i] = mat[i]->transnullsp;
9074:     PetscCall(PetscObjectReference((PetscObject)(*nullsp)[2 * n + i]));
9075:   }
9076:   PetscFunctionReturn(PETSC_SUCCESS);
9077: }

9079: /*@C
9080:   MatRestoreNullSpaces - sets the null spaces, transpose null spaces, and near null spaces obtained with `MatGetNullSpaces()` for an array of matrices

9082:   Logically Collective

9084:   Input Parameters:
9085: + n      - the number of matrices
9086: . mat    - the array of matrices
9087: - nullsp - an array of null spaces

9089:   Level: developer

9091:   Note:
9092:   Call `MatGetNullSpaces()` to create `nullsp`

9094: .seealso: [](ch_matrices), `Mat`, `MatCreate()`, `MatNullSpaceCreate()`, `MatSetNearNullSpace()`, `MatGetNullSpace()`, `MatSetTransposeNullSpace()`, `MatGetTransposeNullSpace()`,
9095:           `MatNullSpaceRemove()`, `MatGetNullSpaces()`
9096: @*/
9097: PetscErrorCode MatRestoreNullSpaces(PetscInt n, Mat mat[], MatNullSpace *nullsp[])
9098: {
9099:   PetscFunctionBegin;
9100:   PetscCheck(n >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Number of matrices %" PetscInt_FMT " must be non-negative", n);
9101:   PetscAssertPointer(mat, 2);
9102:   PetscAssertPointer(nullsp, 3);
9103:   PetscAssertPointer(*nullsp, 3);

9105:   for (PetscInt i = 0; i < n; i++) {
9107:     PetscCall(MatSetNullSpace(mat[i], (*nullsp)[i]));
9108:     PetscCall(PetscObjectDereference((PetscObject)(*nullsp)[i]));
9109:     PetscCall(MatSetNearNullSpace(mat[i], (*nullsp)[n + i]));
9110:     PetscCall(PetscObjectDereference((PetscObject)(*nullsp)[n + i]));
9111:     PetscCall(MatSetTransposeNullSpace(mat[i], (*nullsp)[2 * n + i]));
9112:     PetscCall(PetscObjectDereference((PetscObject)(*nullsp)[2 * n + i]));
9113:   }
9114:   PetscCall(PetscFree(*nullsp));
9115:   PetscFunctionReturn(PETSC_SUCCESS);
9116: }

9118: /*@
9119:   MatSetNullSpace - attaches a null space to a matrix.

9121:   Logically Collective

9123:   Input Parameters:
9124: + mat    - the matrix
9125: - nullsp - the null space object

9127:   Level: advanced

9129:   Notes:
9130:   This null space is used by the `KSP` linear solvers to solve singular systems.

9132:   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`

9134:   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
9135:   to zero but the linear system will still be solved in a least squares sense.

9137:   The fundamental theorem of linear algebra (Gilbert Strang, Introduction to Applied Mathematics, page 72) states that
9138:   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)$.
9139:   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
9140:   $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
9141:   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)$.
9142:   This  $\hat{b}$ can be obtained by calling `MatNullSpaceRemove()` with the null space of the transpose of the matrix.

9144:   If the matrix is known to be symmetric because it is an `MATSBAIJ` matrix or one has called
9145:   `MatSetOption`(mat,`MAT_SYMMETRIC` or possibly `MAT_SYMMETRY_ETERNAL`,`PETSC_TRUE`); this
9146:   routine also automatically calls `MatSetTransposeNullSpace()`.

9148:   The user should call `MatNullSpaceDestroy()`.

9150: .seealso: [](ch_matrices), `Mat`, `MatCreate()`, `MatNullSpaceCreate()`, `MatSetNearNullSpace()`, `MatGetNullSpace()`, `MatSetTransposeNullSpace()`, `MatGetTransposeNullSpace()`, `MatNullSpaceRemove()`,
9151:           `KSPSetPCSide()`
9152: @*/
9153: PetscErrorCode MatSetNullSpace(Mat mat, MatNullSpace nullsp)
9154: {
9155:   PetscFunctionBegin;
9158:   PetscCall(PetscObjectReference((PetscObject)nullsp));
9159:   PetscCall(MatNullSpaceDestroy(&mat->nullsp));
9160:   mat->nullsp = nullsp;
9161:   if (mat->symmetric == PETSC_BOOL3_TRUE) PetscCall(MatSetTransposeNullSpace(mat, nullsp));
9162:   PetscFunctionReturn(PETSC_SUCCESS);
9163: }

9165: /*@
9166:   MatGetTransposeNullSpace - retrieves the null space of the transpose of a matrix.

9168:   Logically Collective

9170:   Input Parameters:
9171: + mat    - the matrix
9172: - nullsp - the null space object

9174:   Level: developer

9176: .seealso: [](ch_matrices), `Mat`, `MatNullSpace`, `MatCreate()`, `MatNullSpaceCreate()`, `MatSetNearNullSpace()`, `MatSetTransposeNullSpace()`, `MatSetNullSpace()`, `MatGetNullSpace()`
9177: @*/
9178: PetscErrorCode MatGetTransposeNullSpace(Mat mat, MatNullSpace *nullsp)
9179: {
9180:   PetscFunctionBegin;
9183:   PetscAssertPointer(nullsp, 2);
9184:   *nullsp = (mat->symmetric == PETSC_BOOL3_TRUE && !mat->transnullsp) ? mat->nullsp : mat->transnullsp;
9185:   PetscFunctionReturn(PETSC_SUCCESS);
9186: }

9188: /*@
9189:   MatSetTransposeNullSpace - attaches the null space of a transpose of a matrix to the matrix

9191:   Logically Collective

9193:   Input Parameters:
9194: + mat    - the matrix
9195: - nullsp - the null space object

9197:   Level: advanced

9199:   Notes:
9200:   This allows solving singular linear systems defined by the transpose of the matrix using `KSP` solvers with left preconditioning.

9202:   See `MatSetNullSpace()`

9204: .seealso: [](ch_matrices), `Mat`, `MatNullSpace`, `MatCreate()`, `MatNullSpaceCreate()`, `MatSetNearNullSpace()`, `MatGetNullSpace()`, `MatSetNullSpace()`, `MatGetTransposeNullSpace()`, `MatNullSpaceRemove()`, `KSPSetPCSide()`
9205: @*/
9206: PetscErrorCode MatSetTransposeNullSpace(Mat mat, MatNullSpace nullsp)
9207: {
9208:   PetscFunctionBegin;
9211:   PetscCall(PetscObjectReference((PetscObject)nullsp));
9212:   PetscCall(MatNullSpaceDestroy(&mat->transnullsp));
9213:   mat->transnullsp = nullsp;
9214:   PetscFunctionReturn(PETSC_SUCCESS);
9215: }

9217: /*@
9218:   MatSetNearNullSpace - attaches a null space to a matrix, which is often the null space (rigid body modes) of the operator without boundary conditions
9219:   This null space will be used to provide near null space vectors to a multigrid preconditioner built from this matrix.

9221:   Logically Collective

9223:   Input Parameters:
9224: + mat    - the matrix
9225: - nullsp - the null space object

9227:   Level: advanced

9229:   Notes:
9230:   Overwrites any previous near null space that may have been attached

9232:   You can remove the null space by calling this routine with an `nullsp` of `NULL`

9234: .seealso: [](ch_matrices), `Mat`, `MatNullSpace`, `MatCreate()`, `MatNullSpaceCreate()`, `MatSetNullSpace()`, `MatNullSpaceCreateRigidBody()`, `MatGetNearNullSpace()`
9235: @*/
9236: PetscErrorCode MatSetNearNullSpace(Mat mat, MatNullSpace nullsp)
9237: {
9238:   PetscFunctionBegin;
9242:   MatCheckPreallocated(mat, 1);
9243:   PetscCall(PetscObjectReference((PetscObject)nullsp));
9244:   PetscCall(MatNullSpaceDestroy(&mat->nearnullsp));
9245:   mat->nearnullsp = nullsp;
9246:   PetscFunctionReturn(PETSC_SUCCESS);
9247: }

9249: /*@
9250:   MatGetNearNullSpace - Get null space attached with `MatSetNearNullSpace()`

9252:   Not Collective

9254:   Input Parameter:
9255: . mat - the matrix

9257:   Output Parameter:
9258: . nullsp - the null space object, `NULL` if not set

9260:   Level: advanced

9262: .seealso: [](ch_matrices), `Mat`, `MatNullSpace`, `MatSetNearNullSpace()`, `MatGetNullSpace()`, `MatNullSpaceCreate()`
9263: @*/
9264: PetscErrorCode MatGetNearNullSpace(Mat mat, MatNullSpace *nullsp)
9265: {
9266:   PetscFunctionBegin;
9269:   PetscAssertPointer(nullsp, 2);
9270:   MatCheckPreallocated(mat, 1);
9271:   *nullsp = mat->nearnullsp;
9272:   PetscFunctionReturn(PETSC_SUCCESS);
9273: }

9275: /*@
9276:   MatICCFactor - Performs in-place incomplete Cholesky factorization of matrix.

9278:   Collective

9280:   Input Parameters:
9281: + mat  - the matrix
9282: . row  - row/column permutation
9283: - info - information on desired factorization process

9285:   Level: developer

9287:   Notes:
9288:   Probably really in-place only when level of fill is zero, otherwise allocates
9289:   new space to store factored matrix and deletes previous memory.

9291:   Most users should employ the `KSP` interface for linear solvers
9292:   instead of working directly with matrix algebra routines such as this.
9293:   See, e.g., `KSPCreate()`.

9295:   Fortran Note:
9296:   A valid (non-null) `info` argument must be provided

9298: .seealso: [](ch_matrices), `Mat`, `MatFactorInfo`, `MatGetFactor()`, `MatICCFactorSymbolic()`, `MatLUFactorNumeric()`, `MatCholeskyFactor()`
9299: @*/
9300: PetscErrorCode MatICCFactor(Mat mat, IS row, const MatFactorInfo *info)
9301: {
9302:   PetscFunctionBegin;
9306:   PetscAssertPointer(info, 3);
9307:   PetscCheck(mat->rmap->N == mat->cmap->N, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONG, "matrix must be square");
9308:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
9309:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
9310:   MatCheckPreallocated(mat, 1);
9311:   PetscUseTypeMethod(mat, iccfactor, row, info);
9312:   PetscCall(PetscObjectStateIncrease((PetscObject)mat));
9313:   PetscFunctionReturn(PETSC_SUCCESS);
9314: }

9316: /*@
9317:   MatDiagonalScaleLocal - Scales columns of a matrix given the scaling values including the
9318:   ghosted ones.

9320:   Not Collective

9322:   Input Parameters:
9323: + mat  - the matrix
9324: - diag - the diagonal values, including ghost ones

9326:   Level: developer

9328:   Notes:
9329:   Works only for `MATMPIAIJ` and `MATMPIBAIJ` matrices

9331:   This allows one to avoid during communication to perform the scaling that must be done with `MatDiagonalScale()`

9333: .seealso: [](ch_matrices), `Mat`, `MatDiagonalScale()`
9334: @*/
9335: PetscErrorCode MatDiagonalScaleLocal(Mat mat, Vec diag)
9336: {
9337:   PetscMPIInt size;

9339:   PetscFunctionBegin;

9344:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Matrix must be already assembled");
9345:   PetscCall(PetscLogEventBegin(MAT_Scale, mat, 0, 0, 0));
9346:   PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)mat), &size));
9347:   if (size == 1) {
9348:     PetscInt n, m;
9349:     PetscCall(VecGetSize(diag, &n));
9350:     PetscCall(MatGetSize(mat, NULL, &m));
9351:     PetscCheck(m == n, PETSC_COMM_SELF, PETSC_ERR_SUP, "Only supported for sequential matrices when no ghost points/periodic conditions");
9352:     PetscCall(MatDiagonalScale(mat, NULL, diag));
9353:   } else PetscUseMethod(mat, "MatDiagonalScaleLocal_C", (Mat, Vec), (mat, diag));
9354:   PetscCall(PetscLogEventEnd(MAT_Scale, mat, 0, 0, 0));
9355:   PetscCall(PetscObjectStateIncrease((PetscObject)mat));
9356:   PetscFunctionReturn(PETSC_SUCCESS);
9357: }

9359: /*@
9360:   MatGetInertia - Gets the inertia from a factored matrix

9362:   Collective

9364:   Input Parameter:
9365: . mat - the matrix

9367:   Output Parameters:
9368: + nneg  - number of negative eigenvalues
9369: . nzero - number of zero eigenvalues
9370: - npos  - number of positive eigenvalues

9372:   Level: advanced

9374:   Note:
9375:   Matrix must have been factored by `MatCholeskyFactor()`

9377: .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatCholeskyFactor()`
9378: @*/
9379: PetscErrorCode MatGetInertia(Mat mat, PetscInt *nneg, PetscInt *nzero, PetscInt *npos)
9380: {
9381:   PetscFunctionBegin;
9384:   PetscCheck(mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Unfactored matrix");
9385:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Numeric factor mat is not assembled");
9386:   PetscUseTypeMethod(mat, getinertia, nneg, nzero, npos);
9387:   PetscFunctionReturn(PETSC_SUCCESS);
9388: }

9390: /*@C
9391:   MatSolves - Solves $A x = b$, given a factored matrix, for a collection of vectors

9393:   Neighbor-wise Collective

9395:   Input Parameters:
9396: + mat - the factored matrix obtained with `MatGetFactor()`
9397: - b   - the right-hand-side vectors

9399:   Output Parameter:
9400: . x - the result vectors

9402:   Level: developer

9404:   Note:
9405:   The vectors `b` and `x` cannot be the same.  I.e., one cannot
9406:   call `MatSolves`(A,x,x).

9408: .seealso: [](ch_matrices), `Mat`, `Vecs`, `MatSolveAdd()`, `MatSolveTranspose()`, `MatSolveTransposeAdd()`, `MatSolve()`
9409: @*/
9410: PetscErrorCode MatSolves(Mat mat, Vecs b, Vecs x)
9411: {
9412:   PetscFunctionBegin;
9415:   PetscCheck(x != b, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_IDN, "x and b must be different vectors");
9416:   PetscCheck(mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Unfactored matrix");
9417:   if (!mat->rmap->N && !mat->cmap->N) PetscFunctionReturn(PETSC_SUCCESS);

9419:   MatCheckPreallocated(mat, 1);
9420:   PetscCall(PetscLogEventBegin(MAT_Solves, mat, 0, 0, 0));
9421:   PetscUseTypeMethod(mat, solves, b, x);
9422:   PetscCall(PetscLogEventEnd(MAT_Solves, mat, 0, 0, 0));
9423:   PetscFunctionReturn(PETSC_SUCCESS);
9424: }

9426: /*@
9427:   MatIsSymmetric - Test whether a matrix is symmetric

9429:   Collective

9431:   Input Parameters:
9432: + A   - the matrix to test
9433: - tol - difference between value and its transpose less than this amount counts as equal (use 0.0 for exact transpose)

9435:   Output Parameter:
9436: . flg - the result

9438:   Level: intermediate

9440:   Notes:
9441:   For real numbers `MatIsSymmetric()` and `MatIsHermitian()` return identical results

9443:   If the matrix does not yet know if it is symmetric or not this can be an expensive operation, also available `MatIsSymmetricKnown()`

9445:   One can declare that a matrix is symmetric with `MatSetOption`(mat,`MAT_SYMMETRIC`,`PETSC_TRUE`) and if it is known to remain symmetric
9446:   after changes to the matrices values one can call `MatSetOption`(mat,`MAT_SYMMETRY_ETERNAL`,`PETSC_TRUE`)

9448: .seealso: [](ch_matrices), `Mat`, `MatTranspose()`, `MatIsTranspose()`, `MatIsHermitian()`, `MatIsStructurallySymmetric()`, `MatSetOption()`, `MatIsSymmetricKnown()`,
9449:           `MAT_SYMMETRIC`, `MAT_SYMMETRY_ETERNAL`
9450: @*/
9451: PetscErrorCode MatIsSymmetric(Mat A, PetscReal tol, PetscBool *flg)
9452: {
9453:   PetscFunctionBegin;
9455:   PetscAssertPointer(flg, 3);
9456:   if (A->symmetric != PETSC_BOOL3_UNKNOWN && !tol) *flg = PetscBool3ToBool(A->symmetric);
9457:   else {
9458:     if (A->ops->issymmetric) PetscUseTypeMethod(A, issymmetric, tol, flg);
9459:     else PetscCall(MatIsTranspose(A, A, tol, flg));
9460:     if (!tol) PetscCall(MatSetOption(A, MAT_SYMMETRIC, *flg));
9461:   }
9462:   PetscFunctionReturn(PETSC_SUCCESS);
9463: }

9465: /*@
9466:   MatIsHermitian - Test whether a matrix is Hermitian

9468:   Collective

9470:   Input Parameters:
9471: + A   - the matrix to test
9472: - tol - difference between value and its transpose less than this amount counts as equal (use 0.0 for exact Hermitian)

9474:   Output Parameter:
9475: . flg - the result

9477:   Level: intermediate

9479:   Notes:
9480:   For real numbers `MatIsSymmetric()` and `MatIsHermitian()` return identical results

9482:   If the matrix does not yet know if it is Hermitian or not this can be an expensive operation, also available `MatIsHermitianKnown()`

9484:   One can declare that a matrix is Hermitian with `MatSetOption`(mat,`MAT_HERMITIAN`,`PETSC_TRUE`) and if it is known to remain Hermitian
9485:   after changes to the matrices values one can call `MatSetOption`(mat,`MAT_SYMEMTRY_ETERNAL`,`PETSC_TRUE`)

9487: .seealso: [](ch_matrices), `Mat`, `MatTranspose()`, `MatIsTranspose()`, `MatIsHermitianKnown()`, `MatIsStructurallySymmetric()`, `MatSetOption()`,
9488:           `MatIsSymmetricKnown()`, `MatIsSymmetric()`, `MAT_HERMITIAN`, `MAT_SYMMETRY_ETERNAL`
9489: @*/
9490: PetscErrorCode MatIsHermitian(Mat A, PetscReal tol, PetscBool *flg)
9491: {
9492:   PetscFunctionBegin;
9494:   PetscAssertPointer(flg, 3);
9495:   if (A->hermitian != PETSC_BOOL3_UNKNOWN && !tol) *flg = PetscBool3ToBool(A->hermitian);
9496:   else {
9497:     if (A->ops->ishermitian) PetscUseTypeMethod(A, ishermitian, tol, flg);
9498:     else PetscCall(MatIsHermitianTranspose(A, A, tol, flg));
9499:     if (!tol) PetscCall(MatSetOption(A, MAT_HERMITIAN, *flg));
9500:   }
9501:   PetscFunctionReturn(PETSC_SUCCESS);
9502: }

9504: /*@
9505:   MatIsSymmetricKnown - Checks if a matrix knows if it is symmetric or not and its symmetric state

9507:   Not Collective

9509:   Input Parameter:
9510: . A - the matrix to check

9512:   Output Parameters:
9513: + set - `PETSC_TRUE` if the matrix knows its symmetry state (this tells you if the next flag is valid)
9514: - flg - the result (only valid if set is `PETSC_TRUE`)

9516:   Level: advanced

9518:   Notes:
9519:   Does not check the matrix values directly, so this may return unknown (set = `PETSC_FALSE`). Use `MatIsSymmetric()`
9520:   if you want it explicitly checked

9522:   One can declare that a matrix is symmetric with `MatSetOption`(mat,`MAT_SYMMETRIC`,`PETSC_TRUE`) and if it is known to remain symmetric
9523:   after changes to the matrices values one can call `MatSetOption`(mat,`MAT_SYMMETRY_ETERNAL`,`PETSC_TRUE`)

9525: .seealso: [](ch_matrices), `Mat`, `MAT_SYMMETRY_ETERNAL`, `MatTranspose()`, `MatIsTranspose()`, `MatIsHermitian()`, `MatIsStructurallySymmetric()`, `MatSetOption()`, `MatIsSymmetric()`, `MatIsHermitianKnown()`
9526: @*/
9527: PetscErrorCode MatIsSymmetricKnown(Mat A, PetscBool *set, PetscBool *flg)
9528: {
9529:   PetscFunctionBegin;
9531:   PetscAssertPointer(set, 2);
9532:   PetscAssertPointer(flg, 3);
9533:   if (A->symmetric != PETSC_BOOL3_UNKNOWN) {
9534:     *set = PETSC_TRUE;
9535:     *flg = PetscBool3ToBool(A->symmetric);
9536:   } else *set = PETSC_FALSE;
9537:   PetscFunctionReturn(PETSC_SUCCESS);
9538: }

9540: /*@
9541:   MatIsSPDKnown - Checks if a matrix knows if it is symmetric positive definite or not and its symmetric positive definite state

9543:   Not Collective

9545:   Input Parameter:
9546: . A - the matrix to check

9548:   Output Parameters:
9549: + set - `PETSC_TRUE` if the matrix knows its symmetric positive definite state (this tells you if the next flag is valid)
9550: - flg - the result (only valid if set is `PETSC_TRUE`)

9552:   Level: advanced

9554:   Notes:
9555:   Does not check the matrix values directly, so this may return unknown (set = `PETSC_FALSE`).

9557:   One can declare that a matrix is SPD with `MatSetOption`(mat,`MAT_SPD`,`PETSC_TRUE`) and if it is known to remain SPD
9558:   after changes to the matrices values one can call `MatSetOption`(mat,`MAT_SPD_ETERNAL`,`PETSC_TRUE`)

9560: .seealso: [](ch_matrices), `Mat`, `MAT_SPD_ETERNAL`, `MAT_SPD`, `MatTranspose()`, `MatIsTranspose()`, `MatIsHermitian()`, `MatIsStructurallySymmetric()`, `MatSetOption()`, `MatIsSymmetric()`, `MatIsHermitianKnown()`
9561: @*/
9562: PetscErrorCode MatIsSPDKnown(Mat A, PetscBool *set, PetscBool *flg)
9563: {
9564:   PetscFunctionBegin;
9566:   PetscAssertPointer(set, 2);
9567:   PetscAssertPointer(flg, 3);
9568:   if (A->spd != PETSC_BOOL3_UNKNOWN) {
9569:     *set = PETSC_TRUE;
9570:     *flg = PetscBool3ToBool(A->spd);
9571:   } else *set = PETSC_FALSE;
9572:   PetscFunctionReturn(PETSC_SUCCESS);
9573: }

9575: /*@
9576:   MatIsHermitianKnown - Checks if a matrix knows if it is Hermitian or not and its Hermitian state

9578:   Not Collective

9580:   Input Parameter:
9581: . A - the matrix to check

9583:   Output Parameters:
9584: + set - `PETSC_TRUE` if the matrix knows its Hermitian state (this tells you if the next flag is valid)
9585: - flg - the result (only valid if set is `PETSC_TRUE`)

9587:   Level: advanced

9589:   Notes:
9590:   Does not check the matrix values directly, so this may return unknown (set = `PETSC_FALSE`). Use `MatIsHermitian()`
9591:   if you want it explicitly checked

9593:   One can declare that a matrix is Hermitian with `MatSetOption`(mat,`MAT_HERMITIAN`,`PETSC_TRUE`) and if it is known to remain Hermitian
9594:   after changes to the matrices values one can call `MatSetOption`(mat,`MAT_SYMMETRY_ETERNAL`,`PETSC_TRUE`)

9596: .seealso: [](ch_matrices), `Mat`, `MAT_SYMMETRY_ETERNAL`, `MAT_HERMITIAN`, `MatTranspose()`, `MatIsTranspose()`, `MatIsHermitian()`, `MatIsStructurallySymmetric()`, `MatSetOption()`, `MatIsSymmetric()`
9597: @*/
9598: PetscErrorCode MatIsHermitianKnown(Mat A, PetscBool *set, PetscBool *flg)
9599: {
9600:   PetscFunctionBegin;
9602:   PetscAssertPointer(set, 2);
9603:   PetscAssertPointer(flg, 3);
9604:   if (A->hermitian != PETSC_BOOL3_UNKNOWN) {
9605:     *set = PETSC_TRUE;
9606:     *flg = PetscBool3ToBool(A->hermitian);
9607:   } else *set = PETSC_FALSE;
9608:   PetscFunctionReturn(PETSC_SUCCESS);
9609: }

9611: /*@
9612:   MatIsStructurallySymmetric - Test whether a matrix is structurally symmetric

9614:   Collective

9616:   Input Parameter:
9617: . A - the matrix to test

9619:   Output Parameter:
9620: . flg - the result

9622:   Level: intermediate

9624:   Notes:
9625:   If the matrix does yet know it is structurally symmetric this can be an expensive operation, also available `MatIsStructurallySymmetricKnown()`

9627:   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
9628:   symmetric after changes to the matrices values one can call `MatSetOption`(mat,`MAT_STRUCTURAL_SYMMETRY_ETERNAL`,`PETSC_TRUE`)

9630: .seealso: [](ch_matrices), `Mat`, `MAT_STRUCTURALLY_SYMMETRIC`, `MAT_STRUCTURAL_SYMMETRY_ETERNAL`, `MatTranspose()`, `MatIsTranspose()`, `MatIsHermitian()`, `MatIsSymmetric()`, `MatSetOption()`, `MatIsStructurallySymmetricKnown()`
9631: @*/
9632: PetscErrorCode MatIsStructurallySymmetric(Mat A, PetscBool *flg)
9633: {
9634:   PetscFunctionBegin;
9636:   PetscAssertPointer(flg, 2);
9637:   if (A->structurally_symmetric != PETSC_BOOL3_UNKNOWN) *flg = PetscBool3ToBool(A->structurally_symmetric);
9638:   else {
9639:     PetscUseTypeMethod(A, isstructurallysymmetric, flg);
9640:     PetscCall(MatSetOption(A, MAT_STRUCTURALLY_SYMMETRIC, *flg));
9641:   }
9642:   PetscFunctionReturn(PETSC_SUCCESS);
9643: }

9645: /*@
9646:   MatIsStructurallySymmetricKnown - Checks if a matrix knows if it is structurally symmetric or not and its structurally symmetric state

9648:   Not Collective

9650:   Input Parameter:
9651: . A - the matrix to check

9653:   Output Parameters:
9654: + set - PETSC_TRUE if the matrix knows its structurally symmetric state (this tells you if the next flag is valid)
9655: - flg - the result (only valid if set is PETSC_TRUE)

9657:   Level: advanced

9659:   Notes:
9660:   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
9661:   symmetric after changes to the matrices values one can call `MatSetOption`(mat,`MAT_STRUCTURAL_SYMMETRY_ETERNAL`,`PETSC_TRUE`)

9663:   Use `MatIsStructurallySymmetric()` to explicitly check if a matrix is structurally symmetric (this is an expensive operation)

9665: .seealso: [](ch_matrices), `Mat`, `MAT_STRUCTURALLY_SYMMETRIC`, `MatTranspose()`, `MatIsTranspose()`, `MatIsHermitian()`, `MatIsStructurallySymmetric()`, `MatSetOption()`, `MatIsSymmetric()`, `MatIsHermitianKnown()`
9666: @*/
9667: PetscErrorCode MatIsStructurallySymmetricKnown(Mat A, PetscBool *set, PetscBool *flg)
9668: {
9669:   PetscFunctionBegin;
9671:   PetscAssertPointer(set, 2);
9672:   PetscAssertPointer(flg, 3);
9673:   if (A->structurally_symmetric != PETSC_BOOL3_UNKNOWN) {
9674:     *set = PETSC_TRUE;
9675:     *flg = PetscBool3ToBool(A->structurally_symmetric);
9676:   } else *set = PETSC_FALSE;
9677:   PetscFunctionReturn(PETSC_SUCCESS);
9678: }

9680: /*@
9681:   MatStashGetInfo - Gets how many values are currently in the matrix stash, i.e. need
9682:   to be communicated to other processors during the `MatAssemblyBegin()`/`MatAssemblyEnd()` process

9684:   Not Collective

9686:   Input Parameter:
9687: . mat - the matrix

9689:   Output Parameters:
9690: + nstash    - the size of the stash
9691: . reallocs  - the number of additional mallocs incurred.
9692: . bnstash   - the size of the block stash
9693: - breallocs - the number of additional mallocs incurred.in the block stash

9695:   Level: advanced

9697: .seealso: [](ch_matrices), `MatAssemblyBegin()`, `MatAssemblyEnd()`, `Mat`, `MatStashSetInitialSize()`
9698: @*/
9699: PetscErrorCode MatStashGetInfo(Mat mat, PetscInt *nstash, PetscInt *reallocs, PetscInt *bnstash, PetscInt *breallocs)
9700: {
9701:   PetscFunctionBegin;
9702:   PetscCall(MatStashGetInfo_Private(&mat->stash, nstash, reallocs));
9703:   PetscCall(MatStashGetInfo_Private(&mat->bstash, bnstash, breallocs));
9704:   PetscFunctionReturn(PETSC_SUCCESS);
9705: }

9707: /*@
9708:   MatCreateVecs - Get vector(s) compatible with the matrix, i.e. with the same
9709:   parallel layout, `PetscLayout` for rows and columns

9711:   Collective

9713:   Input Parameter:
9714: . mat - the matrix

9716:   Output Parameters:
9717: + right - (optional) vector that the matrix can be multiplied against
9718: - left  - (optional) vector that the matrix vector product can be stored in

9720:   Options Database Key:
9721: . -mat_vec_type type - set the `VecType` of the created vectors during `MatSetFromOptions()`

9723:   Level: advanced

9725:   Notes:
9726:   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()`.

9728:   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`.

9730:   These are new vectors which are not owned by the `mat`, they should be destroyed with `VecDestroy()` when no longer needed.

9732:   PETSc `Vec` always have all zero entries when created with `MatCreateVecs()` until routines such as `VecSet()` or `VecSetValues()`
9733:   are used to change the values. There is no reason to call `VecZeroEntries()` after creation.

9735: .seealso: [](ch_matrices), `Mat`, `Vec`, `VecCreate()`, `VecDestroy()`, `DMCreateGlobalVector()`, `MatSetVecType()`
9736: @*/
9737: PetscErrorCode MatCreateVecs(Mat mat, Vec *right, Vec *left)
9738: {
9739:   PetscFunctionBegin;
9742:   if (mat->ops->getvecs) {
9743:     PetscUseTypeMethod(mat, getvecs, right, left);
9744:   } else {
9745:     if (right) {
9746:       PetscCheck(mat->cmap->n >= 0, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "PetscLayout for columns not yet setup");
9747:       PetscCall(VecCreateWithLayout_Private(mat->cmap, right));
9748:       PetscCall(VecSetType(*right, mat->defaultvectype));
9749: #if defined(PETSC_HAVE_VIENNACL) || defined(PETSC_HAVE_CUDA) || defined(PETSC_HAVE_HIP)
9750:       if (mat->boundtocpu && mat->bindingpropagates) {
9751:         PetscCall(VecSetBindingPropagates(*right, PETSC_TRUE));
9752:         PetscCall(VecBindToCPU(*right, PETSC_TRUE));
9753:       }
9754: #endif
9755:     }
9756:     if (left) {
9757:       PetscCheck(mat->rmap->n >= 0, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "PetscLayout for rows not yet setup");
9758:       PetscCall(VecCreateWithLayout_Private(mat->rmap, left));
9759:       PetscCall(VecSetType(*left, mat->defaultvectype));
9760: #if defined(PETSC_HAVE_VIENNACL) || defined(PETSC_HAVE_CUDA) || defined(PETSC_HAVE_HIP)
9761:       if (mat->boundtocpu && mat->bindingpropagates) {
9762:         PetscCall(VecSetBindingPropagates(*left, PETSC_TRUE));
9763:         PetscCall(VecBindToCPU(*left, PETSC_TRUE));
9764:       }
9765: #endif
9766:     }
9767:   }
9768:   PetscFunctionReturn(PETSC_SUCCESS);
9769: }

9771: /*@
9772:   MatFactorInfoInitialize - Initializes a `MatFactorInfo` data structure
9773:   with default values.

9775:   Not Collective

9777:   Input Parameter:
9778: . info - the `MatFactorInfo` data structure

9780:   Level: developer

9782:   Notes:
9783:   The solvers are generally used through the `KSP` and `PC` objects, for example
9784:   `PCLU`, `PCILU`, `PCCHOLESKY`, `PCICC`

9786:   Once the data structure is initialized one may change certain entries as desired for the particular factorization to be performed

9788: .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatFactorInfo`
9789: @*/
9790: PetscErrorCode MatFactorInfoInitialize(MatFactorInfo *info)
9791: {
9792:   PetscFunctionBegin;
9793:   PetscCall(PetscMemzero(info, sizeof(MatFactorInfo)));
9794:   PetscFunctionReturn(PETSC_SUCCESS);
9795: }

9797: /*@
9798:   MatFactorSetSchurIS - Set indices corresponding to the Schur complement you wish to have computed

9800:   Collective

9802:   Input Parameters:
9803: + mat - the factored matrix
9804: - is  - the index set defining the Schur indices (0-based)

9806:   Level: advanced

9808:   Notes:
9809:   Call `MatFactorSolveSchurComplement()` or `MatFactorSolveSchurComplementTranspose()` after this call to solve a Schur complement system.

9811:   You can call `MatFactorGetSchurComplement()` or `MatFactorCreateSchurComplement()` after this call.

9813:   This functionality is only supported for `MATSOLVERMUMPS` and `MATSOLVERMKL_PARDISO`

9815: .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatFactorGetSchurComplement()`, `MatFactorRestoreSchurComplement()`, `MatFactorCreateSchurComplement()`, `MatFactorSolveSchurComplement()`,
9816:           `MatFactorSolveSchurComplementTranspose()`, `MATSOLVERMUMPS`, `MATSOLVERMKL_PARDISO`
9817: @*/
9818: PetscErrorCode MatFactorSetSchurIS(Mat mat, IS is)
9819: {
9820:   PetscErrorCode (*f)(Mat, IS);

9822:   PetscFunctionBegin;
9827:   PetscCheckSameComm(mat, 1, is, 2);
9828:   PetscCheck(mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Only for factored matrix");
9829:   PetscCall(PetscObjectQueryFunction((PetscObject)mat, "MatFactorSetSchurIS_C", &f));
9830:   PetscCheck(f, PetscObjectComm((PetscObject)mat), PETSC_ERR_SUP, "The selected MatSolverType does not support Schur complement computation. You should use MATSOLVERMUMPS or MATSOLVERMKL_PARDISO");
9831:   PetscCall(MatDestroy(&mat->schur));
9832:   PetscCall((*f)(mat, is));
9833:   PetscCheck(mat->schur, PetscObjectComm((PetscObject)mat), PETSC_ERR_PLIB, "Schur complement has not been created");
9834:   PetscFunctionReturn(PETSC_SUCCESS);
9835: }

9837: /*@
9838:   MatFactorCreateSchurComplement - Create a Schur complement matrix object using Schur data computed during the factorization step

9840:   Logically Collective

9842:   Input Parameters:
9843: + F      - the factored matrix obtained by calling `MatGetFactor()`
9844: . S      - location where to return the Schur complement, can be `NULL`
9845: - status - the status of the Schur complement matrix, can be `NULL`

9847:   Level: advanced

9849:   Notes:
9850:   You must call `MatFactorSetSchurIS()` before calling this routine.

9852:   This functionality is only supported for `MATSOLVERMUMPS` and `MATSOLVERMKL_PARDISO`

9854:   The routine provides a copy of the Schur matrix stored within the solver data structures.
9855:   The caller must destroy the object when it is no longer needed.
9856:   If `MatFactorInvertSchurComplement()` has been called, the routine gets back the inverse.

9858:   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)

9860:   See `MatCreateSchurComplement()` or `MatGetSchurComplement()` for ways to create virtual or approximate Schur complements.

9862:   Developer Note:
9863:   The reason this routine exists is because the representation of the Schur complement within the factor matrix may be different than a standard PETSc
9864:   matrix representation and we normally do not want to use the time or memory to make a copy as a regular PETSc matrix.

9866: .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatFactorSetSchurIS()`, `MatFactorGetSchurComplement()`, `MatFactorSchurStatus`, `MATSOLVERMUMPS`, `MATSOLVERMKL_PARDISO`
9867: @*/
9868: PetscErrorCode MatFactorCreateSchurComplement(Mat F, Mat *S, MatFactorSchurStatus *status)
9869: {
9870:   PetscFunctionBegin;
9872:   if (S) PetscAssertPointer(S, 2);
9873:   if (status) PetscAssertPointer(status, 3);
9874:   if (S) {
9875:     PetscErrorCode (*f)(Mat, Mat *);

9877:     PetscCall(PetscObjectQueryFunction((PetscObject)F, "MatFactorCreateSchurComplement_C", &f));
9878:     if (f) PetscCall((*f)(F, S));
9879:     else PetscCall(MatDuplicate(F->schur, MAT_COPY_VALUES, S));
9880:   }
9881:   if (status) *status = F->schur_status;
9882:   PetscFunctionReturn(PETSC_SUCCESS);
9883: }

9885: /*@
9886:   MatFactorGetSchurComplement - Gets access to a Schur complement matrix using the current Schur data within a factored matrix

9888:   Logically Collective

9890:   Input Parameters:
9891: + F      - the factored matrix obtained by calling `MatGetFactor()`
9892: . S      - location where to return the Schur complement, can be `NULL`
9893: - status - the status of the Schur complement matrix, can be `NULL`

9895:   Level: advanced

9897:   Notes:
9898:   You must call `MatFactorSetSchurIS()` before calling this routine.

9900:   Schur complement mode is currently implemented for sequential matrices with factor type of `MATSOLVERMUMPS`

9902:   The routine returns a the Schur Complement stored within the data structures of the solver.

9904:   If `MatFactorInvertSchurComplement()` has previously been called, the returned matrix is actually the inverse of the Schur complement.

9906:   The returned matrix should not be destroyed; the caller should call `MatFactorRestoreSchurComplement()` when the object is no longer needed.

9908:   Use `MatFactorCreateSchurComplement()` to create a copy of the Schur complement matrix that is within a factored matrix

9910:   See `MatCreateSchurComplement()` or `MatGetSchurComplement()` for ways to create virtual or approximate Schur complements.

9912: .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatFactorSetSchurIS()`, `MatFactorRestoreSchurComplement()`, `MatFactorCreateSchurComplement()`, `MatFactorSchurStatus`
9913: @*/
9914: PetscErrorCode MatFactorGetSchurComplement(Mat F, Mat *S, MatFactorSchurStatus *status)
9915: {
9916:   PetscFunctionBegin;
9918:   if (S) {
9919:     PetscAssertPointer(S, 2);
9920:     *S = F->schur;
9921:   }
9922:   if (status) {
9923:     PetscAssertPointer(status, 3);
9924:     *status = F->schur_status;
9925:   }
9926:   PetscFunctionReturn(PETSC_SUCCESS);
9927: }

9929: static PetscErrorCode MatFactorUpdateSchurStatus_Private(Mat F)
9930: {
9931:   Mat S = F->schur;

9933:   PetscFunctionBegin;
9934:   switch (F->schur_status) {
9935:   case MAT_FACTOR_SCHUR_UNFACTORED: // fall-through
9936:   case MAT_FACTOR_SCHUR_INVERTED:
9937:     if (S) {
9938:       S->ops->solve             = NULL;
9939:       S->ops->matsolve          = NULL;
9940:       S->ops->solvetranspose    = NULL;
9941:       S->ops->matsolvetranspose = NULL;
9942:       S->ops->solveadd          = NULL;
9943:       S->ops->solvetransposeadd = NULL;
9944:       S->factortype             = MAT_FACTOR_NONE;
9945:       PetscCall(PetscFree(S->solvertype));
9946:     }
9947:   case MAT_FACTOR_SCHUR_FACTORED: // fall-through
9948:     break;
9949:   default:
9950:     SETERRQ(PetscObjectComm((PetscObject)F), PETSC_ERR_SUP, "Unhandled MatFactorSchurStatus %d", F->schur_status);
9951:   }
9952:   PetscFunctionReturn(PETSC_SUCCESS);
9953: }

9955: /*@
9956:   MatFactorRestoreSchurComplement - Restore the Schur complement matrix object obtained from a call to `MatFactorGetSchurComplement()`

9958:   Logically Collective

9960:   Input Parameters:
9961: + F      - the factored matrix obtained by calling `MatGetFactor()`
9962: . S      - location where the Schur complement is stored
9963: - status - the status of the Schur complement matrix (see `MatFactorSchurStatus`)

9965:   Level: advanced

9967: .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatFactorSetSchurIS()`, `MatFactorCreateSchurComplement()`, `MatFactorSchurStatus`
9968: @*/
9969: PetscErrorCode MatFactorRestoreSchurComplement(Mat F, Mat *S, MatFactorSchurStatus status)
9970: {
9971:   PetscFunctionBegin;
9973:   if (S) {
9975:     *S = NULL;
9976:   }
9977:   F->schur_status = status;
9978:   PetscCall(MatFactorUpdateSchurStatus_Private(F));
9979:   PetscFunctionReturn(PETSC_SUCCESS);
9980: }

9982: /*@
9983:   MatFactorSolveSchurComplementTranspose - Solve the transpose of the Schur complement system computed during the factorization step

9985:   Logically Collective

9987:   Input Parameters:
9988: + F   - the factored matrix obtained by calling `MatGetFactor()`
9989: . rhs - location where the right-hand side of the Schur complement system is stored
9990: - sol - location where the solution of the Schur complement system has to be returned

9992:   Level: advanced

9994:   Notes:
9995:   The sizes of the vectors should match the size of the Schur complement

9997:   Must be called after `MatFactorSetSchurIS()`

9999: .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatFactorSetSchurIS()`, `MatFactorSolveSchurComplement()`
10000: @*/
10001: PetscErrorCode MatFactorSolveSchurComplementTranspose(Mat F, Vec rhs, Vec sol)
10002: {
10003:   PetscFunctionBegin;
10010:   PetscCheckSameComm(F, 1, rhs, 2);
10011:   PetscCheckSameComm(F, 1, sol, 3);
10012:   PetscCall(MatFactorFactorizeSchurComplement(F));
10013:   switch (F->schur_status) {
10014:   case MAT_FACTOR_SCHUR_FACTORED:
10015:     PetscCall(MatSolveTranspose(F->schur, rhs, sol));
10016:     break;
10017:   case MAT_FACTOR_SCHUR_INVERTED:
10018:     PetscCall(MatMultTranspose(F->schur, rhs, sol));
10019:     break;
10020:   default:
10021:     SETERRQ(PetscObjectComm((PetscObject)F), PETSC_ERR_SUP, "Unhandled MatFactorSchurStatus %d", F->schur_status);
10022:   }
10023:   PetscFunctionReturn(PETSC_SUCCESS);
10024: }

10026: /*@
10027:   MatFactorSolveSchurComplement - Solve the Schur complement system computed during the factorization step

10029:   Logically Collective

10031:   Input Parameters:
10032: + F   - the factored matrix obtained by calling `MatGetFactor()`
10033: . rhs - location where the right-hand side of the Schur complement system is stored
10034: - sol - location where the solution of the Schur complement system has to be returned

10036:   Level: advanced

10038:   Notes:
10039:   The sizes of the vectors should match the size of the Schur complement

10041:   Must be called after `MatFactorSetSchurIS()`

10043: .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatFactorSetSchurIS()`, `MatFactorSolveSchurComplementTranspose()`
10044: @*/
10045: PetscErrorCode MatFactorSolveSchurComplement(Mat F, Vec rhs, Vec sol)
10046: {
10047:   PetscFunctionBegin;
10054:   PetscCheckSameComm(F, 1, rhs, 2);
10055:   PetscCheckSameComm(F, 1, sol, 3);
10056:   PetscCall(MatFactorFactorizeSchurComplement(F));
10057:   switch (F->schur_status) {
10058:   case MAT_FACTOR_SCHUR_FACTORED:
10059:     PetscCall(MatSolve(F->schur, rhs, sol));
10060:     break;
10061:   case MAT_FACTOR_SCHUR_INVERTED:
10062:     PetscCall(MatMult(F->schur, rhs, sol));
10063:     break;
10064:   default:
10065:     SETERRQ(PetscObjectComm((PetscObject)F), PETSC_ERR_SUP, "Unhandled MatFactorSchurStatus %d", F->schur_status);
10066:   }
10067:   PetscFunctionReturn(PETSC_SUCCESS);
10068: }

10070: PETSC_SINGLE_LIBRARY_INTERN PetscErrorCode MatSeqDenseInvertFactors_Private(Mat);
10071: #if PetscDefined(HAVE_CUDA)
10072: PETSC_SINGLE_LIBRARY_INTERN PetscErrorCode MatSeqDenseCUDAInvertFactors_Internal(Mat);
10073: #endif

10075: /* Schur status updated in the interface */
10076: static PetscErrorCode MatFactorInvertSchurComplement_Private(Mat F)
10077: {
10078:   Mat S = F->schur;

10080:   PetscFunctionBegin;
10081:   if (S) {
10082:     PetscMPIInt size;
10083:     PetscBool   isdense, isdensecuda;

10085:     PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)S), &size));
10086:     PetscCheck(size <= 1, PetscObjectComm((PetscObject)S), PETSC_ERR_SUP, "Not yet implemented");
10087:     PetscCall(PetscObjectTypeCompare((PetscObject)S, MATSEQDENSE, &isdense));
10088:     PetscCall(PetscObjectTypeCompare((PetscObject)S, MATSEQDENSECUDA, &isdensecuda));
10089:     PetscCheck(isdense || isdensecuda, PetscObjectComm((PetscObject)S), PETSC_ERR_SUP, "Not implemented for type %s", ((PetscObject)S)->type_name);
10090:     PetscCall(PetscLogEventBegin(MAT_FactorInvS, F, 0, 0, 0));
10091:     if (isdense) {
10092:       PetscCall(MatSeqDenseInvertFactors_Private(S));
10093:     } else if (isdensecuda) {
10094: #if defined(PETSC_HAVE_CUDA)
10095:       PetscCall(MatSeqDenseCUDAInvertFactors_Internal(S));
10096: #endif
10097:     }
10098:     // HIP??????????????
10099:     PetscCall(PetscLogEventEnd(MAT_FactorInvS, F, 0, 0, 0));
10100:   }
10101:   PetscFunctionReturn(PETSC_SUCCESS);
10102: }

10104: /*@
10105:   MatFactorInvertSchurComplement - Invert the Schur complement matrix computed during the factorization step

10107:   Logically Collective

10109:   Input Parameter:
10110: . F - the factored matrix obtained by calling `MatGetFactor()`

10112:   Level: advanced

10114:   Notes:
10115:   Must be called after `MatFactorSetSchurIS()`.

10117:   Call `MatFactorGetSchurComplement()` or  `MatFactorCreateSchurComplement()` AFTER this call to actually compute the inverse and get access to it.

10119: .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatFactorSetSchurIS()`, `MatFactorGetSchurComplement()`, `MatFactorCreateSchurComplement()`
10120: @*/
10121: PetscErrorCode MatFactorInvertSchurComplement(Mat F)
10122: {
10123:   PetscFunctionBegin;
10126:   if (F->schur_status == MAT_FACTOR_SCHUR_INVERTED) PetscFunctionReturn(PETSC_SUCCESS);
10127:   PetscCall(MatFactorFactorizeSchurComplement(F));
10128:   PetscCall(MatFactorInvertSchurComplement_Private(F));
10129:   F->schur_status = MAT_FACTOR_SCHUR_INVERTED;
10130:   PetscFunctionReturn(PETSC_SUCCESS);
10131: }

10133: /*@
10134:   MatFactorFactorizeSchurComplement - Factorize the Schur complement matrix computed during the factorization step

10136:   Logically Collective

10138:   Input Parameter:
10139: . F - the factored matrix obtained by calling `MatGetFactor()`

10141:   Level: advanced

10143:   Note:
10144:   Must be called after `MatFactorSetSchurIS()`

10146: .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatFactorSetSchurIS()`, `MatFactorInvertSchurComplement()`
10147: @*/
10148: PetscErrorCode MatFactorFactorizeSchurComplement(Mat F)
10149: {
10150:   MatFactorInfo info;

10152:   PetscFunctionBegin;
10155:   if (F->schur_status == MAT_FACTOR_SCHUR_INVERTED || F->schur_status == MAT_FACTOR_SCHUR_FACTORED) PetscFunctionReturn(PETSC_SUCCESS);
10156:   PetscCall(PetscLogEventBegin(MAT_FactorFactS, F, 0, 0, 0));
10157:   PetscCall(PetscMemzero(&info, sizeof(MatFactorInfo)));
10158:   if (F->factortype == MAT_FACTOR_CHOLESKY) { /* LDL^t regarded as Cholesky */
10159:     PetscCall(MatCholeskyFactor(F->schur, NULL, &info));
10160:   } else {
10161:     PetscCall(MatLUFactor(F->schur, NULL, NULL, &info));
10162:   }
10163:   PetscCall(PetscLogEventEnd(MAT_FactorFactS, F, 0, 0, 0));
10164:   F->schur_status = MAT_FACTOR_SCHUR_FACTORED;
10165:   PetscFunctionReturn(PETSC_SUCCESS);
10166: }

10168: /*@
10169:   MatPtAP - Creates the matrix product $C = P^T * A * P$

10171:   Neighbor-wise Collective

10173:   Input Parameters:
10174: + A     - the matrix
10175: . P     - the projection matrix
10176: . scall - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`
10177: - 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
10178:           if the result is a dense matrix this is irrelevant

10180:   Output Parameter:
10181: . C - the product matrix

10183:   Level: intermediate

10185:   Notes:
10186:   `C` will be created and must be destroyed by the user with `MatDestroy()`.

10188:   This is a convenience routine that wraps the use of the `MatProductCreate()` with a `MatProductType` of `MATPRODUCT_PtAP`
10189:   functionality into a single function call. For more involved matrix-matrix operations see `MatProductCreate()`.

10191:   The deprecated `PETSC_DEFAULT` in `fill` also means use the current value

10193:   Developer Note:
10194:   For matrix types without special implementation the function fallbacks to `MatMatMult()` followed by `MatTransposeMatMult()`.

10196: .seealso: [](ch_matrices), `Mat`, `MatProductCreate()`, `MatMatMult()`, `MatRARt()`
10197: @*/
10198: PetscErrorCode MatPtAP(Mat A, Mat P, MatReuse scall, PetscReal fill, Mat *C)
10199: {
10200:   PetscFunctionBegin;
10201:   if (scall == MAT_REUSE_MATRIX) MatCheckProduct(*C, 5);
10202:   PetscCheck(scall != MAT_INPLACE_MATRIX, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "Inplace product not supported");

10204:   if (scall == MAT_INITIAL_MATRIX) {
10205:     PetscCall(MatProductCreate(A, P, NULL, C));
10206:     PetscCall(MatProductSetType(*C, MATPRODUCT_PtAP));
10207:     PetscCall(MatProductSetAlgorithm(*C, "default"));
10208:     PetscCall(MatProductSetFill(*C, fill));

10210:     (*C)->product->api_user = PETSC_TRUE;
10211:     PetscCall(MatProductSetFromOptions(*C));
10212:     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);
10213:     PetscCall(MatProductSymbolic(*C));
10214:   } else { /* scall == MAT_REUSE_MATRIX */
10215:     PetscCall(MatProductReplaceMats(A, P, NULL, *C));
10216:   }

10218:   PetscCall(MatProductNumeric(*C));
10219:   if (A->symmetric == PETSC_BOOL3_TRUE) {
10220:     PetscCall(MatSetOption(*C, MAT_SYMMETRIC, PETSC_TRUE));
10221:     (*C)->spd = A->spd;
10222:   }
10223:   PetscFunctionReturn(PETSC_SUCCESS);
10224: }

10226: /*@
10227:   MatRARt - Creates the matrix product $C = R * A * R^T$

10229:   Neighbor-wise Collective

10231:   Input Parameters:
10232: + A     - the matrix
10233: . R     - the projection matrix
10234: . scall - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`
10235: - fill  - expected fill as ratio of nnz(C)/nnz(A), use `PETSC_DETERMINE` or `PETSC_CURRENT` if you do not have a good estimate
10236:           if the result is a dense matrix this is irrelevant

10238:   Output Parameter:
10239: . C - the product matrix

10241:   Level: intermediate

10243:   Notes:
10244:   `C` will be created and must be destroyed by the user with `MatDestroy()`.

10246:   This is a convenience routine that wraps the use of the `MatProductCreate()` with a `MatProductType` of `MATPRODUCT_RARt`
10247:   functionality into a single function call. For more involved matrix-matrix operations see `MatProductCreate()`.

10249:   This routine is currently only implemented for pairs of `MATAIJ` matrices and classes
10250:   which inherit from `MATAIJ`. Due to PETSc sparse matrix block row distribution among processes,
10251:   the parallel `MatRARt()` is implemented computing the explicit transpose of `R`, which can be very expensive.
10252:   We recommend using `MatPtAP()` when possible.

10254:   The deprecated `PETSC_DEFAULT` in `fill` also means use the current value

10256: .seealso: [](ch_matrices), `Mat`, `MatProductCreate()`, `MatMatMult()`, `MatPtAP()`
10257: @*/
10258: PetscErrorCode MatRARt(Mat A, Mat R, MatReuse scall, PetscReal fill, Mat *C)
10259: {
10260:   PetscFunctionBegin;
10261:   if (scall == MAT_REUSE_MATRIX) MatCheckProduct(*C, 5);
10262:   PetscCheck(scall != MAT_INPLACE_MATRIX, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "Inplace product not supported");

10264:   if (scall == MAT_INITIAL_MATRIX) {
10265:     PetscCall(MatProductCreate(A, R, NULL, C));
10266:     PetscCall(MatProductSetType(*C, MATPRODUCT_RARt));
10267:     PetscCall(MatProductSetAlgorithm(*C, "default"));
10268:     PetscCall(MatProductSetFill(*C, fill));

10270:     (*C)->product->api_user = PETSC_TRUE;
10271:     PetscCall(MatProductSetFromOptions(*C));
10272:     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);
10273:     PetscCall(MatProductSymbolic(*C));
10274:   } else { /* scall == MAT_REUSE_MATRIX */
10275:     PetscCall(MatProductReplaceMats(A, R, NULL, *C));
10276:   }

10278:   PetscCall(MatProductNumeric(*C));
10279:   if (A->symmetric == PETSC_BOOL3_TRUE) PetscCall(MatSetOption(*C, MAT_SYMMETRIC, PETSC_TRUE));
10280:   PetscFunctionReturn(PETSC_SUCCESS);
10281: }

10283: static PetscErrorCode MatProduct_Private(Mat A, Mat B, MatReuse scall, PetscReal fill, MatProductType ptype, Mat *C)
10284: {
10285:   PetscBool flg = PETSC_TRUE;

10287:   PetscFunctionBegin;
10288:   PetscCheck(scall != MAT_INPLACE_MATRIX, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "MAT_INPLACE_MATRIX product not supported");
10289:   if (scall == MAT_INITIAL_MATRIX) {
10290:     PetscCall(PetscInfo(A, "Calling MatProduct API with MAT_INITIAL_MATRIX and product type %s\n", MatProductTypes[ptype]));
10291:     PetscCall(MatProductCreate(A, B, NULL, C));
10292:     PetscCall(MatProductSetAlgorithm(*C, MATPRODUCTALGORITHMDEFAULT));
10293:     PetscCall(MatProductSetFill(*C, fill));
10294:   } else { /* scall == MAT_REUSE_MATRIX */
10295:     Mat_Product *product = (*C)->product;

10297:     PetscCall(PetscObjectBaseTypeCompareAny((PetscObject)*C, &flg, MATSEQDENSE, MATMPIDENSE, ""));
10298:     if (flg && product && product->type != ptype) {
10299:       PetscCall(MatProductClear(*C));
10300:       product = NULL;
10301:     }
10302:     PetscCall(PetscInfo(A, "Calling MatProduct API with MAT_REUSE_MATRIX %s product present and product type %s\n", product ? "with" : "without", MatProductTypes[ptype]));
10303:     if (!product) { /* user provide the dense matrix *C without calling MatProductCreate() or reusing it from previous calls */
10304:       PetscCheck(flg, PetscObjectComm((PetscObject)*C), PETSC_ERR_SUP, "Call MatProductCreate() first");
10305:       PetscCall(MatProductCreate_Private(A, B, NULL, *C));
10306:       product        = (*C)->product;
10307:       product->fill  = fill;
10308:       product->clear = PETSC_TRUE;
10309:     } else { /* user may change input matrices A or B when MAT_REUSE_MATRIX */
10310:       flg = PETSC_FALSE;
10311:       PetscCall(MatProductReplaceMats(A, B, NULL, *C));
10312:     }
10313:   }
10314:   if (flg) {
10315:     (*C)->product->api_user = PETSC_TRUE;
10316:     PetscCall(MatProductSetType(*C, ptype));
10317:     PetscCall(MatProductSetFromOptions(*C));
10318:     PetscCall(MatProductSymbolic(*C));
10319:   }
10320:   PetscCall(MatProductNumeric(*C));
10321:   PetscFunctionReturn(PETSC_SUCCESS);
10322: }

10324: /*@
10325:   MatMatMult - Performs matrix-matrix multiplication $ C=A*B $.

10327:   Neighbor-wise Collective

10329:   Input Parameters:
10330: + A     - the left matrix
10331: . B     - the right matrix
10332: . scall - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`
10333: - 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
10334:           if the result is a dense matrix this is irrelevant

10336:   Output Parameter:
10337: . C - the product matrix

10339:   Notes:
10340:   Unless scall is `MAT_REUSE_MATRIX` C will be created.

10342:   `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
10343:   call to this function with `MAT_INITIAL_MATRIX`.

10345:   To determine the correct fill value, run with `-info` and search for the string "Fill ratio" to see the value actually needed.

10347:   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`,
10348:   rather than first having `MatMatMult()` create it for you. You can NEVER do this if the matrix `C` is sparse.

10350:   The deprecated `PETSC_DEFAULT` in `fill` also means use the current value

10352:   This is a convenience routine that wraps the use of the `MatProductCreate()` with a `MatProductType` of `MATPRODUCT_AB`
10353:   functionality into a single function call. For more involved matrix-matrix operations see `MatProductCreate()`.

10355:   Example of Usage:
10356: .vb
10357:      MatProductCreate(A,B,NULL,&C);
10358:      MatProductSetType(C,MATPRODUCT_AB);
10359:      MatProductSymbolic(C);
10360:      MatProductNumeric(C); // compute C=A * B
10361:      MatProductReplaceMats(A1,B1,NULL,C); // compute C=A1 * B1
10362:      MatProductNumeric(C);
10363:      MatProductReplaceMats(A2,NULL,NULL,C); // compute C=A2 * B1
10364:      MatProductNumeric(C);
10365: .ve

10367:   Level: intermediate

10369: .seealso: [](ch_matrices), `Mat`, `MatProductType`, `MATPRODUCT_AB`, `MatTransposeMatMult()`, `MatMatTransposeMult()`, `MatPtAP()`, `MatProductCreate()`, `MatProductSymbolic()`, `MatProductReplaceMats()`, `MatProductNumeric()`
10370: @*/
10371: PetscErrorCode MatMatMult(Mat A, Mat B, MatReuse scall, PetscReal fill, Mat *C)
10372: {
10373:   PetscFunctionBegin;
10374:   PetscCall(MatProduct_Private(A, B, scall, fill, MATPRODUCT_AB, C));
10375:   PetscFunctionReturn(PETSC_SUCCESS);
10376: }

10378: /*@
10379:   MatMatTransposeMult - Performs matrix-matrix multiplication $C = A*B^T$.

10381:   Neighbor-wise Collective

10383:   Input Parameters:
10384: + A     - the left matrix
10385: . B     - the right matrix
10386: . scall - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`
10387: - fill  - expected fill as ratio of nnz(C)/(nnz(A) + nnz(B)), use `PETSC_DETERMINE` or `PETSC_CURRENT` if not known

10389:   Output Parameter:
10390: . C - the product matrix

10392:   Options Database Key:
10393: . -matmattransmult_mpidense_mpidense_via {allgatherv,cyclic} - Choose between algorithms for `MATMPIDENSE` matrices: the
10394:               first redundantly copies the transposed `B` matrix on each process and requires O(log P) communication complexity;
10395:               the second never stores more than one portion of the `B` matrix at a time but requires O(P) communication complexity.

10397:   Level: intermediate

10399:   Notes:
10400:   C will be created if `MAT_INITIAL_MATRIX` and must be destroyed by the user with `MatDestroy()`.

10402:   `MAT_REUSE_MATRIX` can only be used if the matrices A and B have the same nonzero pattern as in the previous call

10404:   To determine the correct fill value, run with -info and search for the string "Fill ratio" to see the value
10405:   actually needed.

10407:   This routine is currently only implemented for pairs of `MATSEQAIJ` matrices, for the `MATSEQDENSE` class,
10408:   and for pairs of `MATMPIDENSE` matrices.

10410:   This is a convenience routine that wraps the use of the `MatProductCreate()` with a `MatProductType` of `MATPRODUCT_ABt`
10411:   functionality into a single function call. For more involved matrix-matrix operations see `MatProductCreate()`.

10413:   The deprecated `PETSC_DEFAULT` in `fill` also means use the current value

10415: .seealso: [](ch_matrices), `Mat`, `MatProductCreate()`, `MATPRODUCT_ABt`, `MatMatMult()`, `MatTransposeMatMult()`, `MatPtAP()`, `MatProductAlgorithm`, `MatProductType`
10416: @*/
10417: PetscErrorCode MatMatTransposeMult(Mat A, Mat B, MatReuse scall, PetscReal fill, Mat *C)
10418: {
10419:   PetscFunctionBegin;
10420:   PetscCall(MatProduct_Private(A, B, scall, fill, MATPRODUCT_ABt, C));
10421:   if (A == B) PetscCall(MatSetOption(*C, MAT_SYMMETRIC, PETSC_TRUE));
10422:   PetscFunctionReturn(PETSC_SUCCESS);
10423: }

10425: /*@
10426:   MatTransposeMatMult - Performs matrix-matrix multiplication $C = A^T*B$.

10428:   Neighbor-wise Collective

10430:   Input Parameters:
10431: + A     - the left matrix
10432: . B     - the right matrix
10433: . scall - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`
10434: - fill  - expected fill as ratio of nnz(C)/(nnz(A) + nnz(B)), use `PETSC_DETERMINE` or `PETSC_CURRENT` if not known

10436:   Output Parameter:
10437: . C - the product matrix

10439:   Level: intermediate

10441:   Notes:
10442:   `C` will be created if `MAT_INITIAL_MATRIX` and must be destroyed by the user with `MatDestroy()`.

10444:   `MAT_REUSE_MATRIX` can only be used if `A` and `B` have the same nonzero pattern as in the previous call.

10446:   This is a convenience routine that wraps the use of `MatProductCreate()` with a `MatProductType` of `MATPRODUCT_AtB`
10447:   functionality into a single function call. For more involved matrix-matrix operations see `MatProductCreate()`.

10449:   To determine the correct fill value, run with -info and search for the string "Fill ratio" to see the value
10450:   actually needed.

10452:   This routine is currently implemented for pairs of `MATAIJ` matrices and pairs of `MATSEQDENSE` matrices and classes
10453:   which inherit from `MATSEQAIJ`.  `C` will be of the same type as the input matrices.

10455:   The deprecated `PETSC_DEFAULT` in `fill` also means use the current value

10457: .seealso: [](ch_matrices), `Mat`, `MatProductCreate()`, `MATPRODUCT_AtB`, `MatMatMult()`, `MatMatTransposeMult()`, `MatPtAP()`
10458: @*/
10459: PetscErrorCode MatTransposeMatMult(Mat A, Mat B, MatReuse scall, PetscReal fill, Mat *C)
10460: {
10461:   PetscFunctionBegin;
10462:   PetscCall(MatProduct_Private(A, B, scall, fill, MATPRODUCT_AtB, C));
10463:   PetscFunctionReturn(PETSC_SUCCESS);
10464: }

10466: /*@
10467:   MatMatMatMult - Performs matrix-matrix-matrix multiplication D=A*B*C.

10469:   Neighbor-wise Collective

10471:   Input Parameters:
10472: + A     - the left matrix
10473: . B     - the middle matrix
10474: . C     - the right matrix
10475: . scall - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`
10476: - 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
10477:           if the result is a dense matrix this is irrelevant

10479:   Output Parameter:
10480: . D - the product matrix

10482:   Level: intermediate

10484:   Notes:
10485:   Unless `scall` is `MAT_REUSE_MATRIX` `D` will be created.

10487:   `MAT_REUSE_MATRIX` can only be used if the matrices `A`, `B`, and `C` have the same nonzero pattern as in the previous call

10489:   This is a convenience routine that wraps the use of the `MatProductCreate()` with a `MatProductType` of `MATPRODUCT_ABC`
10490:   functionality into a single function call. For more involved matrix-matrix operations see `MatProductCreate()`.

10492:   To determine the correct fill value, run with `-info` and search for the string "Fill ratio" to see the value
10493:   actually needed.

10495:   If you have many matrices with the same non-zero structure to multiply, you
10496:   should use `MAT_REUSE_MATRIX` in all calls but the first

10498:   The deprecated `PETSC_DEFAULT` in `fill` also means use the current value

10500: .seealso: [](ch_matrices), `Mat`, `MatProductCreate()`, `MATPRODUCT_ABC`, `MatMatMult`, `MatPtAP()`, `MatMatTransposeMult()`, `MatTransposeMatMult()`
10501: @*/
10502: PetscErrorCode MatMatMatMult(Mat A, Mat B, Mat C, MatReuse scall, PetscReal fill, Mat *D)
10503: {
10504:   PetscFunctionBegin;
10505:   if (scall == MAT_REUSE_MATRIX) MatCheckProduct(*D, 6);
10506:   PetscCheck(scall != MAT_INPLACE_MATRIX, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "Inplace product not supported");

10508:   if (scall == MAT_INITIAL_MATRIX) {
10509:     PetscCall(MatProductCreate(A, B, C, D));
10510:     PetscCall(MatProductSetType(*D, MATPRODUCT_ABC));
10511:     PetscCall(MatProductSetAlgorithm(*D, "default"));
10512:     PetscCall(MatProductSetFill(*D, fill));

10514:     (*D)->product->api_user = PETSC_TRUE;
10515:     PetscCall(MatProductSetFromOptions(*D));
10516:     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,
10517:                ((PetscObject)C)->type_name);
10518:     PetscCall(MatProductSymbolic(*D));
10519:   } else { /* user may change input matrices when REUSE */
10520:     PetscCall(MatProductReplaceMats(A, B, C, *D));
10521:   }
10522:   PetscCall(MatProductNumeric(*D));
10523:   PetscFunctionReturn(PETSC_SUCCESS);
10524: }

10526: /*@
10527:   MatCreateRedundantMatrix - Create redundant matrices and put them into processors of subcommunicators.

10529:   Collective

10531:   Input Parameters:
10532: + mat      - the matrix
10533: . nsubcomm - the number of subcommunicators (= number of redundant parallel or sequential matrices)
10534: . subcomm  - MPI communicator split from the communicator where mat resides in (or `MPI_COMM_NULL` if nsubcomm is used)
10535: - reuse    - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`

10537:   Output Parameter:
10538: . matredundant - redundant matrix

10540:   Level: advanced

10542:   Notes:
10543:   `MAT_REUSE_MATRIX` can only be used when the nonzero structure of the
10544:   original matrix has not changed from that last call to `MatCreateRedundantMatrix()`.

10546:   This routine creates the duplicated matrices in the subcommunicators; you should NOT create them before
10547:   calling it.

10549:   `PetscSubcommCreate()` can be used to manage the creation of the subcomm but need not be.

10551: .seealso: [](ch_matrices), `Mat`, `MatDestroy()`, `PetscSubcommCreate()`, `PetscSubcomm`
10552: @*/
10553: PetscErrorCode MatCreateRedundantMatrix(Mat mat, PetscInt nsubcomm, MPI_Comm subcomm, MatReuse reuse, Mat *matredundant)
10554: {
10555:   MPI_Comm       comm;
10556:   PetscMPIInt    size;
10557:   PetscInt       mloc_sub, nloc_sub, rstart, rend, M = mat->rmap->N, N = mat->cmap->N, bs = mat->rmap->bs;
10558:   Mat_Redundant *redund     = NULL;
10559:   PetscSubcomm   psubcomm   = NULL;
10560:   MPI_Comm       subcomm_in = subcomm;
10561:   Mat           *matseq;
10562:   IS             isrow, iscol;
10563:   PetscBool      newsubcomm = PETSC_FALSE;

10565:   PetscFunctionBegin;
10567:   if (nsubcomm && reuse == MAT_REUSE_MATRIX) {
10568:     PetscAssertPointer(*matredundant, 5);
10570:   }

10572:   PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)mat), &size));
10573:   if (size == 1 || nsubcomm == 1) {
10574:     if (reuse == MAT_INITIAL_MATRIX) {
10575:       PetscCall(MatDuplicate(mat, MAT_COPY_VALUES, matredundant));
10576:     } else {
10577:       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");
10578:       PetscCall(MatCopy(mat, *matredundant, SAME_NONZERO_PATTERN));
10579:     }
10580:     PetscFunctionReturn(PETSC_SUCCESS);
10581:   }

10583:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
10584:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
10585:   MatCheckPreallocated(mat, 1);

10587:   PetscCall(PetscLogEventBegin(MAT_RedundantMat, mat, 0, 0, 0));
10588:   if (subcomm_in == MPI_COMM_NULL && reuse == MAT_INITIAL_MATRIX) { /* get subcomm if user does not provide subcomm */
10589:     /* create psubcomm, then get subcomm */
10590:     PetscCall(PetscObjectGetComm((PetscObject)mat, &comm));
10591:     PetscCallMPI(MPI_Comm_size(comm, &size));
10592:     PetscCheck(nsubcomm >= 1 && nsubcomm <= size, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "nsubcomm must between 1 and %d", size);

10594:     PetscCall(PetscSubcommCreate(comm, &psubcomm));
10595:     PetscCall(PetscSubcommSetNumber(psubcomm, nsubcomm));
10596:     PetscCall(PetscSubcommSetType(psubcomm, PETSC_SUBCOMM_CONTIGUOUS));
10597:     PetscCall(PetscSubcommSetFromOptions(psubcomm));
10598:     PetscCall(PetscCommDuplicate(PetscSubcommChild(psubcomm), &subcomm, NULL));
10599:     newsubcomm = PETSC_TRUE;
10600:     PetscCall(PetscSubcommDestroy(&psubcomm));
10601:   }

10603:   /* get isrow, iscol and a local sequential matrix matseq[0] */
10604:   if (reuse == MAT_INITIAL_MATRIX) {
10605:     mloc_sub = PETSC_DECIDE;
10606:     nloc_sub = PETSC_DECIDE;
10607:     if (bs < 1) {
10608:       PetscCall(PetscSplitOwnership(subcomm, &mloc_sub, &M));
10609:       PetscCall(PetscSplitOwnership(subcomm, &nloc_sub, &N));
10610:     } else {
10611:       PetscCall(PetscSplitOwnershipBlock(subcomm, bs, &mloc_sub, &M));
10612:       PetscCall(PetscSplitOwnershipBlock(subcomm, bs, &nloc_sub, &N));
10613:     }
10614:     PetscCallMPI(MPI_Scan(&mloc_sub, &rend, 1, MPIU_INT, MPI_SUM, subcomm));
10615:     rstart = rend - mloc_sub;
10616:     PetscCall(ISCreateStride(PETSC_COMM_SELF, mloc_sub, rstart, 1, &isrow));
10617:     PetscCall(ISCreateStride(PETSC_COMM_SELF, N, 0, 1, &iscol));
10618:     PetscCall(ISSetIdentity(iscol));
10619:   } else { /* reuse == MAT_REUSE_MATRIX */
10620:     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");
10621:     /* retrieve subcomm */
10622:     PetscCall(PetscObjectGetComm((PetscObject)*matredundant, &subcomm));
10623:     redund = (*matredundant)->redundant;
10624:     isrow  = redund->isrow;
10625:     iscol  = redund->iscol;
10626:     matseq = redund->matseq;
10627:   }
10628:   PetscCall(MatCreateSubMatrices(mat, 1, &isrow, &iscol, reuse, &matseq));

10630:   /* get matredundant over subcomm */
10631:   if (reuse == MAT_INITIAL_MATRIX) {
10632:     PetscCall(MatCreateMPIMatConcatenateSeqMat(subcomm, matseq[0], nloc_sub, reuse, matredundant));

10634:     /* create a supporting struct and attach it to C for reuse */
10635:     PetscCall(PetscNew(&redund));
10636:     (*matredundant)->redundant = redund;
10637:     redund->isrow              = isrow;
10638:     redund->iscol              = iscol;
10639:     redund->matseq             = matseq;
10640:     if (newsubcomm) {
10641:       redund->subcomm = subcomm;
10642:     } else {
10643:       redund->subcomm = MPI_COMM_NULL;
10644:     }
10645:   } else {
10646:     PetscCall(MatCreateMPIMatConcatenateSeqMat(subcomm, matseq[0], PETSC_DECIDE, reuse, matredundant));
10647:   }
10648: #if defined(PETSC_HAVE_VIENNACL) || defined(PETSC_HAVE_CUDA) || defined(PETSC_HAVE_HIP)
10649:   if (matseq[0]->boundtocpu && matseq[0]->bindingpropagates) {
10650:     PetscCall(MatBindToCPU(*matredundant, PETSC_TRUE));
10651:     PetscCall(MatSetBindingPropagates(*matredundant, PETSC_TRUE));
10652:   }
10653: #endif
10654:   PetscCall(PetscLogEventEnd(MAT_RedundantMat, mat, 0, 0, 0));
10655:   PetscFunctionReturn(PETSC_SUCCESS);
10656: }

10658: /*@C
10659:   MatGetMultiProcBlock - Create multiple 'parallel submatrices' from
10660:   a given `Mat`. Each submatrix can span multiple procs.

10662:   Collective

10664:   Input Parameters:
10665: + mat     - the matrix
10666: . subComm - the sub communicator obtained as if by `MPI_Comm_split(PetscObjectComm((PetscObject)mat))`
10667: - scall   - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`

10669:   Output Parameter:
10670: . subMat - parallel sub-matrices each spanning a given `subcomm`

10672:   Level: advanced

10674:   Notes:
10675:   The submatrix partition across processors is dictated by `subComm` a
10676:   communicator obtained by `MPI_comm_split()` or via `PetscSubcommCreate()`. The `subComm`
10677:   is not restricted to be grouped with consecutive original MPI processes.

10679:   Due the `MPI_Comm_split()` usage, the parallel layout of the submatrices
10680:   map directly to the layout of the original matrix [wrt the local
10681:   row,col partitioning]. So the original 'DiagonalMat' naturally maps
10682:   into the 'DiagonalMat' of the `subMat`, hence it is used directly from
10683:   the `subMat`. However the offDiagMat looses some columns - and this is
10684:   reconstructed with `MatSetValues()`

10686:   This is used by `PCBJACOBI` when a single block spans multiple MPI processes.

10688: .seealso: [](ch_matrices), `Mat`, `MatCreateRedundantMatrix()`, `MatCreateSubMatrices()`, `PCBJACOBI`
10689: @*/
10690: PetscErrorCode MatGetMultiProcBlock(Mat mat, MPI_Comm subComm, MatReuse scall, Mat *subMat)
10691: {
10692:   PetscMPIInt commsize, subCommSize;

10694:   PetscFunctionBegin;
10695:   PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)mat), &commsize));
10696:   PetscCallMPI(MPI_Comm_size(subComm, &subCommSize));
10697:   PetscCheck(subCommSize <= commsize, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_OUTOFRANGE, "CommSize %d < SubCommZize %d", commsize, subCommSize);

10699:   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");
10700:   PetscCall(PetscLogEventBegin(MAT_GetMultiProcBlock, mat, 0, 0, 0));
10701:   PetscUseTypeMethod(mat, getmultiprocblock, subComm, scall, subMat);
10702:   PetscCall(PetscLogEventEnd(MAT_GetMultiProcBlock, mat, 0, 0, 0));
10703:   PetscFunctionReturn(PETSC_SUCCESS);
10704: }

10706: /*@
10707:   MatGetLocalSubMatrix - Gets a reference to a submatrix specified in local numbering

10709:   Not Collective

10711:   Input Parameters:
10712: + mat   - matrix to extract local submatrix from
10713: . isrow - local row indices for submatrix
10714: - iscol - local column indices for submatrix

10716:   Output Parameter:
10717: . submat - the submatrix

10719:   Level: intermediate

10721:   Notes:
10722:   `submat` should be disposed of with `MatRestoreLocalSubMatrix()`.

10724:   Depending on the format of `mat`, the returned `submat` may not implement `MatMult()`.  Its communicator may be
10725:   the same as `mat`, it may be `PETSC_COMM_SELF`, or some other sub-communictor of `mat`'s.

10727:   `submat` always implements `MatSetValuesLocal()`.  If `isrow` and `iscol` have the same block size, then
10728:   `MatSetValuesBlockedLocal()` will also be implemented.

10730:   `mat` must have had a `ISLocalToGlobalMapping` provided to it with `MatSetLocalToGlobalMapping()`.
10731:   Matrices obtained with `DMCreateMatrix()` generally already have the local to global mapping provided.

10733: .seealso: [](ch_matrices), `Mat`, `MatRestoreLocalSubMatrix()`, `MatCreateLocalRef()`, `MatSetLocalToGlobalMapping()`
10734: @*/
10735: PetscErrorCode MatGetLocalSubMatrix(Mat mat, IS isrow, IS iscol, Mat *submat)
10736: {
10737:   PetscFunctionBegin;
10741:   PetscCheckSameComm(isrow, 2, iscol, 3);
10742:   PetscAssertPointer(submat, 4);
10743:   PetscCheck(mat->rmap->mapping, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Matrix must have local to global mapping provided before this call");

10745:   if (mat->ops->getlocalsubmatrix) {
10746:     PetscUseTypeMethod(mat, getlocalsubmatrix, isrow, iscol, submat);
10747:   } else {
10748:     PetscCall(MatCreateLocalRef(mat, isrow, iscol, submat));
10749:   }
10750:   (*submat)->assembled = mat->assembled;
10751:   PetscFunctionReturn(PETSC_SUCCESS);
10752: }

10754: /*@
10755:   MatRestoreLocalSubMatrix - Restores a reference to a submatrix specified in local numbering obtained with `MatGetLocalSubMatrix()`

10757:   Not Collective

10759:   Input Parameters:
10760: + mat    - matrix to extract local submatrix from
10761: . isrow  - local row indices for submatrix
10762: . iscol  - local column indices for submatrix
10763: - submat - the submatrix

10765:   Level: intermediate

10767: .seealso: [](ch_matrices), `Mat`, `MatGetLocalSubMatrix()`
10768: @*/
10769: PetscErrorCode MatRestoreLocalSubMatrix(Mat mat, IS isrow, IS iscol, Mat *submat)
10770: {
10771:   PetscFunctionBegin;
10775:   PetscCheckSameComm(isrow, 2, iscol, 3);
10776:   PetscAssertPointer(submat, 4);

10779:   if (mat->ops->restorelocalsubmatrix) {
10780:     PetscUseTypeMethod(mat, restorelocalsubmatrix, isrow, iscol, submat);
10781:   } else {
10782:     PetscCall(MatDestroy(submat));
10783:   }
10784:   *submat = NULL;
10785:   PetscFunctionReturn(PETSC_SUCCESS);
10786: }

10788: /*@
10789:   MatFindZeroDiagonals - Finds all the rows of a matrix that have zero or no diagonal entry in the matrix

10791:   Collective

10793:   Input Parameter:
10794: . mat - the matrix

10796:   Output Parameter:
10797: . is - if any rows have zero diagonals this contains the list of them

10799:   Level: developer

10801: .seealso: [](ch_matrices), `Mat`, `MatMultTranspose()`, `MatMultAdd()`, `MatMultTransposeAdd()`
10802: @*/
10803: PetscErrorCode MatFindZeroDiagonals(Mat mat, IS *is)
10804: {
10805:   PetscFunctionBegin;
10808:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
10809:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");

10811:   if (!mat->ops->findzerodiagonals) {
10812:     Vec                diag;
10813:     const PetscScalar *a;
10814:     PetscInt          *rows;
10815:     PetscInt           rStart, rEnd, r, nrow = 0;

10817:     PetscCall(MatCreateVecs(mat, &diag, NULL));
10818:     PetscCall(MatGetDiagonal(mat, diag));
10819:     PetscCall(MatGetOwnershipRange(mat, &rStart, &rEnd));
10820:     PetscCall(VecGetArrayRead(diag, &a));
10821:     for (r = 0; r < rEnd - rStart; ++r)
10822:       if (a[r] == 0.0) ++nrow;
10823:     PetscCall(PetscMalloc1(nrow, &rows));
10824:     nrow = 0;
10825:     for (r = 0; r < rEnd - rStart; ++r)
10826:       if (a[r] == 0.0) rows[nrow++] = r + rStart;
10827:     PetscCall(VecRestoreArrayRead(diag, &a));
10828:     PetscCall(VecDestroy(&diag));
10829:     PetscCall(ISCreateGeneral(PetscObjectComm((PetscObject)mat), nrow, rows, PETSC_OWN_POINTER, is));
10830:   } else {
10831:     PetscUseTypeMethod(mat, findzerodiagonals, is);
10832:   }
10833:   PetscFunctionReturn(PETSC_SUCCESS);
10834: }

10836: /*@
10837:   MatFindOffBlockDiagonalEntries - Finds all the rows of a matrix that have entries outside of the main diagonal block (defined by the matrix block size)

10839:   Collective

10841:   Input Parameter:
10842: . mat - the matrix

10844:   Output Parameter:
10845: . is - contains the list of rows with off block diagonal entries

10847:   Level: developer

10849: .seealso: [](ch_matrices), `Mat`, `MatMultTranspose()`, `MatMultAdd()`, `MatMultTransposeAdd()`
10850: @*/
10851: PetscErrorCode MatFindOffBlockDiagonalEntries(Mat mat, IS *is)
10852: {
10853:   PetscFunctionBegin;
10856:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
10857:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");

10859:   PetscUseTypeMethod(mat, findoffblockdiagonalentries, is);
10860:   PetscFunctionReturn(PETSC_SUCCESS);
10861: }

10863: /*@C
10864:   MatInvertBlockDiagonal - Inverts the block diagonal entries.

10866:   Collective; No Fortran Support

10868:   Input Parameter:
10869: . mat - the matrix

10871:   Output Parameter:
10872: . values - the block inverses in column major order (FORTRAN-like)

10874:   Level: advanced

10876:   Notes:
10877:   The size of the blocks is determined by the block size of the matrix.

10879:   The blocks never overlap between two MPI processes, use `MatInvertVariableBlockEnvelope()` for that case

10881:   The blocks all have the same size, use `MatInvertVariableBlockDiagonal()` for variable block size

10883: .seealso: [](ch_matrices), `Mat`, `MatInvertVariableBlockEnvelope()`, `MatInvertBlockDiagonalMat()`
10884: @*/
10885: PetscErrorCode MatInvertBlockDiagonal(Mat mat, const PetscScalar *values[])
10886: {
10887:   PetscFunctionBegin;
10889:   PetscCheck(mat->assembled, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
10890:   PetscCheck(!mat->factortype, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
10891:   PetscUseTypeMethod(mat, invertblockdiagonal, values);
10892:   PetscFunctionReturn(PETSC_SUCCESS);
10893: }

10895: /*@
10896:   MatInvertVariableBlockDiagonal - Inverts the point block diagonal entries.

10898:   Collective; No Fortran Support

10900:   Input Parameters:
10901: + mat     - the matrix
10902: . nblocks - the number of blocks on the process, set with `MatSetVariableBlockSizes()`
10903: - bsizes  - the size of each block on the process, set with `MatSetVariableBlockSizes()`

10905:   Output Parameter:
10906: . values - the block inverses in column major order (FORTRAN-like)

10908:   Level: advanced

10910:   Notes:
10911:   Use `MatInvertBlockDiagonal()` if all blocks have the same size

10913:   The blocks never overlap between two MPI processes, use `MatInvertVariableBlockEnvelope()` for that case

10915: .seealso: [](ch_matrices), `Mat`, `MatInvertBlockDiagonal()`, `MatSetVariableBlockSizes()`, `MatInvertVariableBlockEnvelope()`
10916: @*/
10917: PetscErrorCode MatInvertVariableBlockDiagonal(Mat mat, PetscInt nblocks, const PetscInt bsizes[], PetscScalar values[])
10918: {
10919:   PetscFunctionBegin;
10921:   PetscCheck(mat->assembled, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
10922:   PetscCheck(!mat->factortype, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
10923:   PetscUseTypeMethod(mat, invertvariableblockdiagonal, nblocks, bsizes, values);
10924:   PetscFunctionReturn(PETSC_SUCCESS);
10925: }

10927: /*@
10928:   MatInvertBlockDiagonalMat - set the values of matrix C to be the inverted block diagonal of matrix A

10930:   Collective

10932:   Input Parameters:
10933: + A - the matrix
10934: - C - matrix with inverted block diagonal of `A`.  This matrix should be created and may have its type set.

10936:   Level: advanced

10938:   Note:
10939:   The blocksize of the matrix is used to determine the blocks on the diagonal of `C`

10941: .seealso: [](ch_matrices), `Mat`, `MatInvertBlockDiagonal()`
10942: @*/
10943: PetscErrorCode MatInvertBlockDiagonalMat(Mat A, Mat C)
10944: {
10945:   const PetscScalar *vals;
10946:   PetscInt          *dnnz;
10947:   PetscInt           m, rstart, rend, bs, i, j;

10949:   PetscFunctionBegin;
10950:   PetscCall(MatInvertBlockDiagonal(A, &vals));
10951:   PetscCall(MatGetBlockSize(A, &bs));
10952:   PetscCall(MatGetLocalSize(A, &m, NULL));
10953:   PetscCall(MatSetLayouts(C, A->rmap, A->cmap));
10954:   PetscCall(MatSetBlockSizes(C, A->rmap->bs, A->cmap->bs));
10955:   PetscCall(PetscMalloc1(m / bs, &dnnz));
10956:   for (j = 0; j < m / bs; j++) dnnz[j] = 1;
10957:   PetscCall(MatXAIJSetPreallocation(C, bs, dnnz, NULL, NULL, NULL));
10958:   PetscCall(PetscFree(dnnz));
10959:   PetscCall(MatGetOwnershipRange(C, &rstart, &rend));
10960:   PetscCall(MatSetOption(C, MAT_ROW_ORIENTED, PETSC_FALSE));
10961:   for (i = rstart / bs; i < rend / bs; i++) PetscCall(MatSetValuesBlocked(C, 1, &i, 1, &i, &vals[(i - rstart / bs) * bs * bs], INSERT_VALUES));
10962:   PetscCall(MatSetOption(C, MAT_NO_OFF_PROC_ENTRIES, PETSC_TRUE));
10963:   PetscCall(MatAssemblyBegin(C, MAT_FINAL_ASSEMBLY));
10964:   PetscCall(MatAssemblyEnd(C, MAT_FINAL_ASSEMBLY));
10965:   PetscCall(MatSetOption(C, MAT_NO_OFF_PROC_ENTRIES, PETSC_FALSE));
10966:   PetscCall(MatSetOption(C, MAT_ROW_ORIENTED, PETSC_TRUE));
10967:   PetscFunctionReturn(PETSC_SUCCESS);
10968: }

10970: /*@
10971:   MatTransposeColoringDestroy - Destroys a coloring context for matrix product $C = A*B^T$ that was created
10972:   via `MatTransposeColoringCreate()`.

10974:   Collective

10976:   Input Parameter:
10977: . c - coloring context

10979:   Level: intermediate

10981: .seealso: [](ch_matrices), `Mat`, `MatTransposeColoringCreate()`
10982: @*/
10983: PetscErrorCode MatTransposeColoringDestroy(MatTransposeColoring *c)
10984: {
10985:   MatTransposeColoring matcolor = *c;

10987:   PetscFunctionBegin;
10988:   if (!matcolor) PetscFunctionReturn(PETSC_SUCCESS);
10989:   if (--((PetscObject)matcolor)->refct > 0) {
10990:     matcolor = NULL;
10991:     PetscFunctionReturn(PETSC_SUCCESS);
10992:   }

10994:   PetscCall(PetscFree3(matcolor->ncolumns, matcolor->nrows, matcolor->colorforrow));
10995:   PetscCall(PetscFree(matcolor->rows));
10996:   PetscCall(PetscFree(matcolor->den2sp));
10997:   PetscCall(PetscFree(matcolor->colorforcol));
10998:   PetscCall(PetscFree(matcolor->columns));
10999:   if (matcolor->brows > 0) PetscCall(PetscFree(matcolor->lstart));
11000:   PetscCall(PetscHeaderDestroy(c));
11001:   PetscFunctionReturn(PETSC_SUCCESS);
11002: }

11004: /*@
11005:   MatTransColoringApplySpToDen - Given a symbolic matrix product $C = A*B^T$ for which
11006:   a `MatTransposeColoring` context has been created, computes a dense $B^T$ by applying
11007:   `MatTransposeColoring` to sparse `B`.

11009:   Collective

11011:   Input Parameters:
11012: + coloring - coloring context created with `MatTransposeColoringCreate()`
11013: - B        - sparse matrix

11015:   Output Parameter:
11016: . Btdense - dense matrix $B^T$

11018:   Level: developer

11020:   Note:
11021:   These are used internally for some implementations of `MatRARt()`

11023: .seealso: [](ch_matrices), `Mat`, `MatTransposeColoringCreate()`, `MatTransposeColoringDestroy()`, `MatTransColoringApplyDenToSp()`
11024: @*/
11025: PetscErrorCode MatTransColoringApplySpToDen(MatTransposeColoring coloring, Mat B, Mat Btdense)
11026: {
11027:   PetscFunctionBegin;

11032:   PetscCall((*B->ops->transcoloringapplysptoden)(coloring, B, Btdense));
11033:   PetscFunctionReturn(PETSC_SUCCESS);
11034: }

11036: /*@
11037:   MatTransColoringApplyDenToSp - Given a symbolic matrix product $C_{sp} = A*B^T$ for which
11038:   a `MatTransposeColoring` context has been created and a dense matrix $C_{den} = A*B^T_{dense}$
11039:   in which `B^T_{dens}` is obtained from `MatTransColoringApplySpToDen()`, recover sparse matrix
11040:   $C_{sp}$ from $C_{den}$.

11042:   Collective

11044:   Input Parameters:
11045: + matcoloring - coloring context created with `MatTransposeColoringCreate()`
11046: - Cden        - matrix product of a sparse matrix and a dense matrix Btdense

11048:   Output Parameter:
11049: . Csp - sparse matrix

11051:   Level: developer

11053:   Note:
11054:   These are used internally for some implementations of `MatRARt()`

11056: .seealso: [](ch_matrices), `Mat`, `MatTransposeColoringCreate()`, `MatTransposeColoringDestroy()`, `MatTransColoringApplySpToDen()`
11057: @*/
11058: PetscErrorCode MatTransColoringApplyDenToSp(MatTransposeColoring matcoloring, Mat Cden, Mat Csp)
11059: {
11060:   PetscFunctionBegin;

11065:   PetscCall((*Csp->ops->transcoloringapplydentosp)(matcoloring, Cden, Csp));
11066:   PetscCall(MatAssemblyBegin(Csp, MAT_FINAL_ASSEMBLY));
11067:   PetscCall(MatAssemblyEnd(Csp, MAT_FINAL_ASSEMBLY));
11068:   PetscFunctionReturn(PETSC_SUCCESS);
11069: }

11071: /*@
11072:   MatTransposeColoringCreate - Creates a matrix coloring context for the matrix product $C = A*B^T$.

11074:   Collective

11076:   Input Parameters:
11077: + mat        - the matrix product C
11078: - iscoloring - the coloring of the matrix; usually obtained with `MatColoringCreate()` or `DMCreateColoring()`

11080:   Output Parameter:
11081: . color - the new coloring context

11083:   Level: intermediate

11085: .seealso: [](ch_matrices), `Mat`, `MatTransposeColoringDestroy()`, `MatTransColoringApplySpToDen()`,
11086:           `MatTransColoringApplyDenToSp()`
11087: @*/
11088: PetscErrorCode MatTransposeColoringCreate(Mat mat, ISColoring iscoloring, MatTransposeColoring *color)
11089: {
11090:   MatTransposeColoring c;
11091:   MPI_Comm             comm;

11093:   PetscFunctionBegin;
11094:   PetscAssertPointer(color, 3);

11096:   PetscCall(PetscLogEventBegin(MAT_TransposeColoringCreate, mat, 0, 0, 0));
11097:   PetscCall(PetscObjectGetComm((PetscObject)mat, &comm));
11098:   PetscCall(PetscHeaderCreate(c, MAT_TRANSPOSECOLORING_CLASSID, "MatTransposeColoring", "Matrix product C=A*B^T via coloring", "Mat", comm, MatTransposeColoringDestroy, NULL));
11099:   c->ctype = iscoloring->ctype;
11100:   PetscUseTypeMethod(mat, transposecoloringcreate, iscoloring, c);
11101:   *color = c;
11102:   PetscCall(PetscLogEventEnd(MAT_TransposeColoringCreate, mat, 0, 0, 0));
11103:   PetscFunctionReturn(PETSC_SUCCESS);
11104: }

11106: /*@
11107:   MatGetNonzeroState - Returns a 64-bit integer representing the current state of nonzeros in the matrix. If the
11108:   matrix has had new nonzero locations added to (or removed from) the matrix since the previous call, the value will be larger.

11110:   Not Collective

11112:   Input Parameter:
11113: . mat - the matrix

11115:   Output Parameter:
11116: . state - the current state

11118:   Level: intermediate

11120:   Notes:
11121:   You can only compare states from two different calls to the SAME matrix, you cannot compare calls between
11122:   different matrices

11124:   Use `PetscObjectStateGet()` to check for changes to the numerical values in a matrix

11126:   Use the result of `PetscObjectGetId()` to compare if a previously checked matrix is the same as the current matrix, do not compare object pointers.

11128: .seealso: [](ch_matrices), `Mat`, `PetscObjectStateGet()`, `PetscObjectGetId()`
11129: @*/
11130: PetscErrorCode MatGetNonzeroState(Mat mat, PetscObjectState *state)
11131: {
11132:   PetscFunctionBegin;
11134:   *state = mat->nonzerostate;
11135:   PetscFunctionReturn(PETSC_SUCCESS);
11136: }

11138: /*@
11139:   MatCreateMPIMatConcatenateSeqMat - Creates a single large PETSc matrix by concatenating sequential
11140:   matrices from each processor

11142:   Collective

11144:   Input Parameters:
11145: + comm   - the communicators the parallel matrix will live on
11146: . seqmat - the input sequential matrices
11147: . n      - number of local columns (or `PETSC_DECIDE`)
11148: - reuse  - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`

11150:   Output Parameter:
11151: . mpimat - the parallel matrix generated

11153:   Level: developer

11155:   Note:
11156:   The number of columns of the matrix in EACH processor MUST be the same.

11158: .seealso: [](ch_matrices), `Mat`
11159: @*/
11160: PetscErrorCode MatCreateMPIMatConcatenateSeqMat(MPI_Comm comm, Mat seqmat, PetscInt n, MatReuse reuse, Mat *mpimat)
11161: {
11162:   PetscMPIInt size;

11164:   PetscFunctionBegin;
11165:   PetscCallMPI(MPI_Comm_size(comm, &size));
11166:   if (size == 1) {
11167:     if (reuse == MAT_INITIAL_MATRIX) {
11168:       PetscCall(MatDuplicate(seqmat, MAT_COPY_VALUES, mpimat));
11169:     } else {
11170:       PetscCall(MatCopy(seqmat, *mpimat, SAME_NONZERO_PATTERN));
11171:     }
11172:     PetscFunctionReturn(PETSC_SUCCESS);
11173:   }

11175:   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");

11177:   PetscCall(PetscLogEventBegin(MAT_Merge, seqmat, 0, 0, 0));
11178:   PetscCall((*seqmat->ops->creatempimatconcatenateseqmat)(comm, seqmat, n, reuse, mpimat));
11179:   PetscCall(PetscLogEventEnd(MAT_Merge, seqmat, 0, 0, 0));
11180:   PetscFunctionReturn(PETSC_SUCCESS);
11181: }

11183: /*@
11184:   MatSubdomainsCreateCoalesce - Creates index subdomains by coalescing adjacent MPI processes' ownership ranges.

11186:   Collective

11188:   Input Parameters:
11189: + A - the matrix to create subdomains from
11190: - N - requested number of subdomains

11192:   Output Parameters:
11193: + n   - number of subdomains resulting on this MPI process
11194: - iss - `IS` list with indices of subdomains on this MPI process

11196:   Level: advanced

11198:   Note:
11199:   The number of subdomains must be smaller than the communicator size

11201: .seealso: [](ch_matrices), `Mat`, `IS`
11202: @*/
11203: PetscErrorCode MatSubdomainsCreateCoalesce(Mat A, PetscInt N, PetscInt *n, IS *iss[])
11204: {
11205:   MPI_Comm    comm, subcomm;
11206:   PetscMPIInt size, rank, color;
11207:   PetscInt    rstart, rend, k;

11209:   PetscFunctionBegin;
11210:   PetscCall(PetscObjectGetComm((PetscObject)A, &comm));
11211:   PetscCallMPI(MPI_Comm_size(comm, &size));
11212:   PetscCallMPI(MPI_Comm_rank(comm, &rank));
11213:   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);
11214:   *n    = 1;
11215:   k     = size / N + (size % N > 0); /* There are up to k ranks to a color */
11216:   color = rank / k;
11217:   PetscCallMPI(MPI_Comm_split(comm, color, rank, &subcomm));
11218:   PetscCall(PetscMalloc1(1, iss));
11219:   PetscCall(MatGetOwnershipRange(A, &rstart, &rend));
11220:   PetscCall(ISCreateStride(subcomm, rend - rstart, rstart, 1, iss[0]));
11221:   PetscCallMPI(MPI_Comm_free(&subcomm));
11222:   PetscFunctionReturn(PETSC_SUCCESS);
11223: }

11225: /*@
11226:   MatGalerkin - Constructs the coarse grid problem matrix via Galerkin projection.

11228:   If the interpolation and restriction operators are the same, uses `MatPtAP()`.
11229:   If they are not the same, uses `MatMatMatMult()`.

11231:   Once the coarse grid problem is constructed, correct for interpolation operators
11232:   that are not of full rank, which can legitimately happen in the case of non-nested
11233:   geometric multigrid.

11235:   Input Parameters:
11236: + restrct     - restriction operator
11237: . dA          - fine grid matrix
11238: . interpolate - interpolation operator
11239: . reuse       - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`
11240: - fill        - expected fill, use `PETSC_DETERMINE` or `PETSC_DETERMINE` if you do not have a good estimate

11242:   Output Parameter:
11243: . A - the Galerkin coarse matrix

11245:   Options Database Key:
11246: . -pc_mg_galerkin (both|pmat|mat|none) - for what matrices the Galerkin process should be used

11248:   Level: developer

11250:   Note:
11251:   The deprecated `PETSC_DEFAULT` in `fill` also means use the current value

11253: .seealso: [](ch_matrices), `Mat`, `MatPtAP()`, `MatMatMatMult()`
11254: @*/
11255: PetscErrorCode MatGalerkin(Mat restrct, Mat dA, Mat interpolate, MatReuse reuse, PetscReal fill, Mat *A)
11256: {
11257:   IS  zerorows;
11258:   Vec diag;

11260:   PetscFunctionBegin;
11261:   PetscCheck(reuse != MAT_INPLACE_MATRIX, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "Inplace product not supported");
11262:   /* Construct the coarse grid matrix */
11263:   if (interpolate == restrct) {
11264:     PetscCall(MatPtAP(dA, interpolate, reuse, fill, A));
11265:   } else {
11266:     PetscCall(MatMatMatMult(restrct, dA, interpolate, reuse, fill, A));
11267:   }

11269:   /* If the interpolation matrix is not of full rank, A will have zero rows.
11270:      This can legitimately happen in the case of non-nested geometric multigrid.
11271:      In that event, we set the rows of the matrix to the rows of the identity,
11272:      ignoring the equations (as the RHS will also be zero). */

11274:   PetscCall(MatFindZeroRows(*A, &zerorows));

11276:   if (zerorows != NULL) { /* if there are any zero rows */
11277:     PetscCall(MatCreateVecs(*A, &diag, NULL));
11278:     PetscCall(MatGetDiagonal(*A, diag));
11279:     PetscCall(VecISSet(diag, zerorows, 1.0));
11280:     PetscCall(MatDiagonalSet(*A, diag, INSERT_VALUES));
11281:     PetscCall(VecDestroy(&diag));
11282:     PetscCall(ISDestroy(&zerorows));
11283:   }
11284:   PetscFunctionReturn(PETSC_SUCCESS);
11285: }

11287: /*@C
11288:   MatSetOperation - Allows user to set a matrix operation for any matrix type

11290:   Logically Collective

11292:   Input Parameters:
11293: + mat - the matrix
11294: . op  - the name of the operation
11295: - f   - the function that provides the operation

11297:   Level: developer

11299:   Example Usage:
11300: .vb
11301:   extern PetscErrorCode usermult(Mat, Vec, Vec);

11303:   PetscCall(MatCreateXXX(comm, ..., &A));
11304:   PetscCall(MatSetOperation(A, MATOP_MULT, (PetscErrorCodeFn *)usermult));
11305: .ve

11307:   Notes:
11308:   See the file `include/petscmat.h` for a complete list of matrix
11309:   operations, which all have the form MATOP_<OPERATION>, where
11310:   <OPERATION> is the name (in all capital letters) of the
11311:   user interface routine (e.g., `MatMult()` -> `MATOP_MULT`).

11313:   All user-provided functions (except for `MATOP_DESTROY`) should have the same calling
11314:   sequence as the usual matrix interface routines, since they
11315:   are intended to be accessed via the usual matrix interface
11316:   routines, e.g.,
11317: .vb
11318:   MatMult(Mat, Vec, Vec) -> usermult(Mat, Vec, Vec)
11319: .ve

11321:   In particular each function MUST return `PETSC_SUCCESS` on success and
11322:   nonzero on failure.

11324:   This routine is distinct from `MatShellSetOperation()` in that it can be called on any matrix type.

11326: .seealso: [](ch_matrices), `Mat`, `MatGetOperation()`, `MatCreateShell()`, `MatShellSetContext()`, `MatShellSetOperation()`
11327: @*/
11328: PetscErrorCode MatSetOperation(Mat mat, MatOperation op, PetscErrorCodeFn *f)
11329: {
11330:   PetscFunctionBegin;
11332:   if (op == MATOP_VIEW && !mat->ops->viewnative && f != (PetscErrorCodeFn *)mat->ops->view) mat->ops->viewnative = mat->ops->view;
11333:   (((PetscErrorCodeFn **)mat->ops)[op]) = f;
11334:   PetscFunctionReturn(PETSC_SUCCESS);
11335: }

11337: /*@C
11338:   MatGetOperation - Gets a matrix operation for any matrix type.

11340:   Not Collective

11342:   Input Parameters:
11343: + mat - the matrix
11344: - op  - the name of the operation

11346:   Output Parameter:
11347: . f - the function that provides the operation

11349:   Level: developer

11351:   Example Usage:
11352: .vb
11353:   PetscErrorCode (*usermult)(Mat, Vec, Vec);

11355:   MatGetOperation(A, MATOP_MULT, (PetscErrorCodeFn **)&usermult);
11356: .ve

11358:   Notes:
11359:   See the file `include/petscmat.h` for a complete list of matrix
11360:   operations, which all have the form MATOP_<OPERATION>, where
11361:   <OPERATION> is the name (in all capital letters) of the
11362:   user interface routine (e.g., `MatMult()` -> `MATOP_MULT`).

11364:   This routine is distinct from `MatShellGetOperation()` in that it can be called on any matrix type.

11366: .seealso: [](ch_matrices), `Mat`, `MatSetOperation()`, `MatCreateShell()`, `MatShellGetContext()`, `MatShellGetOperation()`
11367: @*/
11368: PetscErrorCode MatGetOperation(Mat mat, MatOperation op, PetscErrorCodeFn **f)
11369: {
11370:   PetscFunctionBegin;
11372:   *f = (((PetscErrorCodeFn **)mat->ops)[op]);
11373:   PetscFunctionReturn(PETSC_SUCCESS);
11374: }

11376: /*@
11377:   MatHasOperation - Determines whether the given matrix supports the particular operation.

11379:   Not Collective

11381:   Input Parameters:
11382: + mat - the matrix
11383: - op  - the operation, for example, `MATOP_GET_DIAGONAL`

11385:   Output Parameter:
11386: . has - either `PETSC_TRUE` or `PETSC_FALSE`

11388:   Level: advanced

11390:   Note:
11391:   See `MatSetOperation()` for additional discussion on naming convention and usage of `op`.

11393: .seealso: [](ch_matrices), `Mat`, `MatCreateShell()`, `MatGetOperation()`, `MatSetOperation()`
11394: @*/
11395: PetscErrorCode MatHasOperation(Mat mat, MatOperation op, PetscBool *has)
11396: {
11397:   PetscFunctionBegin;
11399:   PetscAssertPointer(has, 3);
11400:   if (mat->ops->hasoperation) {
11401:     PetscUseTypeMethod(mat, hasoperation, op, has);
11402:   } else {
11403:     if (((void **)mat->ops)[op]) *has = PETSC_TRUE;
11404:     else {
11405:       *has = PETSC_FALSE;
11406:       if (op == MATOP_CREATE_SUBMATRIX) {
11407:         PetscMPIInt size;

11409:         PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)mat), &size));
11410:         if (size == 1) PetscCall(MatHasOperation(mat, MATOP_CREATE_SUBMATRICES, has));
11411:       }
11412:     }
11413:   }
11414:   PetscFunctionReturn(PETSC_SUCCESS);
11415: }

11417: /*@
11418:   MatHasCongruentLayouts - Determines whether the rows and columns layouts of the matrix are congruent

11420:   Collective

11422:   Input Parameter:
11423: . mat - the matrix

11425:   Output Parameter:
11426: . cong - either `PETSC_TRUE` or `PETSC_FALSE`

11428:   Level: beginner

11430: .seealso: [](ch_matrices), `Mat`, `MatCreate()`, `MatSetSizes()`, `PetscLayout`
11431: @*/
11432: PetscErrorCode MatHasCongruentLayouts(Mat mat, PetscBool *cong)
11433: {
11434:   PetscFunctionBegin;
11437:   PetscAssertPointer(cong, 2);
11438:   if (!mat->rmap || !mat->cmap) {
11439:     *cong = mat->rmap == mat->cmap ? PETSC_TRUE : PETSC_FALSE;
11440:     PetscFunctionReturn(PETSC_SUCCESS);
11441:   }
11442:   if (mat->congruentlayouts == PETSC_DECIDE) { /* first time we compare rows and cols layouts */
11443:     PetscCall(PetscLayoutSetUp(mat->rmap));
11444:     PetscCall(PetscLayoutSetUp(mat->cmap));
11445:     PetscCall(PetscLayoutCompare(mat->rmap, mat->cmap, cong));
11446:     if (*cong) mat->congruentlayouts = 1;
11447:     else mat->congruentlayouts = 0;
11448:   } else *cong = mat->congruentlayouts ? PETSC_TRUE : PETSC_FALSE;
11449:   PetscFunctionReturn(PETSC_SUCCESS);
11450: }

11452: PetscErrorCode MatSetInf(Mat A)
11453: {
11454:   PetscFunctionBegin;
11455:   PetscUseTypeMethod(A, setinf);
11456:   PetscFunctionReturn(PETSC_SUCCESS);
11457: }

11459: /*@
11460:   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
11461:   and possibly removes small values from the graph structure.

11463:   Collective

11465:   Input Parameters:
11466: + A       - the matrix
11467: . sym     - `PETSC_TRUE` indicates that the graph should be symmetrized
11468: . scale   - `PETSC_TRUE` indicates that the graph edge weights should be symmetrically scaled with the diagonal entry
11469: . filter  - filter value - < 0: does nothing; == 0: removes only 0.0 entries; otherwise: removes entries with abs(entries) <= value
11470: . num_idx - size of `index` array
11471: - index   - array of block indices to use for graph strength of connection weight

11473:   Output Parameter:
11474: . graph - the resulting graph

11476:   Level: advanced

11478: .seealso: [](ch_matrices), `Mat`, `MatCreate()`, `PCGAMG`
11479: @*/
11480: PetscErrorCode MatCreateGraph(Mat A, PetscBool sym, PetscBool scale, PetscReal filter, PetscInt num_idx, PetscInt index[], Mat *graph)
11481: {
11482:   PetscFunctionBegin;
11486:   PetscAssertPointer(graph, 7);
11487:   PetscCall(PetscLogEventBegin(MAT_CreateGraph, A, 0, 0, 0));
11488:   PetscUseTypeMethod(A, creategraph, sym, scale, filter, num_idx, index, graph);
11489:   PetscCall(PetscLogEventEnd(MAT_CreateGraph, A, 0, 0, 0));
11490:   PetscFunctionReturn(PETSC_SUCCESS);
11491: }

11493: /*@
11494:   MatEliminateZeros - eliminate the nondiagonal zero entries in place from the nonzero structure of a sparse `Mat` in place,
11495:   meaning the same memory is used for the matrix, and no new memory is allocated.

11497:   Collective

11499:   Input Parameters:
11500: + A    - the matrix
11501: - 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

11503:   Level: intermediate

11505:   Developer Note:
11506:   The entries in the sparse matrix data structure are shifted to fill in the unneeded locations in the data. Thus the end
11507:   of the arrays in the data structure are unneeded.

11509: .seealso: [](ch_matrices), `Mat`, `MatCreate()`, `MatCreateGraph()`, `MatFilter()`
11510: @*/
11511: PetscErrorCode MatEliminateZeros(Mat A, PetscBool keep)
11512: {
11513:   PetscFunctionBegin;
11515:   PetscUseTypeMethod(A, eliminatezeros, keep);
11516:   PetscFunctionReturn(PETSC_SUCCESS);
11517: }

11519: /*@C
11520:   MatGetCurrentMemType - Get the memory location of the matrix

11522:   Not Collective, but the result will be the same on all MPI processes

11524:   Input Parameter:
11525: . A - the matrix whose memory type we are checking

11527:   Output Parameter:
11528: . m - the memory type

11530:   Level: intermediate

11532: .seealso: [](ch_matrices), `Mat`, `MatBoundToCPU()`, `PetscMemType`
11533: @*/
11534: PetscErrorCode MatGetCurrentMemType(Mat A, PetscMemType *m)
11535: {
11536:   PetscFunctionBegin;
11538:   PetscAssertPointer(m, 2);
11539:   if (A->ops->getcurrentmemtype) PetscUseTypeMethod(A, getcurrentmemtype, m);
11540:   else *m = PETSC_MEMTYPE_HOST;
11541:   PetscFunctionReturn(PETSC_SUCCESS);
11542: }