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: . -mat_view [viewertype]:... - the viewer and its options

1019:   Level: intermediate

1021:   Note:
1022: .vb
1023:     If no value is provided ascii:stdout is used
1024:        ascii[:[filename][:[format][:append]]]    defaults to stdout - format can be one of ascii_info, ascii_info_detail, or ascii_matlab,
1025:                                                   for example ascii::ascii_info prints just the information about the object not all details
1026:                                                   unless :append is given filename opens in write mode, overwriting what was already there
1027:        binary[:[filename][:[format][:append]]]   defaults to the file binaryoutput
1028:        draw[:drawtype[:filename]]                for example, draw:tikz, draw:tikz:figure.tex  or draw:x
1029:        socket[:port]                             defaults to the standard output port
1030:        saws[:communicatorname]                    publishes object to the Scientific Application Webserver (SAWs)
1031: .ve

1033: .seealso: [](ch_matrices), `Mat`, `MatView()`, `PetscObjectViewFromOptions()`, `MatCreate()`
1034: @*/
1035: PetscErrorCode MatViewFromOptions(Mat A, PetscObject obj, const char name[])
1036: {
1037:   PetscFunctionBegin;
1039: #if !defined(PETSC_HAVE_THREADSAFETY)
1040:   if (insidematview) PetscFunctionReturn(PETSC_SUCCESS);
1041: #endif
1042:   PetscCall(PetscObjectViewFromOptions((PetscObject)A, obj, name));
1043:   PetscFunctionReturn(PETSC_SUCCESS);
1044: }

1046: /*@
1047:   MatView - display information about a matrix in a variety ways

1049:   Collective on viewer

1051:   Input Parameters:
1052: + mat    - the matrix
1053: - viewer - visualization context

1055:   Options Database Keys:
1056: + -mat_view ::ascii_info         - Prints info on matrix at conclusion of `MatAssemblyEnd()`
1057: . -mat_view ::ascii_info_detail  - Prints more detailed info
1058: . -mat_view                      - Prints matrix in ASCII format
1059: . -mat_view ::ascii_matlab       - Prints matrix in MATLAB format
1060: . -mat_view draw                 - PetscDraws nonzero structure of matrix, using `MatView()` and `PetscDrawOpenX()`.
1061: . -display name                  - Sets display name (default is host)
1062: . -draw_pause sec                - Sets number of seconds to pause after display
1063: . -mat_view socket               - Sends matrix to socket, can be accessed from MATLAB (see Users-Manual: ch_matlab for details)
1064: . -viewer_socket_machine machine - -
1065: . -viewer_socket_port port       - -
1066: . -mat_view binary               - save matrix to file in binary format
1067: - -viewer_binary_filename name   - -

1069:   Level: beginner

1071:   Notes:
1072:   The available visualization contexts include
1073: +    `PETSC_VIEWER_STDOUT_SELF`   - for sequential matrices
1074: .    `PETSC_VIEWER_STDOUT_WORLD`  - for parallel matrices created on `PETSC_COMM_WORLD`
1075: .    `PETSC_VIEWER_STDOUT_`(comm) - for matrices created on MPI communicator comm
1076: -     `PETSC_VIEWER_DRAW_WORLD`   - graphical display of nonzero structure

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

1084:   The user can call `PetscViewerPushFormat()` to specify the output
1085:   format of ASCII printed objects (when using `PETSC_VIEWER_STDOUT_SELF`,
1086:   `PETSC_VIEWER_STDOUT_WORLD` and `PetscViewerASCIIOpen()`).  Available formats include
1087: +    `PETSC_VIEWER_DEFAULT`           - default, prints matrix contents
1088: .    `PETSC_VIEWER_ASCII_MATLAB`      - prints matrix contents in MATLAB format
1089: .    `PETSC_VIEWER_ASCII_DENSE`       - prints entire matrix including zeros
1090: .    `PETSC_VIEWER_ASCII_COMMON`      - prints matrix contents, using a sparse  format common among all matrix types
1091: .    `PETSC_VIEWER_ASCII_IMPL`        - prints matrix contents, using an implementation-specific format (which is in many cases the same as the default)
1092: .    `PETSC_VIEWER_ASCII_INFO`        - prints basic information about the matrix size and structure (not the matrix entries)
1093: -    `PETSC_VIEWER_ASCII_INFO_DETAIL` - prints more detailed information about the matrix nonzero structure (still not vector or matrix entries)

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

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

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

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

1106:   One can use '-mat_view draw -draw_pause -1' to pause the graphical display of matrix nonzero structure,
1107:   and then use the following mouse functions.
1108: .vb
1109:   left mouse: zoom in
1110:   middle mouse: zoom out
1111:   right mouse: continue with the simulation
1112: .ve

1114: .seealso: [](ch_matrices), `Mat`, `PetscViewerPushFormat()`, `PetscViewerASCIIOpen()`, `PetscViewerDrawOpen()`, `PetscViewer`,
1115:           `PetscViewerSocketOpen()`, `PetscViewerBinaryOpen()`, `MatLoad()`, `MatViewFromOptions()`
1116: @*/
1117: PetscErrorCode MatView(Mat mat, PetscViewer viewer)
1118: {
1119:   PetscInt          rows, cols, rbs, cbs;
1120:   PetscBool         isascii, isstring, issaws;
1121:   PetscViewerFormat format;
1122:   PetscMPIInt       size;

1124:   PetscFunctionBegin;
1127:   if (!viewer) PetscCall(PetscViewerASCIIGetStdout(PetscObjectComm((PetscObject)mat), &viewer));

1130:   PetscCall(PetscViewerGetFormat(viewer, &format));
1131:   PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)viewer), &size));
1132:   if (size == 1 && format == PETSC_VIEWER_LOAD_BALANCE) PetscFunctionReturn(PETSC_SUCCESS);

1134: #if !defined(PETSC_HAVE_THREADSAFETY)
1135:   insidematview++;
1136: #endif
1137:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERSTRING, &isstring));
1138:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERASCII, &isascii));
1139:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERSAWS, &issaws));
1140:   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");

1142:   PetscCall(PetscLogEventBegin(MAT_View, mat, viewer, 0, 0));
1143:   if (isascii) {
1144:     if (!mat->preallocated) {
1145:       PetscCall(PetscViewerASCIIPrintf(viewer, "Matrix has not been preallocated yet\n"));
1146: #if !defined(PETSC_HAVE_THREADSAFETY)
1147:       insidematview--;
1148: #endif
1149:       PetscCall(PetscLogEventEnd(MAT_View, mat, viewer, 0, 0));
1150:       PetscFunctionReturn(PETSC_SUCCESS);
1151:     }
1152:     if (!mat->assembled) {
1153:       PetscCall(PetscViewerASCIIPrintf(viewer, "Matrix has not been assembled yet\n"));
1154: #if !defined(PETSC_HAVE_THREADSAFETY)
1155:       insidematview--;
1156: #endif
1157:       PetscCall(PetscLogEventEnd(MAT_View, mat, viewer, 0, 0));
1158:       PetscFunctionReturn(PETSC_SUCCESS);
1159:     }
1160:     PetscCall(PetscObjectPrintClassNamePrefixType((PetscObject)mat, viewer));
1161:     if (format == PETSC_VIEWER_ASCII_INFO || format == PETSC_VIEWER_ASCII_INFO_DETAIL) {
1162:       MatNullSpace nullsp, transnullsp;

1164:       PetscCall(PetscViewerASCIIPushTab(viewer));
1165:       PetscCall(MatGetSize(mat, &rows, &cols));
1166:       PetscCall(MatGetBlockSizes(mat, &rbs, &cbs));
1167:       if (rbs != 1 || cbs != 1) {
1168:         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" : ""));
1169:         else PetscCall(PetscViewerASCIIPrintf(viewer, "rows=%" PetscInt_FMT ", cols=%" PetscInt_FMT ", bs=%" PetscInt_FMT "%s\n", rows, cols, rbs, mat->bsizes ? " variable blocks set" : ""));
1170:       } else PetscCall(PetscViewerASCIIPrintf(viewer, "rows=%" PetscInt_FMT ", cols=%" PetscInt_FMT "\n", rows, cols));
1171:       if (mat->factortype) {
1172:         MatSolverType solver;
1173:         PetscCall(MatFactorGetSolverType(mat, &solver));
1174:         PetscCall(PetscViewerASCIIPrintf(viewer, "package used to perform factorization: %s\n", solver));
1175:       }
1176:       if (mat->ops->getinfo) {
1177:         PetscBool is_constant_or_diagonal;

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

1184:           PetscCall(MatGetInfo(mat, MAT_GLOBAL_SUM, &info));
1185:           PetscCall(PetscViewerASCIIPrintf(viewer, "total: nonzeros=%.f, allocated nonzeros=%.f\n", info.nz_used, info.nz_allocated));
1186:           if (!mat->factortype) PetscCall(PetscViewerASCIIPrintf(viewer, "total number of mallocs used during MatSetValues calls=%" PetscInt_FMT "\n", (PetscInt)info.mallocs));
1187:         }
1188:       }
1189:       PetscCall(MatGetNullSpace(mat, &nullsp));
1190:       PetscCall(MatGetTransposeNullSpace(mat, &transnullsp));
1191:       if (nullsp) PetscCall(PetscViewerASCIIPrintf(viewer, "  has attached null space\n"));
1192:       if (transnullsp && transnullsp != nullsp) PetscCall(PetscViewerASCIIPrintf(viewer, "  has attached transposed null space\n"));
1193:       PetscCall(MatGetNearNullSpace(mat, &nullsp));
1194:       if (nullsp) PetscCall(PetscViewerASCIIPrintf(viewer, "  has attached near null space\n"));
1195:       PetscCall(PetscViewerASCIIPushTab(viewer));
1196:       PetscCall(MatProductView(mat, viewer));
1197:       PetscCall(PetscViewerASCIIPopTab(viewer));
1198:       if (mat->bsizes && format == PETSC_VIEWER_ASCII_INFO_DETAIL) {
1199:         IS tmp;

1201:         PetscCall(ISCreateGeneral(PetscObjectComm((PetscObject)viewer), mat->nblocks, mat->bsizes, PETSC_USE_POINTER, &tmp));
1202:         PetscCall(PetscObjectSetName((PetscObject)tmp, "Block Sizes"));
1203:         PetscCall(PetscViewerASCIIPushTab(viewer));
1204:         PetscCall(ISView(tmp, viewer));
1205:         PetscCall(PetscViewerASCIIPopTab(viewer));
1206:         PetscCall(ISDestroy(&tmp));
1207:       }
1208:     }
1209:   } else if (issaws) {
1210: #if defined(PETSC_HAVE_SAWS)
1211:     PetscMPIInt rank;

1213:     PetscCall(PetscObjectName((PetscObject)mat));
1214:     PetscCallMPI(MPI_Comm_rank(PETSC_COMM_WORLD, &rank));
1215:     if (!((PetscObject)mat)->amsmem && rank == 0) PetscCall(PetscObjectViewSAWs((PetscObject)mat, viewer));
1216: #endif
1217:   } else if (isstring) {
1218:     const char *type;
1219:     PetscCall(MatGetType(mat, &type));
1220:     PetscCall(PetscViewerStringSPrintf(viewer, " MatType: %-7.7s", type));
1221:     PetscTryTypeMethod(mat, view, viewer);
1222:   }
1223:   if ((format == PETSC_VIEWER_NATIVE || format == PETSC_VIEWER_LOAD_BALANCE) && mat->ops->viewnative) {
1224:     PetscCall(PetscViewerASCIIPushTab(viewer));
1225:     PetscUseTypeMethod(mat, viewnative, viewer);
1226:     PetscCall(PetscViewerASCIIPopTab(viewer));
1227:   } else if (mat->ops->view) {
1228:     PetscCall(PetscViewerASCIIPushTab(viewer));
1229:     PetscUseTypeMethod(mat, view, viewer);
1230:     PetscCall(PetscViewerASCIIPopTab(viewer));
1231:   }
1232:   if (isascii) {
1233:     PetscCall(PetscViewerGetFormat(viewer, &format));
1234:     if (format == PETSC_VIEWER_ASCII_INFO || format == PETSC_VIEWER_ASCII_INFO_DETAIL) PetscCall(PetscViewerASCIIPopTab(viewer));
1235:   }
1236:   PetscCall(PetscLogEventEnd(MAT_View, mat, viewer, 0, 0));
1237: #if !defined(PETSC_HAVE_THREADSAFETY)
1238:   insidematview--;
1239: #endif
1240:   PetscFunctionReturn(PETSC_SUCCESS);
1241: }

1243: #if defined(PETSC_USE_DEBUG)
1244: #include <../src/sys/totalview/tv_data_display.h>
1245: PETSC_UNUSED static int TV_display_type(const struct _p_Mat *mat)
1246: {
1247:   TV_add_row("Local rows", "int", &mat->rmap->n);
1248:   TV_add_row("Local columns", "int", &mat->cmap->n);
1249:   TV_add_row("Global rows", "int", &mat->rmap->N);
1250:   TV_add_row("Global columns", "int", &mat->cmap->N);
1251:   TV_add_row("Typename", TV_ascii_string_type, ((PetscObject)mat)->type_name);
1252:   return TV_format_OK;
1253: }
1254: #endif

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

1262:   Collective

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

1269:   Options Database Key:
1270: . -matload_block_size bs - set block size

1272:   Level: beginner

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

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

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

1287:   In parallel, each processor can load a subset of rows (or the
1288:   entire matrix).  This routine is especially useful when a large
1289:   matrix is stored on disk and only part of it is desired on each
1290:   processor.  For example, a parallel solver may access only some of
1291:   the rows from each processor.  The algorithm used here reads
1292:   relatively small blocks of data rather than reading the entire
1293:   matrix and then subsetting it.

1295:   Viewer's `PetscViewerType` must be either `PETSCVIEWERBINARY` or `PETSCVIEWERHDF5`.
1296:   Such viewer can be created using `PetscViewerBinaryOpen()` or `PetscViewerHDF5Open()`,
1297:   or the sequence like
1298: .vb
1299:     `PetscViewer` v;
1300:     `PetscViewerCreate`(`PETSC_COMM_WORLD`,&v);
1301:     `PetscViewerSetType`(v,`PETSCVIEWERBINARY`);
1302:     `PetscViewerSetFromOptions`(v);
1303:     `PetscViewerFileSetMode`(v,`FILE_MODE_READ`);
1304:     `PetscViewerFileSetName`(v,"datafile");
1305: .ve
1306:   The optional `PetscViewerSetFromOptions()` call allows overriding `PetscViewerSetType()` using the option
1307: .vb
1308:   -viewer_type {binary, hdf5}
1309: .ve

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

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

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

1324: .vb
1325:     PetscInt    MAT_FILE_CLASSID
1326:     PetscInt    number of rows
1327:     PetscInt    number of columns
1328:     PetscInt    total number of nonzeros
1329:     PetscInt    *number nonzeros in each row
1330:     PetscInt    *column indices of all nonzeros (starting index is zero)
1331:     PetscScalar *values of all nonzeros
1332: .ve
1333:   If PETSc was not configured with `--with-64-bit-indices` then only `MATMPIAIJ` matrices with more than `PETSC_INT_MAX` non-zeros can be
1334:   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
1335:   case will not fit in a (32-bit) `PetscInt` the value `PETSC_INT_MAX` is used for the header entry `total number of nonzeros`.

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

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

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

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

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

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

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

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

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

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

1375: .seealso: [](ch_matrices), `Mat`, `PetscViewerBinaryOpen()`, `PetscViewerSetType()`, `MatView()`, `VecLoad()`
1376:  @*/
1377: PetscErrorCode MatLoad(Mat mat, PetscViewer viewer)
1378: {
1379:   PetscBool flg;

1381:   PetscFunctionBegin;

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

1387:   flg = PETSC_FALSE;
1388:   PetscCall(PetscOptionsGetBool(((PetscObject)mat)->options, ((PetscObject)mat)->prefix, "-matload_symmetric", &flg, NULL));
1389:   if (flg) {
1390:     PetscCall(MatSetOption(mat, MAT_SYMMETRIC, PETSC_TRUE));
1391:     PetscCall(MatSetOption(mat, MAT_SYMMETRY_ETERNAL, PETSC_TRUE));
1392:   }
1393:   flg = PETSC_FALSE;
1394:   PetscCall(PetscOptionsGetBool(((PetscObject)mat)->options, ((PetscObject)mat)->prefix, "-matload_spd", &flg, NULL));
1395:   if (flg) PetscCall(MatSetOption(mat, MAT_SPD, PETSC_TRUE));

1397:   PetscCall(PetscLogEventBegin(MAT_Load, mat, viewer, 0, 0));
1398:   PetscUseTypeMethod(mat, load, viewer);
1399:   PetscCall(PetscLogEventEnd(MAT_Load, mat, viewer, 0, 0));
1400:   PetscFunctionReturn(PETSC_SUCCESS);
1401: }

1403: static PetscErrorCode MatDestroy_Redundant(Mat_Redundant **redundant)
1404: {
1405:   Mat_Redundant *redund = *redundant;

1407:   PetscFunctionBegin;
1408:   if (redund) {
1409:     if (redund->matseq) { /* via MatCreateSubMatrices()  */
1410:       PetscCall(ISDestroy(&redund->isrow));
1411:       PetscCall(ISDestroy(&redund->iscol));
1412:       PetscCall(MatDestroySubMatrices(1, &redund->matseq));
1413:     } else {
1414:       PetscCall(PetscFree2(redund->send_rank, redund->recv_rank));
1415:       PetscCall(PetscFree(redund->sbuf_j));
1416:       PetscCall(PetscFree(redund->sbuf_a));
1417:       for (PetscInt i = 0; i < redund->nrecvs; i++) {
1418:         PetscCall(PetscFree(redund->rbuf_j[i]));
1419:         PetscCall(PetscFree(redund->rbuf_a[i]));
1420:       }
1421:       PetscCall(PetscFree4(redund->sbuf_nz, redund->rbuf_nz, redund->rbuf_j, redund->rbuf_a));
1422:     }

1424:     if (redund->subcomm) PetscCall(PetscCommDestroy(&redund->subcomm));
1425:     PetscCall(PetscFree(redund));
1426:   }
1427:   PetscFunctionReturn(PETSC_SUCCESS);
1428: }

1430: /*@
1431:   MatDestroy - Frees space taken by a matrix.

1433:   Collective

1435:   Input Parameter:
1436: . A - the matrix

1438:   Level: beginner

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

1446: .seealso: [](ch_matrices), `Mat`, `MatCreate()`
1447: @*/
1448: PetscErrorCode MatDestroy(Mat *A)
1449: {
1450:   PetscFunctionBegin;
1451:   if (!*A) PetscFunctionReturn(PETSC_SUCCESS);
1453:   if (--((PetscObject)*A)->refct > 0) {
1454:     *A = NULL;
1455:     PetscFunctionReturn(PETSC_SUCCESS);
1456:   }

1458:   /* if memory was published with SAWs then destroy it */
1459:   PetscCall(PetscObjectSAWsViewOff((PetscObject)*A));
1460:   PetscTryTypeMethod(*A, destroy);

1462:   PetscCall(PetscFree((*A)->factorprefix));
1463:   PetscCall(PetscFree((*A)->defaultvectype));
1464:   PetscCall(PetscFree((*A)->defaultrandtype));
1465:   PetscCall(PetscFree((*A)->bsizes));
1466:   PetscCall(PetscFree((*A)->solvertype));
1467:   for (PetscInt i = 0; i < MAT_FACTOR_NUM_TYPES; i++) PetscCall(PetscFree((*A)->preferredordering[i]));
1468:   if ((*A)->redundant && (*A)->redundant->matseq[0] == *A) (*A)->redundant->matseq[0] = NULL;
1469:   PetscCall(MatDestroy_Redundant(&(*A)->redundant));
1470:   PetscCall(MatProductClear(*A));
1471:   PetscCall(MatNullSpaceDestroy(&(*A)->nullsp));
1472:   PetscCall(MatNullSpaceDestroy(&(*A)->transnullsp));
1473:   PetscCall(MatNullSpaceDestroy(&(*A)->nearnullsp));
1474:   PetscCall(MatDestroy(&(*A)->schur));
1475:   PetscCall(VecDestroy(&(*A)->dot_vec));
1476:   PetscCall(PetscLayoutDestroy(&(*A)->rmap));
1477:   PetscCall(PetscLayoutDestroy(&(*A)->cmap));
1478:   PetscCall(PetscHeaderDestroy(A));
1479:   PetscFunctionReturn(PETSC_SUCCESS);
1480: }

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

1488:   Not Collective

1490:   Input Parameters:
1491: + mat  - the matrix
1492: . m    - the number of rows
1493: . idxm - the global indices of the rows
1494: . n    - the number of columns
1495: . idxn - the global indices of the columns
1496: . v    - a one-dimensional array that contains the values implicitly stored as a two-dimensional array, by default in row-major order.
1497:          See `MAT_ROW_ORIENTED` in `MatSetOption()` for how to use column-major order.
1498: - addv - either `ADD_VALUES` to add values to any existing entries, or `INSERT_VALUES` to replace existing entries with new values

1500:   Level: beginner

1502:   Notes:
1503:   Calls to `MatSetValues()` with the `INSERT_VALUES` and `ADD_VALUES`
1504:   options cannot be mixed without intervening calls to the assembly
1505:   routines.

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

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

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

1519:   Fortran Notes:
1520:   If any of `idxm`, `idxn`, and `v` are scalars pass them using, for example,
1521: .vb
1522:   call MatSetValues(mat, one, [idxm], one, [idxn], [v], INSERT_VALUES, ierr)
1523: .ve

1525:   If `v` is a two-dimensional array use `reshape()` to pass it as a one dimensional array

1527:   Developer Note:
1528:   This is labeled with C so does not automatically generate Fortran stubs and interfaces
1529:   because it requires multiple Fortran interfaces depending on which arguments are scalar or arrays.

1531: .seealso: [](ch_matrices), `Mat`, `MatSetOption()`, `MatAssemblyBegin()`, `MatAssemblyEnd()`, `MatSetValuesBlocked()`, `MatSetValuesLocal()`,
1532:           `InsertMode`, `INSERT_VALUES`, `ADD_VALUES`
1533: @*/
1534: PetscErrorCode MatSetValues(Mat mat, PetscInt m, const PetscInt idxm[], PetscInt n, const PetscInt idxn[], const PetscScalar v[], InsertMode addv)
1535: {
1536:   PetscFunctionBeginHot;
1539:   if (!m || !n) PetscFunctionReturn(PETSC_SUCCESS); /* no values to insert */
1540:   PetscAssertPointer(idxm, 3);
1541:   PetscAssertPointer(idxn, 5);
1542:   MatCheckPreallocated(mat, 1);

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

1547:   if (PetscDefined(USE_DEBUG)) {
1548:     PetscInt i, j;

1550:     PetscCheck(!mat->factortype, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
1551:     if (v) {
1552:       for (i = 0; i < m; i++) {
1553:         for (j = 0; j < n; j++) {
1554:           if (mat->erroriffailure && PetscIsInfOrNanScalar(v[i * n + j]))
1555: #if defined(PETSC_USE_COMPLEX)
1556:             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]);
1557: #else
1558:             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]);
1559: #endif
1560:         }
1561:       }
1562:     }
1563:     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);
1564:     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);
1565:   }

1567:   if (mat->assembled) {
1568:     mat->was_assembled = PETSC_TRUE;
1569:     mat->assembled     = PETSC_FALSE;
1570:   }
1571:   PetscCall(PetscLogEventBegin(MAT_SetValues, mat, 0, 0, 0));
1572:   PetscUseTypeMethod(mat, setvalues, m, idxm, n, idxn, v, addv);
1573:   PetscCall(PetscLogEventEnd(MAT_SetValues, mat, 0, 0, 0));
1574:   PetscFunctionReturn(PETSC_SUCCESS);
1575: }

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

1583:   Not Collective

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

1593:   Level: beginner

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

1598:   Calls to `MatSetValues()` with the `INSERT_VALUES` and `ADD_VALUES`
1599:   options cannot be mixed without intervening calls to the assembly
1600:   routines.

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

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

1610:   Fortran Note:
1611:   If `v` is a two-dimensional array use `reshape()` to pass it as a one dimensional array

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

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

1619: .seealso: [](ch_matrices), `Mat`, `MatSetOption()`, `MatSetValues()`, `MatAssemblyBegin()`, `MatAssemblyEnd()`, `MatSetValuesBlocked()`, `MatSetValuesLocal()`,
1620:           `InsertMode`, `INSERT_VALUES`, `ADD_VALUES`
1621: @*/
1622: PetscErrorCode MatSetValuesIS(Mat mat, IS ism, IS isn, const PetscScalar v[], InsertMode addv)
1623: {
1624:   PetscInt        m, n;
1625:   const PetscInt *rows, *cols;

1627:   PetscFunctionBeginHot;
1629:   PetscCall(ISGetIndices(ism, &rows));
1630:   PetscCall(ISGetIndices(isn, &cols));
1631:   PetscCall(ISGetLocalSize(ism, &m));
1632:   PetscCall(ISGetLocalSize(isn, &n));
1633:   PetscCall(MatSetValues(mat, m, rows, n, cols, v, addv));
1634:   PetscCall(ISRestoreIndices(ism, &rows));
1635:   PetscCall(ISRestoreIndices(isn, &cols));
1636:   PetscFunctionReturn(PETSC_SUCCESS);
1637: }

1639: /*@
1640:   MatSetValuesRowLocal - Inserts a row (block row for `MATBAIJ` matrices) of nonzero
1641:   values into a matrix

1643:   Not Collective

1645:   Input Parameters:
1646: + mat - the matrix
1647: . row - the (block) row to set
1648: - v   - a one-dimensional array that contains the values. For `MATBAIJ` they are implicitly stored as a two-dimensional array, by default in row-major order.
1649:         See `MAT_ROW_ORIENTED` in `MatSetOption()` for how to use column-major order.

1651:   Level: intermediate

1653:   Notes:
1654:   The values, `v`, are column-oriented (for the block version) and sorted

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

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

1660:   `row` must belong to this MPI process

1662:   Fortran Note:
1663:   If `v` is a two-dimensional array use `reshape()` to pass it as a one dimensional array

1665: .seealso: [](ch_matrices), `Mat`, `MatSetOption()`, `MatAssemblyBegin()`, `MatAssemblyEnd()`, `MatSetValuesBlocked()`, `MatSetValuesLocal()`,
1666:           `InsertMode`, `INSERT_VALUES`, `ADD_VALUES`, `MatSetValues()`, `MatSetValuesRow()`, `MatSetLocalToGlobalMapping()`
1667: @*/
1668: PetscErrorCode MatSetValuesRowLocal(Mat mat, PetscInt row, const PetscScalar v[])
1669: {
1670:   PetscInt globalrow;

1672:   PetscFunctionBegin;
1675:   PetscAssertPointer(v, 3);
1676:   PetscCall(ISLocalToGlobalMappingApply(mat->rmap->mapping, 1, &row, &globalrow));
1677:   PetscCall(MatSetValuesRow(mat, globalrow, v));
1678:   PetscFunctionReturn(PETSC_SUCCESS);
1679: }

1681: /*@
1682:   MatSetValuesRow - Inserts a row (block row for `MATBAIJ` matrices) of nonzero
1683:   values into a matrix

1685:   Not Collective

1687:   Input Parameters:
1688: + mat - the matrix
1689: . row - the (block) row to set
1690: - v   - a logically two-dimensional (column major) array of values for  block matrices with blocksize larger than one, otherwise a one dimensional array of values

1692:   Level: advanced

1694:   Notes:
1695:   The values, `v`, are column-oriented for the block version.

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

1699:   THE MATRIX MUST HAVE PREVIOUSLY HAD ITS COLUMN INDICES SET. IT IS RARE THAT THIS ROUTINE IS USED, usually `MatSetValues()` is used.

1701:   `row` must belong to this process

1703: .seealso: [](ch_matrices), `Mat`, `MatSetValues()`, `MatSetOption()`, `MatAssemblyBegin()`, `MatAssemblyEnd()`, `MatSetValuesBlocked()`, `MatSetValuesLocal()`,
1704:           `InsertMode`, `INSERT_VALUES`, `ADD_VALUES`
1705: @*/
1706: PetscErrorCode MatSetValuesRow(Mat mat, PetscInt row, const PetscScalar v[])
1707: {
1708:   PetscFunctionBeginHot;
1711:   MatCheckPreallocated(mat, 1);
1712:   PetscAssertPointer(v, 3);
1713:   PetscCheck(mat->insertmode != ADD_VALUES, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Cannot mix add and insert values");
1714:   PetscCheck(!mat->factortype, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
1715:   mat->insertmode = INSERT_VALUES;

1717:   if (mat->assembled) {
1718:     mat->was_assembled = PETSC_TRUE;
1719:     mat->assembled     = PETSC_FALSE;
1720:   }
1721:   PetscCall(PetscLogEventBegin(MAT_SetValues, mat, 0, 0, 0));
1722:   PetscUseTypeMethod(mat, setvaluesrow, row, v);
1723:   PetscCall(PetscLogEventEnd(MAT_SetValues, mat, 0, 0, 0));
1724:   PetscFunctionReturn(PETSC_SUCCESS);
1725: }

1727: // PetscClangLinter pragma disable: -fdoc-section-header-unknown
1728: /*@
1729:   MatSetValuesStencil - Inserts or adds a block of values into a matrix.
1730:   Using structured grid indexing

1732:   Not Collective

1734:   Input Parameters:
1735: + mat  - the matrix
1736: . m    - number of rows being entered
1737: . idxm - grid coordinates (and component number when dof > 1) for matrix rows being entered
1738: . n    - number of columns being entered
1739: . idxn - grid coordinates (and component number when dof > 1) for matrix columns being entered
1740: . v    - a one-dimensional array that contains the values implicitly stored as a two-dimensional array, by default in row-major order.
1741:          See `MAT_ROW_ORIENTED` in `MatSetOption()` for how to use column-major order.
1742: - addv - either `ADD_VALUES` to add to existing entries at that location or `INSERT_VALUES` to replace existing entries with new values

1744:   Level: beginner

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

1749:   Calls to `MatSetValuesStencil()` with the `INSERT_VALUES` and `ADD_VALUES`
1750:   options cannot be mixed without intervening calls to the assembly
1751:   routines.

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

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

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

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

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

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

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

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

1780:   Fortran Note:
1781:   If `y` is a two-dimensional array use `reshape()` to pass it as a one dimensional array

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

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

1796:   PetscFunctionBegin;
1797:   if (!m || !n) PetscFunctionReturn(PETSC_SUCCESS); /* no values to insert */
1800:   PetscAssertPointer(idxm, 3);
1801:   PetscAssertPointer(idxn, 5);

1803:   if ((m + n) <= (PetscInt)PETSC_STATIC_ARRAY_LENGTH(buf)) {
1804:     jdxm = buf;
1805:     jdxn = buf + m;
1806:   } else {
1807:     PetscCall(PetscMalloc2(m, &bufm, n, &bufn));
1808:     jdxm = bufm;
1809:     jdxn = bufn;
1810:   }
1811:   for (i = 0; i < m; i++) {
1812:     for (j = 0; j < 3 - sdim; j++) dxm++;
1813:     tmp = *dxm++ - starts[0];
1814:     for (j = 0; j < dim - 1; j++) {
1815:       if ((*dxm++ - starts[j + 1]) < 0 || tmp < 0) tmp = -1;
1816:       else tmp = tmp * dims[j] + *(dxm - 1) - starts[j + 1];
1817:     }
1818:     if (mat->stencil.noc) dxm++;
1819:     jdxm[i] = tmp;
1820:   }
1821:   for (i = 0; i < n; i++) {
1822:     for (j = 0; j < 3 - sdim; j++) dxn++;
1823:     tmp = *dxn++ - starts[0];
1824:     for (j = 0; j < dim - 1; j++) {
1825:       if ((*dxn++ - starts[j + 1]) < 0 || tmp < 0) tmp = -1;
1826:       else tmp = tmp * dims[j] + *(dxn - 1) - starts[j + 1];
1827:     }
1828:     if (mat->stencil.noc) dxn++;
1829:     jdxn[i] = tmp;
1830:   }
1831:   PetscCall(MatSetValuesLocal(mat, m, jdxm, n, jdxn, v, addv));
1832:   PetscCall(PetscFree2(bufm, bufn));
1833:   PetscFunctionReturn(PETSC_SUCCESS);
1834: }

1836: /*@
1837:   MatSetValuesBlockedStencil - Inserts or adds a block of values into a matrix.
1838:   Using structured grid indexing

1840:   Not Collective

1842:   Input Parameters:
1843: + mat  - the matrix
1844: . m    - number of rows being entered
1845: . idxm - grid coordinates for matrix rows being entered
1846: . n    - number of columns being entered
1847: . idxn - grid coordinates for matrix columns being entered
1848: . v    - a one-dimensional array that contains the values implicitly stored as a two-dimensional array, by default in row-major order.
1849:          See `MAT_ROW_ORIENTED` in `MatSetOption()` for how to use column-major order.
1850: - addv - either `ADD_VALUES` to add to existing entries or `INSERT_VALUES` to replace existing entries with new values

1852:   Level: beginner

1854:   Notes:
1855:   By default the values, `v`, are row-oriented and unsorted.
1856:   See `MatSetOption()` for other options.

1858:   Calls to `MatSetValuesBlockedStencil()` with the `INSERT_VALUES` and `ADD_VALUES`
1859:   options cannot be mixed without intervening calls to the assembly
1860:   routines.

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

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

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

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

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

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

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

1886:   Fortran Notes:
1887:   `idxm` and `idxn` should be declared as
1888: .vb
1889:     MatStencil idxm(4,m),idxn(4,n)
1890: .ve
1891:   and the values inserted using
1892: .vb
1893:     idxm(MatStencil_i,1) = i
1894:     idxm(MatStencil_j,1) = j
1895:     idxm(MatStencil_k,1) = k
1896:    etc
1897: .ve

1899:   If `v` is a two-dimensional array use `reshape()` to pass it as a one dimensional array

1901: .seealso: [](ch_matrices), `Mat`, `DMDA`, `MatSetOption()`, `MatAssemblyBegin()`, `MatAssemblyEnd()`, `MatSetValuesBlocked()`, `MatSetValuesLocal()`,
1902:           `MatSetValues()`, `MatSetValuesStencil()`, `MatSetStencil()`, `DMCreateMatrix()`, `DMDAVecGetArray()`, `MatStencil`,
1903:           `MatSetBlockSize()`, `MatSetLocalToGlobalMapping()`
1904: @*/
1905: PetscErrorCode MatSetValuesBlockedStencil(Mat mat, PetscInt m, const MatStencil idxm[], PetscInt n, const MatStencil idxn[], const PetscScalar v[], InsertMode addv)
1906: {
1907:   PetscInt  buf[8192], *bufm = NULL, *bufn = NULL, *jdxm, *jdxn;
1908:   PetscInt  j, i, dim = mat->stencil.dim, *dims = mat->stencil.dims + 1, tmp;
1909:   PetscInt *starts = mat->stencil.starts, *dxm = (PetscInt *)idxm, *dxn = (PetscInt *)idxn, sdim = dim - (1 - (PetscInt)mat->stencil.noc);

1911:   PetscFunctionBegin;
1912:   if (!m || !n) PetscFunctionReturn(PETSC_SUCCESS); /* no values to insert */
1915:   PetscAssertPointer(idxm, 3);
1916:   PetscAssertPointer(idxn, 5);
1917:   PetscAssertPointer(v, 6);

1919:   if ((m + n) <= (PetscInt)PETSC_STATIC_ARRAY_LENGTH(buf)) {
1920:     jdxm = buf;
1921:     jdxn = buf + m;
1922:   } else {
1923:     PetscCall(PetscMalloc2(m, &bufm, n, &bufn));
1924:     jdxm = bufm;
1925:     jdxn = bufn;
1926:   }
1927:   for (i = 0; i < m; i++) {
1928:     for (j = 0; j < 3 - sdim; j++) dxm++;
1929:     tmp = *dxm++ - starts[0];
1930:     for (j = 0; j < sdim - 1; j++) {
1931:       if ((*dxm++ - starts[j + 1]) < 0 || tmp < 0) tmp = -1;
1932:       else tmp = tmp * dims[j] + *(dxm - 1) - starts[j + 1];
1933:     }
1934:     dxm++;
1935:     jdxm[i] = tmp;
1936:   }
1937:   for (i = 0; i < n; i++) {
1938:     for (j = 0; j < 3 - sdim; j++) dxn++;
1939:     tmp = *dxn++ - starts[0];
1940:     for (j = 0; j < sdim - 1; j++) {
1941:       if ((*dxn++ - starts[j + 1]) < 0 || tmp < 0) tmp = -1;
1942:       else tmp = tmp * dims[j] + *(dxn - 1) - starts[j + 1];
1943:     }
1944:     dxn++;
1945:     jdxn[i] = tmp;
1946:   }
1947:   PetscCall(MatSetValuesBlockedLocal(mat, m, jdxm, n, jdxn, v, addv));
1948:   PetscCall(PetscFree2(bufm, bufn));
1949:   PetscFunctionReturn(PETSC_SUCCESS);
1950: }

1952: /*@
1953:   MatSetStencil - Sets the grid information for setting values into a matrix via
1954:   `MatSetValuesStencil()`

1956:   Not Collective

1958:   Input Parameters:
1959: + mat    - the matrix
1960: . dim    - dimension of the grid 1, 2, or 3
1961: . dims   - number of grid points in x, y, and z direction, including ghost points on your processor
1962: . starts - starting point of ghost nodes on your processor in x, y, and z direction
1963: - dof    - number of degrees of freedom per node

1965:   Level: beginner

1967:   Notes:
1968:   Inspired by the structured grid interface to the HYPRE package
1969:   (www.llnl.gov/CASC/hyper)

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

1974: .seealso: [](ch_matrices), `Mat`, `MatStencil`, `MatSetOption()`, `MatAssemblyBegin()`, `MatAssemblyEnd()`, `MatSetValuesBlocked()`, `MatSetValuesLocal()`,
1975:           `MatSetValues()`, `MatSetValuesBlockedStencil()`, `MatSetValuesStencil()`
1976: @*/
1977: PetscErrorCode MatSetStencil(Mat mat, PetscInt dim, const PetscInt dims[], const PetscInt starts[], PetscInt dof)
1978: {
1979:   PetscFunctionBegin;
1981:   PetscAssertPointer(dims, 3);
1982:   PetscAssertPointer(starts, 4);

1984:   mat->stencil.dim = dim + (dof > 1);
1985:   for (PetscInt i = 0; i < dim; i++) {
1986:     mat->stencil.dims[i]   = dims[dim - i - 1]; /* copy the values in backwards */
1987:     mat->stencil.starts[i] = starts[dim - i - 1];
1988:   }
1989:   mat->stencil.dims[dim]   = dof;
1990:   mat->stencil.starts[dim] = 0;
1991:   mat->stencil.noc         = (PetscBool)(dof == 1);
1992:   PetscFunctionReturn(PETSC_SUCCESS);
1993: }

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

1998:   Not Collective

2000:   Input Parameters:
2001: + mat  - the matrix
2002: . m    - the number of block rows
2003: . idxm - the global block indices
2004: . n    - the number of block columns
2005: . idxn - the global block indices
2006: . v    - a one-dimensional array that contains the values implicitly stored as a two-dimensional array, by default in row-major order.
2007:          See `MAT_ROW_ORIENTED` in `MatSetOption()` for how to use column-major order.
2008: - addv - either `ADD_VALUES` to add values to any existing entries, or `INSERT_VALUES` replaces existing entries with new values

2010:   Level: intermediate

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

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

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

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

2027:   Calls to `MatSetValuesBlocked()` with the `INSERT_VALUES` and `ADD_VALUES`
2028:   options cannot be mixed without intervening calls to the assembly
2029:   routines.

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

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

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

2045:   Example:
2046: .vb
2047:    Suppose m=n=2 and block size(bs) = 2 The array is

2049:    1  2  | 3  4
2050:    5  6  | 7  8
2051:    - - - | - - -
2052:    9  10 | 11 12
2053:    13 14 | 15 16

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

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

2062:   Fortran Notes:
2063:   If any of `idmx`, `idxn`, and `v` are scalars pass them using, for example,
2064: .vb
2065:   call MatSetValuesBlocked(mat, one, [idxm], one, [idxn], [v], INSERT_VALUES, ierr)
2066: .ve

2068:   If `v` is a two-dimensional array use `reshape()` to pass it as a one dimensional array

2070: .seealso: [](ch_matrices), `Mat`, `MatSetBlockSize()`, `MatSetOption()`, `MatAssemblyBegin()`, `MatAssemblyEnd()`, `MatSetValues()`, `MatSetValuesBlockedLocal()`
2071: @*/
2072: PetscErrorCode MatSetValuesBlocked(Mat mat, PetscInt m, const PetscInt idxm[], PetscInt n, const PetscInt idxn[], const PetscScalar v[], InsertMode addv)
2073: {
2074:   PetscFunctionBeginHot;
2077:   if (!m || !n) PetscFunctionReturn(PETSC_SUCCESS); /* no values to insert */
2078:   PetscAssertPointer(idxm, 3);
2079:   PetscAssertPointer(idxn, 5);
2080:   MatCheckPreallocated(mat, 1);
2081:   if (mat->insertmode == NOT_SET_VALUES) mat->insertmode = addv;
2082:   else PetscCheck(mat->insertmode == addv, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Cannot mix add values and insert values");
2083:   if (PetscDefined(USE_DEBUG)) {
2084:     PetscCheck(!mat->factortype, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
2085:     PetscCheck(mat->ops->setvaluesblocked || mat->ops->setvalues, PETSC_COMM_SELF, PETSC_ERR_SUP, "Mat type %s", ((PetscObject)mat)->type_name);
2086:   }
2087:   if (PetscDefined(USE_DEBUG)) {
2088:     PetscInt rbs, cbs, M, N, i;
2089:     PetscCall(MatGetBlockSizes(mat, &rbs, &cbs));
2090:     PetscCall(MatGetSize(mat, &M, &N));
2091:     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);
2092:     for (i = 0; i < n; i++)
2093:       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);
2094:   }
2095:   if (mat->assembled) {
2096:     mat->was_assembled = PETSC_TRUE;
2097:     mat->assembled     = PETSC_FALSE;
2098:   }
2099:   PetscCall(PetscLogEventBegin(MAT_SetValues, mat, 0, 0, 0));
2100:   if (mat->ops->setvaluesblocked) PetscUseTypeMethod(mat, setvaluesblocked, m, idxm, n, idxn, v, addv);
2101:   else {
2102:     PetscInt buf[8192], *bufr = NULL, *bufc = NULL, *iidxm, *iidxn;
2103:     PetscInt i, j, bs, cbs;

2105:     PetscCall(MatGetBlockSizes(mat, &bs, &cbs));
2106:     if ((m * bs + n * cbs) <= (PetscInt)PETSC_STATIC_ARRAY_LENGTH(buf)) {
2107:       iidxm = buf;
2108:       iidxn = buf + m * bs;
2109:     } else {
2110:       PetscCall(PetscMalloc2(m * bs, &bufr, n * cbs, &bufc));
2111:       iidxm = bufr;
2112:       iidxn = bufc;
2113:     }
2114:     for (i = 0; i < m; i++) {
2115:       for (j = 0; j < bs; j++) iidxm[i * bs + j] = bs * idxm[i] + j;
2116:     }
2117:     if (m != n || bs != cbs || idxm != idxn) {
2118:       for (i = 0; i < n; i++) {
2119:         for (j = 0; j < cbs; j++) iidxn[i * cbs + j] = cbs * idxn[i] + j;
2120:       }
2121:     } else iidxn = iidxm;
2122:     PetscCall(MatSetValues(mat, m * bs, iidxm, n * cbs, iidxn, v, addv));
2123:     PetscCall(PetscFree2(bufr, bufc));
2124:   }
2125:   PetscCall(PetscLogEventEnd(MAT_SetValues, mat, 0, 0, 0));
2126:   PetscFunctionReturn(PETSC_SUCCESS);
2127: }

2129: /*@
2130:   MatGetValues - Gets a block of local values from a matrix.

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

2134:   Input Parameters:
2135: + mat  - the matrix
2136: . v    - a logically two-dimensional array for storing the values
2137: . m    - the number of rows
2138: . idxm - the  global indices of the rows
2139: . n    - the number of columns
2140: - idxn - the global indices of the columns

2142:   Level: advanced

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

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

2152:   `MatGetValues()` requires that the matrix has been assembled
2153:   with `MatAssemblyBegin()`/`MatAssemblyEnd()`.  Thus, calls to
2154:   `MatSetValues()` and `MatGetValues()` CANNOT be made in succession
2155:   without intermediate matrix assembly.

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

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

2164: .seealso: [](ch_matrices), `Mat`, `MatGetRow()`, `MatCreateSubMatrices()`, `MatSetValues()`, `MatGetOwnershipRange()`, `MatGetValuesLocal()`, `MatGetValue()`
2165: @*/
2166: PetscErrorCode MatGetValues(Mat mat, PetscInt m, const PetscInt idxm[], PetscInt n, const PetscInt idxn[], PetscScalar v[])
2167: {
2168:   PetscFunctionBegin;
2171:   if (!m || !n) PetscFunctionReturn(PETSC_SUCCESS);
2172:   PetscAssertPointer(idxm, 3);
2173:   PetscAssertPointer(idxn, 5);
2174:   PetscAssertPointer(v, 6);
2175:   PetscCheck(mat->assembled, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
2176:   PetscCheck(!mat->factortype, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
2177:   MatCheckPreallocated(mat, 1);

2179:   PetscCall(PetscLogEventBegin(MAT_GetValues, mat, 0, 0, 0));
2180:   PetscUseTypeMethod(mat, getvalues, m, idxm, n, idxn, v);
2181:   PetscCall(PetscLogEventEnd(MAT_GetValues, mat, 0, 0, 0));
2182:   PetscFunctionReturn(PETSC_SUCCESS);
2183: }

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

2189:   Not Collective

2191:   Input Parameters:
2192: + mat  - the matrix
2193: . nrow - number of rows
2194: . irow - the row local indices
2195: . ncol - number of columns
2196: - icol - the column local indices

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

2202:   Level: advanced

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

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

2212: .seealso: [](ch_matrices), `Mat`, `MatAssemblyBegin()`, `MatAssemblyEnd()`, `MatSetValues()`, `MatSetLocalToGlobalMapping()`,
2213:           `MatSetValuesLocal()`, `MatGetValues()`
2214: @*/
2215: PetscErrorCode MatGetValuesLocal(Mat mat, PetscInt nrow, const PetscInt irow[], PetscInt ncol, const PetscInt icol[], PetscScalar y[])
2216: {
2217:   PetscFunctionBeginHot;
2220:   MatCheckPreallocated(mat, 1);
2221:   if (!nrow || !ncol) PetscFunctionReturn(PETSC_SUCCESS); /* no values to retrieve */
2222:   PetscAssertPointer(irow, 3);
2223:   PetscAssertPointer(icol, 5);
2224:   if (PetscDefined(USE_DEBUG)) {
2225:     PetscCheck(!mat->factortype, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
2226:     PetscCheck(mat->ops->getvalueslocal || mat->ops->getvalues, PETSC_COMM_SELF, PETSC_ERR_SUP, "Mat type %s", ((PetscObject)mat)->type_name);
2227:   }
2228:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
2229:   PetscCall(PetscLogEventBegin(MAT_GetValues, mat, 0, 0, 0));
2230:   if (mat->ops->getvalueslocal) PetscUseTypeMethod(mat, getvalueslocal, nrow, irow, ncol, icol, y);
2231:   else {
2232:     PetscInt buf[8192], *bufr = NULL, *bufc = NULL, *irowm, *icolm;
2233:     if ((nrow + ncol) <= (PetscInt)PETSC_STATIC_ARRAY_LENGTH(buf)) {
2234:       irowm = buf;
2235:       icolm = buf + nrow;
2236:     } else {
2237:       PetscCall(PetscMalloc2(nrow, &bufr, ncol, &bufc));
2238:       irowm = bufr;
2239:       icolm = bufc;
2240:     }
2241:     PetscCheck(mat->rmap->mapping, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "MatGetValuesLocal() cannot proceed without local-to-global row mapping (See MatSetLocalToGlobalMapping()).");
2242:     PetscCheck(mat->cmap->mapping, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "MatGetValuesLocal() cannot proceed without local-to-global column mapping (See MatSetLocalToGlobalMapping()).");
2243:     PetscCall(ISLocalToGlobalMappingApply(mat->rmap->mapping, nrow, irow, irowm));
2244:     PetscCall(ISLocalToGlobalMappingApply(mat->cmap->mapping, ncol, icol, icolm));
2245:     PetscCall(MatGetValues(mat, nrow, irowm, ncol, icolm, y));
2246:     PetscCall(PetscFree2(bufr, bufc));
2247:   }
2248:   PetscCall(PetscLogEventEnd(MAT_GetValues, mat, 0, 0, 0));
2249:   PetscFunctionReturn(PETSC_SUCCESS);
2250: }

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

2256:   Not Collective

2258:   Input Parameters:
2259: + mat  - the matrix
2260: . nb   - the number of blocks
2261: . bs   - the number of rows (and columns) in each block
2262: . rows - a concatenation of the rows for each block
2263: - v    - a concatenation of logically two-dimensional arrays of values

2265:   Level: advanced

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

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

2272: .seealso: [](ch_matrices), `Mat`, `MatSetOption()`, `MatAssemblyBegin()`, `MatAssemblyEnd()`, `MatSetValuesBlocked()`, `MatSetValuesLocal()`,
2273:           `InsertMode`, `INSERT_VALUES`, `ADD_VALUES`, `MatSetValues()`, `MatSetPreallocationCOO()`, `MatSetValuesCOO()`
2274: @*/
2275: PetscErrorCode MatSetValuesBatch(Mat mat, PetscInt nb, PetscInt bs, PetscInt rows[], const PetscScalar v[])
2276: {
2277:   PetscFunctionBegin;
2280:   PetscAssertPointer(rows, 4);
2281:   PetscAssertPointer(v, 5);
2282:   PetscAssert(!mat->factortype, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");

2284:   PetscCall(PetscLogEventBegin(MAT_SetValuesBatch, mat, 0, 0, 0));
2285:   if (mat->ops->setvaluesbatch) PetscUseTypeMethod(mat, setvaluesbatch, nb, bs, rows, v);
2286:   else {
2287:     for (PetscInt b = 0; b < nb; ++b) PetscCall(MatSetValues(mat, bs, &rows[b * bs], bs, &rows[b * bs], &v[b * bs * bs], ADD_VALUES));
2288:   }
2289:   PetscCall(PetscLogEventEnd(MAT_SetValuesBatch, mat, 0, 0, 0));
2290:   PetscFunctionReturn(PETSC_SUCCESS);
2291: }

2293: /*@
2294:   MatSetLocalToGlobalMapping - Sets a local-to-global numbering for use by
2295:   the routine `MatSetValuesLocal()` to allow users to insert matrix entries
2296:   using a local (per-processor) numbering.

2298:   Not Collective

2300:   Input Parameters:
2301: + x        - the matrix
2302: . rmapping - row mapping created with `ISLocalToGlobalMappingCreate()` or `ISLocalToGlobalMappingCreateIS()`
2303: - cmapping - column mapping

2305:   Level: intermediate

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

2310: .seealso: [](ch_matrices), `Mat`, `DM`, `DMCreateMatrix()`, `MatGetLocalToGlobalMapping()`, `MatAssemblyBegin()`, `MatAssemblyEnd()`, `MatSetValues()`, `MatSetValuesLocal()`, `MatGetValuesLocal()`
2311: @*/
2312: PetscErrorCode MatSetLocalToGlobalMapping(Mat x, ISLocalToGlobalMapping rmapping, ISLocalToGlobalMapping cmapping)
2313: {
2314:   PetscFunctionBegin;
2319:   if (x->ops->setlocaltoglobalmapping) PetscUseTypeMethod(x, setlocaltoglobalmapping, rmapping, cmapping);
2320:   else {
2321:     PetscCall(PetscLayoutSetISLocalToGlobalMapping(x->rmap, rmapping));
2322:     PetscCall(PetscLayoutSetISLocalToGlobalMapping(x->cmap, cmapping));
2323:   }
2324:   PetscFunctionReturn(PETSC_SUCCESS);
2325: }

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

2330:   Not Collective

2332:   Input Parameter:
2333: . A - the matrix

2335:   Output Parameters:
2336: + rmapping - row mapping
2337: - cmapping - column mapping

2339:   Level: advanced

2341: .seealso: [](ch_matrices), `Mat`, `MatSetLocalToGlobalMapping()`, `MatSetValuesLocal()`
2342: @*/
2343: PetscErrorCode MatGetLocalToGlobalMapping(Mat A, ISLocalToGlobalMapping *rmapping, ISLocalToGlobalMapping *cmapping)
2344: {
2345:   PetscFunctionBegin;
2348:   if (rmapping) {
2349:     PetscAssertPointer(rmapping, 2);
2350:     *rmapping = A->rmap->mapping;
2351:   }
2352:   if (cmapping) {
2353:     PetscAssertPointer(cmapping, 3);
2354:     *cmapping = A->cmap->mapping;
2355:   }
2356:   PetscFunctionReturn(PETSC_SUCCESS);
2357: }

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

2362:   Logically Collective

2364:   Input Parameters:
2365: + A    - the matrix
2366: . rmap - row layout
2367: - cmap - column layout

2369:   Level: advanced

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

2374: .seealso: [](ch_matrices), `Mat`, `PetscLayout`, `MatCreateVecs()`, `MatGetLocalToGlobalMapping()`, `MatGetLayouts()`
2375: @*/
2376: PetscErrorCode MatSetLayouts(Mat A, PetscLayout rmap, PetscLayout cmap)
2377: {
2378:   PetscFunctionBegin;
2380:   PetscCall(PetscLayoutReference(rmap, &A->rmap));
2381:   PetscCall(PetscLayoutReference(cmap, &A->cmap));
2382:   PetscFunctionReturn(PETSC_SUCCESS);
2383: }

2385: /*@
2386:   MatGetLayouts - Gets the `PetscLayout` objects for rows and columns

2388:   Not Collective

2390:   Input Parameter:
2391: . A - the matrix

2393:   Output Parameters:
2394: + rmap - row layout
2395: - cmap - column layout

2397:   Level: advanced

2399: .seealso: [](ch_matrices), `Mat`, [Matrix Layouts](sec_matlayout), `PetscLayout`, `MatCreateVecs()`, `MatGetLocalToGlobalMapping()`, `MatSetLayouts()`
2400: @*/
2401: PetscErrorCode MatGetLayouts(Mat A, PetscLayout *rmap, PetscLayout *cmap)
2402: {
2403:   PetscFunctionBegin;
2406:   if (rmap) {
2407:     PetscAssertPointer(rmap, 2);
2408:     *rmap = A->rmap;
2409:   }
2410:   if (cmap) {
2411:     PetscAssertPointer(cmap, 3);
2412:     *cmap = A->cmap;
2413:   }
2414:   PetscFunctionReturn(PETSC_SUCCESS);
2415: }

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

2421:   Not Collective

2423:   Input Parameters:
2424: + mat  - the matrix
2425: . nrow - number of rows
2426: . irow - the row local indices
2427: . ncol - number of columns
2428: . icol - the column local indices
2429: . y    - a one-dimensional array that contains the values implicitly stored as a two-dimensional array, by default in row-major order.
2430:          See `MAT_ROW_ORIENTED` in `MatSetOption()` for how to use column-major order.
2431: - addv - either `ADD_VALUES` to add values to any existing entries, or `INSERT_VALUES` to replace existing entries with new values

2433:   Level: intermediate

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

2438:   Calls to `MatSetValuesLocal()` with the `INSERT_VALUES` and `ADD_VALUES`
2439:   options cannot be mixed without intervening calls to the assembly
2440:   routines.

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

2445:   Fortran Notes:
2446:   If any of `irow`, `icol`, and `y` are scalars pass them using, for example,
2447: .vb
2448:   call MatSetValuesLocal(mat, one, [irow], one, [icol], [y], INSERT_VALUES, ierr)
2449: .ve

2451:   If `y` is a two-dimensional array use `reshape()` to pass it as a one dimensional array

2453: .seealso: [](ch_matrices), `Mat`, `MatAssemblyBegin()`, `MatAssemblyEnd()`, `MatSetValues()`, `MatSetLocalToGlobalMapping()`,
2454:           `MatGetValuesLocal()`
2455: @*/
2456: PetscErrorCode MatSetValuesLocal(Mat mat, PetscInt nrow, const PetscInt irow[], PetscInt ncol, const PetscInt icol[], const PetscScalar y[], InsertMode addv)
2457: {
2458:   PetscFunctionBeginHot;
2461:   MatCheckPreallocated(mat, 1);
2462:   if (!nrow || !ncol) PetscFunctionReturn(PETSC_SUCCESS); /* no values to insert */
2463:   PetscAssertPointer(irow, 3);
2464:   PetscAssertPointer(icol, 5);
2465:   if (mat->insertmode == NOT_SET_VALUES) mat->insertmode = addv;
2466:   else PetscCheck(mat->insertmode == addv, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Cannot mix add values and insert values");
2467:   if (PetscDefined(USE_DEBUG)) {
2468:     PetscCheck(!mat->factortype, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
2469:     PetscCheck(mat->ops->setvalueslocal || mat->ops->setvalues, PETSC_COMM_SELF, PETSC_ERR_SUP, "Mat type %s", ((PetscObject)mat)->type_name);
2470:   }

2472:   if (mat->assembled) {
2473:     mat->was_assembled = PETSC_TRUE;
2474:     mat->assembled     = PETSC_FALSE;
2475:   }
2476:   PetscCall(PetscLogEventBegin(MAT_SetValues, mat, 0, 0, 0));
2477:   if (mat->ops->setvalueslocal) PetscUseTypeMethod(mat, setvalueslocal, nrow, irow, ncol, icol, y, addv);
2478:   else {
2479:     PetscInt        buf[8192], *bufr = NULL, *bufc = NULL;
2480:     const PetscInt *irowm, *icolm;

2482:     if ((!mat->rmap->mapping && !mat->cmap->mapping) || (nrow + ncol) <= (PetscInt)PETSC_STATIC_ARRAY_LENGTH(buf)) {
2483:       bufr  = buf;
2484:       bufc  = buf + nrow;
2485:       irowm = bufr;
2486:       icolm = bufc;
2487:     } else {
2488:       PetscCall(PetscMalloc2(nrow, &bufr, ncol, &bufc));
2489:       irowm = bufr;
2490:       icolm = bufc;
2491:     }
2492:     if (mat->rmap->mapping) PetscCall(ISLocalToGlobalMappingApply(mat->rmap->mapping, nrow, irow, bufr));
2493:     else irowm = irow;
2494:     if (mat->cmap->mapping) {
2495:       if (mat->cmap->mapping != mat->rmap->mapping || ncol != nrow || icol != irow) PetscCall(ISLocalToGlobalMappingApply(mat->cmap->mapping, ncol, icol, bufc));
2496:       else icolm = irowm;
2497:     } else icolm = icol;
2498:     PetscCall(MatSetValues(mat, nrow, irowm, ncol, icolm, y, addv));
2499:     if (bufr != buf) PetscCall(PetscFree2(bufr, bufc));
2500:   }
2501:   PetscCall(PetscLogEventEnd(MAT_SetValues, mat, 0, 0, 0));
2502:   PetscFunctionReturn(PETSC_SUCCESS);
2503: }

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

2509:   Not Collective

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

2521:   Level: intermediate

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

2527:   Calls to `MatSetValuesBlockedLocal()` with the `INSERT_VALUES` and `ADD_VALUES`
2528:   options cannot be mixed without intervening calls to the assembly
2529:   routines.

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

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

2540:   If `y` is a two-dimensional array use `reshape()` to pass it as a one dimensional array

2542: .seealso: [](ch_matrices), `Mat`, `MatSetBlockSize()`, `MatSetLocalToGlobalMapping()`, `MatAssemblyBegin()`, `MatAssemblyEnd()`,
2543:           `MatSetValuesLocal()`, `MatSetValuesBlocked()`
2544: @*/
2545: PetscErrorCode MatSetValuesBlockedLocal(Mat mat, PetscInt nrow, const PetscInt irow[], PetscInt ncol, const PetscInt icol[], const PetscScalar y[], InsertMode addv)
2546: {
2547:   PetscFunctionBeginHot;
2550:   MatCheckPreallocated(mat, 1);
2551:   if (!nrow || !ncol) PetscFunctionReturn(PETSC_SUCCESS); /* no values to insert */
2552:   PetscAssertPointer(irow, 3);
2553:   PetscAssertPointer(icol, 5);
2554:   if (mat->insertmode == NOT_SET_VALUES) mat->insertmode = addv;
2555:   else PetscCheck(mat->insertmode == addv, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Cannot mix add values and insert values");
2556:   if (PetscDefined(USE_DEBUG)) {
2557:     PetscCheck(!mat->factortype, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
2558:     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);
2559:   }

2561:   if (mat->assembled) {
2562:     mat->was_assembled = PETSC_TRUE;
2563:     mat->assembled     = PETSC_FALSE;
2564:   }
2565:   if (PetscUnlikelyDebug(mat->rmap->mapping)) { /* Condition on the mapping existing, because MatSetValuesBlockedLocal_IS does not require it to be set. */
2566:     PetscInt irbs, rbs;
2567:     PetscCall(MatGetBlockSizes(mat, &rbs, NULL));
2568:     PetscCall(ISLocalToGlobalMappingGetBlockSize(mat->rmap->mapping, &irbs));
2569:     PetscCheck(rbs == irbs, PetscObjectComm((PetscObject)mat), PETSC_ERR_SUP, "Different row block sizes! mat %" PetscInt_FMT ", row l2g map %" PetscInt_FMT, rbs, irbs);
2570:   }
2571:   if (PetscUnlikelyDebug(mat->cmap->mapping)) {
2572:     PetscInt icbs, cbs;
2573:     PetscCall(MatGetBlockSizes(mat, NULL, &cbs));
2574:     PetscCall(ISLocalToGlobalMappingGetBlockSize(mat->cmap->mapping, &icbs));
2575:     PetscCheck(cbs == icbs, PetscObjectComm((PetscObject)mat), PETSC_ERR_SUP, "Different col block sizes! mat %" PetscInt_FMT ", col l2g map %" PetscInt_FMT, cbs, icbs);
2576:   }
2577:   PetscCall(PetscLogEventBegin(MAT_SetValues, mat, 0, 0, 0));
2578:   if (mat->ops->setvaluesblockedlocal) PetscUseTypeMethod(mat, setvaluesblockedlocal, nrow, irow, ncol, icol, y, addv);
2579:   else {
2580:     PetscInt        buf[8192], *bufr = NULL, *bufc = NULL;
2581:     const PetscInt *irowm, *icolm;

2583:     if ((!mat->rmap->mapping && !mat->cmap->mapping) || (nrow + ncol) <= ((PetscInt)PETSC_STATIC_ARRAY_LENGTH(buf))) {
2584:       bufr  = buf;
2585:       bufc  = buf + nrow;
2586:       irowm = bufr;
2587:       icolm = bufc;
2588:     } else {
2589:       PetscCall(PetscMalloc2(nrow, &bufr, ncol, &bufc));
2590:       irowm = bufr;
2591:       icolm = bufc;
2592:     }
2593:     if (mat->rmap->mapping) PetscCall(ISLocalToGlobalMappingApplyBlock(mat->rmap->mapping, nrow, irow, bufr));
2594:     else irowm = irow;
2595:     if (mat->cmap->mapping) {
2596:       if (mat->cmap->mapping != mat->rmap->mapping || ncol != nrow || icol != irow) PetscCall(ISLocalToGlobalMappingApplyBlock(mat->cmap->mapping, ncol, icol, bufc));
2597:       else icolm = irowm;
2598:     } else icolm = icol;
2599:     PetscCall(MatSetValuesBlocked(mat, nrow, irowm, ncol, icolm, y, addv));
2600:     if (bufr != buf) PetscCall(PetscFree2(bufr, bufc));
2601:   }
2602:   PetscCall(PetscLogEventEnd(MAT_SetValues, mat, 0, 0, 0));
2603:   PetscFunctionReturn(PETSC_SUCCESS);
2604: }

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

2609:   Collective

2611:   Input Parameters:
2612: + mat - the matrix
2613: - x   - the vector to be multiplied

2615:   Output Parameter:
2616: . y - the result

2618:   Level: developer

2620:   Note:
2621:   The vectors `x` and `y` cannot be the same.  I.e., one cannot
2622:   call `MatMultDiagonalBlock`(A,y,y).

2624: .seealso: [](ch_matrices), `Mat`, `MatMult()`, `MatMultTranspose()`, `MatMultAdd()`, `MatMultTransposeAdd()`
2625: @*/
2626: PetscErrorCode MatMultDiagonalBlock(Mat mat, Vec x, Vec y)
2627: {
2628:   PetscFunctionBegin;

2634:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
2635:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
2636:   PetscCheck(x != y, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "x and y must be different vectors");
2637:   MatCheckPreallocated(mat, 1);

2639:   PetscUseTypeMethod(mat, multdiagonalblock, x, y);
2640:   PetscCall(PetscObjectStateIncrease((PetscObject)y));
2641:   PetscFunctionReturn(PETSC_SUCCESS);
2642: }

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

2647:   Neighbor-wise Collective

2649:   Input Parameters:
2650: + mat - the matrix
2651: - x   - the vector to be multiplied

2653:   Output Parameter:
2654: . y - the result

2656:   Level: beginner

2658:   Note:
2659:   The vectors `x` and `y` cannot be the same.  I.e., one cannot
2660:   call `MatMult`(A,y,y).

2662: .seealso: [](ch_matrices), `Mat`, `MatMultTranspose()`, `MatMultAdd()`, `MatMultTransposeAdd()`
2663: @*/
2664: PetscErrorCode MatMult(Mat mat, Vec x, Vec y)
2665: {
2666:   PetscFunctionBegin;
2670:   VecCheckAssembled(x);
2672:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
2673:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
2674:   PetscCheck(x != y, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "x and y must be different vectors");
2675:   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);
2676:   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);
2677:   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);
2678:   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);
2679:   PetscCall(VecSetErrorIfLocked(y, 3));
2680:   if (mat->erroriffailure) PetscCall(VecValidValues_Internal(x, 2, PETSC_TRUE));
2681:   MatCheckPreallocated(mat, 1);

2683:   PetscCall(VecLockReadPush(x));
2684:   PetscCall(PetscLogEventBegin(MAT_Mult, mat, x, y, 0));
2685:   PetscUseTypeMethod(mat, mult, x, y);
2686:   PetscCall(PetscLogEventEnd(MAT_Mult, mat, x, y, 0));
2687:   if (mat->erroriffailure) PetscCall(VecValidValues_Internal(y, 3, PETSC_FALSE));
2688:   PetscCall(VecLockReadPop(x));
2689:   PetscFunctionReturn(PETSC_SUCCESS);
2690: }

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

2695:   Neighbor-wise Collective

2697:   Input Parameters:
2698: + mat - the matrix
2699: - x   - the vector to be multiplied

2701:   Output Parameter:
2702: . y - the result

2704:   Level: beginner

2706:   Notes:
2707:   The vectors `x` and `y` cannot be the same.  I.e., one cannot
2708:   call `MatMultTranspose`(A,y,y).

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

2713: .seealso: [](ch_matrices), `Mat`, `MatMult()`, `MatMultAdd()`, `MatMultTransposeAdd()`, `MatMultHermitianTranspose()`, `MatTranspose()`
2714: @*/
2715: PetscErrorCode MatMultTranspose(Mat mat, Vec x, Vec y)
2716: {
2717:   PetscErrorCode (*op)(Mat, Vec, Vec) = NULL;

2719:   PetscFunctionBegin;
2723:   VecCheckAssembled(x);

2726:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
2727:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
2728:   PetscCheck(x != y, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "x and y must be different vectors");
2729:   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);
2730:   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);
2731:   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);
2732:   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);
2733:   if (mat->erroriffailure) PetscCall(VecValidValues_Internal(x, 2, PETSC_TRUE));
2734:   MatCheckPreallocated(mat, 1);

2736:   if (!mat->ops->multtranspose) {
2737:     if (mat->symmetric == PETSC_BOOL3_TRUE && mat->ops->mult) op = mat->ops->mult;
2738:     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);
2739:   } else op = mat->ops->multtranspose;
2740:   PetscCall(PetscLogEventBegin(MAT_MultTranspose, mat, x, y, 0));
2741:   PetscCall(VecLockReadPush(x));
2742:   PetscCall((*op)(mat, x, y));
2743:   PetscCall(VecLockReadPop(x));
2744:   PetscCall(PetscLogEventEnd(MAT_MultTranspose, mat, x, y, 0));
2745:   PetscCall(PetscObjectStateIncrease((PetscObject)y));
2746:   if (mat->erroriffailure) PetscCall(VecValidValues_Internal(y, 3, PETSC_FALSE));
2747:   PetscFunctionReturn(PETSC_SUCCESS);
2748: }

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

2753:   Neighbor-wise Collective

2755:   Input Parameters:
2756: + mat - the matrix
2757: - x   - the vector to be multiplied

2759:   Output Parameter:
2760: . y - the result

2762:   Level: beginner

2764:   Notes:
2765:   The vectors `x` and `y` cannot be the same.  I.e., one cannot
2766:   call `MatMultHermitianTranspose`(A,y,y).

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

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

2772: .seealso: [](ch_matrices), `Mat`, `MatMult()`, `MatMultAdd()`, `MatMultHermitianTransposeAdd()`, `MatMultTranspose()`
2773: @*/
2774: PetscErrorCode MatMultHermitianTranspose(Mat mat, Vec x, Vec y)
2775: {
2776:   PetscFunctionBegin;

2782:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
2783:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
2784:   PetscCheck(x != y, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "x and y must be different vectors");
2785:   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);
2786:   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);
2787:   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);
2788:   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);
2789:   MatCheckPreallocated(mat, 1);

2791:   PetscCall(PetscLogEventBegin(MAT_MultHermitianTranspose, mat, x, y, 0));
2792: #if defined(PETSC_USE_COMPLEX)
2793:   if (mat->ops->multhermitiantranspose || (mat->hermitian == PETSC_BOOL3_TRUE && mat->ops->mult)) {
2794:     PetscCall(VecLockReadPush(x));
2795:     if (mat->ops->multhermitiantranspose) PetscUseTypeMethod(mat, multhermitiantranspose, x, y);
2796:     else PetscUseTypeMethod(mat, mult, x, y);
2797:     PetscCall(VecLockReadPop(x));
2798:   } else {
2799:     Vec w;
2800:     PetscCall(VecDuplicate(x, &w));
2801:     PetscCall(VecCopy(x, w));
2802:     PetscCall(VecConjugate(w));
2803:     PetscCall(MatMultTranspose(mat, w, y));
2804:     PetscCall(VecDestroy(&w));
2805:     PetscCall(VecConjugate(y));
2806:   }
2807:   PetscCall(PetscObjectStateIncrease((PetscObject)y));
2808: #else
2809:   PetscCall(MatMultTranspose(mat, x, y));
2810: #endif
2811:   PetscCall(PetscLogEventEnd(MAT_MultHermitianTranspose, mat, x, y, 0));
2812:   PetscFunctionReturn(PETSC_SUCCESS);
2813: }

2815: /*@
2816:   MatMultAdd -  Computes $v3 = v2 + A * v1$.

2818:   Neighbor-wise Collective

2820:   Input Parameters:
2821: + mat - the matrix
2822: . v1  - the vector to be multiplied by `mat`
2823: - v2  - the vector to be added to the result

2825:   Output Parameter:
2826: . v3 - the result

2828:   Level: beginner

2830:   Note:
2831:   The vectors `v1` and `v3` cannot be the same.  I.e., one cannot
2832:   call `MatMultAdd`(A,v1,v2,v1).

2834: .seealso: [](ch_matrices), `Mat`, `MatMultTranspose()`, `MatMult()`, `MatMultTransposeAdd()`
2835: @*/
2836: PetscErrorCode MatMultAdd(Mat mat, Vec v1, Vec v2, Vec v3)
2837: {
2838:   PetscFunctionBegin;

2845:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
2846:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
2847:   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);
2848:   /* 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);
2849:      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); */
2850:   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);
2851:   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);
2852:   PetscCheck(v1 != v3, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_IDN, "v1 and v3 must be different vectors");
2853:   MatCheckPreallocated(mat, 1);

2855:   PetscCall(PetscLogEventBegin(MAT_MultAdd, mat, v1, v2, v3));
2856:   PetscCall(VecLockReadPush(v1));
2857:   PetscUseTypeMethod(mat, multadd, v1, v2, v3);
2858:   PetscCall(VecLockReadPop(v1));
2859:   PetscCall(PetscLogEventEnd(MAT_MultAdd, mat, v1, v2, v3));
2860:   PetscCall(PetscObjectStateIncrease((PetscObject)v3));
2861:   PetscFunctionReturn(PETSC_SUCCESS);
2862: }

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

2867:   Neighbor-wise Collective

2869:   Input Parameters:
2870: + mat - the matrix
2871: . v1  - the vector to be multiplied by the transpose of the matrix
2872: - v2  - the vector to be added to the result

2874:   Output Parameter:
2875: . v3 - the result

2877:   Level: beginner

2879:   Note:
2880:   The vectors `v1` and `v3` cannot be the same.  I.e., one cannot
2881:   call `MatMultTransposeAdd`(A,v1,v2,v1).

2883: .seealso: [](ch_matrices), `Mat`, `MatMultTranspose()`, `MatMultAdd()`, `MatMult()`
2884: @*/
2885: PetscErrorCode MatMultTransposeAdd(Mat mat, Vec v1, Vec v2, Vec v3)
2886: {
2887:   PetscErrorCode (*op)(Mat, Vec, Vec, Vec) = (!mat->ops->multtransposeadd && mat->symmetric) ? mat->ops->multadd : mat->ops->multtransposeadd;

2889:   PetscFunctionBegin;

2896:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
2897:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
2898:   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);
2899:   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);
2900:   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);
2901:   PetscCheck(v1 != v3, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_IDN, "v1 and v3 must be different vectors");
2902:   PetscCheck(op, PetscObjectComm((PetscObject)mat), PETSC_ERR_SUP, "Mat type %s", ((PetscObject)mat)->type_name);
2903:   MatCheckPreallocated(mat, 1);

2905:   PetscCall(PetscLogEventBegin(MAT_MultTransposeAdd, mat, v1, v2, v3));
2906:   PetscCall(VecLockReadPush(v1));
2907:   PetscCall((*op)(mat, v1, v2, v3));
2908:   PetscCall(VecLockReadPop(v1));
2909:   PetscCall(PetscLogEventEnd(MAT_MultTransposeAdd, mat, v1, v2, v3));
2910:   PetscCall(PetscObjectStateIncrease((PetscObject)v3));
2911:   PetscFunctionReturn(PETSC_SUCCESS);
2912: }

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

2917:   Neighbor-wise Collective

2919:   Input Parameters:
2920: + mat - the matrix
2921: . v1  - the vector to be multiplied by the Hermitian transpose
2922: - v2  - the vector to be added to the result

2924:   Output Parameter:
2925: . v3 - the result

2927:   Level: beginner

2929:   Note:
2930:   The vectors `v1` and `v3` cannot be the same.  I.e., one cannot
2931:   call `MatMultHermitianTransposeAdd`(A,v1,v2,v1).

2933: .seealso: [](ch_matrices), `Mat`, `MatMultHermitianTranspose()`, `MatMultTranspose()`, `MatMultAdd()`, `MatMult()`
2934: @*/
2935: PetscErrorCode MatMultHermitianTransposeAdd(Mat mat, Vec v1, Vec v2, Vec v3)
2936: {
2937:   PetscFunctionBegin;

2944:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
2945:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
2946:   PetscCheck(v1 != v3, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_IDN, "v1 and v3 must be different vectors");
2947:   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);
2948:   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);
2949:   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);
2950:   MatCheckPreallocated(mat, 1);

2952:   PetscCall(PetscLogEventBegin(MAT_MultHermitianTransposeAdd, mat, v1, v2, v3));
2953:   PetscCall(VecLockReadPush(v1));
2954:   if (mat->ops->multhermitiantransposeadd) PetscUseTypeMethod(mat, multhermitiantransposeadd, v1, v2, v3);
2955:   else {
2956:     Vec w, z;
2957:     PetscCall(VecDuplicate(v1, &w));
2958:     PetscCall(VecCopy(v1, w));
2959:     PetscCall(VecConjugate(w));
2960:     PetscCall(VecDuplicate(v3, &z));
2961:     PetscCall(MatMultTranspose(mat, w, z));
2962:     PetscCall(VecDestroy(&w));
2963:     PetscCall(VecConjugate(z));
2964:     if (v2 != v3) PetscCall(VecWAXPY(v3, 1.0, v2, z));
2965:     else PetscCall(VecAXPY(v3, 1.0, z));
2966:     PetscCall(VecDestroy(&z));
2967:   }
2968:   PetscCall(VecLockReadPop(v1));
2969:   PetscCall(PetscLogEventEnd(MAT_MultHermitianTransposeAdd, mat, v1, v2, v3));
2970:   PetscCall(PetscObjectStateIncrease((PetscObject)v3));
2971:   PetscFunctionReturn(PETSC_SUCCESS);
2972: }

2974: PetscErrorCode MatADot_Default(Mat mat, Vec x, Vec y, PetscScalar *val)
2975: {
2976:   PetscFunctionBegin;
2977:   if (!mat->dot_vec) PetscCall(MatCreateVecs(mat, &mat->dot_vec, NULL));
2978:   PetscCall(MatMult(mat, x, mat->dot_vec));
2979:   PetscCall(VecDot(mat->dot_vec, y, val));
2980:   PetscFunctionReturn(PETSC_SUCCESS);
2981: }

2983: PetscErrorCode MatANorm_Default(Mat mat, Vec x, PetscReal *val)
2984: {
2985:   PetscScalar sval;

2987:   PetscFunctionBegin;
2988:   PetscCall(MatADot_Default(mat, x, x, &sval));
2989:   PetscCheck(PetscRealPart(sval) >= 0.0, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONG, "Matrix argument is not positive definite");
2990:   PetscCheck(PetscAbsReal(PetscImaginaryPart(sval)) < 100 * PETSC_MACHINE_EPSILON, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONG, "Matrix argument is not Hermitian");
2991:   *val = PetscSqrtReal(PetscRealPart(sval));
2992:   PetscFunctionReturn(PETSC_SUCCESS);
2993: }

2995: /*@
2996:   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)
2997:   positive definite.

2999:   Collective

3001:   Input Parameters:
3002: + mat - matrix used to define the inner product
3003: . x   - first vector
3004: - y   - second vector

3006:   Output Parameter:
3007: . val - the dot product with respect to `A`

3009:   Level: intermediate

3011:   Note:
3012:   For complex vectors, `MatADot()` computes
3013: $$
3014:   val = (x,y)_A = y^H A x,
3015: $$
3016:   where $y^H$ denotes the conjugate transpose of `y`. Note that this corresponds to the "mathematicians" complex
3017:   inner product where the SECOND argument gets the complex conjugate.

3019: .seealso: [](ch_matrices), `Mat`, `MatANorm()`, `VecDot()`, `VecNorm()`, `MatMult()`, `MatMultAdd()`, `MatMultTransposeAdd()`
3020: @*/
3021: PetscErrorCode MatADot(Mat mat, Vec x, Vec y, PetscScalar *val)
3022: {
3023:   PetscFunctionBegin;
3027:   VecCheckAssembled(x);
3029:   VecCheckAssembled(y);
3032:   PetscAssertPointer(val, 4);
3033:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
3034:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
3035:   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);
3036:   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);
3037:   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);
3038:   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);
3039:   if (mat->erroriffailure) PetscCall(VecValidValues_Internal(x, 2, PETSC_TRUE));
3040:   if (mat->erroriffailure) PetscCall(VecValidValues_Internal(y, 3, PETSC_TRUE));
3041:   MatCheckPreallocated(mat, 1);

3043:   PetscCall(VecLockReadPush(x));
3044:   PetscCall(VecLockReadPush(y));
3045:   PetscCall(PetscLogEventBegin(MAT_ADot, mat, x, y, 0));
3046:   PetscUseTypeMethod(mat, adot, x, y, val);
3047:   PetscCall(PetscLogEventEnd(MAT_ADot, mat, x, y, 0));
3048:   PetscCall(VecLockReadPop(y));
3049:   PetscCall(VecLockReadPop(x));
3050:   PetscFunctionReturn(PETSC_SUCCESS);
3051: }

3053: /*@
3054:   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)
3055:   positive definite.

3057:   Collective

3059:   Input Parameters:
3060: + mat - matrix used to define norm
3061: - x   - the vector to compute the norm of

3063:   Output Parameter:
3064: . val - the norm with respect to `A`

3066:   Level: intermediate

3068:   Note:
3069:   For complex vectors, `MatANorm()` computes
3070: $$
3071:   val = (x,x)_A^{1/2} = (x^H A x)^{1/2},
3072: $$
3073:   where $x^H$ denotes the conjugate transpose of `x`.

3075: .seealso: [](ch_matrices), `Mat`, `MatADot()`, `VecDot()`, `VecNorm()`, `MatMult()`, `MatMultAdd()`, `MatMultTransposeAdd()`
3076: @*/
3077: PetscErrorCode MatANorm(Mat mat, Vec x, PetscReal *val)
3078: {
3079:   PetscFunctionBegin;
3083:   VecCheckAssembled(x);
3085:   PetscAssertPointer(val, 3);
3086:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
3087:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
3088:   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);
3089:   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);
3090:   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);
3091:   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);
3092:   if (mat->erroriffailure) PetscCall(VecValidValues_Internal(x, 2, PETSC_TRUE));
3093:   MatCheckPreallocated(mat, 1);

3095:   PetscCall(VecLockReadPush(x));
3096:   PetscCall(PetscLogEventBegin(MAT_ANorm, mat, x, 0, 0));
3097:   PetscUseTypeMethod(mat, anorm, x, val);
3098:   PetscCall(PetscLogEventEnd(MAT_ANorm, mat, x, 0, 0));
3099:   PetscCall(VecLockReadPop(x));
3100:   PetscFunctionReturn(PETSC_SUCCESS);
3101: }

3103: /*@
3104:   MatGetFactorType - gets the type of factorization a matrix is

3106:   Not Collective

3108:   Input Parameter:
3109: . mat - the matrix

3111:   Output Parameter:
3112: . 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`

3114:   Level: intermediate

3116: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatFactorType`, `MatGetFactor()`, `MatSetFactorType()`, `MAT_FACTOR_NONE`, `MAT_FACTOR_LU`, `MAT_FACTOR_CHOLESKY`, `MAT_FACTOR_ILU`,
3117:           `MAT_FACTOR_ICC`, `MAT_FACTOR_ILUDT`, `MAT_FACTOR_QR`
3118: @*/
3119: PetscErrorCode MatGetFactorType(Mat mat, MatFactorType *t)
3120: {
3121:   PetscFunctionBegin;
3124:   PetscAssertPointer(t, 2);
3125:   *t = mat->factortype;
3126:   PetscFunctionReturn(PETSC_SUCCESS);
3127: }

3129: /*@
3130:   MatSetFactorType - sets the type of factorization a matrix is

3132:   Logically Collective

3134:   Input Parameters:
3135: + mat - the matrix
3136: - 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`

3138:   Level: intermediate

3140: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatFactorType`, `MatGetFactor()`, `MatGetFactorType()`, `MAT_FACTOR_NONE`, `MAT_FACTOR_LU`, `MAT_FACTOR_CHOLESKY`, `MAT_FACTOR_ILU`,
3141:           `MAT_FACTOR_ICC`, `MAT_FACTOR_ILUDT`, `MAT_FACTOR_QR`
3142: @*/
3143: PetscErrorCode MatSetFactorType(Mat mat, MatFactorType t)
3144: {
3145:   PetscFunctionBegin;
3148:   mat->factortype = t;
3149:   PetscFunctionReturn(PETSC_SUCCESS);
3150: }

3152: /*@
3153:   MatGetInfo - Returns information about matrix storage (number of
3154:   nonzeros, memory, etc.).

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

3158:   Input Parameters:
3159: + mat  - the matrix
3160: - 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)

3162:   Output Parameter:
3163: . info - matrix information context

3165:   Options Database Key:
3166: . -mat_view ::ascii_info - print matrix info to `PETSC_STDOUT`

3168:   Level: intermediate

3170:   Notes:
3171:   The `MatInfo` context contains a variety of matrix data, including
3172:   number of nonzeros allocated and used, number of mallocs during
3173:   matrix assembly, etc.  Additional information for factored matrices
3174:   is provided (such as the fill ratio, number of mallocs during
3175:   factorization, etc.).

3177:   Example:
3178:   See the file ${PETSC_DIR}/include/petscmat.h for a complete list of
3179:   data within the `MatInfo` context.  For example,
3180: .vb
3181:       MatInfo info;
3182:       Mat     A;
3183:       double  mal, nz_a, nz_u;

3185:       MatGetInfo(A, MAT_LOCAL, &info);
3186:       mal  = info.mallocs;
3187:       nz_a = info.nz_allocated;
3188: .ve

3190: .seealso: [](ch_matrices), `Mat`, `MatInfo`, `MatStashGetInfo()`
3191: @*/
3192: PetscErrorCode MatGetInfo(Mat mat, MatInfoType flag, MatInfo *info)
3193: {
3194:   PetscFunctionBegin;
3197:   PetscAssertPointer(info, 3);
3198:   MatCheckPreallocated(mat, 1);
3199:   PetscUseTypeMethod(mat, getinfo, flag, info);
3200:   PetscFunctionReturn(PETSC_SUCCESS);
3201: }

3203: /*
3204:    This is used by external packages where it is not easy to get the info from the actual
3205:    matrix factorization.
3206: */
3207: PetscErrorCode MatGetInfo_External(Mat A, MatInfoType flag, MatInfo *info)
3208: {
3209:   PetscFunctionBegin;
3210:   PetscCall(PetscMemzero(info, sizeof(MatInfo)));
3211:   PetscFunctionReturn(PETSC_SUCCESS);
3212: }

3214: /*@
3215:   MatLUFactor - Performs in-place LU factorization of matrix.

3217:   Collective

3219:   Input Parameters:
3220: + mat  - the matrix
3221: . row  - row permutation
3222: . col  - column permutation
3223: - info - options for factorization, includes
3224: .vb
3225:           fill - expected fill as ratio of original fill.
3226:           dtcol - pivot tolerance (0 no pivot, 1 full column pivoting)
3227:                    Run with the option -info to determine an optimal value to use
3228: .ve

3230:   Level: developer

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

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

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

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

3246: .seealso: [](ch_matrices), [Matrix Factorization](sec_matfactor), `Mat`, `MatFactorType`, `MatLUFactorSymbolic()`, `MatLUFactorNumeric()`, `MatCholeskyFactor()`,
3247:           `MatGetOrdering()`, `MatSetUnfactored()`, `MatFactorInfo`, `MatGetFactor()`
3248: @*/
3249: PetscErrorCode MatLUFactor(Mat mat, IS row, IS col, const MatFactorInfo *info)
3250: {
3251:   MatFactorInfo tinfo;

3253:   PetscFunctionBegin;
3257:   if (info) PetscAssertPointer(info, 4);
3259:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
3260:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
3261:   MatCheckPreallocated(mat, 1);
3262:   if (!info) {
3263:     PetscCall(MatFactorInfoInitialize(&tinfo));
3264:     info = &tinfo;
3265:   }

3267:   PetscCall(PetscLogEventBegin(MAT_LUFactor, mat, row, col, 0));
3268:   PetscUseTypeMethod(mat, lufactor, row, col, info);
3269:   PetscCall(PetscLogEventEnd(MAT_LUFactor, mat, row, col, 0));
3270:   PetscCall(PetscObjectStateIncrease((PetscObject)mat));
3271:   PetscFunctionReturn(PETSC_SUCCESS);
3272: }

3274: /*@
3275:   MatILUFactor - Performs in-place ILU factorization of matrix.

3277:   Collective

3279:   Input Parameters:
3280: + mat  - the matrix
3281: . row  - row permutation
3282: . col  - column permutation
3283: - info - structure containing
3284: .vb
3285:       levels - number of levels of fill.
3286:       expected fill - as ratio of original fill.
3287:       1 or 0 - indicating force fill on diagonal (improves robustness for matrices
3288:                 missing diagonal entries)
3289: .ve

3291:   Level: developer

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

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

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

3305: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatILUFactorSymbolic()`, `MatLUFactorNumeric()`, `MatCholeskyFactor()`, `MatFactorInfo`
3306: @*/
3307: PetscErrorCode MatILUFactor(Mat mat, IS row, IS col, const MatFactorInfo *info)
3308: {
3309:   PetscFunctionBegin;
3313:   PetscAssertPointer(info, 4);
3315:   PetscCheck(mat->rmap->N == mat->cmap->N, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONG, "matrix must be square");
3316:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
3317:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
3318:   MatCheckPreallocated(mat, 1);

3320:   PetscCall(PetscLogEventBegin(MAT_ILUFactor, mat, row, col, 0));
3321:   PetscUseTypeMethod(mat, ilufactor, row, col, info);
3322:   PetscCall(PetscLogEventEnd(MAT_ILUFactor, mat, row, col, 0));
3323:   PetscCall(PetscObjectStateIncrease((PetscObject)mat));
3324:   PetscFunctionReturn(PETSC_SUCCESS);
3325: }

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

3331:   Collective

3333:   Input Parameters:
3334: + fact - the factor matrix obtained with `MatGetFactor()`
3335: . mat  - the matrix
3336: . row  - the row permutation
3337: . col  - the column permutation
3338: - info - options for factorization, includes
3339: .vb
3340:           fill - expected fill as ratio of original fill. Run with the option -info to determine an optimal value to use
3341:           dtcol - pivot tolerance (0 no pivot, 1 full column pivoting)
3342: .ve

3344:   Level: developer

3346:   Notes:
3347:   See [Matrix Factorization](sec_matfactor) for additional information about factorizations

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

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

3356: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatGetFactor()`, `MatLUFactor()`, `MatLUFactorNumeric()`, `MatCholeskyFactor()`, `MatFactorInfo`, `MatFactorInfoInitialize()`
3357: @*/
3358: PetscErrorCode MatLUFactorSymbolic(Mat fact, Mat mat, IS row, IS col, const MatFactorInfo *info)
3359: {
3360:   MatFactorInfo tinfo;

3362:   PetscFunctionBegin;
3367:   if (info) PetscAssertPointer(info, 5);
3370:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
3371:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
3372:   MatCheckPreallocated(mat, 2);
3373:   if (!info) {
3374:     PetscCall(MatFactorInfoInitialize(&tinfo));
3375:     info = &tinfo;
3376:   }

3378:   if (!fact->trivialsymbolic) PetscCall(PetscLogEventBegin(MAT_LUFactorSymbolic, mat, row, col, 0));
3379:   PetscUseTypeMethod(fact, lufactorsymbolic, mat, row, col, info);
3380:   if (!fact->trivialsymbolic) PetscCall(PetscLogEventEnd(MAT_LUFactorSymbolic, mat, row, col, 0));
3381:   PetscCall(PetscObjectStateIncrease((PetscObject)fact));
3382:   PetscFunctionReturn(PETSC_SUCCESS);
3383: }

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

3389:   Collective

3391:   Input Parameters:
3392: + fact - the factor matrix obtained with `MatGetFactor()`
3393: . mat  - the matrix
3394: - info - options for factorization

3396:   Level: developer

3398:   Notes:
3399:   See `MatLUFactor()` for in-place factorization.  See
3400:   `MatCholeskyFactorNumeric()` for the symmetric, positive definite case.

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

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

3409: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatGetFactor()`, `MatFactorInfo`, `MatLUFactorSymbolic()`, `MatLUFactor()`, `MatCholeskyFactor()`
3410: @*/
3411: PetscErrorCode MatLUFactorNumeric(Mat fact, Mat mat, const MatFactorInfo *info)
3412: {
3413:   MatFactorInfo tinfo;

3415:   PetscFunctionBegin;
3420:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
3421:   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,
3422:              mat->rmap->N, (fact)->rmap->N, mat->cmap->N, (fact)->cmap->N);

3424:   MatCheckPreallocated(mat, 2);
3425:   if (!info) {
3426:     PetscCall(MatFactorInfoInitialize(&tinfo));
3427:     info = &tinfo;
3428:   }

3430:   if (!fact->trivialsymbolic) PetscCall(PetscLogEventBegin(MAT_LUFactorNumeric, mat, fact, 0, 0));
3431:   else PetscCall(PetscLogEventBegin(MAT_LUFactor, mat, fact, 0, 0));
3432:   PetscUseTypeMethod(fact, lufactornumeric, mat, info);
3433:   if (!fact->trivialsymbolic) PetscCall(PetscLogEventEnd(MAT_LUFactorNumeric, mat, fact, 0, 0));
3434:   else PetscCall(PetscLogEventEnd(MAT_LUFactor, mat, fact, 0, 0));
3435:   PetscCall(MatViewFromOptions(fact, NULL, "-mat_factor_view"));
3436:   PetscCall(PetscObjectStateIncrease((PetscObject)fact));
3437:   PetscFunctionReturn(PETSC_SUCCESS);
3438: }

3440: /*@
3441:   MatCholeskyFactor - Performs in-place Cholesky factorization of a
3442:   symmetric matrix.

3444:   Collective

3446:   Input Parameters:
3447: + mat  - the matrix
3448: . perm - row and column permutations
3449: - info - expected fill as ratio of original fill

3451:   Level: developer

3453:   Notes:
3454:   See `MatLUFactor()` for the nonsymmetric case.  See also `MatGetFactor()`,
3455:   `MatCholeskyFactorSymbolic()`, and `MatCholeskyFactorNumeric()`.

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

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

3464: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatGetFactor()`, `MatFactorInfo`, `MatLUFactor()`, `MatCholeskyFactorSymbolic()`, `MatCholeskyFactorNumeric()`,
3465:           `MatGetOrdering()`
3466: @*/
3467: PetscErrorCode MatCholeskyFactor(Mat mat, IS perm, const MatFactorInfo *info)
3468: {
3469:   MatFactorInfo tinfo;

3471:   PetscFunctionBegin;
3474:   if (info) PetscAssertPointer(info, 3);
3476:   PetscCheck(mat->rmap->N == mat->cmap->N, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONG, "Matrix must be square");
3477:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
3478:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
3479:   MatCheckPreallocated(mat, 1);
3480:   if (!info) {
3481:     PetscCall(MatFactorInfoInitialize(&tinfo));
3482:     info = &tinfo;
3483:   }

3485:   PetscCall(PetscLogEventBegin(MAT_CholeskyFactor, mat, perm, 0, 0));
3486:   PetscUseTypeMethod(mat, choleskyfactor, perm, info);
3487:   PetscCall(PetscLogEventEnd(MAT_CholeskyFactor, mat, perm, 0, 0));
3488:   PetscCall(PetscObjectStateIncrease((PetscObject)mat));
3489:   PetscFunctionReturn(PETSC_SUCCESS);
3490: }

3492: /*@
3493:   MatCholeskyFactorSymbolic - Performs symbolic Cholesky factorization
3494:   of a symmetric matrix.

3496:   Collective

3498:   Input Parameters:
3499: + fact - the factor matrix obtained with `MatGetFactor()`
3500: . mat  - the matrix
3501: . perm - row and column permutations
3502: - info - options for factorization, includes
3503: .vb
3504:           fill - expected fill as ratio of original fill.
3505:           dtcol - pivot tolerance (0 no pivot, 1 full column pivoting)
3506:                    Run with the option -info to determine an optimal value to use
3507: .ve

3509:   Level: developer

3511:   Notes:
3512:   See `MatLUFactorSymbolic()` for the nonsymmetric case.  See also
3513:   `MatCholeskyFactor()` and `MatCholeskyFactorNumeric()`.

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

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

3522: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatFactorInfo`, `MatGetFactor()`, `MatLUFactorSymbolic()`, `MatCholeskyFactor()`, `MatCholeskyFactorNumeric()`,
3523:           `MatGetOrdering()`
3524: @*/
3525: PetscErrorCode MatCholeskyFactorSymbolic(Mat fact, Mat mat, IS perm, const MatFactorInfo *info)
3526: {
3527:   MatFactorInfo tinfo;

3529:   PetscFunctionBegin;
3533:   if (info) PetscAssertPointer(info, 4);
3536:   PetscCheck(mat->rmap->N == mat->cmap->N, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONG, "Matrix must be square");
3537:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
3538:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
3539:   MatCheckPreallocated(mat, 2);
3540:   if (!info) {
3541:     PetscCall(MatFactorInfoInitialize(&tinfo));
3542:     info = &tinfo;
3543:   }

3545:   if (!fact->trivialsymbolic) PetscCall(PetscLogEventBegin(MAT_CholeskyFactorSymbolic, mat, perm, 0, 0));
3546:   PetscUseTypeMethod(fact, choleskyfactorsymbolic, mat, perm, info);
3547:   if (!fact->trivialsymbolic) PetscCall(PetscLogEventEnd(MAT_CholeskyFactorSymbolic, mat, perm, 0, 0));
3548:   PetscCall(PetscObjectStateIncrease((PetscObject)fact));
3549:   PetscFunctionReturn(PETSC_SUCCESS);
3550: }

3552: /*@
3553:   MatCholeskyFactorNumeric - Performs numeric Cholesky factorization
3554:   of a symmetric matrix. Call this routine after first calling `MatGetFactor()` and
3555:   `MatCholeskyFactorSymbolic()`.

3557:   Collective

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

3564:   Level: developer

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

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

3574: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatFactorInfo`, `MatGetFactor()`, `MatCholeskyFactorSymbolic()`, `MatCholeskyFactor()`, `MatLUFactorNumeric()`
3575: @*/
3576: PetscErrorCode MatCholeskyFactorNumeric(Mat fact, Mat mat, const MatFactorInfo *info)
3577: {
3578:   MatFactorInfo tinfo;

3580:   PetscFunctionBegin;
3585:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
3586:   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,
3587:              mat->rmap->N, (fact)->rmap->N, mat->cmap->N, (fact)->cmap->N);
3588:   MatCheckPreallocated(mat, 2);
3589:   if (!info) {
3590:     PetscCall(MatFactorInfoInitialize(&tinfo));
3591:     info = &tinfo;
3592:   }

3594:   if (!fact->trivialsymbolic) PetscCall(PetscLogEventBegin(MAT_CholeskyFactorNumeric, mat, fact, 0, 0));
3595:   else PetscCall(PetscLogEventBegin(MAT_CholeskyFactor, mat, fact, 0, 0));
3596:   PetscUseTypeMethod(fact, choleskyfactornumeric, mat, info);
3597:   if (!fact->trivialsymbolic) PetscCall(PetscLogEventEnd(MAT_CholeskyFactorNumeric, mat, fact, 0, 0));
3598:   else PetscCall(PetscLogEventEnd(MAT_CholeskyFactor, mat, fact, 0, 0));
3599:   PetscCall(MatViewFromOptions(fact, NULL, "-mat_factor_view"));
3600:   PetscCall(PetscObjectStateIncrease((PetscObject)fact));
3601:   PetscFunctionReturn(PETSC_SUCCESS);
3602: }

3604: /*@
3605:   MatQRFactor - Performs in-place QR factorization of matrix.

3607:   Collective

3609:   Input Parameters:
3610: + mat  - the matrix
3611: . col  - column permutation
3612: - info - options for factorization, includes
3613: .vb
3614:           fill - expected fill as ratio of original fill.
3615:           dtcol - pivot tolerance (0 no pivot, 1 full column pivoting)
3616:                    Run with the option -info to determine an optimal value to use
3617: .ve

3619:   Level: developer

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

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

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

3632: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatFactorInfo`, `MatGetFactor()`, `MatQRFactorSymbolic()`, `MatQRFactorNumeric()`, `MatLUFactor()`,
3633:           `MatSetUnfactored()`
3634: @*/
3635: PetscErrorCode MatQRFactor(Mat mat, IS col, const MatFactorInfo *info)
3636: {
3637:   PetscFunctionBegin;
3640:   if (info) PetscAssertPointer(info, 3);
3642:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
3643:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
3644:   MatCheckPreallocated(mat, 1);
3645:   PetscCall(PetscLogEventBegin(MAT_QRFactor, mat, col, 0, 0));
3646:   PetscUseMethod(mat, "MatQRFactor_C", (Mat, IS, const MatFactorInfo *), (mat, col, info));
3647:   PetscCall(PetscLogEventEnd(MAT_QRFactor, mat, col, 0, 0));
3648:   PetscCall(PetscObjectStateIncrease((PetscObject)mat));
3649:   PetscFunctionReturn(PETSC_SUCCESS);
3650: }

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

3656:   Collective

3658:   Input Parameters:
3659: + fact - the factor matrix obtained with `MatGetFactor()`
3660: . mat  - the matrix
3661: . col  - column permutation
3662: - info - options for factorization, includes
3663: .vb
3664:           fill - expected fill as ratio of original fill.
3665:           dtcol - pivot tolerance (0 no pivot, 1 full column pivoting)
3666:                    Run with the option -info to determine an optimal value to use
3667: .ve

3669:   Level: developer

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

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

3679: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatGetFactor()`, `MatFactorInfo`, `MatQRFactor()`, `MatQRFactorNumeric()`, `MatLUFactor()`, `MatFactorInfoInitialize()`
3680: @*/
3681: PetscErrorCode MatQRFactorSymbolic(Mat fact, Mat mat, IS col, const MatFactorInfo *info)
3682: {
3683:   MatFactorInfo tinfo;

3685:   PetscFunctionBegin;
3689:   if (info) PetscAssertPointer(info, 4);
3692:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
3693:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
3694:   MatCheckPreallocated(mat, 2);
3695:   if (!info) {
3696:     PetscCall(MatFactorInfoInitialize(&tinfo));
3697:     info = &tinfo;
3698:   }

3700:   if (!fact->trivialsymbolic) PetscCall(PetscLogEventBegin(MAT_QRFactorSymbolic, fact, mat, col, 0));
3701:   PetscUseMethod(fact, "MatQRFactorSymbolic_C", (Mat, Mat, IS, const MatFactorInfo *), (fact, mat, col, info));
3702:   if (!fact->trivialsymbolic) PetscCall(PetscLogEventEnd(MAT_QRFactorSymbolic, fact, mat, col, 0));
3703:   PetscCall(PetscObjectStateIncrease((PetscObject)fact));
3704:   PetscFunctionReturn(PETSC_SUCCESS);
3705: }

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

3711:   Collective

3713:   Input Parameters:
3714: + fact - the factor matrix obtained with `MatGetFactor()`
3715: . mat  - the matrix
3716: - info - options for factorization

3718:   Level: developer

3720:   Notes:
3721:   See `MatQRFactor()` for in-place factorization.

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

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

3730: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatFactorInfo`, `MatGetFactor()`, `MatQRFactor()`, `MatQRFactorSymbolic()`, `MatLUFactor()`
3731: @*/
3732: PetscErrorCode MatQRFactorNumeric(Mat fact, Mat mat, const MatFactorInfo *info)
3733: {
3734:   MatFactorInfo tinfo;

3736:   PetscFunctionBegin;
3741:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
3742:   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,
3743:              mat->rmap->N, (fact)->rmap->N, mat->cmap->N, (fact)->cmap->N);

3745:   MatCheckPreallocated(mat, 2);
3746:   if (!info) {
3747:     PetscCall(MatFactorInfoInitialize(&tinfo));
3748:     info = &tinfo;
3749:   }

3751:   if (!fact->trivialsymbolic) PetscCall(PetscLogEventBegin(MAT_QRFactorNumeric, mat, fact, 0, 0));
3752:   else PetscCall(PetscLogEventBegin(MAT_QRFactor, mat, fact, 0, 0));
3753:   PetscUseMethod(fact, "MatQRFactorNumeric_C", (Mat, Mat, const MatFactorInfo *), (fact, mat, info));
3754:   if (!fact->trivialsymbolic) PetscCall(PetscLogEventEnd(MAT_QRFactorNumeric, mat, fact, 0, 0));
3755:   else PetscCall(PetscLogEventEnd(MAT_QRFactor, mat, fact, 0, 0));
3756:   PetscCall(MatViewFromOptions(fact, NULL, "-mat_factor_view"));
3757:   PetscCall(PetscObjectStateIncrease((PetscObject)fact));
3758:   PetscFunctionReturn(PETSC_SUCCESS);
3759: }

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

3764:   Neighbor-wise Collective

3766:   Input Parameters:
3767: + mat - the factored matrix
3768: - b   - the right-hand-side vector

3770:   Output Parameter:
3771: . x - the result vector

3773:   Level: developer

3775:   Notes:
3776:   The vectors `b` and `x` cannot be the same.  I.e., one cannot
3777:   call `MatSolve`(A,x,x).

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

3783: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatGetFactor()`, `MatLUFactor()`, `MatSolveAdd()`, `MatSolveTranspose()`, `MatSolveTransposeAdd()`
3784: @*/
3785: PetscErrorCode MatSolve(Mat mat, Vec b, Vec x)
3786: {
3787:   PetscFunctionBegin;
3792:   PetscCheckSameComm(mat, 1, b, 2);
3793:   PetscCheckSameComm(mat, 1, x, 3);
3794:   PetscCheck(x != b, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_IDN, "x and b must be different vectors");
3795:   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);
3796:   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);
3797:   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);
3798:   if (!mat->rmap->N && !mat->cmap->N) PetscFunctionReturn(PETSC_SUCCESS);
3799:   MatCheckPreallocated(mat, 1);

3801:   PetscCall(PetscLogEventBegin(MAT_Solve, mat, b, x, 0));
3802:   PetscCall(VecFlag(x, mat->factorerrortype));
3803:   if (mat->factorerrortype) PetscCall(PetscInfo(mat, "MatFactorError %d\n", mat->factorerrortype));
3804:   else PetscUseTypeMethod(mat, solve, b, x);
3805:   PetscCall(PetscLogEventEnd(MAT_Solve, mat, b, x, 0));
3806:   PetscCall(PetscObjectStateIncrease((PetscObject)x));
3807:   PetscFunctionReturn(PETSC_SUCCESS);
3808: }

3810: static PetscErrorCode MatMatSolve_Basic(Mat A, Mat B, Mat X, PetscBool trans)
3811: {
3812:   Vec      b, x;
3813:   PetscInt N, i;
3814:   PetscErrorCode (*f)(Mat, Vec, Vec);
3815:   PetscBool Abound, Bneedconv = PETSC_FALSE, Xneedconv = PETSC_FALSE;

3817:   PetscFunctionBegin;
3818:   if (A->factorerrortype) {
3819:     PetscCall(PetscInfo(A, "MatFactorError %d\n", A->factorerrortype));
3820:     PetscCall(MatSetInf(X));
3821:     PetscFunctionReturn(PETSC_SUCCESS);
3822:   }
3823:   f = (!trans || (!A->ops->solvetranspose && A->symmetric)) ? A->ops->solve : A->ops->solvetranspose;
3824:   PetscCheck(f, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "Mat type %s", ((PetscObject)A)->type_name);
3825:   PetscCall(MatBoundToCPU(A, &Abound));
3826:   if (!Abound) {
3827:     PetscCall(PetscObjectTypeCompareAny((PetscObject)B, &Bneedconv, MATSEQDENSE, MATMPIDENSE, ""));
3828:     PetscCall(PetscObjectTypeCompareAny((PetscObject)X, &Xneedconv, MATSEQDENSE, MATMPIDENSE, ""));
3829:   }
3830: #if PetscDefined(HAVE_CUDA)
3831:   if (Bneedconv) PetscCall(MatConvert(B, MATDENSECUDA, MAT_INPLACE_MATRIX, &B));
3832:   if (Xneedconv) PetscCall(MatConvert(X, MATDENSECUDA, MAT_INPLACE_MATRIX, &X));
3833: #elif PetscDefined(HAVE_HIP)
3834:   if (Bneedconv) PetscCall(MatConvert(B, MATDENSEHIP, MAT_INPLACE_MATRIX, &B));
3835:   if (Xneedconv) PetscCall(MatConvert(X, MATDENSEHIP, MAT_INPLACE_MATRIX, &X));
3836: #endif
3837:   PetscCall(MatGetSize(B, NULL, &N));
3838:   for (i = 0; i < N; i++) {
3839:     PetscCall(MatDenseGetColumnVecRead(B, i, &b));
3840:     PetscCall(MatDenseGetColumnVecWrite(X, i, &x));
3841:     PetscCall((*f)(A, b, x));
3842:     PetscCall(MatDenseRestoreColumnVecWrite(X, i, &x));
3843:     PetscCall(MatDenseRestoreColumnVecRead(B, i, &b));
3844:   }
3845:   if (Bneedconv) PetscCall(MatConvert(B, MATDENSE, MAT_INPLACE_MATRIX, &B));
3846:   if (Xneedconv) PetscCall(MatConvert(X, MATDENSE, MAT_INPLACE_MATRIX, &X));
3847:   PetscFunctionReturn(PETSC_SUCCESS);
3848: }

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

3853:   Neighbor-wise Collective

3855:   Input Parameters:
3856: + A - the factored matrix
3857: - B - the right-hand-side matrix `MATDENSE` (or sparse `MATAIJ`-- when using MUMPS)

3859:   Output Parameter:
3860: . X - the result matrix (dense matrix)

3862:   Level: developer

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

3868: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatGetFactor()`, `MatSolve()`, `MatMatSolveTranspose()`, `MatLUFactor()`, `MatCholeskyFactor()`
3869: @*/
3870: PetscErrorCode MatMatSolve(Mat A, Mat B, Mat X)
3871: {
3872:   PetscFunctionBegin;
3877:   PetscCheckSameComm(A, 1, B, 2);
3878:   PetscCheckSameComm(A, 1, X, 3);
3879:   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);
3880:   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);
3881:   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");
3882:   if (!A->rmap->N && !A->cmap->N) PetscFunctionReturn(PETSC_SUCCESS);
3883:   MatCheckPreallocated(A, 1);

3885:   PetscCall(PetscLogEventBegin(MAT_MatSolve, A, B, X, 0));
3886:   if (!A->ops->matsolve) {
3887:     PetscCall(PetscInfo(A, "Mat type %s using basic MatMatSolve\n", ((PetscObject)A)->type_name));
3888:     PetscCall(MatMatSolve_Basic(A, B, X, PETSC_FALSE));
3889:   } else PetscUseTypeMethod(A, matsolve, B, X);
3890:   PetscCall(PetscLogEventEnd(MAT_MatSolve, A, B, X, 0));
3891:   PetscCall(PetscObjectStateIncrease((PetscObject)X));
3892:   PetscFunctionReturn(PETSC_SUCCESS);
3893: }

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

3898:   Neighbor-wise Collective

3900:   Input Parameters:
3901: + A - the factored matrix
3902: - B - the right-hand-side matrix  (`MATDENSE` matrix)

3904:   Output Parameter:
3905: . X - the result matrix (dense matrix)

3907:   Level: developer

3909:   Note:
3910:   The matrices `B` and `X` cannot be the same.  I.e., one cannot
3911:   call `MatMatSolveTranspose`(A,X,X).

3913: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatGetFactor()`, `MatSolveTranspose()`, `MatMatSolve()`, `MatLUFactor()`, `MatCholeskyFactor()`
3914: @*/
3915: PetscErrorCode MatMatSolveTranspose(Mat A, Mat B, Mat X)
3916: {
3917:   PetscFunctionBegin;
3922:   PetscCheckSameComm(A, 1, B, 2);
3923:   PetscCheckSameComm(A, 1, X, 3);
3924:   PetscCheck(X != B, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_IDN, "X and B must be different matrices");
3925:   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);
3926:   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);
3927:   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);
3928:   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");
3929:   if (!A->rmap->N && !A->cmap->N) PetscFunctionReturn(PETSC_SUCCESS);
3930:   MatCheckPreallocated(A, 1);

3932:   PetscCall(PetscLogEventBegin(MAT_MatSolve, A, B, X, 0));
3933:   if (!A->ops->matsolvetranspose) {
3934:     PetscCall(PetscInfo(A, "Mat type %s using basic MatMatSolveTranspose\n", ((PetscObject)A)->type_name));
3935:     PetscCall(MatMatSolve_Basic(A, B, X, PETSC_TRUE));
3936:   } else PetscUseTypeMethod(A, matsolvetranspose, B, X);
3937:   PetscCall(PetscLogEventEnd(MAT_MatSolve, A, B, X, 0));
3938:   PetscCall(PetscObjectStateIncrease((PetscObject)X));
3939:   PetscFunctionReturn(PETSC_SUCCESS);
3940: }

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

3945:   Neighbor-wise Collective

3947:   Input Parameters:
3948: + A  - the factored matrix
3949: - Bt - the transpose of right-hand-side matrix as a `MATDENSE`

3951:   Output Parameter:
3952: . X - the result matrix (dense matrix)

3954:   Level: developer

3956:   Note:
3957:   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
3958:   format on the host processor and call `MatMatTransposeSolve()` to implement MUMPS' `MatMatSolve()`.

3960: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatMatSolve()`, `MatMatSolveTranspose()`, `MatLUFactor()`, `MatCholeskyFactor()`
3961: @*/
3962: PetscErrorCode MatMatTransposeSolve(Mat A, Mat Bt, Mat X)
3963: {
3964:   PetscFunctionBegin;
3969:   PetscCheckSameComm(A, 1, Bt, 2);
3970:   PetscCheckSameComm(A, 1, X, 3);

3972:   PetscCheck(X != Bt, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_IDN, "X and B must be different matrices");
3973:   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);
3974:   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);
3975:   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");
3976:   if (!A->rmap->N && !A->cmap->N) PetscFunctionReturn(PETSC_SUCCESS);
3977:   PetscCheck(A->factortype, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_WRONGSTATE, "Unfactored matrix");
3978:   MatCheckPreallocated(A, 1);

3980:   PetscCall(PetscLogEventBegin(MAT_MatTrSolve, A, Bt, X, 0));
3981:   PetscUseTypeMethod(A, mattransposesolve, Bt, X);
3982:   PetscCall(PetscLogEventEnd(MAT_MatTrSolve, A, Bt, X, 0));
3983:   PetscCall(PetscObjectStateIncrease((PetscObject)X));
3984:   PetscFunctionReturn(PETSC_SUCCESS);
3985: }

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

3991:   Neighbor-wise Collective

3993:   Input Parameters:
3994: + mat - the factored matrix
3995: - b   - the right-hand-side vector

3997:   Output Parameter:
3998: . x - the result vector

4000:   Level: developer

4002:   Notes:
4003:   `MatSolve()` should be used for most applications, as it performs
4004:   a forward solve followed by a backward solve.

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

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

4015: .seealso: [](ch_matrices), `Mat`, `MatBackwardSolve()`, `MatGetFactor()`, `MatSolve()`
4016: @*/
4017: PetscErrorCode MatForwardSolve(Mat mat, Vec b, Vec x)
4018: {
4019:   PetscFunctionBegin;
4024:   PetscCheckSameComm(mat, 1, b, 2);
4025:   PetscCheckSameComm(mat, 1, x, 3);
4026:   PetscCheck(x != b, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_IDN, "x and b must be different vectors");
4027:   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);
4028:   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);
4029:   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);
4030:   if (!mat->rmap->N && !mat->cmap->N) PetscFunctionReturn(PETSC_SUCCESS);
4031:   MatCheckPreallocated(mat, 1);

4033:   PetscCall(PetscLogEventBegin(MAT_ForwardSolve, mat, b, x, 0));
4034:   PetscUseTypeMethod(mat, forwardsolve, b, x);
4035:   PetscCall(PetscLogEventEnd(MAT_ForwardSolve, mat, b, x, 0));
4036:   PetscCall(PetscObjectStateIncrease((PetscObject)x));
4037:   PetscFunctionReturn(PETSC_SUCCESS);
4038: }

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

4044:   Neighbor-wise Collective

4046:   Input Parameters:
4047: + mat - the factored matrix
4048: - b   - the right-hand-side vector

4050:   Output Parameter:
4051: . x - the result vector

4053:   Level: developer

4055:   Notes:
4056:   `MatSolve()` should be used for most applications, as it performs
4057:   a forward solve followed by a backward solve.

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

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

4068: .seealso: [](ch_matrices), `Mat`, `MatForwardSolve()`, `MatGetFactor()`, `MatSolve()`
4069: @*/
4070: PetscErrorCode MatBackwardSolve(Mat mat, Vec b, Vec x)
4071: {
4072:   PetscFunctionBegin;
4077:   PetscCheckSameComm(mat, 1, b, 2);
4078:   PetscCheckSameComm(mat, 1, x, 3);
4079:   PetscCheck(x != b, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_IDN, "x and b must be different vectors");
4080:   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);
4081:   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);
4082:   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);
4083:   if (!mat->rmap->N && !mat->cmap->N) PetscFunctionReturn(PETSC_SUCCESS);
4084:   MatCheckPreallocated(mat, 1);

4086:   PetscCall(PetscLogEventBegin(MAT_BackwardSolve, mat, b, x, 0));
4087:   PetscUseTypeMethod(mat, backwardsolve, b, x);
4088:   PetscCall(PetscLogEventEnd(MAT_BackwardSolve, mat, b, x, 0));
4089:   PetscCall(PetscObjectStateIncrease((PetscObject)x));
4090:   PetscFunctionReturn(PETSC_SUCCESS);
4091: }

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

4096:   Neighbor-wise Collective

4098:   Input Parameters:
4099: + mat - the factored matrix
4100: . b   - the right-hand-side vector
4101: - y   - the vector to be added to

4103:   Output Parameter:
4104: . x - the result vector

4106:   Level: developer

4108:   Note:
4109:   The vectors `b` and `x` cannot be the same.  I.e., one cannot
4110:   call `MatSolveAdd`(A,x,y,x).

4112: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatSolve()`, `MatGetFactor()`, `MatSolveTranspose()`, `MatSolveTransposeAdd()`
4113: @*/
4114: PetscErrorCode MatSolveAdd(Mat mat, Vec b, Vec y, Vec x)
4115: {
4116:   PetscScalar one = 1.0;
4117:   Vec         tmp;

4119:   PetscFunctionBegin;
4125:   PetscCheckSameComm(mat, 1, b, 2);
4126:   PetscCheckSameComm(mat, 1, y, 3);
4127:   PetscCheckSameComm(mat, 1, x, 4);
4128:   PetscCheck(x != b, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_IDN, "x and b must be different vectors");
4129:   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);
4130:   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);
4131:   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);
4132:   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);
4133:   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);
4134:   if (!mat->rmap->N && !mat->cmap->N) PetscFunctionReturn(PETSC_SUCCESS);
4135:   MatCheckPreallocated(mat, 1);

4137:   PetscCall(PetscLogEventBegin(MAT_SolveAdd, mat, b, x, y));
4138:   PetscCall(VecFlag(x, mat->factorerrortype));
4139:   if (mat->factorerrortype) {
4140:     PetscCall(PetscInfo(mat, "MatFactorError %d\n", mat->factorerrortype));
4141:   } else if (mat->ops->solveadd) {
4142:     PetscUseTypeMethod(mat, solveadd, b, y, x);
4143:   } else {
4144:     /* do the solve then the add manually */
4145:     if (x != y) {
4146:       PetscCall(MatSolve(mat, b, x));
4147:       PetscCall(VecAXPY(x, one, y));
4148:     } else {
4149:       PetscCall(VecDuplicate(x, &tmp));
4150:       PetscCall(VecCopy(x, tmp));
4151:       PetscCall(MatSolve(mat, b, x));
4152:       PetscCall(VecAXPY(x, one, tmp));
4153:       PetscCall(VecDestroy(&tmp));
4154:     }
4155:   }
4156:   PetscCall(PetscLogEventEnd(MAT_SolveAdd, mat, b, x, y));
4157:   PetscCall(PetscObjectStateIncrease((PetscObject)x));
4158:   PetscFunctionReturn(PETSC_SUCCESS);
4159: }

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

4164:   Neighbor-wise Collective

4166:   Input Parameters:
4167: + mat - the factored matrix
4168: - b   - the right-hand-side vector

4170:   Output Parameter:
4171: . x - the result vector

4173:   Level: developer

4175:   Notes:
4176:   The vectors `b` and `x` cannot be the same.  I.e., one cannot
4177:   call `MatSolveTranspose`(A,x,x).

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

4183: .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `KSP`, `MatSolve()`, `MatSolveAdd()`, `MatSolveTransposeAdd()`
4184: @*/
4185: PetscErrorCode MatSolveTranspose(Mat mat, Vec b, Vec x)
4186: {
4187:   PetscErrorCode (*f)(Mat, Vec, Vec) = (!mat->ops->solvetranspose && mat->symmetric) ? mat->ops->solve : mat->ops->solvetranspose;

4189:   PetscFunctionBegin;
4194:   PetscCheckSameComm(mat, 1, b, 2);
4195:   PetscCheckSameComm(mat, 1, x, 3);
4196:   PetscCheck(x != b, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_IDN, "x and b must be different vectors");
4197:   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);
4198:   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);
4199:   if (!mat->rmap->N && !mat->cmap->N) PetscFunctionReturn(PETSC_SUCCESS);
4200:   MatCheckPreallocated(mat, 1);
4201:   PetscCall(PetscLogEventBegin(MAT_SolveTranspose, mat, b, x, 0));
4202:   PetscCall(VecFlag(x, mat->factorerrortype));
4203:   if (mat->factorerrortype) {
4204:     PetscCall(PetscInfo(mat, "MatFactorError %d\n", mat->factorerrortype));
4205:   } else {
4206:     PetscCheck(f, PetscObjectComm((PetscObject)mat), PETSC_ERR_SUP, "Matrix type %s", ((PetscObject)mat)->type_name);
4207:     PetscCall((*f)(mat, b, x));
4208:   }
4209:   PetscCall(PetscLogEventEnd(MAT_SolveTranspose, mat, b, x, 0));
4210:   PetscCall(PetscObjectStateIncrease((PetscObject)x));
4211:   PetscFunctionReturn(PETSC_SUCCESS);
4212: }

4214: /*@
4215:   MatSolveTransposeAdd - Computes $x = y + A^{-T} b$
4216:   factored matrix.

4218:   Neighbor-wise Collective

4220:   Input Parameters:
4221: + mat - the factored matrix
4222: . b   - the right-hand-side vector
4223: - y   - the vector to be added to

4225:   Output Parameter:
4226: . x - the result vector

4228:   Level: developer

4230:   Note:
4231:   The vectors `b` and `x` cannot be the same.  I.e., one cannot
4232:   call `MatSolveTransposeAdd`(A,x,y,x).

4234: .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatSolve()`, `MatSolveAdd()`, `MatSolveTranspose()`
4235: @*/
4236: PetscErrorCode MatSolveTransposeAdd(Mat mat, Vec b, Vec y, Vec x)
4237: {
4238:   PetscScalar one = 1.0;
4239:   Vec         tmp;
4240:   PetscErrorCode (*f)(Mat, Vec, Vec, Vec) = (!mat->ops->solvetransposeadd && mat->symmetric) ? mat->ops->solveadd : mat->ops->solvetransposeadd;

4242:   PetscFunctionBegin;
4248:   PetscCheckSameComm(mat, 1, b, 2);
4249:   PetscCheckSameComm(mat, 1, y, 3);
4250:   PetscCheckSameComm(mat, 1, x, 4);
4251:   PetscCheck(x != b, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_IDN, "x and b must be different vectors");
4252:   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);
4253:   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);
4254:   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);
4255:   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);
4256:   if (!mat->rmap->N && !mat->cmap->N) PetscFunctionReturn(PETSC_SUCCESS);
4257:   MatCheckPreallocated(mat, 1);

4259:   PetscCall(PetscLogEventBegin(MAT_SolveTransposeAdd, mat, b, x, y));
4260:   PetscCall(VecFlag(x, mat->factorerrortype));
4261:   if (mat->factorerrortype) {
4262:     PetscCall(PetscInfo(mat, "MatFactorError %d\n", mat->factorerrortype));
4263:   } else if (f) {
4264:     PetscCall((*f)(mat, b, y, x));
4265:   } else {
4266:     /* do the solve then the add manually */
4267:     if (x != y) {
4268:       PetscCall(MatSolveTranspose(mat, b, x));
4269:       PetscCall(VecAXPY(x, one, y));
4270:     } else {
4271:       PetscCall(VecDuplicate(x, &tmp));
4272:       PetscCall(VecCopy(x, tmp));
4273:       PetscCall(MatSolveTranspose(mat, b, x));
4274:       PetscCall(VecAXPY(x, one, tmp));
4275:       PetscCall(VecDestroy(&tmp));
4276:     }
4277:   }
4278:   PetscCall(PetscLogEventEnd(MAT_SolveTransposeAdd, mat, b, x, y));
4279:   PetscCall(PetscObjectStateIncrease((PetscObject)x));
4280:   PetscFunctionReturn(PETSC_SUCCESS);
4281: }

4283: // PetscClangLinter pragma disable: -fdoc-section-header-unknown
4284: /*@
4285:   MatSOR - Computes relaxation (SOR, Gauss-Seidel) sweeps.

4287:   Neighbor-wise Collective

4289:   Input Parameters:
4290: + mat   - the matrix
4291: . b     - the right-hand side
4292: . omega - the relaxation factor
4293: . flag  - flag indicating the type of SOR (see below)
4294: . shift - diagonal shift
4295: . its   - the number of iterations
4296: - lits  - the number of local iterations

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

4301:   SOR Flags:
4302: +     `SOR_FORWARD_SWEEP` - forward SOR
4303: .     `SOR_BACKWARD_SWEEP` - backward SOR
4304: .     `SOR_SYMMETRIC_SWEEP` - SSOR (symmetric SOR)
4305: .     `SOR_LOCAL_FORWARD_SWEEP` - local forward SOR
4306: .     `SOR_LOCAL_BACKWARD_SWEEP` - local forward SOR
4307: .     `SOR_LOCAL_SYMMETRIC_SWEEP` - local SSOR
4308: .     `SOR_EISENSTAT` - SOR with Eisenstat trick
4309: .     `SOR_APPLY_UPPER`, `SOR_APPLY_LOWER` - applies upper/lower triangular part of matrix to vector (with `omega`)
4310: -     `SOR_ZERO_INITIAL_GUESS` - zero initial guess

4312:   Level: developer

4314:   Notes:
4315:   `SOR_LOCAL_FORWARD_SWEEP`, `SOR_LOCAL_BACKWARD_SWEEP`, and
4316:   `SOR_LOCAL_SYMMETRIC_SWEEP` perform separate independent smoothings
4317:   on each processor.

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

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

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

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

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

4334: .seealso: [](ch_matrices), `Mat`, `MatMult()`, `KSP`, `PC`, `MatGetFactor()`
4335: @*/
4336: PetscErrorCode MatSOR(Mat mat, Vec b, PetscReal omega, MatSORType flag, PetscReal shift, PetscInt its, PetscInt lits, Vec x)
4337: {
4338:   PetscFunctionBegin;
4343:   PetscCheckSameComm(mat, 1, b, 2);
4344:   PetscCheckSameComm(mat, 1, x, 8);
4345:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
4346:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
4347:   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);
4348:   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);
4349:   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);
4350:   PetscCheck(its > 0, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Relaxation requires global its %" PetscInt_FMT " positive", its);
4351:   PetscCheck(lits > 0, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Relaxation requires local its %" PetscInt_FMT " positive", lits);
4352:   PetscCheck(b != x, PETSC_COMM_SELF, PETSC_ERR_ARG_IDN, "b and x vector cannot be the same");

4354:   MatCheckPreallocated(mat, 1);
4355:   PetscCall(PetscLogEventBegin(MAT_SOR, mat, b, x, 0));
4356:   PetscUseTypeMethod(mat, sor, b, omega, flag, shift, its, lits, x);
4357:   PetscCall(PetscLogEventEnd(MAT_SOR, mat, b, x, 0));
4358:   PetscCall(PetscObjectStateIncrease((PetscObject)x));
4359:   PetscFunctionReturn(PETSC_SUCCESS);
4360: }

4362: /*
4363:       Default matrix copy routine.
4364: */
4365: PetscErrorCode MatCopy_Basic(Mat A, Mat B, MatStructure str)
4366: {
4367:   PetscInt           i, rstart = 0, rend = 0, nz;
4368:   const PetscInt    *cwork;
4369:   const PetscScalar *vwork;

4371:   PetscFunctionBegin;
4372:   if (B->assembled) PetscCall(MatZeroEntries(B));
4373:   if (str == SAME_NONZERO_PATTERN) {
4374:     PetscCall(MatGetOwnershipRange(A, &rstart, &rend));
4375:     for (i = rstart; i < rend; i++) {
4376:       PetscCall(MatGetRow(A, i, &nz, &cwork, &vwork));
4377:       PetscCall(MatSetValues(B, 1, &i, nz, cwork, vwork, INSERT_VALUES));
4378:       PetscCall(MatRestoreRow(A, i, &nz, &cwork, &vwork));
4379:     }
4380:   } else {
4381:     PetscCall(MatAYPX(B, 0.0, A, str));
4382:   }
4383:   PetscCall(MatAssemblyBegin(B, MAT_FINAL_ASSEMBLY));
4384:   PetscCall(MatAssemblyEnd(B, MAT_FINAL_ASSEMBLY));
4385:   PetscFunctionReturn(PETSC_SUCCESS);
4386: }

4388: /*@
4389:   MatCopy - Copies a matrix to another matrix.

4391:   Collective

4393:   Input Parameters:
4394: + A   - the matrix
4395: - str - `SAME_NONZERO_PATTERN` or `DIFFERENT_NONZERO_PATTERN`

4397:   Output Parameter:
4398: . B - where the copy is put

4400:   Level: intermediate

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

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

4409: .seealso: [](ch_matrices), `Mat`, `MatConvert()`, `MatDuplicate()`
4410: @*/
4411: PetscErrorCode MatCopy(Mat A, Mat B, MatStructure str)
4412: {
4413:   PetscInt i;

4415:   PetscFunctionBegin;
4420:   PetscCheckSameComm(A, 1, B, 2);
4421:   MatCheckPreallocated(B, 2);
4422:   PetscCheck(A->assembled, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
4423:   PetscCheck(!A->factortype, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
4424:   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,
4425:              A->cmap->N, B->cmap->N);
4426:   MatCheckPreallocated(A, 1);
4427:   if (A == B) PetscFunctionReturn(PETSC_SUCCESS);

4429:   PetscCall(PetscLogEventBegin(MAT_Copy, A, B, 0, 0));
4430:   if (A->ops->copy) PetscUseTypeMethod(A, copy, B, str);
4431:   else PetscCall(MatCopy_Basic(A, B, str));

4433:   B->stencil.dim = A->stencil.dim;
4434:   B->stencil.noc = A->stencil.noc;
4435:   for (i = 0; i <= A->stencil.dim + (A->stencil.noc ? 0 : -1); i++) {
4436:     B->stencil.dims[i]   = A->stencil.dims[i];
4437:     B->stencil.starts[i] = A->stencil.starts[i];
4438:   }

4440:   PetscCall(PetscLogEventEnd(MAT_Copy, A, B, 0, 0));
4441:   PetscCall(PetscObjectStateIncrease((PetscObject)B));
4442:   PetscFunctionReturn(PETSC_SUCCESS);
4443: }

4445: /*@
4446:   MatConvert - Converts a matrix to another matrix, either of the same
4447:   or different type.

4449:   Collective

4451:   Input Parameters:
4452: + mat     - the matrix
4453: . newtype - new matrix type.  Use `MATSAME` to create a new matrix of the
4454:             same type as the original matrix.
4455: - reuse   - denotes if the destination matrix is to be created or reused.
4456:             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
4457:             `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).

4459:   Output Parameter:
4460: . M - pointer to place new matrix

4462:   Level: intermediate

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

4469:   Cannot be used to convert a sequential matrix to parallel or parallel to sequential,
4470:   the MPI communicator of the generated matrix is always the same as the communicator
4471:   of the input matrix.

4473: .seealso: [](ch_matrices), `Mat`, `MatCopy()`, `MatDuplicate()`, `MAT_INITIAL_MATRIX`, `MAT_REUSE_MATRIX`, `MAT_INPLACE_MATRIX`
4474: @*/
4475: PetscErrorCode MatConvert(Mat mat, MatType newtype, MatReuse reuse, Mat *M)
4476: {
4477:   PetscBool  sametype, issame, flg;
4478:   PetscBool3 issymmetric, ishermitian, isspd;
4479:   char       convname[256], mtype[256];
4480:   Mat        B;

4482:   PetscFunctionBegin;
4485:   PetscAssertPointer(M, 4);
4486:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
4487:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
4488:   MatCheckPreallocated(mat, 1);

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

4493:   PetscCall(PetscObjectTypeCompare((PetscObject)mat, newtype, &sametype));
4494:   PetscCall(PetscStrcmp(newtype, "same", &issame));
4495:   PetscCheck(!(reuse == MAT_INPLACE_MATRIX) || !(mat != *M), PetscObjectComm((PetscObject)mat), PETSC_ERR_SUP, "MAT_INPLACE_MATRIX requires same input and output matrix");
4496:   if (reuse == MAT_REUSE_MATRIX) {
4498:     PetscCheck(mat != *M, PetscObjectComm((PetscObject)mat), PETSC_ERR_SUP, "MAT_REUSE_MATRIX means reuse matrix in final argument, perhaps you mean MAT_INPLACE_MATRIX");
4499:   }

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

4506:   /* Cache Mat options because some converters use MatHeaderReplace() */
4507:   issymmetric = mat->symmetric;
4508:   ishermitian = mat->hermitian;
4509:   isspd       = mat->spd;

4511:   if ((sametype || issame) && (reuse == MAT_INITIAL_MATRIX) && mat->ops->duplicate) {
4512:     PetscCall(PetscInfo(mat, "Calling duplicate for initial matrix %s %d %d\n", ((PetscObject)mat)->type_name, sametype, issame));
4513:     PetscUseTypeMethod(mat, duplicate, MAT_COPY_VALUES, M);
4514:   } else {
4515:     PetscErrorCode (*conv)(Mat, MatType, MatReuse, Mat *) = NULL;
4516:     const char *prefix[3]                                 = {"seq", "mpi", ""};
4517:     PetscInt    i;
4518:     /*
4519:        Order of precedence:
4520:        0) See if newtype is a superclass of the current matrix.
4521:        1) See if a specialized converter is known to the current matrix.
4522:        2) See if a specialized converter is known to the desired matrix class.
4523:        3) See if a good general converter is registered for the desired class
4524:           (as of 6/27/03 only MATMPIADJ falls into this category).
4525:        4) See if a good general converter is known for the current matrix.
4526:        5) Use a really basic converter.
4527:     */

4529:     /* 0) See if newtype is a superclass of the current matrix.
4530:           i.e mat is mpiaij and newtype is aij */
4531:     for (i = 0; i < (PetscInt)PETSC_STATIC_ARRAY_LENGTH(prefix); i++) {
4532:       PetscCall(PetscStrncpy(convname, prefix[i], sizeof(convname)));
4533:       PetscCall(PetscStrlcat(convname, newtype, sizeof(convname)));
4534:       PetscCall(PetscStrcmp(convname, ((PetscObject)mat)->type_name, &flg));
4535:       PetscCall(PetscInfo(mat, "Check superclass %s %s -> %d\n", convname, ((PetscObject)mat)->type_name, flg));
4536:       if (flg) {
4537:         if (reuse == MAT_INPLACE_MATRIX) {
4538:           PetscCall(PetscInfo(mat, "Early return\n"));
4539:           PetscFunctionReturn(PETSC_SUCCESS);
4540:         } else if (reuse == MAT_INITIAL_MATRIX && mat->ops->duplicate) {
4541:           PetscCall(PetscInfo(mat, "Calling MatDuplicate\n"));
4542:           PetscUseTypeMethod(mat, duplicate, MAT_COPY_VALUES, M);
4543:           PetscFunctionReturn(PETSC_SUCCESS);
4544:         } else if (reuse == MAT_REUSE_MATRIX && mat->ops->copy) {
4545:           PetscCall(PetscInfo(mat, "Calling MatCopy\n"));
4546:           PetscCall(MatCopy(mat, *M, SAME_NONZERO_PATTERN));
4547:           PetscFunctionReturn(PETSC_SUCCESS);
4548:         }
4549:       }
4550:     }
4551:     /* 1) See if a specialized converter is known to the current matrix and the desired class */
4552:     for (i = 0; i < (PetscInt)PETSC_STATIC_ARRAY_LENGTH(prefix); i++) {
4553:       PetscCall(PetscStrncpy(convname, "MatConvert_", sizeof(convname)));
4554:       PetscCall(PetscStrlcat(convname, ((PetscObject)mat)->type_name, sizeof(convname)));
4555:       PetscCall(PetscStrlcat(convname, "_", sizeof(convname)));
4556:       PetscCall(PetscStrlcat(convname, prefix[i], sizeof(convname)));
4557:       PetscCall(PetscStrlcat(convname, issame ? ((PetscObject)mat)->type_name : newtype, sizeof(convname)));
4558:       PetscCall(PetscStrlcat(convname, "_C", sizeof(convname)));
4559:       PetscCall(PetscObjectQueryFunction((PetscObject)mat, convname, &conv));
4560:       PetscCall(PetscInfo(mat, "Check specialized (1) %s (%s) -> %d\n", convname, ((PetscObject)mat)->type_name, !!conv));
4561:       if (conv) goto foundconv;
4562:     }

4564:     /* 2)  See if a specialized converter is known to the desired matrix class. */
4565:     PetscCall(MatCreate(PetscObjectComm((PetscObject)mat), &B));
4566:     PetscCall(MatSetSizes(B, mat->rmap->n, mat->cmap->n, mat->rmap->N, mat->cmap->N));
4567:     PetscCall(MatSetType(B, newtype));
4568:     for (i = 0; i < (PetscInt)PETSC_STATIC_ARRAY_LENGTH(prefix); i++) {
4569:       PetscCall(PetscStrncpy(convname, "MatConvert_", sizeof(convname)));
4570:       PetscCall(PetscStrlcat(convname, ((PetscObject)mat)->type_name, sizeof(convname)));
4571:       PetscCall(PetscStrlcat(convname, "_", sizeof(convname)));
4572:       PetscCall(PetscStrlcat(convname, prefix[i], sizeof(convname)));
4573:       PetscCall(PetscStrlcat(convname, newtype, sizeof(convname)));
4574:       PetscCall(PetscStrlcat(convname, "_C", sizeof(convname)));
4575:       PetscCall(PetscObjectQueryFunction((PetscObject)B, convname, &conv));
4576:       PetscCall(PetscInfo(mat, "Check specialized (2) %s (%s) -> %d\n", convname, ((PetscObject)B)->type_name, !!conv));
4577:       if (conv) {
4578:         PetscCall(MatDestroy(&B));
4579:         goto foundconv;
4580:       }
4581:     }

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

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

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

4598:   foundconv:
4599:     PetscCall(PetscLogEventBegin(MAT_Convert, mat, 0, 0, 0));
4600:     PetscCall((*conv)(mat, newtype, reuse, M));
4601:     if (mat->rmap->mapping && mat->cmap->mapping && !(*M)->rmap->mapping && !(*M)->cmap->mapping) {
4602:       /* the block sizes must be same if the mappings are copied over */
4603:       (*M)->rmap->bs = mat->rmap->bs;
4604:       (*M)->cmap->bs = mat->cmap->bs;
4605:       PetscCall(PetscObjectReference((PetscObject)mat->rmap->mapping));
4606:       PetscCall(PetscObjectReference((PetscObject)mat->cmap->mapping));
4607:       (*M)->rmap->mapping = mat->rmap->mapping;
4608:       (*M)->cmap->mapping = mat->cmap->mapping;
4609:     }
4610:     (*M)->stencil.dim = mat->stencil.dim;
4611:     (*M)->stencil.noc = mat->stencil.noc;
4612:     for (i = 0; i <= mat->stencil.dim + (mat->stencil.noc ? 0 : -1); i++) {
4613:       (*M)->stencil.dims[i]   = mat->stencil.dims[i];
4614:       (*M)->stencil.starts[i] = mat->stencil.starts[i];
4615:     }
4616:     PetscCall(PetscLogEventEnd(MAT_Convert, mat, 0, 0, 0));
4617:   }
4618:   PetscCall(PetscObjectStateIncrease((PetscObject)*M));

4620:   /* Reset Mat options */
4621:   if (issymmetric != PETSC_BOOL3_UNKNOWN) PetscCall(MatSetOption(*M, MAT_SYMMETRIC, PetscBool3ToBool(issymmetric)));
4622:   if (ishermitian != PETSC_BOOL3_UNKNOWN) PetscCall(MatSetOption(*M, MAT_HERMITIAN, PetscBool3ToBool(ishermitian)));
4623:   if (isspd != PETSC_BOOL3_UNKNOWN) PetscCall(MatSetOption(*M, MAT_SPD, PetscBool3ToBool(isspd)));
4624:   PetscFunctionReturn(PETSC_SUCCESS);
4625: }

4627: /*@
4628:   MatFactorGetSolverType - Returns name of the package providing the factorization routines

4630:   Not Collective

4632:   Input Parameter:
4633: . mat - the matrix, must be a factored matrix

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

4638:   Level: intermediate

4640: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatGetFactor()`, `MatSolverType`, `MatCopy()`, `MatDuplicate()`, `MatGetFactorAvailable()`
4641: @*/
4642: PetscErrorCode MatFactorGetSolverType(Mat mat, MatSolverType *type)
4643: {
4644:   PetscErrorCode (*conv)(Mat, MatSolverType *);

4646:   PetscFunctionBegin;
4649:   PetscAssertPointer(type, 2);
4650:   PetscCheck(mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Only for factored matrix");
4651:   PetscCall(PetscObjectQueryFunction((PetscObject)mat, "MatFactorGetSolverType_C", &conv));
4652:   if (conv) PetscCall((*conv)(mat, type));
4653:   else *type = MATSOLVERPETSC;
4654:   PetscFunctionReturn(PETSC_SUCCESS);
4655: }

4657: typedef struct _MatSolverTypeForSpecifcType *MatSolverTypeForSpecifcType;
4658: struct _MatSolverTypeForSpecifcType {
4659:   MatType mtype;
4660:   /* no entry for MAT_FACTOR_NONE */
4661:   PetscErrorCode (*createfactor[MAT_FACTOR_NUM_TYPES - 1])(Mat, MatFactorType, Mat *);
4662:   MatSolverTypeForSpecifcType next;
4663: };

4665: typedef struct _MatSolverTypeHolder *MatSolverTypeHolder;
4666: struct _MatSolverTypeHolder {
4667:   char                       *name;
4668:   MatSolverTypeForSpecifcType handlers;
4669:   MatSolverTypeHolder         next;
4670: };

4672: static MatSolverTypeHolder MatSolverTypeHolders = NULL;

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

4677:   Logically Collective, No Fortran Support

4679:   Input Parameters:
4680: + package      - name of the package, for example `petsc` or `superlu`
4681: . mtype        - the matrix type that works with this package
4682: . ftype        - the type of factorization supported by the package
4683: - createfactor - routine that will create the factored matrix ready to be used

4685:   Level: developer

4687: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatFactorGetSolverType()`, `MatCopy()`, `MatDuplicate()`, `MatGetFactorAvailable()`,
4688:   `MatGetFactor()`
4689: @*/
4690: PetscErrorCode MatSolverTypeRegister(MatSolverType package, MatType mtype, MatFactorType ftype, PetscErrorCode (*createfactor)(Mat, MatFactorType, Mat *))
4691: {
4692:   MatSolverTypeHolder         next = MatSolverTypeHolders, prev = NULL;
4693:   PetscBool                   flg;
4694:   MatSolverTypeForSpecifcType inext, iprev = NULL;

4696:   PetscFunctionBegin;
4697:   PetscCall(MatInitializePackage());
4698:   if (!next) {
4699:     PetscCall(PetscNew(&MatSolverTypeHolders));
4700:     PetscCall(PetscStrallocpy(package, &MatSolverTypeHolders->name));
4701:     PetscCall(PetscNew(&MatSolverTypeHolders->handlers));
4702:     PetscCall(PetscStrallocpy(mtype, (char **)&MatSolverTypeHolders->handlers->mtype));
4703:     MatSolverTypeHolders->handlers->createfactor[(int)ftype - 1] = createfactor;
4704:     PetscFunctionReturn(PETSC_SUCCESS);
4705:   }
4706:   while (next) {
4707:     PetscCall(PetscStrcasecmp(package, next->name, &flg));
4708:     if (flg) {
4709:       PetscCheck(next->handlers, PETSC_COMM_SELF, PETSC_ERR_PLIB, "MatSolverTypeHolder is missing handlers");
4710:       inext = next->handlers;
4711:       while (inext) {
4712:         PetscCall(PetscStrcasecmp(mtype, inext->mtype, &flg));
4713:         if (flg) {
4714:           inext->createfactor[(int)ftype - 1] = createfactor;
4715:           PetscFunctionReturn(PETSC_SUCCESS);
4716:         }
4717:         iprev = inext;
4718:         inext = inext->next;
4719:       }
4720:       PetscCall(PetscNew(&iprev->next));
4721:       PetscCall(PetscStrallocpy(mtype, (char **)&iprev->next->mtype));
4722:       iprev->next->createfactor[(int)ftype - 1] = createfactor;
4723:       PetscFunctionReturn(PETSC_SUCCESS);
4724:     }
4725:     prev = next;
4726:     next = next->next;
4727:   }
4728:   PetscCall(PetscNew(&prev->next));
4729:   PetscCall(PetscStrallocpy(package, &prev->next->name));
4730:   PetscCall(PetscNew(&prev->next->handlers));
4731:   PetscCall(PetscStrallocpy(mtype, (char **)&prev->next->handlers->mtype));
4732:   prev->next->handlers->createfactor[(int)ftype - 1] = createfactor;
4733:   PetscFunctionReturn(PETSC_SUCCESS);
4734: }

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

4739:   Input Parameters:
4740: + 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
4741: . ftype - the type of factorization supported by the type
4742: - mtype - the matrix type that works with this type

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

4749:   Calling sequence of `createfactor`:
4750: + A     - the matrix providing the factor matrix
4751: . ftype - the `MatFactorType` of the factor requested
4752: - B     - the new factor matrix that responds to MatXXFactorSymbolic,Numeric() functions, such as `MatLUFactorSymbolic()`

4754:   Level: developer

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

4761: .seealso: [](ch_matrices), `Mat`, `MatFactorType`, `MatType`, `MatCopy()`, `MatDuplicate()`, `MatGetFactorAvailable()`, `MatSolverTypeRegister()`, `MatGetFactor()`,
4762:           `MatInitializePackage()`
4763: @*/
4764: PetscErrorCode MatSolverTypeGet(MatSolverType type, MatType mtype, MatFactorType ftype, PetscBool *foundtype, PetscBool *foundmtype, PetscErrorCode (**createfactor)(Mat A, MatFactorType ftype, Mat *B))
4765: {
4766:   MatSolverTypeHolder         next = MatSolverTypeHolders;
4767:   PetscBool                   flg;
4768:   MatSolverTypeForSpecifcType inext;

4770:   PetscFunctionBegin;
4771:   if (foundtype) *foundtype = PETSC_FALSE;
4772:   if (foundmtype) *foundmtype = PETSC_FALSE;
4773:   if (createfactor) *createfactor = NULL;

4775:   if (type) {
4776:     while (next) {
4777:       PetscCall(PetscStrcasecmp(type, next->name, &flg));
4778:       if (flg) {
4779:         if (foundtype) *foundtype = PETSC_TRUE;
4780:         inext = next->handlers;
4781:         while (inext) {
4782:           PetscCall(PetscStrbeginswith(mtype, inext->mtype, &flg));
4783:           if (flg) {
4784:             if (foundmtype) *foundmtype = PETSC_TRUE;
4785:             if (createfactor) *createfactor = inext->createfactor[(int)ftype - 1];
4786:             PetscFunctionReturn(PETSC_SUCCESS);
4787:           }
4788:           inext = inext->next;
4789:         }
4790:       }
4791:       next = next->next;
4792:     }
4793:   } else {
4794:     while (next) {
4795:       inext = next->handlers;
4796:       while (inext) {
4797:         PetscCall(PetscStrcmp(mtype, inext->mtype, &flg));
4798:         if (flg && inext->createfactor[(int)ftype - 1]) {
4799:           if (foundtype) *foundtype = PETSC_TRUE;
4800:           if (foundmtype) *foundmtype = PETSC_TRUE;
4801:           if (createfactor) *createfactor = inext->createfactor[(int)ftype - 1];
4802:           PetscFunctionReturn(PETSC_SUCCESS);
4803:         }
4804:         inext = inext->next;
4805:       }
4806:       next = next->next;
4807:     }
4808:     /* try with base classes inext->mtype */
4809:     next = MatSolverTypeHolders;
4810:     while (next) {
4811:       inext = next->handlers;
4812:       while (inext) {
4813:         PetscCall(PetscStrbeginswith(mtype, inext->mtype, &flg));
4814:         if (flg && inext->createfactor[(int)ftype - 1]) {
4815:           if (foundtype) *foundtype = PETSC_TRUE;
4816:           if (foundmtype) *foundmtype = PETSC_TRUE;
4817:           if (createfactor) *createfactor = inext->createfactor[(int)ftype - 1];
4818:           PetscFunctionReturn(PETSC_SUCCESS);
4819:         }
4820:         inext = inext->next;
4821:       }
4822:       next = next->next;
4823:     }
4824:   }
4825:   PetscFunctionReturn(PETSC_SUCCESS);
4826: }

4828: PetscErrorCode MatSolverTypeDestroy(void)
4829: {
4830:   MatSolverTypeHolder         next = MatSolverTypeHolders, prev;
4831:   MatSolverTypeForSpecifcType inext, iprev;

4833:   PetscFunctionBegin;
4834:   while (next) {
4835:     PetscCall(PetscFree(next->name));
4836:     inext = next->handlers;
4837:     while (inext) {
4838:       PetscCall(PetscFree(inext->mtype));
4839:       iprev = inext;
4840:       inext = inext->next;
4841:       PetscCall(PetscFree(iprev));
4842:     }
4843:     prev = next;
4844:     next = next->next;
4845:     PetscCall(PetscFree(prev));
4846:   }
4847:   MatSolverTypeHolders = NULL;
4848:   PetscFunctionReturn(PETSC_SUCCESS);
4849: }

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

4854:   Logically Collective

4856:   Input Parameter:
4857: . mat - the matrix

4859:   Output Parameter:
4860: . flg - `PETSC_TRUE` if uses the ordering

4862:   Level: developer

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

4868: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatCopy()`, `MatDuplicate()`, `MatGetFactorAvailable()`, `MatGetFactor()`, `MatLUFactorSymbolic()`, `MatCholeskyFactorSymbolic()`
4869: @*/
4870: PetscErrorCode MatFactorGetCanUseOrdering(Mat mat, PetscBool *flg)
4871: {
4872:   PetscFunctionBegin;
4873:   *flg = mat->canuseordering;
4874:   PetscFunctionReturn(PETSC_SUCCESS);
4875: }

4877: /*@
4878:   MatFactorGetPreferredOrdering - The preferred ordering for a particular matrix factor object

4880:   Logically Collective

4882:   Input Parameters:
4883: + mat   - the matrix obtained with `MatGetFactor()`
4884: - ftype - the factorization type to be used

4886:   Output Parameter:
4887: . otype - the preferred ordering type

4889:   Level: developer

4891: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatFactorType`, `MatOrderingType`, `MatCopy()`, `MatDuplicate()`, `MatGetFactorAvailable()`, `MatGetFactor()`, `MatLUFactorSymbolic()`, `MatCholeskyFactorSymbolic()`
4892: @*/
4893: PetscErrorCode MatFactorGetPreferredOrdering(Mat mat, MatFactorType ftype, MatOrderingType *otype)
4894: {
4895:   PetscFunctionBegin;
4896:   *otype = mat->preferredordering[ftype];
4897:   PetscCheck(*otype, PETSC_COMM_SELF, PETSC_ERR_PLIB, "MatFactor did not have a preferred ordering");
4898:   PetscFunctionReturn(PETSC_SUCCESS);
4899: }

4901: /*@
4902:   MatGetFactor - Returns a matrix suitable to calls to routines such as `MatLUFactorSymbolic()`, `MatCholeskyFactorSymbolic()`, `MatILUFactorSymbolic()`,
4903:   `MatICCFactorSymbolic()`, `MatLUFactorNumeric()`, `MatCholeskyFactorNumeric()`, `MatILUFactorNumeric()`, and
4904:   `MatICCFactorNumeric()`

4906:   Collective

4908:   Input Parameters:
4909: + mat   - the matrix
4910: . 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
4911:           the other criteria is returned
4912: - ftype - factor type, `MAT_FACTOR_LU`, `MAT_FACTOR_CHOLESKY`, `MAT_FACTOR_ICC`, `MAT_FACTOR_ILU`, `MAT_FACTOR_QR`

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

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

4922:   Level: intermediate

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

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

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

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

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

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

4947: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `KSP`, `MatSolverType`, `MatFactorType`, `MatCopy()`, `MatDuplicate()`,
4948:           `MatGetFactorAvailable()`, `MatFactorGetCanUseOrdering()`, `MatSolverTypeRegister()`, `MatSolverTypeGet()`,
4949:           `MAT_FACTOR_LU`, `MAT_FACTOR_CHOLESKY`, `MAT_FACTOR_ICC`, `MAT_FACTOR_ILU`, `MAT_FACTOR_QR`, `MatInitializePackage()`,
4950:           `MatLUFactorSymbolic()`, `MatCholeskyFactorSymbolic()`, `MatILUFactorSymbolic()`,
4951:           `MatICCFactorSymbolic()`, `MatLUFactorNumeric()`, `MatCholeskyFactorNumeric()`, `MatILUFactorNumeric()`,
4952:           `MatICCFactorNumeric()`
4953: @*/
4954: PetscErrorCode MatGetFactor(Mat mat, MatSolverType type, MatFactorType ftype, Mat *f)
4955: {
4956:   PetscBool foundtype, foundmtype, shell, hasop = PETSC_FALSE;
4957:   PetscErrorCode (*conv)(Mat, MatFactorType, Mat *);

4959:   PetscFunctionBegin;

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

4966:   PetscCall(MatIsShell(mat, &shell));
4967:   if (shell) PetscCall(MatHasOperation(mat, MATOP_GET_FACTOR, &hasop));
4968:   if (hasop) {
4969:     PetscUseTypeMethod(mat, getfactor, type, ftype, f);
4970:     PetscFunctionReturn(PETSC_SUCCESS);
4971:   }

4973:   PetscCall(MatSolverTypeGet(type, ((PetscObject)mat)->type_name, ftype, &foundtype, &foundmtype, &conv));
4974:   if (!foundtype) {
4975:     if (type) {
4976:       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],
4977:               ((PetscObject)mat)->type_name, type);
4978:     } else {
4979:       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);
4980:     }
4981:   }
4982:   PetscCheck(foundmtype, PetscObjectComm((PetscObject)mat), PETSC_ERR_MISSING_FACTOR, "MatSolverType %s does not support matrix type %s", type, ((PetscObject)mat)->type_name);
4983:   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);

4985:   PetscCall((*conv)(mat, ftype, f));
4986:   if (mat->factorprefix) PetscCall(MatSetOptionsPrefix(*f, mat->factorprefix));
4987:   PetscFunctionReturn(PETSC_SUCCESS);
4988: }

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

4993:   Not Collective

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

5000:   Output Parameter:
5001: . flg - PETSC_TRUE if the factorization is available

5003:   Level: intermediate

5005:   Notes:
5006:   Some PETSc matrix formats have alternative solvers available that are contained in alternative packages
5007:   such as pastix, superlu, mumps etc.

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

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

5014: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatSolverType`, `MatFactorType`, `MatGetFactor()`, `MatCopy()`, `MatDuplicate()`, `MatSolverTypeRegister()`,
5015:           `MAT_FACTOR_LU`, `MAT_FACTOR_CHOLESKY`, `MAT_FACTOR_ICC`, `MAT_FACTOR_ILU`, `MAT_FACTOR_QR`, `MatSolverTypeGet()`
5016: @*/
5017: PetscErrorCode MatGetFactorAvailable(Mat mat, MatSolverType type, MatFactorType ftype, PetscBool *flg)
5018: {
5019:   PetscErrorCode (*gconv)(Mat, MatFactorType, Mat *);

5021:   PetscFunctionBegin;
5023:   PetscAssertPointer(flg, 4);

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

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

5031:   PetscCall(MatSolverTypeGet(type, ((PetscObject)mat)->type_name, ftype, NULL, NULL, &gconv));
5032:   *flg = gconv ? PETSC_TRUE : PETSC_FALSE;
5033:   PetscFunctionReturn(PETSC_SUCCESS);
5034: }

5036: /*@
5037:   MatDuplicate - Duplicates a matrix including the non-zero structure.

5039:   Collective

5041:   Input Parameters:
5042: + mat - the matrix
5043: - op  - One of `MAT_DO_NOT_COPY_VALUES`, `MAT_COPY_VALUES`, or `MAT_SHARE_NONZERO_PATTERN`.
5044:         See the manual page for `MatDuplicateOption()` for an explanation of these options.

5046:   Output Parameter:
5047: . M - pointer to place new matrix

5049:   Level: intermediate

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

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

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

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

5062: .seealso: [](ch_matrices), `Mat`, `MatCopy()`, `MatConvert()`, `MatDuplicateOption`
5063: @*/
5064: PetscErrorCode MatDuplicate(Mat mat, MatDuplicateOption op, Mat *M)
5065: {
5066:   Mat               B;
5067:   VecType           vtype;
5068:   PetscInt          i;
5069:   PetscObject       dm, container_h, container_d;
5070:   PetscErrorCodeFn *viewf;

5072:   PetscFunctionBegin;
5075:   PetscAssertPointer(M, 3);
5076:   PetscCheck(op != MAT_COPY_VALUES || mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "MAT_COPY_VALUES not allowed for unassembled matrix");
5077:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
5078:   MatCheckPreallocated(mat, 1);

5080:   PetscCall(PetscLogEventBegin(MAT_Convert, mat, 0, 0, 0));
5081:   PetscUseTypeMethod(mat, duplicate, op, M);
5082:   PetscCall(PetscLogEventEnd(MAT_Convert, mat, 0, 0, 0));
5083:   B = *M;

5085:   PetscCall(MatGetOperation(mat, MATOP_VIEW, &viewf));
5086:   if (viewf) PetscCall(MatSetOperation(B, MATOP_VIEW, viewf));
5087:   PetscCall(MatGetVecType(mat, &vtype));
5088:   PetscCall(MatSetVecType(B, vtype));

5090:   B->stencil.dim = mat->stencil.dim;
5091:   B->stencil.noc = mat->stencil.noc;
5092:   for (i = 0; i <= mat->stencil.dim + (mat->stencil.noc ? 0 : -1); i++) {
5093:     B->stencil.dims[i]   = mat->stencil.dims[i];
5094:     B->stencil.starts[i] = mat->stencil.starts[i];
5095:   }

5097:   B->nooffproczerorows = mat->nooffproczerorows;
5098:   B->nooffprocentries  = mat->nooffprocentries;

5100:   PetscCall(PetscObjectQuery((PetscObject)mat, "__PETSc_dm", &dm));
5101:   if (dm) PetscCall(PetscObjectCompose((PetscObject)B, "__PETSc_dm", dm));
5102:   PetscCall(PetscObjectQuery((PetscObject)mat, "__PETSc_MatCOOStruct_Host", &container_h));
5103:   if (container_h) PetscCall(PetscObjectCompose((PetscObject)B, "__PETSc_MatCOOStruct_Host", container_h));
5104:   PetscCall(PetscObjectQuery((PetscObject)mat, "__PETSc_MatCOOStruct_Device", &container_d));
5105:   if (container_d) PetscCall(PetscObjectCompose((PetscObject)B, "__PETSc_MatCOOStruct_Device", container_d));
5106:   if (op == MAT_COPY_VALUES) PetscCall(MatPropagateSymmetryOptions(mat, B));
5107:   PetscCall(PetscObjectStateIncrease((PetscObject)B));
5108:   PetscFunctionReturn(PETSC_SUCCESS);
5109: }

5111: /*@
5112:   MatGetDiagonal - Gets the diagonal of a matrix as a `Vec`

5114:   Logically Collective

5116:   Input Parameter:
5117: . mat - the matrix

5119:   Output Parameter:
5120: . v - the diagonal of the matrix

5122:   Level: intermediate

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

5129:   Currently only correct in parallel for square matrices.

5131: .seealso: [](ch_matrices), `Mat`, `Vec`, `MatGetRow()`, `MatCreateSubMatrices()`, `MatCreateSubMatrix()`, `MatGetRowMaxAbs()`
5132: @*/
5133: PetscErrorCode MatGetDiagonal(Mat mat, Vec v)
5134: {
5135:   PetscFunctionBegin;
5139:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
5140:   MatCheckPreallocated(mat, 1);
5141:   if (PetscDefined(USE_DEBUG)) {
5142:     PetscInt nv, row, col, ndiag;

5144:     PetscCall(VecGetLocalSize(v, &nv));
5145:     PetscCall(MatGetLocalSize(mat, &row, &col));
5146:     ndiag = PetscMin(row, col);
5147:     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);
5148:   }

5150:   PetscUseTypeMethod(mat, getdiagonal, v);
5151:   PetscCall(PetscObjectStateIncrease((PetscObject)v));
5152:   PetscFunctionReturn(PETSC_SUCCESS);
5153: }

5155: /*@
5156:   MatGetRowMin - Gets the minimum value (of the real part) of each
5157:   row of the matrix

5159:   Logically Collective

5161:   Input Parameter:
5162: . mat - the matrix

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

5168:   Level: intermediate

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

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

5176: .seealso: [](ch_matrices), `Mat`, `MatGetDiagonal()`, `MatCreateSubMatrices()`, `MatCreateSubMatrix()`, `MatGetRowMaxAbs()`, `MatGetRowMinAbs()`,
5177:           `MatGetRowMax()`
5178: @*/
5179: PetscErrorCode MatGetRowMin(Mat mat, Vec v, PetscInt idx[])
5180: {
5181:   PetscFunctionBegin;
5185:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");

5187:   if (!mat->cmap->N) {
5188:     PetscCall(VecSet(v, PETSC_MAX_REAL));
5189:     if (idx) {
5190:       PetscInt i, m = mat->rmap->n;
5191:       for (i = 0; i < m; i++) idx[i] = -1;
5192:     }
5193:   } else {
5194:     MatCheckPreallocated(mat, 1);
5195:   }
5196:   PetscUseTypeMethod(mat, getrowmin, v, idx);
5197:   PetscCall(PetscObjectStateIncrease((PetscObject)v));
5198:   PetscFunctionReturn(PETSC_SUCCESS);
5199: }

5201: /*@
5202:   MatGetRowMinAbs - Gets the minimum value (in absolute value) of each
5203:   row of the matrix

5205:   Logically Collective

5207:   Input Parameter:
5208: . mat - the matrix

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

5214:   Level: intermediate

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

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

5222: .seealso: [](ch_matrices), `Mat`, `MatGetDiagonal()`, `MatCreateSubMatrices()`, `MatCreateSubMatrix()`, `MatGetRowMax()`, `MatGetRowMaxAbs()`, `MatGetRowMin()`
5223: @*/
5224: PetscErrorCode MatGetRowMinAbs(Mat mat, Vec v, PetscInt idx[])
5225: {
5226:   PetscFunctionBegin;
5230:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
5231:   PetscCheck(!mat->factortype, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");

5233:   if (!mat->cmap->N) {
5234:     PetscCall(VecSet(v, 0.0));
5235:     if (idx) {
5236:       PetscInt i, m = mat->rmap->n;
5237:       for (i = 0; i < m; i++) idx[i] = -1;
5238:     }
5239:   } else {
5240:     MatCheckPreallocated(mat, 1);
5241:     if (idx) PetscCall(PetscArrayzero(idx, mat->rmap->n));
5242:     PetscUseTypeMethod(mat, getrowminabs, v, idx);
5243:   }
5244:   PetscCall(PetscObjectStateIncrease((PetscObject)v));
5245:   PetscFunctionReturn(PETSC_SUCCESS);
5246: }

5248: /*@
5249:   MatGetRowMax - Gets the maximum value (of the real part) of each
5250:   row of the matrix

5252:   Logically Collective

5254:   Input Parameter:
5255: . mat - the matrix

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

5261:   Level: intermediate

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

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

5269: .seealso: [](ch_matrices), `Mat`, `MatGetDiagonal()`, `MatCreateSubMatrices()`, `MatCreateSubMatrix()`, `MatGetRowMaxAbs()`, `MatGetRowMin()`, `MatGetRowMinAbs()`
5270: @*/
5271: PetscErrorCode MatGetRowMax(Mat mat, Vec v, PetscInt idx[])
5272: {
5273:   PetscFunctionBegin;
5277:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");

5279:   if (!mat->cmap->N) {
5280:     PetscCall(VecSet(v, PETSC_MIN_REAL));
5281:     if (idx) {
5282:       PetscInt i, m = mat->rmap->n;
5283:       for (i = 0; i < m; i++) idx[i] = -1;
5284:     }
5285:   } else {
5286:     MatCheckPreallocated(mat, 1);
5287:     PetscUseTypeMethod(mat, getrowmax, v, idx);
5288:   }
5289:   PetscCall(PetscObjectStateIncrease((PetscObject)v));
5290:   PetscFunctionReturn(PETSC_SUCCESS);
5291: }

5293: /*@
5294:   MatGetRowMaxAbs - Gets the maximum value (in absolute value) of each
5295:   row of the matrix

5297:   Logically Collective

5299:   Input Parameter:
5300: . mat - the matrix

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

5306:   Level: intermediate

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

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

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

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

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

5342:   Logically Collective

5344:   Input Parameter:
5345: . mat - the matrix

5347:   Output Parameter:
5348: . v - the vector for storing the sum

5350:   Level: intermediate

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

5354: .seealso: [](ch_matrices), `Mat`, `MatGetDiagonal()`, `MatCreateSubMatrices()`, `MatCreateSubMatrix()`, `MatGetRowMax()`, `MatGetRowMin()`, `MatGetRowMinAbs()`
5355: @*/
5356: PetscErrorCode MatGetRowSumAbs(Mat mat, Vec v)
5357: {
5358:   PetscFunctionBegin;
5362:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");

5364:   if (!mat->cmap->N) PetscCall(VecSet(v, 0.0));
5365:   else {
5366:     MatCheckPreallocated(mat, 1);
5367:     PetscUseTypeMethod(mat, getrowsumabs, v);
5368:   }
5369:   PetscCall(PetscObjectStateIncrease((PetscObject)v));
5370:   PetscFunctionReturn(PETSC_SUCCESS);
5371: }

5373: /*@
5374:   MatGetRowSum - Gets the sum of each row of the matrix

5376:   Logically or Neighborhood Collective

5378:   Input Parameter:
5379: . mat - the matrix

5381:   Output Parameter:
5382: . v - the vector for storing the sum of rows

5384:   Level: intermediate

5386:   Note:
5387:   This code is slow since it is not currently specialized for different formats

5389: .seealso: [](ch_matrices), `Mat`, `MatGetDiagonal()`, `MatCreateSubMatrices()`, `MatCreateSubMatrix()`, `MatGetRowMax()`, `MatGetRowMin()`, `MatGetRowMaxAbs()`, `MatGetRowMinAbs()`, `MatGetRowSumAbs()`
5390: @*/
5391: PetscErrorCode MatGetRowSum(Mat mat, Vec v)
5392: {
5393:   Vec ones;

5395:   PetscFunctionBegin;
5399:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
5400:   MatCheckPreallocated(mat, 1);
5401:   PetscCall(MatCreateVecs(mat, &ones, NULL));
5402:   PetscCall(VecSet(ones, 1.));
5403:   PetscCall(MatMult(mat, ones, v));
5404:   PetscCall(VecDestroy(&ones));
5405:   PetscFunctionReturn(PETSC_SUCCESS);
5406: }

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

5412:   Collective

5414:   Input Parameter:
5415: . mat - the matrix to provide the transpose

5417:   Output Parameter:
5418: . 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

5420:   Level: advanced

5422:   Note:
5423:   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
5424:   routine allows bypassing that call.

5426: .seealso: [](ch_matrices), `Mat`, `MatTransposeSymbolic()`, `MatTranspose()`, `MatMultTranspose()`, `MatMultTransposeAdd()`, `MatIsTranspose()`, `MatReuse`, `MAT_INITIAL_MATRIX`, `MAT_REUSE_MATRIX`, `MAT_INPLACE_MATRIX`
5427: @*/
5428: PetscErrorCode MatTransposeSetPrecursor(Mat mat, Mat B)
5429: {
5430:   MatParentState *rb = NULL;

5432:   PetscFunctionBegin;
5433:   PetscCall(PetscNew(&rb));
5434:   rb->id    = ((PetscObject)mat)->id;
5435:   rb->state = 0;
5436:   PetscCall(MatGetNonzeroState(mat, &rb->nonzerostate));
5437:   PetscCall(PetscObjectContainerCompose((PetscObject)B, "MatTransposeParent", rb, PetscCtxDestroyDefault));
5438:   PetscFunctionReturn(PETSC_SUCCESS);
5439: }

5441: static PetscErrorCode MatTranspose_Private(Mat mat, MatReuse reuse, Mat *B, PetscBool conjugate)
5442: {
5443:   PetscContainer  rB                        = NULL;
5444:   MatParentState *rb                        = NULL;
5445:   PetscErrorCode (*f)(Mat, MatReuse, Mat *) = NULL;

5447:   PetscFunctionBegin;
5450:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
5451:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
5452:   PetscCheck(reuse != MAT_INPLACE_MATRIX || mat == *B, PetscObjectComm((PetscObject)mat), PETSC_ERR_SUP, "MAT_INPLACE_MATRIX requires last matrix to match first");
5453:   PetscCheck(reuse != MAT_REUSE_MATRIX || mat != *B, PetscObjectComm((PetscObject)mat), PETSC_ERR_SUP, "Perhaps you mean MAT_INPLACE_MATRIX");
5454:   MatCheckPreallocated(mat, 1);
5455:   if (reuse == MAT_REUSE_MATRIX) {
5456:     PetscCall(PetscObjectQuery((PetscObject)*B, "MatTransposeParent", (PetscObject *)&rB));
5457:     PetscCheck(rB, PetscObjectComm((PetscObject)*B), PETSC_ERR_ARG_WRONG, "Reuse matrix used was not generated from call to MatTranspose(). Suggest MatTransposeSetPrecursor().");
5458:     PetscCall(PetscContainerGetPointer(rB, &rb));
5459:     PetscCheck(rb->id == ((PetscObject)mat)->id, PetscObjectComm((PetscObject)*B), PETSC_ERR_ARG_WRONG, "Reuse matrix used was not generated from input matrix");
5460:     if (rb->state == ((PetscObject)mat)->state) PetscFunctionReturn(PETSC_SUCCESS);
5461:   }

5463:   if (conjugate) {
5464:     f = mat->ops->hermitiantranspose;
5465:     if (f) PetscCall((*f)(mat, reuse, B));
5466:   }
5467:   if (!f && !(reuse == MAT_INPLACE_MATRIX && mat->hermitian == PETSC_BOOL3_TRUE && conjugate)) {
5468:     PetscCall(PetscLogEventBegin(MAT_Transpose, mat, 0, 0, 0));
5469:     if (reuse != MAT_INPLACE_MATRIX || mat->symmetric != PETSC_BOOL3_TRUE) {
5470:       PetscUseTypeMethod(mat, transpose, reuse, B);
5471:       PetscCall(PetscObjectStateIncrease((PetscObject)*B));
5472:     }
5473:     PetscCall(PetscLogEventEnd(MAT_Transpose, mat, 0, 0, 0));
5474:     if (conjugate) PetscCall(MatConjugate(*B));
5475:   }

5477:   if (reuse == MAT_INITIAL_MATRIX) PetscCall(MatTransposeSetPrecursor(mat, *B));
5478:   if (reuse != MAT_INPLACE_MATRIX) {
5479:     PetscCall(PetscObjectQuery((PetscObject)*B, "MatTransposeParent", (PetscObject *)&rB));
5480:     PetscCall(PetscContainerGetPointer(rB, &rb));
5481:     rb->state        = ((PetscObject)mat)->state;
5482:     rb->nonzerostate = mat->nonzerostate;
5483:   }
5484:   PetscFunctionReturn(PETSC_SUCCESS);
5485: }

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

5490:   Collective

5492:   Input Parameters:
5493: + mat   - the matrix to transpose
5494: - reuse - either `MAT_INITIAL_MATRIX`, `MAT_REUSE_MATRIX`, or `MAT_INPLACE_MATRIX`

5496:   Output Parameter:
5497: . B - the transpose of the matrix

5499:   Level: intermediate

5501:   Notes:
5502:   If you use `MAT_INPLACE_MATRIX` then you must pass in `&mat` for `B`

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

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

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

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

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

5516: .seealso: [](ch_matrices), `Mat`, `MatTransposeSetPrecursor()`, `MatMultTranspose()`, `MatMultTransposeAdd()`, `MatIsTranspose()`, `MatReuse`, `MAT_INITIAL_MATRIX`, `MAT_REUSE_MATRIX`, `MAT_INPLACE_MATRIX`,
5517:           `MatTransposeSymbolic()`, `MatCreateTranspose()`
5518: @*/
5519: PetscErrorCode MatTranspose(Mat mat, MatReuse reuse, Mat *B)
5520: {
5521:   PetscFunctionBegin;
5522:   PetscCall(MatTranspose_Private(mat, reuse, B, PETSC_FALSE));
5523:   PetscFunctionReturn(PETSC_SUCCESS);
5524: }

5526: /*@
5527:   MatTransposeSymbolic - Computes the symbolic part of the transpose of a matrix.

5529:   Collective

5531:   Input Parameter:
5532: . A - the matrix to transpose

5534:   Output Parameter:
5535: . 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
5536:       numerical portion.

5538:   Level: intermediate

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

5543: .seealso: [](ch_matrices), `Mat`, `MatTransposeSetPrecursor()`, `MatTranspose()`, `MatMultTranspose()`, `MatMultTransposeAdd()`, `MatIsTranspose()`, `MatReuse`, `MAT_INITIAL_MATRIX`, `MAT_REUSE_MATRIX`, `MAT_INPLACE_MATRIX`
5544: @*/
5545: PetscErrorCode MatTransposeSymbolic(Mat A, Mat *B)
5546: {
5547:   PetscFunctionBegin;
5550:   PetscCheck(A->assembled, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
5551:   PetscCheck(!A->factortype, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
5552:   PetscCall(PetscLogEventBegin(MAT_Transpose, A, 0, 0, 0));
5553:   PetscUseTypeMethod(A, transposesymbolic, B);
5554:   PetscCall(PetscLogEventEnd(MAT_Transpose, A, 0, 0, 0));

5556:   PetscCall(MatTransposeSetPrecursor(A, *B));
5557:   PetscFunctionReturn(PETSC_SUCCESS);
5558: }

5560: PetscErrorCode MatTransposeCheckNonzeroState_Private(Mat A, Mat B)
5561: {
5562:   PetscContainer  rB;
5563:   MatParentState *rb;

5565:   PetscFunctionBegin;
5568:   PetscCheck(A->assembled, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
5569:   PetscCheck(!A->factortype, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
5570:   PetscCall(PetscObjectQuery((PetscObject)B, "MatTransposeParent", (PetscObject *)&rB));
5571:   PetscCheck(rB, PetscObjectComm((PetscObject)B), PETSC_ERR_ARG_WRONG, "Reuse matrix used was not generated from call to MatTranspose()");
5572:   PetscCall(PetscContainerGetPointer(rB, &rb));
5573:   PetscCheck(rb->id == ((PetscObject)A)->id, PetscObjectComm((PetscObject)B), PETSC_ERR_ARG_WRONG, "Reuse matrix used was not generated from input matrix");
5574:   PetscCheck(rb->nonzerostate == A->nonzerostate, PetscObjectComm((PetscObject)B), PETSC_ERR_ARG_WRONGSTATE, "Reuse matrix has changed nonzero structure");
5575:   PetscFunctionReturn(PETSC_SUCCESS);
5576: }

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

5582:   Collective

5584:   Input Parameters:
5585: + A   - the matrix to test
5586: . B   - the matrix to test against, this can equal the first parameter
5587: - tol - tolerance, differences between entries smaller than this are counted as zero

5589:   Output Parameter:
5590: . flg - the result

5592:   Level: intermediate

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

5598: .seealso: [](ch_matrices), `Mat`, `MatTranspose()`, `MatIsSymmetric()`, `MatIsHermitian()`
5599: @*/
5600: PetscErrorCode MatIsTranspose(Mat A, Mat B, PetscReal tol, PetscBool *flg)
5601: {
5602:   PetscErrorCode (*f)(Mat, Mat, PetscReal, PetscBool *), (*g)(Mat, Mat, PetscReal, PetscBool *);

5604:   PetscFunctionBegin;
5607:   PetscAssertPointer(flg, 4);
5608:   PetscCall(PetscObjectQueryFunction((PetscObject)A, "MatIsTranspose_C", &f));
5609:   PetscCall(PetscObjectQueryFunction((PetscObject)B, "MatIsTranspose_C", &g));
5610:   *flg = PETSC_FALSE;
5611:   if (f && g) {
5612:     PetscCheck(f == g, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_NOTSAMETYPE, "Matrices do not have the same comparator for symmetry test");
5613:     PetscCall((*f)(A, B, tol, flg));
5614:   } else {
5615:     MatType mattype;

5617:     PetscCall(MatGetType(f ? B : A, &mattype));
5618:     SETERRQ(PETSC_COMM_SELF, PETSC_ERR_SUP, "Matrix of type %s does not support checking for transpose", mattype);
5619:   }
5620:   PetscFunctionReturn(PETSC_SUCCESS);
5621: }

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

5626:   Collective

5628:   Input Parameters:
5629: + mat   - the matrix to transpose and complex conjugate
5630: - reuse - either `MAT_INITIAL_MATRIX`, `MAT_REUSE_MATRIX`, or `MAT_INPLACE_MATRIX`

5632:   Output Parameter:
5633: . B - the Hermitian transpose

5635:   Level: intermediate

5637: .seealso: [](ch_matrices), `Mat`, `MatTranspose()`, `MatMultTranspose()`, `MatMultTransposeAdd()`, `MatIsTranspose()`, `MatReuse`
5638: @*/
5639: PetscErrorCode MatHermitianTranspose(Mat mat, MatReuse reuse, Mat *B)
5640: {
5641:   PetscFunctionBegin;
5642:   PetscCall(MatTranspose_Private(mat, reuse, B, PETSC_TRUE));
5643:   PetscFunctionReturn(PETSC_SUCCESS);
5644: }

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

5649:   Collective

5651:   Input Parameters:
5652: + A   - the matrix to test
5653: . B   - the matrix to test against, this can equal the first parameter
5654: - tol - tolerance, differences between entries smaller than this are counted as zero

5656:   Output Parameter:
5657: . flg - the result

5659:   Level: intermediate

5661:   Notes:
5662:   Only available for `MATAIJ` matrices.

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

5668: .seealso: [](ch_matrices), `Mat`, `MatTranspose()`, `MatIsSymmetric()`, `MatIsHermitian()`, `MatIsTranspose()`
5669: @*/
5670: PetscErrorCode MatIsHermitianTranspose(Mat A, Mat B, PetscReal tol, PetscBool *flg)
5671: {
5672:   PetscErrorCode (*f)(Mat, Mat, PetscReal, PetscBool *), (*g)(Mat, Mat, PetscReal, PetscBool *);

5674:   PetscFunctionBegin;
5677:   PetscAssertPointer(flg, 4);
5678:   PetscCall(PetscObjectQueryFunction((PetscObject)A, "MatIsHermitianTranspose_C", &f));
5679:   PetscCall(PetscObjectQueryFunction((PetscObject)B, "MatIsHermitianTranspose_C", &g));
5680:   if (f && g) {
5681:     PetscCheck(f == g, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_NOTSAMETYPE, "Matrices do not have the same comparator for Hermitian test");
5682:     PetscCall((*f)(A, B, tol, flg));
5683:   } else {
5684:     MatType mattype;

5686:     PetscCall(MatGetType(f ? B : A, &mattype));
5687:     SETERRQ(PETSC_COMM_SELF, PETSC_ERR_SUP, "Matrix of type %s does not support checking for Hermitian transpose", mattype);
5688:   }
5689:   PetscFunctionReturn(PETSC_SUCCESS);
5690: }

5692: /*@
5693:   MatPermute - Creates a new matrix with rows and columns permuted from the
5694:   original.

5696:   Collective

5698:   Input Parameters:
5699: + mat - the matrix to permute
5700: . row - row permutation, each processor supplies only the permutation for its rows
5701: - col - column permutation, each processor supplies only the permutation for its columns

5703:   Output Parameter:
5704: . B - the permuted matrix

5706:   Level: advanced

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

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

5717: .seealso: [](ch_matrices), `Mat`, `MatGetOrdering()`, `ISAllGather()`, `MatCreateSubMatrix()`
5718: @*/
5719: PetscErrorCode MatPermute(Mat mat, IS row, IS col, Mat *B)
5720: {
5721:   PetscFunctionBegin;
5726:   PetscAssertPointer(B, 4);
5727:   PetscCheckSameComm(mat, 1, row, 2);
5728:   if (row != col) PetscCheckSameComm(row, 2, col, 3);
5729:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
5730:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
5731:   PetscCheck(mat->ops->permute || mat->ops->createsubmatrix, PETSC_COMM_SELF, PETSC_ERR_SUP, "MatPermute not available for Mat type %s", ((PetscObject)mat)->type_name);
5732:   MatCheckPreallocated(mat, 1);

5734:   if (mat->ops->permute) {
5735:     PetscUseTypeMethod(mat, permute, row, col, B);
5736:     PetscCall(PetscObjectStateIncrease((PetscObject)*B));
5737:   } else {
5738:     PetscCall(MatCreateSubMatrix(mat, row, col, MAT_INITIAL_MATRIX, B));
5739:   }
5740:   PetscFunctionReturn(PETSC_SUCCESS);
5741: }

5743: /*@
5744:   MatEqual - Compares two matrices.

5746:   Collective

5748:   Input Parameters:
5749: + A - the first matrix
5750: - B - the second matrix

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

5755:   Level: intermediate

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

5761: .seealso: [](ch_matrices), `Mat`, `MatMultEqual()`
5762: @*/
5763: PetscErrorCode MatEqual(Mat A, Mat B, PetscBool *flg)
5764: {
5765:   PetscFunctionBegin;
5770:   PetscAssertPointer(flg, 3);
5771:   PetscCheckSameComm(A, 1, B, 2);
5772:   MatCheckPreallocated(A, 1);
5773:   MatCheckPreallocated(B, 2);
5774:   PetscCheck(A->assembled, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
5775:   PetscCheck(B->assembled, PetscObjectComm((PetscObject)B), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
5776:   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,
5777:              B->cmap->N);
5778:   if (A->ops->equal && A->ops->equal == B->ops->equal) PetscUseTypeMethod(A, equal, B, flg);
5779:   else PetscCall(MatMultEqual(A, B, 10, flg));
5780:   PetscFunctionReturn(PETSC_SUCCESS);
5781: }

5783: /*@
5784:   MatDiagonalScale - Scales a matrix on the left and right by diagonal
5785:   matrices that are stored as vectors.  Either of the two scaling
5786:   matrices can be `NULL`.

5788:   Collective

5790:   Input Parameters:
5791: + mat - the matrix to be scaled
5792: . l   - the left scaling vector (or `NULL`)
5793: - r   - the right scaling vector (or `NULL`)

5795:   Level: intermediate

5797:   Note:
5798:   `MatDiagonalScale()` computes $A = LAR$, where
5799:   L = a diagonal matrix (stored as a vector), R = a diagonal matrix (stored as a vector)
5800:   The L scales the rows of the matrix, the R scales the columns of the matrix.

5802: .seealso: [](ch_matrices), `Mat`, `MatScale()`, `MatShift()`, `MatDiagonalSet()`
5803: @*/
5804: PetscErrorCode MatDiagonalScale(Mat mat, Vec l, Vec r)
5805: {
5806:   PetscBool flg = PETSC_FALSE;

5808:   PetscFunctionBegin;
5811:   if (l) {
5813:     PetscCheckSameComm(mat, 1, l, 2);
5814:   }
5815:   if (r) {
5817:     PetscCheckSameComm(mat, 1, r, 3);
5818:   }
5819:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
5820:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
5821:   MatCheckPreallocated(mat, 1);
5822:   if (!l && !r) PetscFunctionReturn(PETSC_SUCCESS);

5824:   PetscCall(PetscLogEventBegin(MAT_Scale, mat, 0, 0, 0));
5825:   PetscUseTypeMethod(mat, diagonalscale, l, r);
5826:   PetscCall(PetscLogEventEnd(MAT_Scale, mat, 0, 0, 0));
5827:   PetscCall(PetscObjectStateIncrease((PetscObject)mat));
5828:   if (l != r && (PetscBool3ToBool(mat->symmetric) || PetscBool3ToBool(mat->hermitian))) {
5829:     if (!PetscDefined(USE_COMPLEX) || PetscBool3ToBool(mat->symmetric)) {
5830:       if (l && r) PetscCall(VecEqual(l, r, &flg));
5831:       if (!flg) {
5832:         PetscCall(PetscObjectTypeCompareAny((PetscObject)mat, &flg, MATSEQSBAIJ, MATMPISBAIJ, ""));
5833:         PetscCheck(!flg, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_OUTOFRANGE, "For symmetric format, left and right scaling vectors must be the same");
5834:         mat->symmetric = mat->spd = PETSC_BOOL3_FALSE;
5835:         if (!PetscDefined(USE_COMPLEX)) mat->hermitian = PETSC_BOOL3_FALSE;
5836:         else mat->hermitian = PETSC_BOOL3_UNKNOWN;
5837:       }
5838:     }
5839:     if (PetscDefined(USE_COMPLEX) && PetscBool3ToBool(mat->hermitian)) {
5840:       flg = PETSC_FALSE;
5841:       if (l && r) {
5842:         Vec conjugate;

5844:         PetscCall(VecDuplicate(l, &conjugate));
5845:         PetscCall(VecCopy(l, conjugate));
5846:         PetscCall(VecConjugate(conjugate));
5847:         PetscCall(VecEqual(conjugate, r, &flg));
5848:         PetscCall(VecDestroy(&conjugate));
5849:       }
5850:       if (!flg) {
5851:         PetscCall(PetscObjectTypeCompareAny((PetscObject)mat, &flg, MATSEQSBAIJ, MATMPISBAIJ, ""));
5852:         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");
5853:         mat->hermitian = PETSC_BOOL3_FALSE;
5854:         mat->symmetric = mat->spd = PETSC_BOOL3_UNKNOWN;
5855:       }
5856:     }
5857:   }
5858:   PetscFunctionReturn(PETSC_SUCCESS);
5859: }

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

5864:   Logically Collective

5866:   Input Parameters:
5867: + mat - the matrix to be scaled
5868: - a   - the scaling value

5870:   Level: intermediate

5872: .seealso: [](ch_matrices), `Mat`, `MatDiagonalScale()`
5873: @*/
5874: PetscErrorCode MatScale(Mat mat, PetscScalar a)
5875: {
5876:   PetscFunctionBegin;
5879:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
5880:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
5882:   MatCheckPreallocated(mat, 1);

5884:   PetscCall(PetscLogEventBegin(MAT_Scale, mat, 0, 0, 0));
5885:   if (a != (PetscScalar)1.0) {
5886:     PetscUseTypeMethod(mat, scale, a);
5887:     PetscCall(PetscObjectStateIncrease((PetscObject)mat));
5888:   }
5889:   PetscCall(PetscLogEventEnd(MAT_Scale, mat, 0, 0, 0));
5890:   PetscFunctionReturn(PETSC_SUCCESS);
5891: }

5893: /*@
5894:   MatNorm - Calculates various norms of a matrix.

5896:   Collective

5898:   Input Parameters:
5899: + mat  - the matrix
5900: - type - the type of norm, `NORM_1`, `NORM_FROBENIUS`, `NORM_INFINITY`

5902:   Output Parameter:
5903: . nrm - the resulting norm

5905:   Level: intermediate

5907: .seealso: [](ch_matrices), `Mat`
5908: @*/
5909: PetscErrorCode MatNorm(Mat mat, NormType type, PetscReal *nrm)
5910: {
5911:   PetscFunctionBegin;
5914:   PetscAssertPointer(nrm, 3);

5916:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
5917:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
5918:   MatCheckPreallocated(mat, 1);

5920:   PetscUseTypeMethod(mat, norm, type, nrm);
5921:   PetscFunctionReturn(PETSC_SUCCESS);
5922: }

5924: /*
5925:      This variable is used to prevent counting of MatAssemblyBegin() that
5926:    are called from within a MatAssemblyEnd().
5927: */
5928: static PetscInt MatAssemblyEnd_InUse = 0;
5929: /*@
5930:   MatAssemblyBegin - Begins assembling the matrix.  This routine should
5931:   be called after completing all calls to `MatSetValues()`.

5933:   Collective

5935:   Input Parameters:
5936: + mat  - the matrix
5937: - type - type of assembly, either `MAT_FLUSH_ASSEMBLY` or `MAT_FINAL_ASSEMBLY`

5939:   Level: beginner

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

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

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

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

5957: .seealso: [](ch_matrices), `Mat`, `MatAssemblyEnd()`, `MatSetValues()`, `MatAssembled()`
5958: @*/
5959: PetscErrorCode MatAssemblyBegin(Mat mat, MatAssemblyType type)
5960: {
5961:   PetscFunctionBegin;
5964:   MatCheckPreallocated(mat, 1);
5965:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix. Did you forget to call MatSetUnfactored()?");
5966:   if (mat->assembled) {
5967:     mat->was_assembled = PETSC_TRUE;
5968:     mat->assembled     = PETSC_FALSE;
5969:   }

5971:   if (!MatAssemblyEnd_InUse) {
5972:     PetscCall(PetscLogEventBegin(MAT_AssemblyBegin, mat, 0, 0, 0));
5973:     PetscTryTypeMethod(mat, assemblybegin, type);
5974:     PetscCall(PetscLogEventEnd(MAT_AssemblyBegin, mat, 0, 0, 0));
5975:   } else PetscTryTypeMethod(mat, assemblybegin, type);
5976:   PetscFunctionReturn(PETSC_SUCCESS);
5977: }

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

5983:   Not Collective

5985:   Input Parameter:
5986: . mat - the matrix

5988:   Output Parameter:
5989: . assembled - `PETSC_TRUE` or `PETSC_FALSE`

5991:   Level: advanced

5993: .seealso: [](ch_matrices), `Mat`, `MatAssemblyEnd()`, `MatSetValues()`, `MatAssemblyBegin()`
5994: @*/
5995: PetscErrorCode MatAssembled(Mat mat, PetscBool *assembled)
5996: {
5997:   PetscFunctionBegin;
5999:   PetscAssertPointer(assembled, 2);
6000:   *assembled = mat->assembled;
6001:   PetscFunctionReturn(PETSC_SUCCESS);
6002: }

6004: /*@
6005:   MatAssemblyEnd - Completes assembling the matrix.  This routine should
6006:   be called after `MatAssemblyBegin()`.

6008:   Collective

6010:   Input Parameters:
6011: + mat  - the matrix
6012: - type - type of assembly, either `MAT_FLUSH_ASSEMBLY` or `MAT_FINAL_ASSEMBLY`

6014:   Options Database Keys:
6015: + -mat_view ::ascii_info             - Prints info on matrix at conclusion of `MatAssemblyEnd()`
6016: . -mat_view ::ascii_info_detail      - Prints more detailed info
6017: . -mat_view                          - Prints matrix in ASCII format
6018: . -mat_view ::ascii_matlab           - Prints matrix in MATLAB format
6019: . -mat_view draw                     - draws nonzero structure of matrix, using `MatView()` and `PetscDrawOpenX()`.
6020: . -display name                      - Sets display name (default is host)
6021: . -draw_pause sec                    - Sets number of seconds to pause after display
6022: . -mat_view socket                   - Sends matrix to socket, can be accessed from MATLAB (See [Using MATLAB with PETSc](ch_matlab))
6023: . -viewer_socket_machine machine     - Machine to use for socket
6024: . -viewer_socket_port port           - Port number to use for socket
6025: - -mat_view binary:filename[:append] - Save matrix to file in binary format

6027:   Level: beginner

6029: .seealso: [](ch_matrices), `Mat`, `MatAssemblyBegin()`, `MatSetValues()`, `PetscDrawOpenX()`, `PetscDrawCreate()`, `MatView()`, `MatAssembled()`, `PetscViewerSocketOpen()`
6030: @*/
6031: PetscErrorCode MatAssemblyEnd(Mat mat, MatAssemblyType type)
6032: {
6033:   static PetscInt inassm = 0;
6034:   PetscBool       flg    = PETSC_FALSE;

6036:   PetscFunctionBegin;

6040:   inassm++;
6041:   MatAssemblyEnd_InUse++;
6042:   if (MatAssemblyEnd_InUse == 1) { /* Do the logging only the first time through */
6043:     PetscCall(PetscLogEventBegin(MAT_AssemblyEnd, mat, 0, 0, 0));
6044:     PetscTryTypeMethod(mat, assemblyend, type);
6045:     PetscCall(PetscLogEventEnd(MAT_AssemblyEnd, mat, 0, 0, 0));
6046:   } else PetscTryTypeMethod(mat, assemblyend, type);

6048:   /* Flush assembly is not a true assembly */
6049:   if (type != MAT_FLUSH_ASSEMBLY) {
6050:     if (mat->num_ass) {
6051:       if (!mat->symmetry_eternal) {
6052:         mat->symmetric = PETSC_BOOL3_UNKNOWN;
6053:         mat->hermitian = PETSC_BOOL3_UNKNOWN;
6054:       }
6055:       if (!mat->structural_symmetry_eternal && mat->ass_nonzerostate != mat->nonzerostate) mat->structurally_symmetric = PETSC_BOOL3_UNKNOWN;
6056:       if (!mat->spd_eternal) mat->spd = PETSC_BOOL3_UNKNOWN;
6057:     }
6058:     mat->num_ass++;
6059:     mat->assembled        = PETSC_TRUE;
6060:     mat->ass_nonzerostate = mat->nonzerostate;
6061:   }

6063:   mat->insertmode = NOT_SET_VALUES;
6064:   MatAssemblyEnd_InUse--;
6065:   PetscCall(PetscObjectStateIncrease((PetscObject)mat));
6066:   if (inassm == 1 && type != MAT_FLUSH_ASSEMBLY) {
6067:     PetscCall(MatViewFromOptions(mat, NULL, "-mat_view"));

6069:     if (mat->checksymmetryonassembly) {
6070:       PetscCall(MatIsSymmetric(mat, mat->checksymmetrytol, &flg));
6071:       if (flg) {
6072:         PetscCall(PetscPrintf(PetscObjectComm((PetscObject)mat), "Matrix is symmetric (tolerance %g)\n", (double)mat->checksymmetrytol));
6073:       } else {
6074:         PetscCall(PetscPrintf(PetscObjectComm((PetscObject)mat), "Matrix is not symmetric (tolerance %g)\n", (double)mat->checksymmetrytol));
6075:       }
6076:     }
6077:     if (mat->nullsp && mat->checknullspaceonassembly) PetscCall(MatNullSpaceTest(mat->nullsp, mat, NULL));
6078:   }
6079:   inassm--;
6080:   PetscFunctionReturn(PETSC_SUCCESS);
6081: }

6083: // PetscClangLinter pragma disable: -fdoc-section-header-unknown
6084: /*@
6085:   MatSetOption - Sets a parameter option for a matrix. Some options
6086:   may be specific to certain storage formats.  Some options
6087:   determine how values will be inserted (or added). Sorted,
6088:   row-oriented input will generally assemble the fastest. The default
6089:   is row-oriented.

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

6093:   Input Parameters:
6094: + mat - the matrix
6095: . op  - the option, one of those listed below (and possibly others),
6096: - flg - turn the option on (`PETSC_TRUE`) or off (`PETSC_FALSE`)

6098:   Options Describing Matrix Structure:
6099: + `MAT_SPD`                         - symmetric positive definite
6100: . `MAT_SYMMETRIC`                   - symmetric in terms of both structure and value
6101: . `MAT_HERMITIAN`                   - transpose is the complex conjugation
6102: . `MAT_STRUCTURALLY_SYMMETRIC`      - symmetric nonzero structure
6103: . `MAT_SYMMETRY_ETERNAL`            - indicates the symmetry (or Hermitian structure) or its absence will persist through any changes to the matrix
6104: . `MAT_STRUCTURAL_SYMMETRY_ETERNAL` - indicates the structural symmetry or its absence will persist through any changes to the matrix
6105: . `MAT_SPD_ETERNAL`                 - indicates the value of `MAT_SPD` (true or false) will persist through any changes to the matrix

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

6110:    Options For Use with `MatSetValues()`:
6111:    Insert a logically dense subblock, which can be
6112: . `MAT_ROW_ORIENTED`                - row-oriented (default)

6114:    These options reflect the data you pass in with `MatSetValues()`; it has
6115:    nothing to do with how the data is stored internally in the matrix
6116:    data structure.

6118:    When (re)assembling a matrix, we can restrict the input for
6119:    efficiency/debugging purposes.  These options include
6120: . `MAT_NEW_NONZERO_LOCATIONS`       - additional insertions will be allowed if they generate a new nonzero (slow)
6121: . `MAT_FORCE_DIAGONAL_ENTRIES`      - forces diagonal entries to be allocated
6122: . `MAT_IGNORE_OFF_PROC_ENTRIES`     - drops off-processor entries
6123: . `MAT_NEW_NONZERO_LOCATION_ERR`    - generates an error for new matrix entry
6124: . `MAT_USE_HASH_TABLE`              - uses a hash table to speed up matrix assembly
6125: . `MAT_NO_OFF_PROC_ENTRIES`         - you know each process will only set values for its own rows, will generate an error if
6126:         any process sets values for another process. This avoids all reductions in the MatAssembly routines and thus improves
6127:         performance for very large process counts.
6128: - `MAT_SUBSET_OFF_PROC_ENTRIES`     - you know that the first assembly after setting this flag will set a superset
6129:         of the off-process entries required for all subsequent assemblies. This avoids a rendezvous step in the MatAssembly
6130:         functions, instead sending only neighbor messages.

6132:   Level: intermediate

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

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

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

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

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

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

6162:   `MAT_IGNORE_OFF_PROC_ENTRIES` set to `PETSC_TRUE` indicates entries destined for
6163:   other processors should be dropped, rather than stashed.
6164:   This is useful if you know that the "owning" processor is also
6165:   always generating the correct matrix entries, so that PETSc need
6166:   not transfer duplicate entries generated on another processor.

6168:   `MAT_USE_HASH_TABLE` indicates that a hash table be used to improve the
6169:   searches during matrix assembly. When this flag is set, the hash table
6170:   is created during the first matrix assembly. This hash table is
6171:   used the next time through, during `MatSetValues()`/`MatSetValuesBlocked()`
6172:   to improve the searching of indices. `MAT_NEW_NONZERO_LOCATIONS` flag
6173:   should be used with `MAT_USE_HASH_TABLE` flag. This option is currently
6174:   supported by `MATMPIBAIJ` format only.

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

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

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

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

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

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

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

6200: .seealso: [](ch_matrices), `MatOption`, `Mat`, `MatGetOption()`
6201: @*/
6202: PetscErrorCode MatSetOption(Mat mat, MatOption op, PetscBool flg)
6203: {
6204:   PetscFunctionBegin;
6206:   if (op > 0) {
6209:   }

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

6213:   switch (op) {
6214:   case MAT_FORCE_DIAGONAL_ENTRIES:
6215:     mat->force_diagonals = flg;
6216:     PetscFunctionReturn(PETSC_SUCCESS);
6217:   case MAT_NO_OFF_PROC_ENTRIES:
6218:     mat->nooffprocentries = flg;
6219:     PetscFunctionReturn(PETSC_SUCCESS);
6220:   case MAT_SUBSET_OFF_PROC_ENTRIES:
6221:     mat->assembly_subset = flg;
6222:     if (!mat->assembly_subset) { /* See the same logic in VecAssembly wrt VEC_SUBSET_OFF_PROC_ENTRIES */
6223: #if !defined(PETSC_HAVE_MPIUNI)
6224:       PetscCall(MatStashScatterDestroy_BTS(&mat->stash));
6225: #endif
6226:       mat->stash.first_assembly_done = PETSC_FALSE;
6227:     }
6228:     PetscFunctionReturn(PETSC_SUCCESS);
6229:   case MAT_NO_OFF_PROC_ZERO_ROWS:
6230:     mat->nooffproczerorows = flg;
6231:     PetscFunctionReturn(PETSC_SUCCESS);
6232:   case MAT_SPD:
6233:     if (flg) {
6234:       mat->spd                    = PETSC_BOOL3_TRUE;
6235:       mat->symmetric              = PETSC_BOOL3_TRUE;
6236:       mat->structurally_symmetric = PETSC_BOOL3_TRUE;
6237: #if !defined(PETSC_USE_COMPLEX)
6238:       mat->hermitian = PETSC_BOOL3_TRUE;
6239: #endif
6240:     } else {
6241:       mat->spd = PETSC_BOOL3_FALSE;
6242:     }
6243:     break;
6244:   case MAT_SYMMETRIC:
6245:     mat->symmetric = PetscBoolToBool3(flg);
6246:     if (flg) mat->structurally_symmetric = PETSC_BOOL3_TRUE;
6247: #if !defined(PETSC_USE_COMPLEX)
6248:     mat->hermitian = PetscBoolToBool3(flg);
6249: #endif
6250:     break;
6251:   case MAT_HERMITIAN:
6252:     mat->hermitian = PetscBoolToBool3(flg);
6253:     if (flg) mat->structurally_symmetric = PETSC_BOOL3_TRUE;
6254: #if !defined(PETSC_USE_COMPLEX)
6255:     mat->symmetric = PetscBoolToBool3(flg);
6256: #endif
6257:     break;
6258:   case MAT_STRUCTURALLY_SYMMETRIC:
6259:     mat->structurally_symmetric = PetscBoolToBool3(flg);
6260:     break;
6261:   case MAT_SYMMETRY_ETERNAL:
6262:     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");
6263:     mat->symmetry_eternal = flg;
6264:     if (flg) mat->structural_symmetry_eternal = PETSC_TRUE;
6265:     break;
6266:   case MAT_STRUCTURAL_SYMMETRY_ETERNAL:
6267:     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");
6268:     mat->structural_symmetry_eternal = flg;
6269:     break;
6270:   case MAT_SPD_ETERNAL:
6271:     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");
6272:     mat->spd_eternal = flg;
6273:     if (flg) {
6274:       mat->structural_symmetry_eternal = PETSC_TRUE;
6275:       mat->symmetry_eternal            = PETSC_TRUE;
6276:     }
6277:     break;
6278:   case MAT_STRUCTURE_ONLY:
6279:     mat->structure_only = flg;
6280:     break;
6281:   case MAT_SORTED_FULL:
6282:     mat->sortedfull = flg;
6283:     break;
6284:   default:
6285:     break;
6286:   }
6287:   PetscTryTypeMethod(mat, setoption, op, flg);
6288:   PetscFunctionReturn(PETSC_SUCCESS);
6289: }

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

6294:   Logically Collective

6296:   Input Parameters:
6297: + mat - the matrix
6298: - op  - the option, this only responds to certain options, check the code for which ones

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

6303:   Level: intermediate

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

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

6311: .seealso: [](ch_matrices), `Mat`, `MatOption`, `MatSetOption()`, `MatIsSymmetric()`, `MatIsHermitian()`, `MatIsStructurallySymmetric()`,
6312:     `MatIsSymmetricKnown()`, `MatIsHermitianKnown()`, `MatIsStructurallySymmetricKnown()`
6313: @*/
6314: PetscErrorCode MatGetOption(Mat mat, MatOption op, PetscBool *flg)
6315: {
6316:   PetscFunctionBegin;

6320:   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);
6321:   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()");

6323:   switch (op) {
6324:   case MAT_NO_OFF_PROC_ENTRIES:
6325:     *flg = mat->nooffprocentries;
6326:     break;
6327:   case MAT_NO_OFF_PROC_ZERO_ROWS:
6328:     *flg = mat->nooffproczerorows;
6329:     break;
6330:   case MAT_SYMMETRIC:
6331:     SETERRQ(PetscObjectComm((PetscObject)mat), PETSC_ERR_SUP, "Use MatIsSymmetric() or MatIsSymmetricKnown()");
6332:     break;
6333:   case MAT_HERMITIAN:
6334:     SETERRQ(PetscObjectComm((PetscObject)mat), PETSC_ERR_SUP, "Use MatIsHermitian() or MatIsHermitianKnown()");
6335:     break;
6336:   case MAT_STRUCTURALLY_SYMMETRIC:
6337:     SETERRQ(PetscObjectComm((PetscObject)mat), PETSC_ERR_SUP, "Use MatIsStructurallySymmetric() or MatIsStructurallySymmetricKnown()");
6338:     break;
6339:   case MAT_SPD:
6340:     SETERRQ(PetscObjectComm((PetscObject)mat), PETSC_ERR_SUP, "Use MatIsSPDKnown()");
6341:     break;
6342:   case MAT_SYMMETRY_ETERNAL:
6343:     *flg = mat->symmetry_eternal;
6344:     break;
6345:   case MAT_STRUCTURAL_SYMMETRY_ETERNAL:
6346:     *flg = mat->symmetry_eternal;
6347:     break;
6348:   default:
6349:     break;
6350:   }
6351:   PetscFunctionReturn(PETSC_SUCCESS);
6352: }

6354: /*@
6355:   MatZeroEntries - Zeros all entries of a matrix.  For sparse matrices
6356:   this routine retains the old nonzero structure.

6358:   Logically Collective

6360:   Input Parameter:
6361: . mat - the matrix

6363:   Level: intermediate

6365:   Note:
6366:   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.
6367:   See the Performance chapter of the users manual for information on preallocating matrices.

6369: .seealso: [](ch_matrices), `Mat`, `MatZeroRows()`, `MatZeroRowsColumns()`
6370: @*/
6371: PetscErrorCode MatZeroEntries(Mat mat)
6372: {
6373:   PetscFunctionBegin;
6376:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
6377:   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");
6378:   MatCheckPreallocated(mat, 1);

6380:   PetscCall(PetscLogEventBegin(MAT_ZeroEntries, mat, 0, 0, 0));
6381:   PetscUseTypeMethod(mat, zeroentries);
6382:   PetscCall(PetscLogEventEnd(MAT_ZeroEntries, mat, 0, 0, 0));
6383:   PetscCall(PetscObjectStateIncrease((PetscObject)mat));
6384:   PetscFunctionReturn(PETSC_SUCCESS);
6385: }

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

6391:   Collective

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

6401:   Level: intermediate

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

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

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

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

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

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

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

6426: .seealso: [](ch_matrices), `Mat`, `MatZeroRowsIS()`, `MatZeroRows()`, `MatZeroRowsLocalIS()`, `MatZeroRowsStencil()`, `MatZeroEntries()`, `MatZeroRowsLocal()`, `MatSetOption()`,
6427:           `MatZeroRowsColumnsLocal()`, `MatZeroRowsColumnsLocalIS()`, `MatZeroRowsColumnsIS()`, `MatZeroRowsColumnsStencil()`
6428: @*/
6429: PetscErrorCode MatZeroRowsColumns(Mat mat, PetscInt numRows, const PetscInt rows[], PetscScalar diag, Vec x, Vec b)
6430: {
6431:   PetscFunctionBegin;
6434:   if (numRows) PetscAssertPointer(rows, 3);
6435:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
6436:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
6437:   MatCheckPreallocated(mat, 1);

6439:   PetscUseTypeMethod(mat, zerorowscolumns, numRows, rows, diag, x, b);
6440:   PetscCall(MatViewFromOptions(mat, NULL, "-mat_view"));
6441:   PetscCall(PetscObjectStateIncrease((PetscObject)mat));
6442:   PetscFunctionReturn(PETSC_SUCCESS);
6443: }

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

6449:   Collective

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

6458:   Level: intermediate

6460:   Note:
6461:   See `MatZeroRowsColumns()` for details on how this routine operates.

6463: .seealso: [](ch_matrices), `Mat`, `MatZeroRowsIS()`, `MatZeroRowsColumns()`, `MatZeroRowsLocalIS()`, `MatZeroRowsStencil()`, `MatZeroEntries()`, `MatZeroRowsLocal()`, `MatSetOption()`,
6464:           `MatZeroRowsColumnsLocal()`, `MatZeroRowsColumnsLocalIS()`, `MatZeroRows()`, `MatZeroRowsColumnsStencil()`
6465: @*/
6466: PetscErrorCode MatZeroRowsColumnsIS(Mat mat, IS is, PetscScalar diag, Vec x, Vec b)
6467: {
6468:   PetscInt        numRows;
6469:   const PetscInt *rows;

6471:   PetscFunctionBegin;
6476:   PetscCall(ISGetLocalSize(is, &numRows));
6477:   PetscCall(ISGetIndices(is, &rows));
6478:   PetscCall(MatZeroRowsColumns(mat, numRows, rows, diag, x, b));
6479:   PetscCall(ISRestoreIndices(is, &rows));
6480:   PetscFunctionReturn(PETSC_SUCCESS);
6481: }

6483: /*@
6484:   MatZeroRows - Zeros all entries (except possibly the main diagonal)
6485:   of a set of rows of a matrix.

6487:   Collective

6489:   Input Parameters:
6490: + mat     - the matrix
6491: . numRows - the number of rows to zero
6492: . rows    - the global row indices
6493: . diag    - value put in the diagonal of the zeroed rows
6494: . x       - optional vector of solutions for zeroed rows (other entries in vector are not used), these must be set before this call
6495: - b       - optional vector of right-hand side, that will be adjusted by provided solution entries

6497:   Level: intermediate

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

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

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

6507:   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)
6508:   from the matrix.

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

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

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

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

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

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

6533: .seealso: [](ch_matrices), `Mat`, `MatZeroRowsIS()`, `MatZeroRowsColumns()`, `MatZeroRowsLocalIS()`, `MatZeroRowsStencil()`, `MatZeroEntries()`, `MatZeroRowsLocal()`, `MatSetOption()`,
6534:           `MatZeroRowsColumnsLocal()`, `MatZeroRowsColumnsLocalIS()`, `MatZeroRowsColumnsIS()`, `MatZeroRowsColumnsStencil()`, `PCREDISTRIBUTE`, `MAT_KEEP_NONZERO_PATTERN`
6535: @*/
6536: PetscErrorCode MatZeroRows(Mat mat, PetscInt numRows, const PetscInt rows[], PetscScalar diag, Vec x, Vec b)
6537: {
6538:   PetscFunctionBegin;
6541:   if (numRows) PetscAssertPointer(rows, 3);
6542:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
6543:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
6544:   MatCheckPreallocated(mat, 1);

6546:   PetscUseTypeMethod(mat, zerorows, numRows, rows, diag, x, b);
6547:   PetscCall(MatViewFromOptions(mat, NULL, "-mat_view"));
6548:   PetscCall(PetscObjectStateIncrease((PetscObject)mat));
6549:   PetscFunctionReturn(PETSC_SUCCESS);
6550: }

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

6556:   Collective

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

6565:   Level: intermediate

6567:   Note:
6568:   See `MatZeroRows()` for details on how this routine operates.

6570: .seealso: [](ch_matrices), `Mat`, `MatZeroRows()`, `MatZeroRowsColumns()`, `MatZeroRowsLocalIS()`, `MatZeroRowsStencil()`, `MatZeroEntries()`, `MatZeroRowsLocal()`, `MatSetOption()`,
6571:           `MatZeroRowsColumnsLocal()`, `MatZeroRowsColumnsLocalIS()`, `MatZeroRowsColumnsIS()`, `MatZeroRowsColumnsStencil()`, `IS`
6572: @*/
6573: PetscErrorCode MatZeroRowsIS(Mat mat, IS is, PetscScalar diag, Vec x, Vec b)
6574: {
6575:   PetscInt        numRows = 0;
6576:   const PetscInt *rows    = NULL;

6578:   PetscFunctionBegin;
6581:   if (is) {
6583:     PetscCall(ISGetLocalSize(is, &numRows));
6584:     PetscCall(ISGetIndices(is, &rows));
6585:   }
6586:   PetscCall(MatZeroRows(mat, numRows, rows, diag, x, b));
6587:   if (is) PetscCall(ISRestoreIndices(is, &rows));
6588:   PetscFunctionReturn(PETSC_SUCCESS);
6589: }

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

6595:   Collective

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

6605:   Level: intermediate

6607:   Notes:
6608:   See `MatZeroRows()` for details on how this routine operates.

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

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

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

6620:   Fortran Note:
6621:   `idxm` and `idxn` should be declared as
6622: .vb
6623:     MatStencil idxm(4, m)
6624: .ve
6625:   and the values inserted using
6626: .vb
6627:     idxm(MatStencil_i, 1) = i
6628:     idxm(MatStencil_j, 1) = j
6629:     idxm(MatStencil_k, 1) = k
6630:     idxm(MatStencil_c, 1) = c
6631:    etc
6632: .ve

6634: .seealso: [](ch_matrices), `Mat`, `MatStencil`, `MatZeroRowsIS()`, `MatZeroRowsColumns()`, `MatZeroRowsLocalIS()`, `MatZeroRows()`, `MatZeroEntries()`, `MatZeroRowsLocal()`, `MatSetOption()`,
6635:           `MatZeroRowsColumnsLocal()`, `MatZeroRowsColumnsLocalIS()`, `MatZeroRowsColumnsIS()`, `MatZeroRowsColumnsStencil()`
6636: @*/
6637: PetscErrorCode MatZeroRowsStencil(Mat mat, PetscInt numRows, const MatStencil rows[], PetscScalar diag, Vec x, Vec b)
6638: {
6639:   PetscInt  dim    = mat->stencil.dim;
6640:   PetscInt  sdim   = dim - (1 - (PetscInt)mat->stencil.noc);
6641:   PetscInt *dims   = mat->stencil.dims + 1;
6642:   PetscInt *starts = mat->stencil.starts;
6643:   PetscInt *dxm    = (PetscInt *)rows;
6644:   PetscInt *jdxm, i, j, tmp, numNewRows = 0;

6646:   PetscFunctionBegin;
6649:   if (numRows) PetscAssertPointer(rows, 3);

6651:   PetscCall(PetscMalloc1(numRows, &jdxm));
6652:   for (i = 0; i < numRows; ++i) {
6653:     /* Skip unused dimensions (they are ordered k, j, i, c) */
6654:     for (j = 0; j < 3 - sdim; ++j) dxm++;
6655:     /* Local index in X dir */
6656:     tmp = *dxm++ - starts[0];
6657:     /* Loop over remaining dimensions */
6658:     for (j = 0; j < dim - 1; ++j) {
6659:       /* If nonlocal, set index to be negative */
6660:       if ((*dxm++ - starts[j + 1]) < 0 || tmp < 0) tmp = PETSC_INT_MIN;
6661:       /* Update local index */
6662:       else tmp = tmp * dims[j] + *(dxm - 1) - starts[j + 1];
6663:     }
6664:     /* Skip component slot if necessary */
6665:     if (mat->stencil.noc) dxm++;
6666:     /* Local row number */
6667:     if (tmp >= 0) jdxm[numNewRows++] = tmp;
6668:   }
6669:   PetscCall(MatZeroRowsLocal(mat, numNewRows, jdxm, diag, x, b));
6670:   PetscCall(PetscFree(jdxm));
6671:   PetscFunctionReturn(PETSC_SUCCESS);
6672: }

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

6678:   Collective

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

6688:   Level: intermediate

6690:   Notes:
6691:   See `MatZeroRowsColumns()` for details on how this routine operates.

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

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

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

6703:   Fortran Note:
6704:   `idxm` and `idxn` should be declared as
6705: .vb
6706:     MatStencil idxm(4, m)
6707: .ve
6708:   and the values inserted using
6709: .vb
6710:     idxm(MatStencil_i, 1) = i
6711:     idxm(MatStencil_j, 1) = j
6712:     idxm(MatStencil_k, 1) = k
6713:     idxm(MatStencil_c, 1) = c
6714:     etc
6715: .ve

6717: .seealso: [](ch_matrices), `Mat`, `MatZeroRowsIS()`, `MatZeroRowsColumns()`, `MatZeroRowsLocalIS()`, `MatZeroRowsStencil()`, `MatZeroEntries()`, `MatZeroRowsLocal()`, `MatSetOption()`,
6718:           `MatZeroRowsColumnsLocal()`, `MatZeroRowsColumnsLocalIS()`, `MatZeroRowsColumnsIS()`, `MatZeroRows()`
6719: @*/
6720: PetscErrorCode MatZeroRowsColumnsStencil(Mat mat, PetscInt numRows, const MatStencil rows[], PetscScalar diag, Vec x, Vec b)
6721: {
6722:   PetscInt  dim    = mat->stencil.dim;
6723:   PetscInt  sdim   = dim - (1 - (PetscInt)mat->stencil.noc);
6724:   PetscInt *dims   = mat->stencil.dims + 1;
6725:   PetscInt *starts = mat->stencil.starts;
6726:   PetscInt *dxm    = (PetscInt *)rows;
6727:   PetscInt *jdxm, i, j, tmp, numNewRows = 0;

6729:   PetscFunctionBegin;
6732:   if (numRows) PetscAssertPointer(rows, 3);

6734:   PetscCall(PetscMalloc1(numRows, &jdxm));
6735:   for (i = 0; i < numRows; ++i) {
6736:     /* Skip unused dimensions (they are ordered k, j, i, c) */
6737:     for (j = 0; j < 3 - sdim; ++j) dxm++;
6738:     /* Local index in X dir */
6739:     tmp = *dxm++ - starts[0];
6740:     /* Loop over remaining dimensions */
6741:     for (j = 0; j < dim - 1; ++j) {
6742:       /* If nonlocal, set index to be negative */
6743:       if ((*dxm++ - starts[j + 1]) < 0 || tmp < 0) tmp = PETSC_INT_MIN;
6744:       /* Update local index */
6745:       else tmp = tmp * dims[j] + *(dxm - 1) - starts[j + 1];
6746:     }
6747:     /* Skip component slot if necessary */
6748:     if (mat->stencil.noc) dxm++;
6749:     /* Local row number */
6750:     if (tmp >= 0) jdxm[numNewRows++] = tmp;
6751:   }
6752:   PetscCall(MatZeroRowsColumnsLocal(mat, numNewRows, jdxm, diag, x, b));
6753:   PetscCall(PetscFree(jdxm));
6754:   PetscFunctionReturn(PETSC_SUCCESS);
6755: }

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

6761:   Collective

6763:   Input Parameters:
6764: + mat     - the matrix
6765: . numRows - the number of rows to remove
6766: . rows    - the local row indices
6767: . diag    - value put in all diagonals of eliminated rows
6768: . x       - optional vector of solutions for zeroed rows (other entries in vector are not used)
6769: - b       - optional vector of right-hand side, that will be adjusted by provided solution

6771:   Level: intermediate

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

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

6779: .seealso: [](ch_matrices), `Mat`, `MatZeroRowsIS()`, `MatZeroRowsColumns()`, `MatZeroRowsLocalIS()`, `MatZeroRowsStencil()`, `MatZeroEntries()`, `MatZeroRows()`, `MatSetOption()`,
6780:           `MatZeroRowsColumnsLocal()`, `MatZeroRowsColumnsLocalIS()`, `MatZeroRowsColumnsIS()`, `MatZeroRowsColumnsStencil()`
6781: @*/
6782: PetscErrorCode MatZeroRowsLocal(Mat mat, PetscInt numRows, const PetscInt rows[], PetscScalar diag, Vec x, Vec b)
6783: {
6784:   PetscFunctionBegin;
6787:   if (numRows) PetscAssertPointer(rows, 3);
6788:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
6789:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
6790:   MatCheckPreallocated(mat, 1);

6792:   if (mat->ops->zerorowslocal) {
6793:     PetscUseTypeMethod(mat, zerorowslocal, numRows, rows, diag, x, b);
6794:   } else {
6795:     IS        is, newis;
6796:     PetscInt *newRows, nl = 0;

6798:     PetscCheck(mat->rmap->mapping, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Need to provide local to global mapping to matrix first");
6799:     PetscCall(ISCreateGeneral(PETSC_COMM_SELF, numRows, rows, PETSC_USE_POINTER, &is));
6800:     PetscCall(ISLocalToGlobalMappingApplyIS(mat->rmap->mapping, is, &newis));
6801:     PetscCall(ISGetIndices(newis, (const PetscInt **)&newRows));
6802:     for (PetscInt i = 0; i < numRows; i++)
6803:       if (newRows[i] > -1) newRows[nl++] = newRows[i];
6804:     PetscUseTypeMethod(mat, zerorows, nl, newRows, diag, x, b);
6805:     PetscCall(ISRestoreIndices(newis, (const PetscInt **)&newRows));
6806:     PetscCall(ISDestroy(&newis));
6807:     PetscCall(ISDestroy(&is));
6808:   }
6809:   PetscCall(PetscObjectStateIncrease((PetscObject)mat));
6810:   PetscFunctionReturn(PETSC_SUCCESS);
6811: }

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

6817:   Collective

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

6826:   Level: intermediate

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

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

6834: .seealso: [](ch_matrices), `Mat`, `MatZeroRowsIS()`, `MatZeroRowsColumns()`, `MatZeroRows()`, `MatZeroRowsStencil()`, `MatZeroEntries()`, `MatZeroRowsLocal()`, `MatSetOption()`,
6835:           `MatZeroRowsColumnsLocal()`, `MatZeroRowsColumnsLocalIS()`, `MatZeroRowsColumnsIS()`, `MatZeroRowsColumnsStencil()`
6836: @*/
6837: PetscErrorCode MatZeroRowsLocalIS(Mat mat, IS is, PetscScalar diag, Vec x, Vec b)
6838: {
6839:   PetscInt        numRows;
6840:   const PetscInt *rows;

6842:   PetscFunctionBegin;
6846:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
6847:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
6848:   MatCheckPreallocated(mat, 1);

6850:   PetscCall(ISGetLocalSize(is, &numRows));
6851:   PetscCall(ISGetIndices(is, &rows));
6852:   PetscCall(MatZeroRowsLocal(mat, numRows, rows, diag, x, b));
6853:   PetscCall(ISRestoreIndices(is, &rows));
6854:   PetscFunctionReturn(PETSC_SUCCESS);
6855: }

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

6861:   Collective

6863:   Input Parameters:
6864: + mat     - the matrix
6865: . numRows - the number of rows to remove
6866: . rows    - the global row indices
6867: . diag    - value put in all diagonals of eliminated rows
6868: . x       - optional vector of solutions for zeroed rows (other entries in vector are not used)
6869: - b       - optional vector of right-hand side, that will be adjusted by provided solution

6871:   Level: intermediate

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

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

6879: .seealso: [](ch_matrices), `Mat`, `MatZeroRowsIS()`, `MatZeroRowsColumns()`, `MatZeroRowsLocalIS()`, `MatZeroRowsStencil()`, `MatZeroEntries()`, `MatZeroRowsLocal()`, `MatSetOption()`,
6880:           `MatZeroRows()`, `MatZeroRowsColumnsLocalIS()`, `MatZeroRowsColumnsIS()`, `MatZeroRowsColumnsStencil()`
6881: @*/
6882: PetscErrorCode MatZeroRowsColumnsLocal(Mat mat, PetscInt numRows, const PetscInt rows[], PetscScalar diag, Vec x, Vec b)
6883: {
6884:   PetscFunctionBegin;
6887:   if (numRows) PetscAssertPointer(rows, 3);
6888:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
6889:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
6890:   MatCheckPreallocated(mat, 1);

6892:   if (mat->ops->zerorowscolumnslocal) {
6893:     PetscUseTypeMethod(mat, zerorowscolumnslocal, numRows, rows, diag, x, b);
6894:   } else {
6895:     IS        is, newis;
6896:     PetscInt *newRows, nl = 0;

6898:     PetscCheck(mat->rmap->mapping, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Need to provide local to global mapping to matrix first");
6899:     PetscCall(ISCreateGeneral(PETSC_COMM_SELF, numRows, rows, PETSC_USE_POINTER, &is));
6900:     PetscCall(ISLocalToGlobalMappingApplyIS(mat->rmap->mapping, is, &newis));
6901:     PetscCall(ISGetIndices(newis, (const PetscInt **)&newRows));
6902:     for (PetscInt i = 0; i < numRows; i++)
6903:       if (newRows[i] > -1) newRows[nl++] = newRows[i];
6904:     PetscUseTypeMethod(mat, zerorowscolumns, nl, newRows, diag, x, b);
6905:     PetscCall(ISRestoreIndices(newis, (const PetscInt **)&newRows));
6906:     PetscCall(ISDestroy(&newis));
6907:     PetscCall(ISDestroy(&is));
6908:   }
6909:   PetscCall(PetscObjectStateIncrease((PetscObject)mat));
6910:   PetscFunctionReturn(PETSC_SUCCESS);
6911: }

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

6917:   Collective

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

6926:   Level: intermediate

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

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

6934: .seealso: [](ch_matrices), `Mat`, `MatZeroRowsIS()`, `MatZeroRowsColumns()`, `MatZeroRowsLocalIS()`, `MatZeroRowsStencil()`, `MatZeroEntries()`, `MatZeroRowsLocal()`, `MatSetOption()`,
6935:           `MatZeroRowsColumnsLocal()`, `MatZeroRows()`, `MatZeroRowsColumnsIS()`, `MatZeroRowsColumnsStencil()`
6936: @*/
6937: PetscErrorCode MatZeroRowsColumnsLocalIS(Mat mat, IS is, PetscScalar diag, Vec x, Vec b)
6938: {
6939:   PetscInt        numRows;
6940:   const PetscInt *rows;

6942:   PetscFunctionBegin;
6946:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
6947:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
6948:   MatCheckPreallocated(mat, 1);

6950:   PetscCall(ISGetLocalSize(is, &numRows));
6951:   PetscCall(ISGetIndices(is, &rows));
6952:   PetscCall(MatZeroRowsColumnsLocal(mat, numRows, rows, diag, x, b));
6953:   PetscCall(ISRestoreIndices(is, &rows));
6954:   PetscFunctionReturn(PETSC_SUCCESS);
6955: }

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

6960:   Not Collective

6962:   Input Parameter:
6963: . mat - the matrix

6965:   Output Parameters:
6966: + m - the number of global rows
6967: - n - the number of global columns

6969:   Level: beginner

6971:   Note:
6972:   Both output parameters can be `NULL` on input.

6974: .seealso: [](ch_matrices), `Mat`, `MatSetSizes()`, `MatGetLocalSize()`
6975: @*/
6976: PetscErrorCode MatGetSize(Mat mat, PetscInt *m, PetscInt *n)
6977: {
6978:   PetscFunctionBegin;
6980:   if (m) *m = mat->rmap->N;
6981:   if (n) *n = mat->cmap->N;
6982:   PetscFunctionReturn(PETSC_SUCCESS);
6983: }

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

6989:   Not Collective

6991:   Input Parameter:
6992: . mat - the matrix

6994:   Output Parameters:
6995: + m - the number of local rows, use `NULL` to not obtain this value
6996: - n - the number of local columns, use `NULL` to not obtain this value

6998:   Level: beginner

7000: .seealso: [](ch_matrices), `Mat`, `MatSetSizes()`, `MatGetSize()`
7001: @*/
7002: PetscErrorCode MatGetLocalSize(Mat mat, PetscInt *m, PetscInt *n)
7003: {
7004:   PetscFunctionBegin;
7006:   if (m) PetscAssertPointer(m, 2);
7007:   if (n) PetscAssertPointer(n, 3);
7008:   if (m) *m = mat->rmap->n;
7009:   if (n) *n = mat->cmap->n;
7010:   PetscFunctionReturn(PETSC_SUCCESS);
7011: }

7013: /*@
7014:   MatGetOwnershipRangeColumn - Returns the range of matrix columns associated with rows of a
7015:   vector one multiplies this matrix by that are owned by this processor.

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

7019:   Input Parameter:
7020: . mat - the matrix

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

7026:   Level: developer

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

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

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

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

7040: .seealso: [](ch_matrices), `Mat`, `MatGetOwnershipRange()`, `MatGetOwnershipRanges()`, `MatGetOwnershipRangesColumn()`, `PetscLayout`,
7041:           `MatSetSizes()`, `MatCreateAIJ()`, `DMDAGetGhostCorners()`, `DM`
7042: @*/
7043: PetscErrorCode MatGetOwnershipRangeColumn(Mat mat, PetscInt *m, PetscInt *n)
7044: {
7045:   PetscFunctionBegin;
7048:   if (m) PetscAssertPointer(m, 2);
7049:   if (n) PetscAssertPointer(n, 3);
7050:   MatCheckPreallocated(mat, 1);
7051:   if (m) *m = mat->cmap->rstart;
7052:   if (n) *n = mat->cmap->rend;
7053:   PetscFunctionReturn(PETSC_SUCCESS);
7054: }

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

7060:   Not Collective

7062:   Input Parameter:
7063: . mat - the matrix

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

7069:   Level: beginner

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

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

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

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

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

7086: .seealso: [](ch_matrices), `Mat`, `MatGetOwnershipRanges()`, `MatGetOwnershipRangeColumn()`, `MatGetOwnershipRangesColumn()`, `PetscSplitOwnership()`,
7087:           `PetscSplitOwnershipBlock()`, `PetscLayout`, `MatSetSizes()`, `MatCreateAIJ()`, `DMDAGetGhostCorners()`, `DM`
7088: @*/
7089: PetscErrorCode MatGetOwnershipRange(Mat mat, PetscInt *m, PetscInt *n)
7090: {
7091:   PetscFunctionBegin;
7094:   if (m) PetscAssertPointer(m, 2);
7095:   if (n) PetscAssertPointer(n, 3);
7096:   MatCheckPreallocated(mat, 1);
7097:   if (m) *m = mat->rmap->rstart;
7098:   if (n) *n = mat->rmap->rend;
7099:   PetscFunctionReturn(PETSC_SUCCESS);
7100: }

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

7106:   Not Collective, unless matrix has not been allocated

7108:   Input Parameter:
7109: . mat - the matrix

7111:   Output Parameter:
7112: . ranges - start of each processors portion plus one more than the total length at the end, of length `size` + 1
7113:            where `size` is the number of MPI processes used by `mat`

7115:   Level: beginner

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

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

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

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

7130: .seealso: [](ch_matrices), `Mat`, `MatGetOwnershipRange()`, `MatGetOwnershipRangeColumn()`, `MatGetOwnershipRangesColumn()`, `PetscLayout`,
7131:           `PetscSplitOwnership()`, `PetscSplitOwnershipBlock()`, `MatSetSizes()`, `MatCreateAIJ()`,
7132:           `DMDAGetGhostCorners()`, `DM`
7133: @*/
7134: PetscErrorCode MatGetOwnershipRanges(Mat mat, const PetscInt *ranges[])
7135: {
7136:   PetscFunctionBegin;
7139:   MatCheckPreallocated(mat, 1);
7140:   PetscCall(PetscLayoutGetRanges(mat->rmap, ranges));
7141:   PetscFunctionReturn(PETSC_SUCCESS);
7142: }

7144: /*@C
7145:   MatGetOwnershipRangesColumn - Returns the ranges of matrix columns associated with rows of a
7146:   vector one multiplies this vector by that are owned by each processor.

7148:   Not Collective, unless matrix has not been allocated

7150:   Input Parameter:
7151: . mat - the matrix

7153:   Output Parameter:
7154: . ranges - start of each processors portion plus one more than the total length at the end

7156:   Level: beginner

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

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

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

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

7170: .seealso: [](ch_matrices), `Mat`, `MatGetOwnershipRange()`, `MatGetOwnershipRangeColumn()`, `MatGetOwnershipRanges()`,
7171:           `PetscSplitOwnership()`, `PetscSplitOwnershipBlock()`, `PetscLayout`, `MatSetSizes()`, `MatCreateAIJ()`,
7172:           `DMDAGetGhostCorners()`, `DM`
7173: @*/
7174: PetscErrorCode MatGetOwnershipRangesColumn(Mat mat, const PetscInt *ranges[])
7175: {
7176:   PetscFunctionBegin;
7179:   MatCheckPreallocated(mat, 1);
7180:   PetscCall(PetscLayoutGetRanges(mat->cmap, ranges));
7181:   PetscFunctionReturn(PETSC_SUCCESS);
7182: }

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

7187:   Not Collective

7189:   Input Parameter:
7190: . A - matrix

7192:   Output Parameters:
7193: + rows - rows in which this process owns elements, , use `NULL` to not obtain this value
7194: - cols - columns in which this process owns elements, use `NULL` to not obtain this value

7196:   Level: intermediate

7198:   Note:
7199:   You should call `ISDestroy()` on the returned `IS`

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

7206: .seealso: [](ch_matrices), `IS`, `Mat`, `MatGetOwnershipRanges()`, `MatSetValues()`, `MATELEMENTAL`, `MATSCALAPACK`
7207: @*/
7208: PetscErrorCode MatGetOwnershipIS(Mat A, IS *rows, IS *cols)
7209: {
7210:   PetscErrorCode (*f)(Mat, IS *, IS *);

7212:   PetscFunctionBegin;
7215:   MatCheckPreallocated(A, 1);
7216:   PetscCall(PetscObjectQueryFunction((PetscObject)A, "MatGetOwnershipIS_C", &f));
7217:   if (f) {
7218:     PetscCall((*f)(A, rows, cols));
7219:   } else { /* Create a standard row-based partition, each process is responsible for ALL columns in their row block */
7220:     if (rows) PetscCall(ISCreateStride(PETSC_COMM_SELF, A->rmap->n, A->rmap->rstart, 1, rows));
7221:     if (cols) PetscCall(ISCreateStride(PETSC_COMM_SELF, A->cmap->N, 0, 1, cols));
7222:   }
7223:   PetscFunctionReturn(PETSC_SUCCESS);
7224: }

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

7231:   Collective

7233:   Input Parameters:
7234: + fact - the factorized matrix obtained with `MatGetFactor()`
7235: . mat  - the matrix
7236: . row  - row permutation
7237: . col  - column permutation
7238: - info - structure containing
7239: .vb
7240:       levels - number of levels of fill.
7241:       expected fill - as ratio of original fill.
7242:       1 or 0 - indicating force fill on diagonal (improves robustness for matrices
7243:                 missing diagonal entries)
7244: .ve

7246:   Level: developer

7248:   Notes:
7249:   See [Matrix Factorization](sec_matfactor) for additional information.

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

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

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

7260: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatGetFactor()`, `MatLUFactorSymbolic()`, `MatLUFactorNumeric()`, `MatCholeskyFactor()`,
7261:           `MatGetOrdering()`, `MatFactorInfo`
7262: @*/
7263: PetscErrorCode MatILUFactorSymbolic(Mat fact, Mat mat, IS row, IS col, const MatFactorInfo *info)
7264: {
7265:   PetscFunctionBegin;
7270:   PetscAssertPointer(info, 5);
7271:   PetscAssertPointer(fact, 1);
7272:   PetscCheck(info->levels >= 0, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_OUTOFRANGE, "Levels of fill negative %" PetscInt_FMT, (PetscInt)info->levels);
7273:   PetscCheck(info->fill >= 1.0, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_OUTOFRANGE, "Expected fill less than 1.0 %g", (double)info->fill);
7274:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
7275:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
7276:   MatCheckPreallocated(mat, 2);

7278:   if (!fact->trivialsymbolic) PetscCall(PetscLogEventBegin(MAT_ILUFactorSymbolic, mat, row, col, 0));
7279:   PetscUseTypeMethod(fact, ilufactorsymbolic, mat, row, col, info);
7280:   if (!fact->trivialsymbolic) PetscCall(PetscLogEventEnd(MAT_ILUFactorSymbolic, mat, row, col, 0));
7281:   PetscFunctionReturn(PETSC_SUCCESS);
7282: }

7284: /*@
7285:   MatICCFactorSymbolic - Performs symbolic incomplete
7286:   Cholesky factorization for a symmetric matrix.  Use
7287:   `MatCholeskyFactorNumeric()` to complete the factorization.

7289:   Collective

7291:   Input Parameters:
7292: + fact - the factorized matrix obtained with `MatGetFactor()`
7293: . mat  - the matrix to be factored
7294: . perm - row and column permutation
7295: - info - structure containing
7296: .vb
7297:       levels - number of levels of fill.
7298:       expected fill - as ratio of original fill.
7299: .ve

7301:   Level: developer

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

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

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

7313: .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatCholeskyFactorNumeric()`, `MatCholeskyFactor()`, `MatFactorInfo`
7314: @*/
7315: PetscErrorCode MatICCFactorSymbolic(Mat fact, Mat mat, IS perm, const MatFactorInfo *info)
7316: {
7317:   PetscFunctionBegin;
7321:   PetscAssertPointer(info, 4);
7322:   PetscAssertPointer(fact, 1);
7323:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
7324:   PetscCheck(info->levels >= 0, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_OUTOFRANGE, "Levels negative %" PetscInt_FMT, (PetscInt)info->levels);
7325:   PetscCheck(info->fill >= 1.0, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_OUTOFRANGE, "Expected fill less than 1.0 %g", (double)info->fill);
7326:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
7327:   MatCheckPreallocated(mat, 2);

7329:   if (!fact->trivialsymbolic) PetscCall(PetscLogEventBegin(MAT_ICCFactorSymbolic, mat, perm, 0, 0));
7330:   PetscUseTypeMethod(fact, iccfactorsymbolic, mat, perm, info);
7331:   if (!fact->trivialsymbolic) PetscCall(PetscLogEventEnd(MAT_ICCFactorSymbolic, mat, perm, 0, 0));
7332:   PetscFunctionReturn(PETSC_SUCCESS);
7333: }

7335: /*@C
7336:   MatCreateSubMatrices - Extracts several submatrices from a matrix. If submat
7337:   points to an array of valid matrices, they may be reused to store the new
7338:   submatrices.

7340:   Collective

7342:   Input Parameters:
7343: + mat   - the matrix
7344: . n     - the number of submatrixes to be extracted (on this processor, may be zero)
7345: . irow  - index set of rows to extract
7346: . icol  - index set of columns to extract
7347: - scall - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`

7349:   Output Parameter:
7350: . submat - the array of submatrices

7352:   Level: advanced

7354:   Notes:
7355:   `MatCreateSubMatrices()` can extract ONLY sequential submatrices
7356:   (from both sequential and parallel matrices). Use `MatCreateSubMatrix()`
7357:   to extract a parallel submatrix.

7359:   Some matrix types place restrictions on the row and column
7360:   indices, such as that they be sorted or that they be equal to each other.

7362:   The index sets may not have duplicate entries.

7364:   When extracting submatrices from a parallel matrix, each processor can
7365:   form a different submatrix by setting the rows and columns of its
7366:   individual index sets according to the local submatrix desired.

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

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

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

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

7382:   Fortran Note:
7383: .vb
7384:   Mat, pointer :: submat(:)
7385: .ve

7387: .seealso: [](ch_matrices), `Mat`, `MatDestroySubMatrices()`, `MatCreateSubMatrix()`, `MatGetRow()`, `MatGetDiagonal()`, `MatReuse`
7388: @*/
7389: PetscErrorCode MatCreateSubMatrices(Mat mat, PetscInt n, const IS irow[], const IS icol[], MatReuse scall, Mat *submat[])
7390: {
7391:   PetscInt  i;
7392:   PetscBool eq;

7394:   PetscFunctionBegin;
7397:   if (n) {
7398:     PetscAssertPointer(irow, 3);
7400:     PetscAssertPointer(icol, 4);
7402:   }
7403:   PetscAssertPointer(submat, 6);
7404:   if (n && scall == MAT_REUSE_MATRIX) {
7405:     PetscAssertPointer(*submat, 6);
7407:   }
7408:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
7409:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
7410:   MatCheckPreallocated(mat, 1);
7411:   PetscCall(PetscLogEventBegin(MAT_CreateSubMats, mat, 0, 0, 0));
7412:   PetscUseTypeMethod(mat, createsubmatrices, n, irow, icol, scall, submat);
7413:   PetscCall(PetscLogEventEnd(MAT_CreateSubMats, mat, 0, 0, 0));
7414:   for (i = 0; i < n; i++) {
7415:     (*submat)[i]->factortype = MAT_FACTOR_NONE; /* in case in place factorization was previously done on submatrix */
7416:     PetscCall(ISEqualUnsorted(irow[i], icol[i], &eq));
7417:     if (eq) PetscCall(MatPropagateSymmetryOptions(mat, (*submat)[i]));
7418: #if defined(PETSC_HAVE_VIENNACL) || defined(PETSC_HAVE_CUDA) || defined(PETSC_HAVE_HIP)
7419:     if (mat->boundtocpu && mat->bindingpropagates) {
7420:       PetscCall(MatBindToCPU((*submat)[i], PETSC_TRUE));
7421:       PetscCall(MatSetBindingPropagates((*submat)[i], PETSC_TRUE));
7422:     }
7423: #endif
7424:   }
7425:   PetscFunctionReturn(PETSC_SUCCESS);
7426: }

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

7431:   Collective

7433:   Input Parameters:
7434: + mat   - the matrix
7435: . n     - the number of submatrixes to be extracted
7436: . irow  - index set of rows to extract
7437: . icol  - index set of columns to extract
7438: - scall - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`

7440:   Output Parameter:
7441: . submat - the array of submatrices

7443:   Level: advanced

7445:   Note:
7446:   This is used by `PCGASM`

7448: .seealso: [](ch_matrices), `Mat`, `PCGASM`, `MatCreateSubMatrices()`, `MatCreateSubMatrix()`, `MatGetRow()`, `MatGetDiagonal()`, `MatReuse`
7449: @*/
7450: PetscErrorCode MatCreateSubMatricesMPI(Mat mat, PetscInt n, const IS irow[], const IS icol[], MatReuse scall, Mat *submat[])
7451: {
7452:   PetscInt  i;
7453:   PetscBool eq;

7455:   PetscFunctionBegin;
7458:   if (n) {
7459:     PetscAssertPointer(irow, 3);
7461:     PetscAssertPointer(icol, 4);
7463:   }
7464:   PetscAssertPointer(submat, 6);
7465:   if (n && scall == MAT_REUSE_MATRIX) {
7466:     PetscAssertPointer(*submat, 6);
7468:   }
7469:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
7470:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
7471:   MatCheckPreallocated(mat, 1);

7473:   PetscCall(PetscLogEventBegin(MAT_CreateSubMats, mat, 0, 0, 0));
7474:   PetscUseTypeMethod(mat, createsubmatricesmpi, n, irow, icol, scall, submat);
7475:   PetscCall(PetscLogEventEnd(MAT_CreateSubMats, mat, 0, 0, 0));
7476:   for (i = 0; i < n; i++) {
7477:     PetscCall(ISEqualUnsorted(irow[i], icol[i], &eq));
7478:     if (eq) PetscCall(MatPropagateSymmetryOptions(mat, (*submat)[i]));
7479:   }
7480:   PetscFunctionReturn(PETSC_SUCCESS);
7481: }

7483: /*@C
7484:   MatDestroyMatrices - Destroys an array of matrices

7486:   Collective

7488:   Input Parameters:
7489: + n   - the number of local matrices
7490: - mat - the matrices (this is a pointer to the array of matrices)

7492:   Level: advanced

7494:   Notes:
7495:   Frees not only the matrices, but also the array that contains the matrices

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

7499: .seealso: [](ch_matrices), `Mat`, `MatCreateSubMatrices()`, `MatDestroySubMatrices()`
7500: @*/
7501: PetscErrorCode MatDestroyMatrices(PetscInt n, Mat *mat[])
7502: {
7503:   PetscInt i;

7505:   PetscFunctionBegin;
7506:   if (!*mat) PetscFunctionReturn(PETSC_SUCCESS);
7507:   PetscCheck(n >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Trying to destroy negative number of matrices %" PetscInt_FMT, n);
7508:   PetscAssertPointer(mat, 2);

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

7512:   /* memory is allocated even if n = 0 */
7513:   PetscCall(PetscFree(*mat));
7514:   PetscFunctionReturn(PETSC_SUCCESS);
7515: }

7517: /*@C
7518:   MatDestroySubMatrices - Destroys a set of matrices obtained with `MatCreateSubMatrices()`.

7520:   Collective

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

7526:   Level: advanced

7528:   Note:
7529:   Frees not only the matrices, but also the array that contains the matrices

7531: .seealso: [](ch_matrices), `Mat`, `MatCreateSubMatrices()`, `MatDestroyMatrices()`
7532: @*/
7533: PetscErrorCode MatDestroySubMatrices(PetscInt n, Mat *mat[])
7534: {
7535:   Mat mat0;

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

7543:   mat0 = (*mat)[0];
7544:   if (mat0 && mat0->ops->destroysubmatrices) {
7545:     PetscCall((*mat0->ops->destroysubmatrices)(n, mat));
7546:   } else {
7547:     PetscCall(MatDestroyMatrices(n, mat));
7548:   }
7549:   PetscFunctionReturn(PETSC_SUCCESS);
7550: }

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

7555:   Collective

7557:   Input Parameter:
7558: . mat - the matrix

7560:   Output Parameter:
7561: . matstruct - the sequential matrix with the nonzero structure of `mat`

7563:   Level: developer

7565: .seealso: [](ch_matrices), `Mat`, `MatDestroySeqNonzeroStructure()`, `MatCreateSubMatrices()`, `MatDestroyMatrices()`
7566: @*/
7567: PetscErrorCode MatGetSeqNonzeroStructure(Mat mat, Mat *matstruct)
7568: {
7569:   PetscFunctionBegin;
7571:   PetscAssertPointer(matstruct, 2);

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

7577:   PetscCall(PetscLogEventBegin(MAT_GetSeqNonzeroStructure, mat, 0, 0, 0));
7578:   PetscUseTypeMethod(mat, getseqnonzerostructure, matstruct);
7579:   PetscCall(PetscLogEventEnd(MAT_GetSeqNonzeroStructure, mat, 0, 0, 0));
7580:   PetscFunctionReturn(PETSC_SUCCESS);
7581: }

7583: /*@C
7584:   MatDestroySeqNonzeroStructure - Destroys matrix obtained with `MatGetSeqNonzeroStructure()`.

7586:   Collective

7588:   Input Parameter:
7589: . mat - the matrix

7591:   Level: advanced

7593:   Note:
7594:   This is not needed, one can just call `MatDestroy()`

7596: .seealso: [](ch_matrices), `Mat`, `MatGetSeqNonzeroStructure()`
7597: @*/
7598: PetscErrorCode MatDestroySeqNonzeroStructure(Mat *mat)
7599: {
7600:   PetscFunctionBegin;
7601:   PetscAssertPointer(mat, 1);
7602:   PetscCall(MatDestroy(mat));
7603:   PetscFunctionReturn(PETSC_SUCCESS);
7604: }

7606: /*@
7607:   MatIncreaseOverlap - Given a set of submatrices indicated by index sets,
7608:   replaces the index sets by larger ones that represent submatrices with
7609:   additional overlap.

7611:   Collective

7613:   Input Parameters:
7614: + mat - the matrix
7615: . n   - the number of index sets
7616: . is  - the array of index sets (these index sets will changed during the call)
7617: - ov  - the additional overlap requested

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

7622:   Level: developer

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

7629: .seealso: [](ch_matrices), `Mat`, `PCASM`, `MatSetBlockSize()`, `MatIncreaseOverlapSplit()`, `MatCreateSubMatrices()`
7630: @*/
7631: PetscErrorCode MatIncreaseOverlap(Mat mat, PetscInt n, IS is[], PetscInt ov)
7632: {
7633:   PetscInt i, bs, cbs;

7635:   PetscFunctionBegin;
7639:   PetscCheck(n >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Must have one or more domains, you have %" PetscInt_FMT, n);
7640:   if (n) {
7641:     PetscAssertPointer(is, 3);
7643:   }
7644:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
7645:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
7646:   MatCheckPreallocated(mat, 1);

7648:   if (!ov || !n) PetscFunctionReturn(PETSC_SUCCESS);
7649:   PetscCall(PetscLogEventBegin(MAT_IncreaseOverlap, mat, 0, 0, 0));
7650:   PetscUseTypeMethod(mat, increaseoverlap, n, is, ov);
7651:   PetscCall(PetscLogEventEnd(MAT_IncreaseOverlap, mat, 0, 0, 0));
7652:   PetscCall(MatGetBlockSizes(mat, &bs, &cbs));
7653:   if (bs == cbs) {
7654:     for (i = 0; i < n; i++) PetscCall(ISSetBlockSize(is[i], bs));
7655:   }
7656:   PetscFunctionReturn(PETSC_SUCCESS);
7657: }

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

7661: /*@
7662:   MatIncreaseOverlapSplit - Given a set of submatrices indicated by index sets across
7663:   a sub communicator, replaces the index sets by larger ones that represent submatrices with
7664:   additional overlap.

7666:   Collective

7668:   Input Parameters:
7669: + mat - the matrix
7670: . n   - the number of index sets
7671: . is  - the array of index sets (these index sets will changed during the call)
7672: - ov  - the additional overlap requested

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

7677:   Level: developer

7679: .seealso: [](ch_matrices), `Mat`, `MatCreateSubMatrices()`, `MatIncreaseOverlap()`
7680: @*/
7681: PetscErrorCode MatIncreaseOverlapSplit(Mat mat, PetscInt n, IS is[], PetscInt ov)
7682: {
7683:   PetscInt i;

7685:   PetscFunctionBegin;
7688:   PetscCheck(n >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Must have one or more domains, you have %" PetscInt_FMT, n);
7689:   if (n) {
7690:     PetscAssertPointer(is, 3);
7692:   }
7693:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
7694:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
7695:   MatCheckPreallocated(mat, 1);
7696:   if (!ov) PetscFunctionReturn(PETSC_SUCCESS);
7697:   PetscCall(PetscLogEventBegin(MAT_IncreaseOverlap, mat, 0, 0, 0));
7698:   for (i = 0; i < n; i++) PetscCall(MatIncreaseOverlapSplit_Single(mat, &is[i], ov));
7699:   PetscCall(PetscLogEventEnd(MAT_IncreaseOverlap, mat, 0, 0, 0));
7700:   PetscFunctionReturn(PETSC_SUCCESS);
7701: }

7703: /*@
7704:   MatGetBlockSize - Returns the matrix block size.

7706:   Not Collective

7708:   Input Parameter:
7709: . mat - the matrix

7711:   Output Parameter:
7712: . bs - block size

7714:   Level: intermediate

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

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

7721: .seealso: [](ch_matrices), `Mat`, `MATBAIJ`, `MATSBAIJ`, `MatCreateSeqBAIJ()`, `MatCreateBAIJ()`, `MatGetBlockSizes()`
7722: @*/
7723: PetscErrorCode MatGetBlockSize(Mat mat, PetscInt *bs)
7724: {
7725:   PetscFunctionBegin;
7727:   PetscAssertPointer(bs, 2);
7728:   *bs = mat->rmap->bs;
7729:   PetscFunctionReturn(PETSC_SUCCESS);
7730: }

7732: /*@
7733:   MatGetBlockSizes - Returns the matrix block row and column sizes.

7735:   Not Collective

7737:   Input Parameter:
7738: . mat - the matrix

7740:   Output Parameters:
7741: + rbs - row block size
7742: - cbs - column block size

7744:   Level: intermediate

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

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

7752: .seealso: [](ch_matrices), `Mat`, `MATBAIJ`, `MATSBAIJ`, `MatCreateSeqBAIJ()`, `MatCreateBAIJ()`, `MatGetBlockSize()`, `MatSetBlockSize()`, `MatSetBlockSizes()`
7753: @*/
7754: PetscErrorCode MatGetBlockSizes(Mat mat, PetscInt *rbs, PetscInt *cbs)
7755: {
7756:   PetscFunctionBegin;
7758:   if (rbs) PetscAssertPointer(rbs, 2);
7759:   if (cbs) PetscAssertPointer(cbs, 3);
7760:   if (rbs) *rbs = mat->rmap->bs;
7761:   if (cbs) *cbs = mat->cmap->bs;
7762:   PetscFunctionReturn(PETSC_SUCCESS);
7763: }

7765: /*@
7766:   MatSetBlockSize - Sets the matrix block size.

7768:   Logically Collective

7770:   Input Parameters:
7771: + mat - the matrix
7772: - bs  - block size

7774:   Level: intermediate

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

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

7783: .seealso: [](ch_matrices), `Mat`, `MATBAIJ`, `MATSBAIJ`, `MATAIJ`, `MatCreateSeqBAIJ()`, `MatCreateBAIJ()`, `MatGetBlockSize()`, `MatSetBlockSizes()`, `MatGetBlockSizes()`
7784: @*/
7785: PetscErrorCode MatSetBlockSize(Mat mat, PetscInt bs)
7786: {
7787:   PetscFunctionBegin;
7790:   PetscCall(MatSetBlockSizes(mat, bs, bs));
7791:   PetscFunctionReturn(PETSC_SUCCESS);
7792: }

7794: typedef struct {
7795:   PetscInt         n;
7796:   IS              *is;
7797:   Mat             *mat;
7798:   PetscObjectState nonzerostate;
7799:   Mat              C;
7800: } EnvelopeData;

7802: static PetscErrorCode EnvelopeDataDestroy(PetscCtxRt ptr)
7803: {
7804:   EnvelopeData *edata = *(EnvelopeData **)ptr;

7806:   PetscFunctionBegin;
7807:   for (PetscInt i = 0; i < edata->n; i++) PetscCall(ISDestroy(&edata->is[i]));
7808:   PetscCall(PetscFree(edata->is));
7809:   PetscCall(PetscFree(edata));
7810:   PetscFunctionReturn(PETSC_SUCCESS);
7811: }

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

7817:   Collective

7819:   Input Parameter:
7820: . mat - the matrix

7822:   Level: intermediate

7824:   Notes:
7825:   There can be zeros within the blocks

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

7829: .seealso: [](ch_matrices), `Mat`, `MatInvertVariableBlockEnvelope()`, `MatSetVariableBlockSizes()`
7830: @*/
7831: PetscErrorCode MatComputeVariableBlockEnvelope(Mat mat)
7832: {
7833:   PetscInt           n, *sizes, *starts, i = 0, env = 0, tbs = 0, lblocks = 0, rstart, II, ln = 0, cnt = 0, cstart, cend;
7834:   PetscInt          *diag, *odiag, sc;
7835:   VecScatter         scatter;
7836:   PetscScalar       *seqv;
7837:   const PetscScalar *parv;
7838:   const PetscInt    *ia, *ja;
7839:   PetscBool          set, flag, done;
7840:   Mat                AA = mat, A;
7841:   MPI_Comm           comm;
7842:   PetscMPIInt        rank, size, tag;
7843:   MPI_Status         status;
7844:   PetscContainer     container;
7845:   EnvelopeData      *edata;
7846:   Vec                seq, par;
7847:   IS                 isglobal;

7849:   PetscFunctionBegin;
7851:   PetscCall(MatIsSymmetricKnown(mat, &set, &flag));
7852:   if (!set || !flag) {
7853:     /* TODO: only needs nonzero structure of transpose */
7854:     PetscCall(MatTranspose(mat, MAT_INITIAL_MATRIX, &AA));
7855:     PetscCall(MatAXPY(AA, 1.0, mat, DIFFERENT_NONZERO_PATTERN));
7856:   }
7857:   PetscCall(MatAIJGetLocalMat(AA, &A));
7858:   PetscCall(MatGetRowIJ(A, 0, PETSC_FALSE, PETSC_FALSE, &n, &ia, &ja, &done));
7859:   PetscCheck(done, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "Unable to get IJ structure from matrix");

7861:   PetscCall(MatGetLocalSize(mat, &n, NULL));
7862:   PetscCall(PetscObjectGetNewTag((PetscObject)mat, &tag));
7863:   PetscCall(PetscObjectGetComm((PetscObject)mat, &comm));
7864:   PetscCallMPI(MPI_Comm_size(comm, &size));
7865:   PetscCallMPI(MPI_Comm_rank(comm, &rank));

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

7869:   if (rank > 0) {
7870:     PetscCallMPI(MPI_Recv(&env, 1, MPIU_INT, rank - 1, tag, comm, &status));
7871:     PetscCallMPI(MPI_Recv(&tbs, 1, MPIU_INT, rank - 1, tag, comm, &status));
7872:   }
7873:   PetscCall(MatGetOwnershipRange(mat, &rstart, NULL));
7874:   for (i = 0; i < n; i++) {
7875:     env = PetscMax(env, ja[ia[i + 1] - 1]);
7876:     II  = rstart + i;
7877:     if (env == II) {
7878:       starts[lblocks]  = tbs;
7879:       sizes[lblocks++] = 1 + II - tbs;
7880:       tbs              = 1 + II;
7881:     }
7882:   }
7883:   if (rank < size - 1) {
7884:     PetscCallMPI(MPI_Send(&env, 1, MPIU_INT, rank + 1, tag, comm));
7885:     PetscCallMPI(MPI_Send(&tbs, 1, MPIU_INT, rank + 1, tag, comm));
7886:   }

7888:   PetscCall(MatRestoreRowIJ(A, 0, PETSC_FALSE, PETSC_FALSE, &n, &ia, &ja, &done));
7889:   if (!set || !flag) PetscCall(MatDestroy(&AA));
7890:   PetscCall(MatDestroy(&A));

7892:   PetscCall(PetscNew(&edata));
7893:   PetscCall(MatGetNonzeroState(mat, &edata->nonzerostate));
7894:   edata->n = lblocks;
7895:   /* create IS needed for extracting blocks from the original matrix */
7896:   PetscCall(PetscMalloc1(lblocks, &edata->is));
7897:   for (PetscInt i = 0; i < lblocks; i++) PetscCall(ISCreateStride(PETSC_COMM_SELF, sizes[i], starts[i], 1, &edata->is[i]));

7899:   /* Create the resulting inverse matrix nonzero structure with preallocation information */
7900:   PetscCall(MatCreate(PetscObjectComm((PetscObject)mat), &edata->C));
7901:   PetscCall(MatSetSizes(edata->C, mat->rmap->n, mat->cmap->n, mat->rmap->N, mat->cmap->N));
7902:   PetscCall(MatSetBlockSizesFromMats(edata->C, mat, mat));
7903:   PetscCall(MatSetType(edata->C, MATAIJ));

7905:   /* Communicate the start and end of each row, from each block to the correct rank */
7906:   /* TODO: Use PetscSF instead of VecScatter */
7907:   for (PetscInt i = 0; i < lblocks; i++) ln += sizes[i];
7908:   PetscCall(VecCreateSeq(PETSC_COMM_SELF, 2 * ln, &seq));
7909:   PetscCall(VecGetArrayWrite(seq, &seqv));
7910:   for (PetscInt i = 0; i < lblocks; i++) {
7911:     for (PetscInt j = 0; j < sizes[i]; j++) {
7912:       seqv[cnt]     = starts[i];
7913:       seqv[cnt + 1] = starts[i] + sizes[i];
7914:       cnt += 2;
7915:     }
7916:   }
7917:   PetscCall(VecRestoreArrayWrite(seq, &seqv));
7918:   PetscCallMPI(MPI_Scan(&cnt, &sc, 1, MPIU_INT, MPI_SUM, PetscObjectComm((PetscObject)mat)));
7919:   sc -= cnt;
7920:   PetscCall(VecCreateMPI(PetscObjectComm((PetscObject)mat), 2 * mat->rmap->n, 2 * mat->rmap->N, &par));
7921:   PetscCall(ISCreateStride(PETSC_COMM_SELF, cnt, sc, 1, &isglobal));
7922:   PetscCall(VecScatterCreate(seq, NULL, par, isglobal, &scatter));
7923:   PetscCall(ISDestroy(&isglobal));
7924:   PetscCall(VecScatterBegin(scatter, seq, par, INSERT_VALUES, SCATTER_FORWARD));
7925:   PetscCall(VecScatterEnd(scatter, seq, par, INSERT_VALUES, SCATTER_FORWARD));
7926:   PetscCall(VecScatterDestroy(&scatter));
7927:   PetscCall(VecDestroy(&seq));
7928:   PetscCall(MatGetOwnershipRangeColumn(mat, &cstart, &cend));
7929:   PetscCall(PetscMalloc2(mat->rmap->n, &diag, mat->rmap->n, &odiag));
7930:   PetscCall(VecGetArrayRead(par, &parv));
7931:   cnt = 0;
7932:   PetscCall(MatGetSize(mat, NULL, &n));
7933:   for (PetscInt i = 0; i < mat->rmap->n; i++) {
7934:     PetscInt start, end, d = 0, od = 0;

7936:     start = (PetscInt)PetscRealPart(parv[cnt]);
7937:     end   = (PetscInt)PetscRealPart(parv[cnt + 1]);
7938:     cnt += 2;

7940:     if (start < cstart) {
7941:       od += cstart - start + n - cend;
7942:       d += cend - cstart;
7943:     } else if (start < cend) {
7944:       od += n - cend;
7945:       d += cend - start;
7946:     } else od += n - start;
7947:     if (end <= cstart) {
7948:       od -= cstart - end + n - cend;
7949:       d -= cend - cstart;
7950:     } else if (end < cend) {
7951:       od -= n - cend;
7952:       d -= cend - end;
7953:     } else od -= n - end;

7955:     odiag[i] = od;
7956:     diag[i]  = d;
7957:   }
7958:   PetscCall(VecRestoreArrayRead(par, &parv));
7959:   PetscCall(VecDestroy(&par));
7960:   PetscCall(MatXAIJSetPreallocation(edata->C, mat->rmap->bs, diag, odiag, NULL, NULL));
7961:   PetscCall(PetscFree2(diag, odiag));
7962:   PetscCall(PetscFree2(sizes, starts));

7964:   PetscCall(PetscContainerCreate(PETSC_COMM_SELF, &container));
7965:   PetscCall(PetscContainerSetPointer(container, edata));
7966:   PetscCall(PetscContainerSetCtxDestroy(container, EnvelopeDataDestroy));
7967:   PetscCall(PetscObjectCompose((PetscObject)mat, "EnvelopeData", (PetscObject)container));
7968:   PetscCall(PetscObjectDereference((PetscObject)container));
7969:   PetscFunctionReturn(PETSC_SUCCESS);
7970: }

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

7975:   Collective

7977:   Input Parameters:
7978: + A     - the matrix
7979: - reuse - indicates if the `C` matrix was obtained from a previous call to this routine

7981:   Output Parameter:
7982: . C - matrix with inverted block diagonal of `A`

7984:   Level: advanced

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

7989: .seealso: [](ch_matrices), `Mat`, `MatInvertBlockDiagonal()`, `MatComputeBlockDiagonal()`
7990: @*/
7991: PetscErrorCode MatInvertVariableBlockEnvelope(Mat A, MatReuse reuse, Mat *C)
7992: {
7993:   PetscContainer   container;
7994:   EnvelopeData    *edata;
7995:   PetscObjectState nonzerostate;

7997:   PetscFunctionBegin;
7998:   PetscCall(PetscObjectQuery((PetscObject)A, "EnvelopeData", (PetscObject *)&container));
7999:   if (!container) {
8000:     PetscCall(MatComputeVariableBlockEnvelope(A));
8001:     PetscCall(PetscObjectQuery((PetscObject)A, "EnvelopeData", (PetscObject *)&container));
8002:   }
8003:   PetscCall(PetscContainerGetPointer(container, &edata));
8004:   PetscCall(MatGetNonzeroState(A, &nonzerostate));
8005:   PetscCheck(nonzerostate <= edata->nonzerostate, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "Cannot handle changes to matrix nonzero structure");
8006:   PetscCheck(reuse != MAT_REUSE_MATRIX || *C == edata->C, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "C matrix must be the same as previously output");

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

8011:   for (PetscInt i = 0; i < edata->n; i++) {
8012:     Mat          D;
8013:     PetscScalar *dvalues;

8015:     PetscCall(MatConvert(edata->mat[i], MATSEQDENSE, MAT_INITIAL_MATRIX, &D));
8016:     PetscCall(MatSetOption(*C, MAT_ROW_ORIENTED, PETSC_FALSE));
8017:     PetscCall(MatSeqDenseInvert(D));
8018:     PetscCall(MatDenseGetArray(D, &dvalues));
8019:     PetscCall(MatSetValuesIS(*C, edata->is[i], edata->is[i], dvalues, INSERT_VALUES));
8020:     PetscCall(MatDestroy(&D));
8021:   }
8022:   PetscCall(MatDestroySubMatrices(edata->n, &edata->mat));
8023:   PetscCall(MatAssemblyBegin(*C, MAT_FINAL_ASSEMBLY));
8024:   PetscCall(MatAssemblyEnd(*C, MAT_FINAL_ASSEMBLY));
8025:   PetscFunctionReturn(PETSC_SUCCESS);
8026: }

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

8031:   Not Collective

8033:   Input Parameters:
8034: + mat     - the matrix
8035: . nblocks - the number of blocks on this process, each block can only exist on a single process
8036: - bsizes  - the block sizes

8038:   Level: intermediate

8040:   Notes:
8041:   Currently used by `PCVPBJACOBI` for `MATAIJ` matrices

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

8045: .seealso: [](ch_matrices), `Mat`, `MatCreateSeqBAIJ()`, `MatCreateBAIJ()`, `MatGetBlockSize()`, `MatSetBlockSizes()`, `MatGetBlockSizes()`, `MatGetVariableBlockSizes()`,
8046:           `MatComputeVariableBlockEnvelope()`, `PCVPBJACOBI`
8047: @*/
8048: PetscErrorCode MatSetVariableBlockSizes(Mat mat, PetscInt nblocks, const PetscInt bsizes[])
8049: {
8050:   PetscInt ncnt = 0, nlocal;

8052:   PetscFunctionBegin;
8054:   PetscCall(MatGetLocalSize(mat, &nlocal, NULL));
8055:   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);
8056:   for (PetscInt i = 0; i < nblocks; i++) ncnt += bsizes[i];
8057:   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);
8058:   PetscCall(PetscFree(mat->bsizes));
8059:   mat->nblocks = nblocks;
8060:   PetscCall(PetscMalloc1(nblocks, &mat->bsizes));
8061:   PetscCall(PetscArraycpy(mat->bsizes, bsizes, nblocks));
8062:   PetscFunctionReturn(PETSC_SUCCESS);
8063: }

8065: /*@C
8066:   MatGetVariableBlockSizes - Gets a diagonal blocks of the matrix that need not be of the same size

8068:   Not Collective; No Fortran Support

8070:   Input Parameter:
8071: . mat - the matrix

8073:   Output Parameters:
8074: + nblocks - the number of blocks on this process
8075: - bsizes  - the block sizes

8077:   Level: intermediate

8079: .seealso: [](ch_matrices), `Mat`, `MatCreateSeqBAIJ()`, `MatCreateBAIJ()`, `MatGetBlockSize()`, `MatSetBlockSizes()`, `MatGetBlockSizes()`, `MatSetVariableBlockSizes()`, `MatComputeVariableBlockEnvelope()`
8080: @*/
8081: PetscErrorCode MatGetVariableBlockSizes(Mat mat, PetscInt *nblocks, const PetscInt *bsizes[])
8082: {
8083:   PetscFunctionBegin;
8085:   if (nblocks) *nblocks = mat->nblocks;
8086:   if (bsizes) *bsizes = mat->bsizes;
8087:   PetscFunctionReturn(PETSC_SUCCESS);
8088: }

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

8093:   Not Collective

8095:   Input Parameter:
8096: + subA  - the submatrix
8097: . A     - the original matrix
8098: - isrow - The `IS` of selected rows for the submatrix, must be sorted

8100:   Level: developer

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

8105: .seealso: [](ch_matrices), `Mat`, `MatSetVariableBlockSizes()`, `MatComputeVariableBlockEnvelope()`
8106: @*/
8107: PetscErrorCode MatSelectVariableBlockSizes(Mat subA, Mat A, IS isrow)
8108: {
8109:   const PetscInt *rows;
8110:   PetscInt        n, rStart, rEnd, Nb = 0;
8111:   PetscBool       flg = A->bsizes ? PETSC_TRUE : PETSC_FALSE;

8113:   PetscFunctionBegin;
8114:   // The code for block size extraction does not support an unsorted IS
8115:   if (flg) PetscCall(ISSorted(isrow, &flg));
8116:   // We don't support originally off-diagonal blocks
8117:   if (flg) {
8118:     PetscCall(MatGetOwnershipRange(A, &rStart, &rEnd));
8119:     PetscCall(ISGetLocalSize(isrow, &n));
8120:     PetscCall(ISGetIndices(isrow, &rows));
8121:     for (PetscInt i = 0; i < n && flg; ++i) {
8122:       if (rows[i] < rStart || rows[i] >= rEnd) flg = PETSC_FALSE;
8123:     }
8124:     PetscCall(ISRestoreIndices(isrow, &rows));
8125:   }
8126:   // quiet return if we can't extract block size
8127:   PetscCallMPI(MPIU_Allreduce(MPI_IN_PLACE, &flg, 1, MPI_C_BOOL, MPI_LAND, PetscObjectComm((PetscObject)subA)));
8128:   if (!flg) PetscFunctionReturn(PETSC_SUCCESS);

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

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

8138:       if (i == n) break;
8139:       if (rows[i] == row) {
8140:         occupied = PETSC_TRUE;
8141:         ++i;
8142:       }
8143:       while (i < n && rows[i] < row) ++i;
8144:     }
8145:     gr += A->bsizes[b];
8146:     if (occupied) ++Nb;
8147:   }
8148:   subA->nblocks = Nb;
8149:   PetscCall(PetscFree(subA->bsizes));
8150:   PetscCall(PetscMalloc1(subA->nblocks, &subA->bsizes));
8151:   PetscInt sb = 0;
8152:   for (PetscInt b = 0, gr = rStart, i = 0; b < A->nblocks; ++b) {
8153:     if (sb < subA->nblocks) subA->bsizes[sb] = 0;
8154:     for (PetscInt br = 0; br < A->bsizes[b]; ++br) {
8155:       const PetscInt row = gr + br;

8157:       if (i == n) break;
8158:       if (rows[i] == row) {
8159:         ++subA->bsizes[sb];
8160:         ++i;
8161:       }
8162:       while (i < n && rows[i] < row) ++i;
8163:     }
8164:     gr += A->bsizes[b];
8165:     if (sb < subA->nblocks && subA->bsizes[sb]) ++sb;
8166:   }
8167:   PetscCheck(sb == subA->nblocks, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Invalid number of blocks %" PetscInt_FMT " != %" PetscInt_FMT, sb, subA->nblocks);
8168:   PetscInt nlocal, ncnt = 0;
8169:   PetscCall(MatGetLocalSize(subA, &nlocal, NULL));
8170:   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);
8171:   for (PetscInt i = 0; i < subA->nblocks; i++) ncnt += subA->bsizes[i];
8172:   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);
8173:   PetscCall(ISRestoreIndices(isrow, &rows));
8174:   PetscFunctionReturn(PETSC_SUCCESS);
8175: }

8177: /*@
8178:   MatSetBlockSizes - Sets the matrix block row and column sizes.

8180:   Logically Collective

8182:   Input Parameters:
8183: + mat - the matrix
8184: . rbs - row block size
8185: - cbs - column block size

8187:   Level: intermediate

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

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

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

8199: .seealso: [](ch_matrices), `Mat`, `MatCreateSeqBAIJ()`, `MatCreateBAIJ()`, `MatGetBlockSize()`, `MatSetBlockSize()`, `MatGetBlockSizes()`
8200: @*/
8201: PetscErrorCode MatSetBlockSizes(Mat mat, PetscInt rbs, PetscInt cbs)
8202: {
8203:   PetscFunctionBegin;
8207:   PetscTryTypeMethod(mat, setblocksizes, rbs, cbs);
8208:   if (mat->rmap->refcnt) {
8209:     ISLocalToGlobalMapping l2g  = NULL;
8210:     PetscLayout            nmap = NULL;

8212:     PetscCall(PetscLayoutDuplicate(mat->rmap, &nmap));
8213:     if (mat->rmap->mapping) PetscCall(ISLocalToGlobalMappingDuplicate(mat->rmap->mapping, &l2g));
8214:     PetscCall(PetscLayoutDestroy(&mat->rmap));
8215:     mat->rmap          = nmap;
8216:     mat->rmap->mapping = l2g;
8217:   }
8218:   if (mat->cmap->refcnt) {
8219:     ISLocalToGlobalMapping l2g  = NULL;
8220:     PetscLayout            nmap = NULL;

8222:     PetscCall(PetscLayoutDuplicate(mat->cmap, &nmap));
8223:     if (mat->cmap->mapping) PetscCall(ISLocalToGlobalMappingDuplicate(mat->cmap->mapping, &l2g));
8224:     PetscCall(PetscLayoutDestroy(&mat->cmap));
8225:     mat->cmap          = nmap;
8226:     mat->cmap->mapping = l2g;
8227:   }
8228:   PetscCall(PetscLayoutSetBlockSize(mat->rmap, rbs));
8229:   PetscCall(PetscLayoutSetBlockSize(mat->cmap, cbs));
8230:   PetscFunctionReturn(PETSC_SUCCESS);
8231: }

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

8236:   Logically Collective

8238:   Input Parameters:
8239: + mat     - the matrix
8240: . fromRow - matrix from which to copy row block size
8241: - fromCol - matrix from which to copy column block size (can be same as `fromRow`)

8243:   Level: developer

8245: .seealso: [](ch_matrices), `Mat`, `MatCreateSeqBAIJ()`, `MatCreateBAIJ()`, `MatGetBlockSize()`, `MatSetBlockSizes()`
8246: @*/
8247: PetscErrorCode MatSetBlockSizesFromMats(Mat mat, Mat fromRow, Mat fromCol)
8248: {
8249:   PetscFunctionBegin;
8253:   PetscTryTypeMethod(mat, setblocksizes, fromRow->rmap->bs, fromCol->cmap->bs);
8254:   PetscCall(PetscLayoutSetBlockSize(mat->rmap, fromRow->rmap->bs));
8255:   PetscCall(PetscLayoutSetBlockSize(mat->cmap, fromCol->cmap->bs));
8256:   PetscFunctionReturn(PETSC_SUCCESS);
8257: }

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

8262:   Collective

8264:   Input Parameters:
8265: + mat - the matrix
8266: . b   - the right-hand-side
8267: - x   - the approximate solution

8269:   Output Parameter:
8270: . r - location to store the residual

8272:   Level: developer

8274: .seealso: [](ch_matrices), `Mat`, `MatMult()`, `MatMultAdd()`, `PCMGSetResidual()`
8275: @*/
8276: PetscErrorCode MatResidual(Mat mat, Vec b, Vec x, Vec r)
8277: {
8278:   PetscFunctionBegin;
8284:   MatCheckPreallocated(mat, 1);
8285:   PetscCall(PetscLogEventBegin(MAT_Residual, mat, 0, 0, 0));
8286:   if (!mat->ops->residual) {
8287:     PetscCall(MatMult(mat, x, r));
8288:     PetscCall(VecAYPX(r, -1.0, b));
8289:   } else {
8290:     PetscUseTypeMethod(mat, residual, b, x, r);
8291:   }
8292:   PetscCall(PetscLogEventEnd(MAT_Residual, mat, 0, 0, 0));
8293:   PetscFunctionReturn(PETSC_SUCCESS);
8294: }

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

8299:   Collective

8301:   Input Parameters:
8302: + mat             - the matrix
8303: . shift           - 0 or 1 indicating we want the indices starting at 0 or 1
8304: . symmetric       - `PETSC_TRUE` or `PETSC_FALSE` indicating the matrix data structure should be symmetrized
8305: - inodecompressed - `PETSC_TRUE` or `PETSC_FALSE`  indicating if the nonzero structure of the
8306:                  inodes or the nonzero elements is wanted. For `MATBAIJ` matrices the compressed version is
8307:                  always used.

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

8316:   Level: developer

8318:   Notes:
8319:   You CANNOT change any of the ia[] or ja[] values.

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

8323:   Fortran Notes:
8324:   Use
8325: .vb
8326:     PetscInt, pointer :: ia(:),ja(:)
8327:     call MatGetRowIJ(mat,shift,symmetric,inodecompressed,n,ia,ja,done,ierr)
8328:     ! Access the ith and jth entries via ia(i) and ja(j)
8329: .ve

8331: .seealso: [](ch_matrices), `Mat`, `MATAIJ`, `MatGetColumnIJ()`, `MatRestoreRowIJ()`, `MatSeqAIJGetArray()`
8332: @*/
8333: PetscErrorCode MatGetRowIJ(Mat mat, PetscInt shift, PetscBool symmetric, PetscBool inodecompressed, PetscInt *n, const PetscInt *ia[], const PetscInt *ja[], PetscBool *done)
8334: {
8335:   PetscFunctionBegin;
8338:   if (n) PetscAssertPointer(n, 5);
8339:   if (ia) PetscAssertPointer(ia, 6);
8340:   if (ja) PetscAssertPointer(ja, 7);
8341:   if (done) PetscAssertPointer(done, 8);
8342:   MatCheckPreallocated(mat, 1);
8343:   if (!mat->ops->getrowij && done) *done = PETSC_FALSE;
8344:   else {
8345:     if (done) *done = PETSC_TRUE;
8346:     PetscCall(PetscLogEventBegin(MAT_GetRowIJ, mat, 0, 0, 0));
8347:     PetscUseTypeMethod(mat, getrowij, shift, symmetric, inodecompressed, n, ia, ja, done);
8348:     PetscCall(PetscLogEventEnd(MAT_GetRowIJ, mat, 0, 0, 0));
8349:   }
8350:   PetscFunctionReturn(PETSC_SUCCESS);
8351: }

8353: /*@C
8354:   MatGetColumnIJ - Returns the compressed column storage i and j indices for sequential matrices.

8356:   Collective

8358:   Input Parameters:
8359: + mat             - the matrix
8360: . shift           - 1 or zero indicating we want the indices starting at 0 or 1
8361: . symmetric       - `PETSC_TRUE` or `PETSC_FALSE` indicating the matrix data structure should be
8362:                 symmetrized
8363: - inodecompressed - `PETSC_TRUE` or `PETSC_FALSE` indicating if the nonzero structure of the
8364:                  inodes or the nonzero elements is wanted. For `MATBAIJ` matrices the compressed version is
8365:                  always used.

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

8373:   Level: developer

8375: .seealso: [](ch_matrices), `Mat`, `MatGetRowIJ()`, `MatRestoreColumnIJ()`
8376: @*/
8377: PetscErrorCode MatGetColumnIJ(Mat mat, PetscInt shift, PetscBool symmetric, PetscBool inodecompressed, PetscInt *n, const PetscInt *ia[], const PetscInt *ja[], PetscBool *done)
8378: {
8379:   PetscFunctionBegin;
8382:   PetscAssertPointer(n, 5);
8383:   if (ia) PetscAssertPointer(ia, 6);
8384:   if (ja) PetscAssertPointer(ja, 7);
8385:   PetscAssertPointer(done, 8);
8386:   MatCheckPreallocated(mat, 1);
8387:   if (!mat->ops->getcolumnij) *done = PETSC_FALSE;
8388:   else {
8389:     *done = PETSC_TRUE;
8390:     PetscUseTypeMethod(mat, getcolumnij, shift, symmetric, inodecompressed, n, ia, ja, done);
8391:   }
8392:   PetscFunctionReturn(PETSC_SUCCESS);
8393: }

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

8398:   Collective

8400:   Input Parameters:
8401: + mat             - the matrix
8402: . shift           - 1 or zero indicating we want the indices starting at 0 or 1
8403: . symmetric       - `PETSC_TRUE` or `PETSC_FALSE` indicating the matrix data structure should be symmetrized
8404: . inodecompressed - `PETSC_TRUE` or `PETSC_FALSE` indicating if the nonzero structure of the
8405:                     inodes or the nonzero elements is wanted. For `MATBAIJ` matrices the compressed version is
8406:                     always used.
8407: . n               - size of (possibly compressed) matrix
8408: . ia              - the row pointers
8409: - ja              - the column indices

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

8414:   Level: developer

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

8421: .seealso: [](ch_matrices), `Mat`, `MatGetRowIJ()`, `MatRestoreColumnIJ()`
8422: @*/
8423: PetscErrorCode MatRestoreRowIJ(Mat mat, PetscInt shift, PetscBool symmetric, PetscBool inodecompressed, PetscInt *n, const PetscInt *ia[], const PetscInt *ja[], PetscBool *done)
8424: {
8425:   PetscFunctionBegin;
8428:   if (ia) PetscAssertPointer(ia, 6);
8429:   if (ja) PetscAssertPointer(ja, 7);
8430:   if (done) PetscAssertPointer(done, 8);
8431:   MatCheckPreallocated(mat, 1);

8433:   if (!mat->ops->restorerowij && done) *done = PETSC_FALSE;
8434:   else {
8435:     if (done) *done = PETSC_TRUE;
8436:     PetscUseTypeMethod(mat, restorerowij, shift, symmetric, inodecompressed, n, ia, ja, done);
8437:     if (n) *n = 0;
8438:     if (ia) *ia = NULL;
8439:     if (ja) *ja = NULL;
8440:   }
8441:   PetscFunctionReturn(PETSC_SUCCESS);
8442: }

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

8447:   Collective

8449:   Input Parameters:
8450: + mat             - the matrix
8451: . shift           - 1 or zero indicating we want the indices starting at 0 or 1
8452: . symmetric       - `PETSC_TRUE` or `PETSC_FALSE` indicating the matrix data structure should be symmetrized
8453: - inodecompressed - `PETSC_TRUE` or `PETSC_FALSE` indicating if the nonzero structure of the
8454:                     inodes or the nonzero elements is wanted. For `MATBAIJ` matrices the compressed version is
8455:                     always used.

8457:   Output Parameters:
8458: + n    - size of (possibly compressed) matrix
8459: . ia   - the column pointers
8460: . ja   - the row indices
8461: - done - `PETSC_TRUE` or `PETSC_FALSE` indicated that the values have been returned

8463:   Level: developer

8465: .seealso: [](ch_matrices), `Mat`, `MatGetColumnIJ()`, `MatRestoreRowIJ()`
8466: @*/
8467: PetscErrorCode MatRestoreColumnIJ(Mat mat, PetscInt shift, PetscBool symmetric, PetscBool inodecompressed, PetscInt *n, const PetscInt *ia[], const PetscInt *ja[], PetscBool *done)
8468: {
8469:   PetscFunctionBegin;
8472:   if (ia) PetscAssertPointer(ia, 6);
8473:   if (ja) PetscAssertPointer(ja, 7);
8474:   PetscAssertPointer(done, 8);
8475:   MatCheckPreallocated(mat, 1);

8477:   if (!mat->ops->restorecolumnij) *done = PETSC_FALSE;
8478:   else {
8479:     *done = PETSC_TRUE;
8480:     PetscUseTypeMethod(mat, restorecolumnij, shift, symmetric, inodecompressed, n, ia, ja, done);
8481:     if (n) *n = 0;
8482:     if (ia) *ia = NULL;
8483:     if (ja) *ja = NULL;
8484:   }
8485:   PetscFunctionReturn(PETSC_SUCCESS);
8486: }

8488: /*@
8489:   MatColoringPatch - Used inside matrix coloring routines that use `MatGetRowIJ()` and/or
8490:   `MatGetColumnIJ()`.

8492:   Collective

8494:   Input Parameters:
8495: + mat        - the matrix
8496: . ncolors    - maximum color value
8497: . n          - number of entries in colorarray
8498: - colorarray - array indicating color for each column

8500:   Output Parameter:
8501: . iscoloring - coloring generated using colorarray information

8503:   Level: developer

8505: .seealso: [](ch_matrices), `Mat`, `MatGetRowIJ()`, `MatGetColumnIJ()`
8506: @*/
8507: PetscErrorCode MatColoringPatch(Mat mat, PetscInt ncolors, PetscInt n, ISColoringValue colorarray[], ISColoring *iscoloring)
8508: {
8509:   PetscFunctionBegin;
8512:   PetscAssertPointer(colorarray, 4);
8513:   PetscAssertPointer(iscoloring, 5);
8514:   MatCheckPreallocated(mat, 1);

8516:   if (!mat->ops->coloringpatch) {
8517:     PetscCall(ISColoringCreate(PetscObjectComm((PetscObject)mat), ncolors, n, colorarray, PETSC_OWN_POINTER, iscoloring));
8518:   } else {
8519:     PetscUseTypeMethod(mat, coloringpatch, ncolors, n, colorarray, iscoloring);
8520:   }
8521:   PetscFunctionReturn(PETSC_SUCCESS);
8522: }

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

8527:   Logically Collective

8529:   Input Parameter:
8530: . mat - the factored matrix to be reset

8532:   Level: developer

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

8541:   One can specify in-place ILU(0) factorization by calling
8542: .vb
8543:      PCType(pc,PCILU);
8544:      PCFactorSeUseInPlace(pc);
8545: .ve
8546:   or by using the options -pc_type ilu -pc_factor_in_place

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

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

8557: .seealso: [](ch_matrices), `Mat`, `PCFactorSetUseInPlace()`, `PCFactorGetUseInPlace()`
8558: @*/
8559: PetscErrorCode MatSetUnfactored(Mat mat)
8560: {
8561:   PetscFunctionBegin;
8564:   MatCheckPreallocated(mat, 1);
8565:   mat->factortype = MAT_FACTOR_NONE;
8566:   if (!mat->ops->setunfactored) PetscFunctionReturn(PETSC_SUCCESS);
8567:   PetscUseTypeMethod(mat, setunfactored);
8568:   PetscFunctionReturn(PETSC_SUCCESS);
8569: }

8571: /*@
8572:   MatCreateSubMatrix - Gets a single submatrix on the same number of processors
8573:   as the original matrix.

8575:   Collective

8577:   Input Parameters:
8578: + mat   - the original matrix
8579: . isrow - parallel `IS` containing the rows this processor should obtain
8580: . 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.
8581: - cll   - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`

8583:   Output Parameter:
8584: . newmat - the new submatrix, of the same type as the original matrix

8586:   Level: advanced

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

8591:   Some matrix types place restrictions on the row and column indices, such
8592:   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;
8593:   for example, if the block size is 3 one cannot select the 0 and 2 rows without selecting the 1 row.

8595:   The index sets may not have duplicate entries.

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

8603:   The communicator of the newly obtained matrix is ALWAYS the same as the communicator of
8604:   the input matrix.

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

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

8611:   Example usage:
8612:   Consider the following 8x8 matrix with 34 non-zero values, that is
8613:   assembled across 3 processors. Let's assume that proc0 owns 3 rows,
8614:   proc1 owns 3 rows, proc2 owns 2 rows. This division can be shown
8615:   as follows
8616: .vb
8617:             1  2  0  |  0  3  0  |  0  4
8618:     Proc0   0  5  6  |  7  0  0  |  8  0
8619:             9  0 10  | 11  0  0  | 12  0
8620:     -------------------------------------
8621:            13  0 14  | 15 16 17  |  0  0
8622:     Proc1   0 18  0  | 19 20 21  |  0  0
8623:             0  0  0  | 22 23  0  | 24  0
8624:     -------------------------------------
8625:     Proc2  25 26 27  |  0  0 28  | 29  0
8626:            30  0  0  | 31 32 33  |  0 34
8627: .ve

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

8631: .vb
8632:             2  0  |  0  3  0  |  0
8633:     Proc0   5  6  |  7  0  0  |  8
8634:     -------------------------------
8635:     Proc1  18  0  | 19 20 21  |  0
8636:     -------------------------------
8637:     Proc2  26 27  |  0  0 28  | 29
8638:             0  0  | 31 32 33  |  0
8639: .ve

8641: .seealso: [](ch_matrices), `Mat`, `MatCreateSubMatrices()`, `MatCreateSubMatricesMPI()`, `MatCreateSubMatrixVirtual()`, `MatSubMatrixVirtualUpdate()`
8642: @*/
8643: PetscErrorCode MatCreateSubMatrix(Mat mat, IS isrow, IS iscol, MatReuse cll, Mat *newmat)
8644: {
8645:   PetscMPIInt size;
8646:   Mat        *local;
8647:   IS          iscoltmp;
8648:   PetscBool   flg;

8650:   PetscFunctionBegin;
8654:   PetscAssertPointer(newmat, 5);
8657:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
8658:   PetscCheck(cll != MAT_IGNORE_MATRIX, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Cannot use MAT_IGNORE_MATRIX");
8659:   PetscCheck(cll != MAT_INPLACE_MATRIX, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Cannot use MAT_INPLACE_MATRIX");

8661:   MatCheckPreallocated(mat, 1);
8662:   PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)mat), &size));

8664:   if (!iscol || isrow == iscol) {
8665:     PetscBool   stride;
8666:     PetscMPIInt grabentirematrix = 0, grab;
8667:     PetscCall(PetscObjectTypeCompare((PetscObject)isrow, ISSTRIDE, &stride));
8668:     if (stride) {
8669:       PetscInt first, step, n, rstart, rend;
8670:       PetscCall(ISStrideGetInfo(isrow, &first, &step));
8671:       if (step == 1) {
8672:         PetscCall(MatGetOwnershipRange(mat, &rstart, &rend));
8673:         if (rstart == first) {
8674:           PetscCall(ISGetLocalSize(isrow, &n));
8675:           if (n == rend - rstart) grabentirematrix = 1;
8676:         }
8677:       }
8678:     }
8679:     PetscCallMPI(MPIU_Allreduce(&grabentirematrix, &grab, 1, MPI_INT, MPI_MIN, PetscObjectComm((PetscObject)mat)));
8680:     if (grab) {
8681:       PetscCall(PetscInfo(mat, "Getting entire matrix as submatrix\n"));
8682:       if (cll == MAT_INITIAL_MATRIX) {
8683:         *newmat = mat;
8684:         PetscCall(PetscObjectReference((PetscObject)mat));
8685:       }
8686:       PetscFunctionReturn(PETSC_SUCCESS);
8687:     }
8688:   }

8690:   if (!iscol) {
8691:     PetscCall(ISCreateStride(PetscObjectComm((PetscObject)mat), mat->cmap->n, mat->cmap->rstart, 1, &iscoltmp));
8692:   } else {
8693:     iscoltmp = iscol;
8694:   }

8696:   /* if original matrix is on just one processor then use submatrix generated */
8697:   if (mat->ops->createsubmatrices && !mat->ops->createsubmatrix && size == 1 && cll == MAT_REUSE_MATRIX) {
8698:     PetscCall(MatCreateSubMatrices(mat, 1, &isrow, &iscoltmp, MAT_REUSE_MATRIX, &newmat));
8699:     goto setproperties;
8700:   } else if (mat->ops->createsubmatrices && !mat->ops->createsubmatrix && size == 1) {
8701:     PetscCall(MatCreateSubMatrices(mat, 1, &isrow, &iscoltmp, MAT_INITIAL_MATRIX, &local));
8702:     *newmat = *local;
8703:     PetscCall(PetscFree(local));
8704:     goto setproperties;
8705:   } else if (!mat->ops->createsubmatrix) {
8706:     /* Create a new matrix type that implements the operation using the full matrix */
8707:     PetscCall(PetscLogEventBegin(MAT_CreateSubMat, mat, 0, 0, 0));
8708:     switch (cll) {
8709:     case MAT_INITIAL_MATRIX:
8710:       PetscCall(MatCreateSubMatrixVirtual(mat, isrow, iscoltmp, newmat));
8711:       break;
8712:     case MAT_REUSE_MATRIX:
8713:       PetscCall(MatSubMatrixVirtualUpdate(*newmat, mat, isrow, iscoltmp));
8714:       break;
8715:     default:
8716:       SETERRQ(PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_OUTOFRANGE, "Invalid MatReuse, must be either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX");
8717:     }
8718:     PetscCall(PetscLogEventEnd(MAT_CreateSubMat, mat, 0, 0, 0));
8719:     goto setproperties;
8720:   }

8722:   PetscCall(PetscLogEventBegin(MAT_CreateSubMat, mat, 0, 0, 0));
8723:   PetscUseTypeMethod(mat, createsubmatrix, isrow, iscoltmp, cll, newmat);
8724:   PetscCall(PetscLogEventEnd(MAT_CreateSubMat, mat, 0, 0, 0));

8726: setproperties:
8727:   if ((*newmat)->symmetric == PETSC_BOOL3_UNKNOWN && (*newmat)->structurally_symmetric == PETSC_BOOL3_UNKNOWN && (*newmat)->spd == PETSC_BOOL3_UNKNOWN && (*newmat)->hermitian == PETSC_BOOL3_UNKNOWN) {
8728:     PetscCall(ISEqualUnsorted(isrow, iscoltmp, &flg));
8729:     if (flg) PetscCall(MatPropagateSymmetryOptions(mat, *newmat));
8730:   }
8731:   if (!iscol) PetscCall(ISDestroy(&iscoltmp));
8732:   if (*newmat && cll == MAT_INITIAL_MATRIX) PetscCall(PetscObjectStateIncrease((PetscObject)*newmat));
8733:   if (!iscol || isrow == iscol) PetscCall(MatSelectVariableBlockSizes(*newmat, mat, isrow));
8734:   PetscFunctionReturn(PETSC_SUCCESS);
8735: }

8737: /*@
8738:   MatPropagateSymmetryOptions - Propagates symmetry options set on a matrix to another matrix

8740:   Not Collective

8742:   Input Parameters:
8743: + A - the matrix we wish to propagate options from
8744: - B - the matrix we wish to propagate options to

8746:   Level: beginner

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

8751: .seealso: [](ch_matrices), `Mat`, `MatSetOption()`, `MatIsSymmetricKnown()`, `MatIsSPDKnown()`, `MatIsHermitianKnown()`, `MatIsStructurallySymmetricKnown()`
8752: @*/
8753: PetscErrorCode MatPropagateSymmetryOptions(Mat A, Mat B)
8754: {
8755:   PetscFunctionBegin;
8758:   B->symmetry_eternal            = A->symmetry_eternal;
8759:   B->structural_symmetry_eternal = A->structural_symmetry_eternal;
8760:   B->symmetric                   = A->symmetric;
8761:   B->structurally_symmetric      = A->structurally_symmetric;
8762:   B->spd                         = A->spd;
8763:   B->hermitian                   = A->hermitian;
8764:   PetscFunctionReturn(PETSC_SUCCESS);
8765: }

8767: /*@
8768:   MatStashSetInitialSize - sets the sizes of the matrix stash, that is
8769:   used during the assembly process to store values that belong to
8770:   other processors.

8772:   Not Collective

8774:   Input Parameters:
8775: + mat   - the matrix
8776: . size  - the initial size of the stash.
8777: - bsize - the initial size of the block-stash(if used).

8779:   Options Database Keys:
8780: + -matstash_initial_size size or size0,size1,...,sizep-1            - set initial size
8781: - -matstash_block_initial_size bsize  or bsize0,bsize1,...,bsizep-1 - set initial block size

8783:   Level: intermediate

8785:   Notes:
8786:   The block-stash is used for values set with `MatSetValuesBlocked()` while
8787:   the stash is used for values set with `MatSetValues()`

8789:   Run with the option -info and look for output of the form
8790:   MatAssemblyBegin_MPIXXX:Stash has MM entries, uses nn mallocs.
8791:   to determine the appropriate value, MM, to use for size and
8792:   MatAssemblyBegin_MPIXXX:Block-Stash has BMM entries, uses nn mallocs.
8793:   to determine the value, BMM to use for bsize

8795: .seealso: [](ch_matrices), `MatAssemblyBegin()`, `MatAssemblyEnd()`, `Mat`, `MatStashGetInfo()`
8796: @*/
8797: PetscErrorCode MatStashSetInitialSize(Mat mat, PetscInt size, PetscInt bsize)
8798: {
8799:   PetscFunctionBegin;
8802:   PetscCall(MatStashSetInitialSize_Private(&mat->stash, size));
8803:   PetscCall(MatStashSetInitialSize_Private(&mat->bstash, bsize));
8804:   PetscFunctionReturn(PETSC_SUCCESS);
8805: }

8807: /*@
8808:   MatInterpolateAdd - $w = y + A*x$ or $A^T*x$ depending on the shape of
8809:   the matrix

8811:   Neighbor-wise Collective

8813:   Input Parameters:
8814: + A - the matrix
8815: . x - the vector to be multiplied by the interpolation operator
8816: - y - the vector to be added to the result

8818:   Output Parameter:
8819: . w - the resulting vector

8821:   Level: intermediate

8823:   Notes:
8824:   `w` may be the same vector as `y`.

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

8829: .seealso: [](ch_matrices), `Mat`, `MatMultAdd()`, `MatMultTransposeAdd()`, `MatRestrict()`, `PCMG`
8830: @*/
8831: PetscErrorCode MatInterpolateAdd(Mat A, Vec x, Vec y, Vec w)
8832: {
8833:   PetscInt M, N, Ny;

8835:   PetscFunctionBegin;
8840:   PetscCall(MatGetSize(A, &M, &N));
8841:   PetscCall(VecGetSize(y, &Ny));
8842:   if (M == Ny) PetscCall(MatMultAdd(A, x, y, w));
8843:   else PetscCall(MatMultTransposeAdd(A, x, y, w));
8844:   PetscFunctionReturn(PETSC_SUCCESS);
8845: }

8847: /*@
8848:   MatInterpolate - $y = A*x$ or $A^T*x$ depending on the shape of
8849:   the matrix

8851:   Neighbor-wise Collective

8853:   Input Parameters:
8854: + A - the matrix
8855: - x - the vector to be interpolated

8857:   Output Parameter:
8858: . y - the resulting vector

8860:   Level: intermediate

8862:   Note:
8863:   This allows one to use either the restriction or interpolation (its transpose)
8864:   matrix to do the interpolation

8866: .seealso: [](ch_matrices), `Mat`, `MatMultAdd()`, `MatMultTransposeAdd()`, `MatRestrict()`, `PCMG`
8867: @*/
8868: PetscErrorCode MatInterpolate(Mat A, Vec x, Vec y)
8869: {
8870:   PetscInt M, N, Ny;

8872:   PetscFunctionBegin;
8876:   PetscCall(MatGetSize(A, &M, &N));
8877:   PetscCall(VecGetSize(y, &Ny));
8878:   if (M == Ny) PetscCall(MatMult(A, x, y));
8879:   else PetscCall(MatMultTranspose(A, x, y));
8880:   PetscFunctionReturn(PETSC_SUCCESS);
8881: }

8883: /*@
8884:   MatRestrict - $y = A*x$ or $A^T*x$

8886:   Neighbor-wise Collective

8888:   Input Parameters:
8889: + A - the matrix
8890: - x - the vector to be restricted

8892:   Output Parameter:
8893: . y - the resulting vector

8895:   Level: intermediate

8897:   Note:
8898:   This allows one to use either the restriction or interpolation (its transpose)
8899:   matrix to do the restriction

8901: .seealso: [](ch_matrices), `Mat`, `MatMultAdd()`, `MatMultTransposeAdd()`, `MatInterpolate()`, `PCMG`
8902: @*/
8903: PetscErrorCode MatRestrict(Mat A, Vec x, Vec y)
8904: {
8905:   PetscInt M, N, Nx;

8907:   PetscFunctionBegin;
8911:   PetscCall(MatGetSize(A, &M, &N));
8912:   PetscCall(VecGetSize(x, &Nx));
8913:   if (M == Nx) PetscCall(MatMultTranspose(A, x, y));
8914:   else PetscCall(MatMult(A, x, y));
8915:   PetscFunctionReturn(PETSC_SUCCESS);
8916: }

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

8921:   Neighbor-wise Collective

8923:   Input Parameters:
8924: + A - the matrix
8925: . x - the input dense matrix to be multiplied
8926: - w - the input dense matrix to be added to the result

8928:   Output Parameter:
8929: . y - the output dense matrix

8931:   Level: intermediate

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

8938: .seealso: [](ch_matrices), `Mat`, `MatInterpolateAdd()`, `MatMatInterpolate()`, `MatMatRestrict()`, `PCMG`
8939: @*/
8940: PetscErrorCode MatMatInterpolateAdd(Mat A, Mat x, Mat w, Mat *y)
8941: {
8942:   PetscInt  M, N, Mx, Nx, Mo, My = 0, Ny = 0;
8943:   PetscBool trans = PETSC_TRUE;
8944:   MatReuse  reuse = MAT_INITIAL_MATRIX;

8946:   PetscFunctionBegin;
8952:   PetscCall(MatGetSize(A, &M, &N));
8953:   PetscCall(MatGetSize(x, &Mx, &Nx));
8954:   if (N == Mx) trans = PETSC_FALSE;
8955:   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);
8956:   Mo = trans ? N : M;
8957:   if (*y) {
8958:     PetscCall(MatGetSize(*y, &My, &Ny));
8959:     if (Mo == My && Nx == Ny) reuse = MAT_REUSE_MATRIX;
8960:     else {
8961:       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);
8962:       PetscCall(MatDestroy(y));
8963:     }
8964:   }

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

8969:     PetscCall(PetscObjectQuery((PetscObject)*y, "__MatMatIntAdd_w", (PetscObject *)&w));
8970:     if (w) {
8971:       PetscInt My, Ny, Mw, Nw;

8973:       PetscCall(PetscObjectTypeCompare((PetscObject)*y, ((PetscObject)w)->type_name, &flg));
8974:       PetscCall(MatGetSize(*y, &My, &Ny));
8975:       PetscCall(MatGetSize(w, &Mw, &Nw));
8976:       if (!flg || My != Mw || Ny != Nw) w = NULL;
8977:     }
8978:     if (!w) {
8979:       PetscCall(MatDuplicate(*y, MAT_COPY_VALUES, &w));
8980:       PetscCall(PetscObjectCompose((PetscObject)*y, "__MatMatIntAdd_w", (PetscObject)w));
8981:       PetscCall(PetscObjectDereference((PetscObject)w));
8982:     } else PetscCall(MatCopy(*y, w, UNKNOWN_NONZERO_PATTERN));
8983:   }
8984:   if (!trans) PetscCall(MatMatMult(A, x, reuse, PETSC_DETERMINE, y));
8985:   else PetscCall(MatTransposeMatMult(A, x, reuse, PETSC_DETERMINE, y));
8986:   if (w) PetscCall(MatAXPY(*y, 1.0, w, UNKNOWN_NONZERO_PATTERN));
8987:   PetscFunctionReturn(PETSC_SUCCESS);
8988: }

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

8993:   Neighbor-wise Collective

8995:   Input Parameters:
8996: + A - the matrix
8997: - x - the input dense matrix

8999:   Output Parameter:
9000: . y - the output dense matrix

9002:   Level: intermediate

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

9009: .seealso: [](ch_matrices), `Mat`, `MatInterpolate()`, `MatRestrict()`, `MatMatRestrict()`, `PCMG`
9010: @*/
9011: PetscErrorCode MatMatInterpolate(Mat A, Mat x, Mat *y)
9012: {
9013:   PetscFunctionBegin;
9014:   PetscCall(MatMatInterpolateAdd(A, x, NULL, y));
9015:   PetscFunctionReturn(PETSC_SUCCESS);
9016: }

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

9021:   Neighbor-wise Collective

9023:   Input Parameters:
9024: + A - the matrix
9025: - x - the input dense matrix

9027:   Output Parameter:
9028: . y - the output dense matrix

9030:   Level: intermediate

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

9037: .seealso: [](ch_matrices), `Mat`, `MatRestrict()`, `MatInterpolate()`, `MatMatInterpolate()`, `PCMG`
9038: @*/
9039: PetscErrorCode MatMatRestrict(Mat A, Mat x, Mat *y)
9040: {
9041:   PetscFunctionBegin;
9042:   PetscCall(MatMatInterpolateAdd(A, x, NULL, y));
9043:   PetscFunctionReturn(PETSC_SUCCESS);
9044: }

9046: /*@
9047:   MatGetNullSpace - retrieves the null space of a matrix.

9049:   Logically Collective

9051:   Input Parameters:
9052: + mat    - the matrix
9053: - nullsp - the null space object

9055:   Level: developer

9057: .seealso: [](ch_matrices), `Mat`, `MatCreate()`, `MatNullSpaceCreate()`, `MatSetNearNullSpace()`, `MatSetNullSpace()`, `MatNullSpace`
9058: @*/
9059: PetscErrorCode MatGetNullSpace(Mat mat, MatNullSpace *nullsp)
9060: {
9061:   PetscFunctionBegin;
9063:   PetscAssertPointer(nullsp, 2);
9064:   *nullsp = (mat->symmetric == PETSC_BOOL3_TRUE && !mat->nullsp) ? mat->transnullsp : mat->nullsp;
9065:   PetscFunctionReturn(PETSC_SUCCESS);
9066: }

9068: /*@C
9069:   MatGetNullSpaces - gets the null spaces, transpose null spaces, and near null spaces from an array of matrices

9071:   Logically Collective

9073:   Input Parameters:
9074: + n   - the number of matrices
9075: - mat - the array of matrices

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

9080:   Level: developer

9082:   Note:
9083:   Call `MatRestoreNullspaces()` to provide these to another array of matrices

9085: .seealso: [](ch_matrices), `Mat`, `MatCreate()`, `MatNullSpaceCreate()`, `MatSetNearNullSpace()`, `MatGetNullSpace()`, `MatSetTransposeNullSpace()`, `MatGetTransposeNullSpace()`,
9086:           `MatNullSpaceRemove()`, `MatRestoreNullSpaces()`
9087: @*/
9088: PetscErrorCode MatGetNullSpaces(PetscInt n, Mat mat[], MatNullSpace *nullsp[])
9089: {
9090:   PetscFunctionBegin;
9091:   PetscCheck(n >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Number of matrices %" PetscInt_FMT " must be non-negative", n);
9092:   PetscAssertPointer(mat, 2);
9093:   PetscAssertPointer(nullsp, 3);

9095:   PetscCall(PetscCalloc1(3 * n, nullsp));
9096:   for (PetscInt i = 0; i < n; i++) {
9098:     (*nullsp)[i] = mat[i]->nullsp;
9099:     PetscCall(PetscObjectReference((PetscObject)(*nullsp)[i]));
9100:     (*nullsp)[n + i] = mat[i]->nearnullsp;
9101:     PetscCall(PetscObjectReference((PetscObject)(*nullsp)[n + i]));
9102:     (*nullsp)[2 * n + i] = mat[i]->transnullsp;
9103:     PetscCall(PetscObjectReference((PetscObject)(*nullsp)[2 * n + i]));
9104:   }
9105:   PetscFunctionReturn(PETSC_SUCCESS);
9106: }

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

9111:   Logically Collective

9113:   Input Parameters:
9114: + n      - the number of matrices
9115: . mat    - the array of matrices
9116: - nullsp - an array of null spaces

9118:   Level: developer

9120:   Note:
9121:   Call `MatGetNullSpaces()` to create `nullsp`

9123: .seealso: [](ch_matrices), `Mat`, `MatCreate()`, `MatNullSpaceCreate()`, `MatSetNearNullSpace()`, `MatGetNullSpace()`, `MatSetTransposeNullSpace()`, `MatGetTransposeNullSpace()`,
9124:           `MatNullSpaceRemove()`, `MatGetNullSpaces()`
9125: @*/
9126: PetscErrorCode MatRestoreNullSpaces(PetscInt n, Mat mat[], MatNullSpace *nullsp[])
9127: {
9128:   PetscFunctionBegin;
9129:   PetscCheck(n >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Number of matrices %" PetscInt_FMT " must be non-negative", n);
9130:   PetscAssertPointer(mat, 2);
9131:   PetscAssertPointer(nullsp, 3);
9132:   PetscAssertPointer(*nullsp, 3);

9134:   for (PetscInt i = 0; i < n; i++) {
9136:     PetscCall(MatSetNullSpace(mat[i], (*nullsp)[i]));
9137:     PetscCall(PetscObjectDereference((PetscObject)(*nullsp)[i]));
9138:     PetscCall(MatSetNearNullSpace(mat[i], (*nullsp)[n + i]));
9139:     PetscCall(PetscObjectDereference((PetscObject)(*nullsp)[n + i]));
9140:     PetscCall(MatSetTransposeNullSpace(mat[i], (*nullsp)[2 * n + i]));
9141:     PetscCall(PetscObjectDereference((PetscObject)(*nullsp)[2 * n + i]));
9142:   }
9143:   PetscCall(PetscFree(*nullsp));
9144:   PetscFunctionReturn(PETSC_SUCCESS);
9145: }

9147: /*@
9148:   MatSetNullSpace - attaches a null space to a matrix.

9150:   Logically Collective

9152:   Input Parameters:
9153: + mat    - the matrix
9154: - nullsp - the null space object

9156:   Level: advanced

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

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

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

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

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

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

9179: .seealso: [](ch_matrices), `Mat`, `MatCreate()`, `MatNullSpaceCreate()`, `MatSetNearNullSpace()`, `MatGetNullSpace()`, `MatSetTransposeNullSpace()`, `MatGetTransposeNullSpace()`, `MatNullSpaceRemove()`,
9180:           `KSPSetPCSide()`
9181: @*/
9182: PetscErrorCode MatSetNullSpace(Mat mat, MatNullSpace nullsp)
9183: {
9184:   PetscFunctionBegin;
9187:   if (nullsp) PetscCall(PetscObjectReference((PetscObject)nullsp));
9188:   PetscCall(MatNullSpaceDestroy(&mat->nullsp));
9189:   mat->nullsp = nullsp;
9190:   if (mat->symmetric == PETSC_BOOL3_TRUE) PetscCall(MatSetTransposeNullSpace(mat, nullsp));
9191:   PetscFunctionReturn(PETSC_SUCCESS);
9192: }

9194: /*@
9195:   MatGetTransposeNullSpace - retrieves the null space of the transpose of a matrix.

9197:   Logically Collective

9199:   Input Parameters:
9200: + mat    - the matrix
9201: - nullsp - the null space object

9203:   Level: developer

9205: .seealso: [](ch_matrices), `Mat`, `MatNullSpace`, `MatCreate()`, `MatNullSpaceCreate()`, `MatSetNearNullSpace()`, `MatSetTransposeNullSpace()`, `MatSetNullSpace()`, `MatGetNullSpace()`
9206: @*/
9207: PetscErrorCode MatGetTransposeNullSpace(Mat mat, MatNullSpace *nullsp)
9208: {
9209:   PetscFunctionBegin;
9212:   PetscAssertPointer(nullsp, 2);
9213:   *nullsp = (mat->symmetric == PETSC_BOOL3_TRUE && !mat->transnullsp) ? mat->nullsp : mat->transnullsp;
9214:   PetscFunctionReturn(PETSC_SUCCESS);
9215: }

9217: /*@
9218:   MatSetTransposeNullSpace - attaches the null space of a transpose of a matrix to the matrix

9220:   Logically Collective

9222:   Input Parameters:
9223: + mat    - the matrix
9224: - nullsp - the null space object

9226:   Level: advanced

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

9231:   See `MatSetNullSpace()`

9233: .seealso: [](ch_matrices), `Mat`, `MatNullSpace`, `MatCreate()`, `MatNullSpaceCreate()`, `MatSetNearNullSpace()`, `MatGetNullSpace()`, `MatSetNullSpace()`, `MatGetTransposeNullSpace()`, `MatNullSpaceRemove()`, `KSPSetPCSide()`
9234: @*/
9235: PetscErrorCode MatSetTransposeNullSpace(Mat mat, MatNullSpace nullsp)
9236: {
9237:   PetscFunctionBegin;
9240:   if (nullsp) PetscCall(PetscObjectReference((PetscObject)nullsp));
9241:   PetscCall(MatNullSpaceDestroy(&mat->transnullsp));
9242:   mat->transnullsp = nullsp;
9243:   PetscFunctionReturn(PETSC_SUCCESS);
9244: }

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

9250:   Logically Collective

9252:   Input Parameters:
9253: + mat    - the matrix
9254: - nullsp - the null space object

9256:   Level: advanced

9258:   Notes:
9259:   Overwrites any previous near null space that may have been attached

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

9263: .seealso: [](ch_matrices), `Mat`, `MatNullSpace`, `MatCreate()`, `MatNullSpaceCreate()`, `MatSetNullSpace()`, `MatNullSpaceCreateRigidBody()`, `MatGetNearNullSpace()`
9264: @*/
9265: PetscErrorCode MatSetNearNullSpace(Mat mat, MatNullSpace nullsp)
9266: {
9267:   PetscFunctionBegin;
9271:   MatCheckPreallocated(mat, 1);
9272:   if (nullsp) PetscCall(PetscObjectReference((PetscObject)nullsp));
9273:   PetscCall(MatNullSpaceDestroy(&mat->nearnullsp));
9274:   mat->nearnullsp = nullsp;
9275:   PetscFunctionReturn(PETSC_SUCCESS);
9276: }

9278: /*@
9279:   MatGetNearNullSpace - Get null space attached with `MatSetNearNullSpace()`

9281:   Not Collective

9283:   Input Parameter:
9284: . mat - the matrix

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

9289:   Level: advanced

9291: .seealso: [](ch_matrices), `Mat`, `MatNullSpace`, `MatSetNearNullSpace()`, `MatGetNullSpace()`, `MatNullSpaceCreate()`
9292: @*/
9293: PetscErrorCode MatGetNearNullSpace(Mat mat, MatNullSpace *nullsp)
9294: {
9295:   PetscFunctionBegin;
9298:   PetscAssertPointer(nullsp, 2);
9299:   MatCheckPreallocated(mat, 1);
9300:   *nullsp = mat->nearnullsp;
9301:   PetscFunctionReturn(PETSC_SUCCESS);
9302: }

9304: /*@
9305:   MatICCFactor - Performs in-place incomplete Cholesky factorization of matrix.

9307:   Collective

9309:   Input Parameters:
9310: + mat  - the matrix
9311: . row  - row/column permutation
9312: - info - information on desired factorization process

9314:   Level: developer

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

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

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

9327: .seealso: [](ch_matrices), `Mat`, `MatFactorInfo`, `MatGetFactor()`, `MatICCFactorSymbolic()`, `MatLUFactorNumeric()`, `MatCholeskyFactor()`
9328: @*/
9329: PetscErrorCode MatICCFactor(Mat mat, IS row, const MatFactorInfo *info)
9330: {
9331:   PetscFunctionBegin;
9335:   PetscAssertPointer(info, 3);
9336:   PetscCheck(mat->rmap->N == mat->cmap->N, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONG, "matrix must be square");
9337:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
9338:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
9339:   MatCheckPreallocated(mat, 1);
9340:   PetscUseTypeMethod(mat, iccfactor, row, info);
9341:   PetscCall(PetscObjectStateIncrease((PetscObject)mat));
9342:   PetscFunctionReturn(PETSC_SUCCESS);
9343: }

9345: /*@
9346:   MatDiagonalScaleLocal - Scales columns of a matrix given the scaling values including the
9347:   ghosted ones.

9349:   Not Collective

9351:   Input Parameters:
9352: + mat  - the matrix
9353: - diag - the diagonal values, including ghost ones

9355:   Level: developer

9357:   Notes:
9358:   Works only for `MATMPIAIJ` and `MATMPIBAIJ` matrices

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

9362: .seealso: [](ch_matrices), `Mat`, `MatDiagonalScale()`
9363: @*/
9364: PetscErrorCode MatDiagonalScaleLocal(Mat mat, Vec diag)
9365: {
9366:   PetscMPIInt size;

9368:   PetscFunctionBegin;

9373:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Matrix must be already assembled");
9374:   PetscCall(PetscLogEventBegin(MAT_Scale, mat, 0, 0, 0));
9375:   PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)mat), &size));
9376:   if (size == 1) {
9377:     PetscInt n, m;
9378:     PetscCall(VecGetSize(diag, &n));
9379:     PetscCall(MatGetSize(mat, NULL, &m));
9380:     PetscCheck(m == n, PETSC_COMM_SELF, PETSC_ERR_SUP, "Only supported for sequential matrices when no ghost points/periodic conditions");
9381:     PetscCall(MatDiagonalScale(mat, NULL, diag));
9382:   } else PetscUseMethod(mat, "MatDiagonalScaleLocal_C", (Mat, Vec), (mat, diag));
9383:   PetscCall(PetscLogEventEnd(MAT_Scale, mat, 0, 0, 0));
9384:   PetscCall(PetscObjectStateIncrease((PetscObject)mat));
9385:   PetscFunctionReturn(PETSC_SUCCESS);
9386: }

9388: /*@
9389:   MatGetInertia - Gets the inertia from a factored matrix

9391:   Collective

9393:   Input Parameter:
9394: . mat - the matrix

9396:   Output Parameters:
9397: + nneg  - number of negative eigenvalues
9398: . nzero - number of zero eigenvalues
9399: - npos  - number of positive eigenvalues

9401:   Level: advanced

9403:   Note:
9404:   Matrix must have been factored by `MatCholeskyFactor()`

9406: .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatCholeskyFactor()`
9407: @*/
9408: PetscErrorCode MatGetInertia(Mat mat, PetscInt *nneg, PetscInt *nzero, PetscInt *npos)
9409: {
9410:   PetscFunctionBegin;
9413:   PetscCheck(mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Unfactored matrix");
9414:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Numeric factor mat is not assembled");
9415:   PetscUseTypeMethod(mat, getinertia, nneg, nzero, npos);
9416:   PetscFunctionReturn(PETSC_SUCCESS);
9417: }

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

9422:   Neighbor-wise Collective

9424:   Input Parameters:
9425: + mat - the factored matrix obtained with `MatGetFactor()`
9426: - b   - the right-hand-side vectors

9428:   Output Parameter:
9429: . x - the result vectors

9431:   Level: developer

9433:   Note:
9434:   The vectors `b` and `x` cannot be the same.  I.e., one cannot
9435:   call `MatSolves`(A,x,x).

9437: .seealso: [](ch_matrices), `Mat`, `Vecs`, `MatSolveAdd()`, `MatSolveTranspose()`, `MatSolveTransposeAdd()`, `MatSolve()`
9438: @*/
9439: PetscErrorCode MatSolves(Mat mat, Vecs b, Vecs x)
9440: {
9441:   PetscFunctionBegin;
9444:   PetscCheck(x != b, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_IDN, "x and b must be different vectors");
9445:   PetscCheck(mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Unfactored matrix");
9446:   if (!mat->rmap->N && !mat->cmap->N) PetscFunctionReturn(PETSC_SUCCESS);

9448:   MatCheckPreallocated(mat, 1);
9449:   PetscCall(PetscLogEventBegin(MAT_Solves, mat, 0, 0, 0));
9450:   PetscUseTypeMethod(mat, solves, b, x);
9451:   PetscCall(PetscLogEventEnd(MAT_Solves, mat, 0, 0, 0));
9452:   PetscFunctionReturn(PETSC_SUCCESS);
9453: }

9455: /*@
9456:   MatIsSymmetric - Test whether a matrix is symmetric

9458:   Collective

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

9464:   Output Parameter:
9465: . flg - the result

9467:   Level: intermediate

9469:   Notes:
9470:   For real numbers `MatIsSymmetric()` and `MatIsHermitian()` return identical results

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

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

9477: .seealso: [](ch_matrices), `Mat`, `MatTranspose()`, `MatIsTranspose()`, `MatIsHermitian()`, `MatIsStructurallySymmetric()`, `MatSetOption()`, `MatIsSymmetricKnown()`,
9478:           `MAT_SYMMETRIC`, `MAT_SYMMETRY_ETERNAL`
9479: @*/
9480: PetscErrorCode MatIsSymmetric(Mat A, PetscReal tol, PetscBool *flg)
9481: {
9482:   PetscFunctionBegin;
9484:   PetscAssertPointer(flg, 3);
9485:   if (A->symmetric != PETSC_BOOL3_UNKNOWN && !tol) *flg = PetscBool3ToBool(A->symmetric);
9486:   else {
9487:     if (A->ops->issymmetric) PetscUseTypeMethod(A, issymmetric, tol, flg);
9488:     else PetscCall(MatIsTranspose(A, A, tol, flg));
9489:     if (!tol) PetscCall(MatSetOption(A, MAT_SYMMETRIC, *flg));
9490:   }
9491:   PetscFunctionReturn(PETSC_SUCCESS);
9492: }

9494: /*@
9495:   MatIsHermitian - Test whether a matrix is Hermitian

9497:   Collective

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

9503:   Output Parameter:
9504: . flg - the result

9506:   Level: intermediate

9508:   Notes:
9509:   For real numbers `MatIsSymmetric()` and `MatIsHermitian()` return identical results

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

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

9516: .seealso: [](ch_matrices), `Mat`, `MatTranspose()`, `MatIsTranspose()`, `MatIsHermitianKnown()`, `MatIsStructurallySymmetric()`, `MatSetOption()`,
9517:           `MatIsSymmetricKnown()`, `MatIsSymmetric()`, `MAT_HERMITIAN`, `MAT_SYMMETRY_ETERNAL`
9518: @*/
9519: PetscErrorCode MatIsHermitian(Mat A, PetscReal tol, PetscBool *flg)
9520: {
9521:   PetscFunctionBegin;
9523:   PetscAssertPointer(flg, 3);
9524:   if (A->hermitian != PETSC_BOOL3_UNKNOWN && !tol) *flg = PetscBool3ToBool(A->hermitian);
9525:   else {
9526:     if (A->ops->ishermitian) PetscUseTypeMethod(A, ishermitian, tol, flg);
9527:     else PetscCall(MatIsHermitianTranspose(A, A, tol, flg));
9528:     if (!tol) PetscCall(MatSetOption(A, MAT_HERMITIAN, *flg));
9529:   }
9530:   PetscFunctionReturn(PETSC_SUCCESS);
9531: }

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

9536:   Not Collective

9538:   Input Parameter:
9539: . A - the matrix to check

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

9545:   Level: advanced

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

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

9554: .seealso: [](ch_matrices), `Mat`, `MAT_SYMMETRY_ETERNAL`, `MatTranspose()`, `MatIsTranspose()`, `MatIsHermitian()`, `MatIsStructurallySymmetric()`, `MatSetOption()`, `MatIsSymmetric()`, `MatIsHermitianKnown()`
9555: @*/
9556: PetscErrorCode MatIsSymmetricKnown(Mat A, PetscBool *set, PetscBool *flg)
9557: {
9558:   PetscFunctionBegin;
9560:   PetscAssertPointer(set, 2);
9561:   PetscAssertPointer(flg, 3);
9562:   if (A->symmetric != PETSC_BOOL3_UNKNOWN) {
9563:     *set = PETSC_TRUE;
9564:     *flg = PetscBool3ToBool(A->symmetric);
9565:   } else *set = PETSC_FALSE;
9566:   PetscFunctionReturn(PETSC_SUCCESS);
9567: }

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

9572:   Not Collective

9574:   Input Parameter:
9575: . A - the matrix to check

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

9581:   Level: advanced

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

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

9589: .seealso: [](ch_matrices), `Mat`, `MAT_SPD_ETERNAL`, `MAT_SPD`, `MatTranspose()`, `MatIsTranspose()`, `MatIsHermitian()`, `MatIsStructurallySymmetric()`, `MatSetOption()`, `MatIsSymmetric()`, `MatIsHermitianKnown()`
9590: @*/
9591: PetscErrorCode MatIsSPDKnown(Mat A, PetscBool *set, PetscBool *flg)
9592: {
9593:   PetscFunctionBegin;
9595:   PetscAssertPointer(set, 2);
9596:   PetscAssertPointer(flg, 3);
9597:   if (A->spd != PETSC_BOOL3_UNKNOWN) {
9598:     *set = PETSC_TRUE;
9599:     *flg = PetscBool3ToBool(A->spd);
9600:   } else *set = PETSC_FALSE;
9601:   PetscFunctionReturn(PETSC_SUCCESS);
9602: }

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

9607:   Not Collective

9609:   Input Parameter:
9610: . A - the matrix to check

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

9616:   Level: advanced

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

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

9625: .seealso: [](ch_matrices), `Mat`, `MAT_SYMMETRY_ETERNAL`, `MAT_HERMITIAN`, `MatTranspose()`, `MatIsTranspose()`, `MatIsHermitian()`, `MatIsStructurallySymmetric()`, `MatSetOption()`, `MatIsSymmetric()`
9626: @*/
9627: PetscErrorCode MatIsHermitianKnown(Mat A, PetscBool *set, PetscBool *flg)
9628: {
9629:   PetscFunctionBegin;
9631:   PetscAssertPointer(set, 2);
9632:   PetscAssertPointer(flg, 3);
9633:   if (A->hermitian != PETSC_BOOL3_UNKNOWN) {
9634:     *set = PETSC_TRUE;
9635:     *flg = PetscBool3ToBool(A->hermitian);
9636:   } else *set = PETSC_FALSE;
9637:   PetscFunctionReturn(PETSC_SUCCESS);
9638: }

9640: /*@
9641:   MatIsStructurallySymmetric - Test whether a matrix is structurally symmetric

9643:   Collective

9645:   Input Parameter:
9646: . A - the matrix to test

9648:   Output Parameter:
9649: . flg - the result

9651:   Level: intermediate

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

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

9659: .seealso: [](ch_matrices), `Mat`, `MAT_STRUCTURALLY_SYMMETRIC`, `MAT_STRUCTURAL_SYMMETRY_ETERNAL`, `MatTranspose()`, `MatIsTranspose()`, `MatIsHermitian()`, `MatIsSymmetric()`, `MatSetOption()`, `MatIsStructurallySymmetricKnown()`
9660: @*/
9661: PetscErrorCode MatIsStructurallySymmetric(Mat A, PetscBool *flg)
9662: {
9663:   PetscFunctionBegin;
9665:   PetscAssertPointer(flg, 2);
9666:   if (A->structurally_symmetric != PETSC_BOOL3_UNKNOWN) *flg = PetscBool3ToBool(A->structurally_symmetric);
9667:   else {
9668:     PetscUseTypeMethod(A, isstructurallysymmetric, flg);
9669:     PetscCall(MatSetOption(A, MAT_STRUCTURALLY_SYMMETRIC, *flg));
9670:   }
9671:   PetscFunctionReturn(PETSC_SUCCESS);
9672: }

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

9677:   Not Collective

9679:   Input Parameter:
9680: . A - the matrix to check

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

9686:   Level: advanced

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

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

9694: .seealso: [](ch_matrices), `Mat`, `MAT_STRUCTURALLY_SYMMETRIC`, `MatTranspose()`, `MatIsTranspose()`, `MatIsHermitian()`, `MatIsStructurallySymmetric()`, `MatSetOption()`, `MatIsSymmetric()`, `MatIsHermitianKnown()`
9695: @*/
9696: PetscErrorCode MatIsStructurallySymmetricKnown(Mat A, PetscBool *set, PetscBool *flg)
9697: {
9698:   PetscFunctionBegin;
9700:   PetscAssertPointer(set, 2);
9701:   PetscAssertPointer(flg, 3);
9702:   if (A->structurally_symmetric != PETSC_BOOL3_UNKNOWN) {
9703:     *set = PETSC_TRUE;
9704:     *flg = PetscBool3ToBool(A->structurally_symmetric);
9705:   } else *set = PETSC_FALSE;
9706:   PetscFunctionReturn(PETSC_SUCCESS);
9707: }

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

9713:   Not Collective

9715:   Input Parameter:
9716: . mat - the matrix

9718:   Output Parameters:
9719: + nstash    - the size of the stash
9720: . reallocs  - the number of additional mallocs incurred.
9721: . bnstash   - the size of the block stash
9722: - breallocs - the number of additional mallocs incurred.in the block stash

9724:   Level: advanced

9726: .seealso: [](ch_matrices), `MatAssemblyBegin()`, `MatAssemblyEnd()`, `Mat`, `MatStashSetInitialSize()`
9727: @*/
9728: PetscErrorCode MatStashGetInfo(Mat mat, PetscInt *nstash, PetscInt *reallocs, PetscInt *bnstash, PetscInt *breallocs)
9729: {
9730:   PetscFunctionBegin;
9731:   PetscCall(MatStashGetInfo_Private(&mat->stash, nstash, reallocs));
9732:   PetscCall(MatStashGetInfo_Private(&mat->bstash, bnstash, breallocs));
9733:   PetscFunctionReturn(PETSC_SUCCESS);
9734: }

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

9740:   Collective

9742:   Input Parameter:
9743: . mat - the matrix

9745:   Output Parameters:
9746: + right - (optional) vector that the matrix can be multiplied against
9747: - left  - (optional) vector that the matrix vector product can be stored in

9749:   Level: advanced

9751:   Notes:
9752:   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()`.

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

9756: .seealso: [](ch_matrices), `Mat`, `Vec`, `VecCreate()`, `VecDestroy()`, `DMCreateGlobalVector()`
9757: @*/
9758: PetscErrorCode MatCreateVecs(Mat mat, Vec *right, Vec *left)
9759: {
9760:   PetscFunctionBegin;
9763:   if (mat->ops->getvecs) {
9764:     PetscUseTypeMethod(mat, getvecs, right, left);
9765:   } else {
9766:     if (right) {
9767:       PetscCheck(mat->cmap->n >= 0, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "PetscLayout for columns not yet setup");
9768:       PetscCall(VecCreateWithLayout_Private(mat->cmap, right));
9769:       PetscCall(VecSetType(*right, mat->defaultvectype));
9770: #if defined(PETSC_HAVE_VIENNACL) || defined(PETSC_HAVE_CUDA) || defined(PETSC_HAVE_HIP)
9771:       if (mat->boundtocpu && mat->bindingpropagates) {
9772:         PetscCall(VecSetBindingPropagates(*right, PETSC_TRUE));
9773:         PetscCall(VecBindToCPU(*right, PETSC_TRUE));
9774:       }
9775: #endif
9776:     }
9777:     if (left) {
9778:       PetscCheck(mat->rmap->n >= 0, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "PetscLayout for rows not yet setup");
9779:       PetscCall(VecCreateWithLayout_Private(mat->rmap, left));
9780:       PetscCall(VecSetType(*left, mat->defaultvectype));
9781: #if defined(PETSC_HAVE_VIENNACL) || defined(PETSC_HAVE_CUDA) || defined(PETSC_HAVE_HIP)
9782:       if (mat->boundtocpu && mat->bindingpropagates) {
9783:         PetscCall(VecSetBindingPropagates(*left, PETSC_TRUE));
9784:         PetscCall(VecBindToCPU(*left, PETSC_TRUE));
9785:       }
9786: #endif
9787:     }
9788:   }
9789:   PetscFunctionReturn(PETSC_SUCCESS);
9790: }

9792: /*@
9793:   MatFactorInfoInitialize - Initializes a `MatFactorInfo` data structure
9794:   with default values.

9796:   Not Collective

9798:   Input Parameter:
9799: . info - the `MatFactorInfo` data structure

9801:   Level: developer

9803:   Notes:
9804:   The solvers are generally used through the `KSP` and `PC` objects, for example
9805:   `PCLU`, `PCILU`, `PCCHOLESKY`, `PCICC`

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

9809: .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatFactorInfo`
9810: @*/
9811: PetscErrorCode MatFactorInfoInitialize(MatFactorInfo *info)
9812: {
9813:   PetscFunctionBegin;
9814:   PetscCall(PetscMemzero(info, sizeof(MatFactorInfo)));
9815:   PetscFunctionReturn(PETSC_SUCCESS);
9816: }

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

9821:   Collective

9823:   Input Parameters:
9824: + mat - the factored matrix
9825: - is  - the index set defining the Schur indices (0-based)

9827:   Level: advanced

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

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

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

9836: .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatFactorGetSchurComplement()`, `MatFactorRestoreSchurComplement()`, `MatFactorCreateSchurComplement()`, `MatFactorSolveSchurComplement()`,
9837:           `MatFactorSolveSchurComplementTranspose()`, `MATSOLVERMUMPS`, `MATSOLVERMKL_PARDISO`
9838: @*/
9839: PetscErrorCode MatFactorSetSchurIS(Mat mat, IS is)
9840: {
9841:   PetscErrorCode (*f)(Mat, IS);

9843:   PetscFunctionBegin;
9848:   PetscCheckSameComm(mat, 1, is, 2);
9849:   PetscCheck(mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Only for factored matrix");
9850:   PetscCall(PetscObjectQueryFunction((PetscObject)mat, "MatFactorSetSchurIS_C", &f));
9851:   PetscCheck(f, PetscObjectComm((PetscObject)mat), PETSC_ERR_SUP, "The selected MatSolverType does not support Schur complement computation. You should use MATSOLVERMUMPS or MATSOLVERMKL_PARDISO");
9852:   PetscCall(MatDestroy(&mat->schur));
9853:   PetscCall((*f)(mat, is));
9854:   PetscCheck(mat->schur, PetscObjectComm((PetscObject)mat), PETSC_ERR_PLIB, "Schur complement has not been created");
9855:   PetscFunctionReturn(PETSC_SUCCESS);
9856: }

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

9861:   Logically Collective

9863:   Input Parameters:
9864: + F      - the factored matrix obtained by calling `MatGetFactor()`
9865: . S      - location where to return the Schur complement, can be `NULL`
9866: - status - the status of the Schur complement matrix, can be `NULL`

9868:   Level: advanced

9870:   Notes:
9871:   You must call `MatFactorSetSchurIS()` before calling this routine.

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

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

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

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

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

9887: .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatFactorSetSchurIS()`, `MatFactorGetSchurComplement()`, `MatFactorSchurStatus`, `MATSOLVERMUMPS`, `MATSOLVERMKL_PARDISO`
9888: @*/
9889: PetscErrorCode MatFactorCreateSchurComplement(Mat F, Mat *S, MatFactorSchurStatus *status)
9890: {
9891:   PetscFunctionBegin;
9893:   if (S) PetscAssertPointer(S, 2);
9894:   if (status) PetscAssertPointer(status, 3);
9895:   if (S) {
9896:     PetscErrorCode (*f)(Mat, Mat *);

9898:     PetscCall(PetscObjectQueryFunction((PetscObject)F, "MatFactorCreateSchurComplement_C", &f));
9899:     if (f) PetscCall((*f)(F, S));
9900:     else PetscCall(MatDuplicate(F->schur, MAT_COPY_VALUES, S));
9901:   }
9902:   if (status) *status = F->schur_status;
9903:   PetscFunctionReturn(PETSC_SUCCESS);
9904: }

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

9909:   Logically Collective

9911:   Input Parameters:
9912: + F      - the factored matrix obtained by calling `MatGetFactor()`
9913: . S      - location where to return the Schur complement, can be `NULL`
9914: - status - the status of the Schur complement matrix, can be `NULL`

9916:   Level: advanced

9918:   Notes:
9919:   You must call `MatFactorSetSchurIS()` before calling this routine.

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

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

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

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

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

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

9933: .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatFactorSetSchurIS()`, `MatFactorRestoreSchurComplement()`, `MatFactorCreateSchurComplement()`, `MatFactorSchurStatus`
9934: @*/
9935: PetscErrorCode MatFactorGetSchurComplement(Mat F, Mat *S, MatFactorSchurStatus *status)
9936: {
9937:   PetscFunctionBegin;
9939:   if (S) {
9940:     PetscAssertPointer(S, 2);
9941:     *S = F->schur;
9942:   }
9943:   if (status) {
9944:     PetscAssertPointer(status, 3);
9945:     *status = F->schur_status;
9946:   }
9947:   PetscFunctionReturn(PETSC_SUCCESS);
9948: }

9950: static PetscErrorCode MatFactorUpdateSchurStatus_Private(Mat F)
9951: {
9952:   Mat S = F->schur;

9954:   PetscFunctionBegin;
9955:   switch (F->schur_status) {
9956:   case MAT_FACTOR_SCHUR_UNFACTORED: // fall-through
9957:   case MAT_FACTOR_SCHUR_INVERTED:
9958:     if (S) {
9959:       S->ops->solve             = NULL;
9960:       S->ops->matsolve          = NULL;
9961:       S->ops->solvetranspose    = NULL;
9962:       S->ops->matsolvetranspose = NULL;
9963:       S->ops->solveadd          = NULL;
9964:       S->ops->solvetransposeadd = NULL;
9965:       S->factortype             = MAT_FACTOR_NONE;
9966:       PetscCall(PetscFree(S->solvertype));
9967:     }
9968:   case MAT_FACTOR_SCHUR_FACTORED: // fall-through
9969:     break;
9970:   default:
9971:     SETERRQ(PetscObjectComm((PetscObject)F), PETSC_ERR_SUP, "Unhandled MatFactorSchurStatus %d", F->schur_status);
9972:   }
9973:   PetscFunctionReturn(PETSC_SUCCESS);
9974: }

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

9979:   Logically Collective

9981:   Input Parameters:
9982: + F      - the factored matrix obtained by calling `MatGetFactor()`
9983: . S      - location where the Schur complement is stored
9984: - status - the status of the Schur complement matrix (see `MatFactorSchurStatus`)

9986:   Level: advanced

9988: .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatFactorSetSchurIS()`, `MatFactorCreateSchurComplement()`, `MatFactorSchurStatus`
9989: @*/
9990: PetscErrorCode MatFactorRestoreSchurComplement(Mat F, Mat *S, MatFactorSchurStatus status)
9991: {
9992:   PetscFunctionBegin;
9994:   if (S) {
9996:     *S = NULL;
9997:   }
9998:   F->schur_status = status;
9999:   PetscCall(MatFactorUpdateSchurStatus_Private(F));
10000:   PetscFunctionReturn(PETSC_SUCCESS);
10001: }

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

10006:   Logically Collective

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

10013:   Level: advanced

10015:   Notes:
10016:   The sizes of the vectors should match the size of the Schur complement

10018:   Must be called after `MatFactorSetSchurIS()`

10020: .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatFactorSetSchurIS()`, `MatFactorSolveSchurComplement()`
10021: @*/
10022: PetscErrorCode MatFactorSolveSchurComplementTranspose(Mat F, Vec rhs, Vec sol)
10023: {
10024:   PetscFunctionBegin;
10031:   PetscCheckSameComm(F, 1, rhs, 2);
10032:   PetscCheckSameComm(F, 1, sol, 3);
10033:   PetscCall(MatFactorFactorizeSchurComplement(F));
10034:   switch (F->schur_status) {
10035:   case MAT_FACTOR_SCHUR_FACTORED:
10036:     PetscCall(MatSolveTranspose(F->schur, rhs, sol));
10037:     break;
10038:   case MAT_FACTOR_SCHUR_INVERTED:
10039:     PetscCall(MatMultTranspose(F->schur, rhs, sol));
10040:     break;
10041:   default:
10042:     SETERRQ(PetscObjectComm((PetscObject)F), PETSC_ERR_SUP, "Unhandled MatFactorSchurStatus %d", F->schur_status);
10043:   }
10044:   PetscFunctionReturn(PETSC_SUCCESS);
10045: }

10047: /*@
10048:   MatFactorSolveSchurComplement - Solve the Schur complement system computed during the factorization step

10050:   Logically Collective

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

10057:   Level: advanced

10059:   Notes:
10060:   The sizes of the vectors should match the size of the Schur complement

10062:   Must be called after `MatFactorSetSchurIS()`

10064: .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatFactorSetSchurIS()`, `MatFactorSolveSchurComplementTranspose()`
10065: @*/
10066: PetscErrorCode MatFactorSolveSchurComplement(Mat F, Vec rhs, Vec sol)
10067: {
10068:   PetscFunctionBegin;
10075:   PetscCheckSameComm(F, 1, rhs, 2);
10076:   PetscCheckSameComm(F, 1, sol, 3);
10077:   PetscCall(MatFactorFactorizeSchurComplement(F));
10078:   switch (F->schur_status) {
10079:   case MAT_FACTOR_SCHUR_FACTORED:
10080:     PetscCall(MatSolve(F->schur, rhs, sol));
10081:     break;
10082:   case MAT_FACTOR_SCHUR_INVERTED:
10083:     PetscCall(MatMult(F->schur, rhs, sol));
10084:     break;
10085:   default:
10086:     SETERRQ(PetscObjectComm((PetscObject)F), PETSC_ERR_SUP, "Unhandled MatFactorSchurStatus %d", F->schur_status);
10087:   }
10088:   PetscFunctionReturn(PETSC_SUCCESS);
10089: }

10091: PETSC_SINGLE_LIBRARY_INTERN PetscErrorCode MatSeqDenseInvertFactors_Private(Mat);
10092: #if PetscDefined(HAVE_CUDA)
10093: PETSC_SINGLE_LIBRARY_INTERN PetscErrorCode MatSeqDenseCUDAInvertFactors_Internal(Mat);
10094: #endif

10096: /* Schur status updated in the interface */
10097: static PetscErrorCode MatFactorInvertSchurComplement_Private(Mat F)
10098: {
10099:   Mat S = F->schur;

10101:   PetscFunctionBegin;
10102:   if (S) {
10103:     PetscMPIInt size;
10104:     PetscBool   isdense, isdensecuda;

10106:     PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)S), &size));
10107:     PetscCheck(size <= 1, PetscObjectComm((PetscObject)S), PETSC_ERR_SUP, "Not yet implemented");
10108:     PetscCall(PetscObjectTypeCompare((PetscObject)S, MATSEQDENSE, &isdense));
10109:     PetscCall(PetscObjectTypeCompare((PetscObject)S, MATSEQDENSECUDA, &isdensecuda));
10110:     PetscCheck(isdense || isdensecuda, PetscObjectComm((PetscObject)S), PETSC_ERR_SUP, "Not implemented for type %s", ((PetscObject)S)->type_name);
10111:     PetscCall(PetscLogEventBegin(MAT_FactorInvS, F, 0, 0, 0));
10112:     if (isdense) {
10113:       PetscCall(MatSeqDenseInvertFactors_Private(S));
10114:     } else if (isdensecuda) {
10115: #if defined(PETSC_HAVE_CUDA)
10116:       PetscCall(MatSeqDenseCUDAInvertFactors_Internal(S));
10117: #endif
10118:     }
10119:     // HIP??????????????
10120:     PetscCall(PetscLogEventEnd(MAT_FactorInvS, F, 0, 0, 0));
10121:   }
10122:   PetscFunctionReturn(PETSC_SUCCESS);
10123: }

10125: /*@
10126:   MatFactorInvertSchurComplement - Invert the Schur complement matrix computed during the factorization step

10128:   Logically Collective

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

10133:   Level: advanced

10135:   Notes:
10136:   Must be called after `MatFactorSetSchurIS()`.

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

10140: .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatFactorSetSchurIS()`, `MatFactorGetSchurComplement()`, `MatFactorCreateSchurComplement()`
10141: @*/
10142: PetscErrorCode MatFactorInvertSchurComplement(Mat F)
10143: {
10144:   PetscFunctionBegin;
10147:   if (F->schur_status == MAT_FACTOR_SCHUR_INVERTED) PetscFunctionReturn(PETSC_SUCCESS);
10148:   PetscCall(MatFactorFactorizeSchurComplement(F));
10149:   PetscCall(MatFactorInvertSchurComplement_Private(F));
10150:   F->schur_status = MAT_FACTOR_SCHUR_INVERTED;
10151:   PetscFunctionReturn(PETSC_SUCCESS);
10152: }

10154: /*@
10155:   MatFactorFactorizeSchurComplement - Factorize the Schur complement matrix computed during the factorization step

10157:   Logically Collective

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

10162:   Level: advanced

10164:   Note:
10165:   Must be called after `MatFactorSetSchurIS()`

10167: .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatFactorSetSchurIS()`, `MatFactorInvertSchurComplement()`
10168: @*/
10169: PetscErrorCode MatFactorFactorizeSchurComplement(Mat F)
10170: {
10171:   MatFactorInfo info;

10173:   PetscFunctionBegin;
10176:   if (F->schur_status == MAT_FACTOR_SCHUR_INVERTED || F->schur_status == MAT_FACTOR_SCHUR_FACTORED) PetscFunctionReturn(PETSC_SUCCESS);
10177:   PetscCall(PetscLogEventBegin(MAT_FactorFactS, F, 0, 0, 0));
10178:   PetscCall(PetscMemzero(&info, sizeof(MatFactorInfo)));
10179:   if (F->factortype == MAT_FACTOR_CHOLESKY) { /* LDL^t regarded as Cholesky */
10180:     PetscCall(MatCholeskyFactor(F->schur, NULL, &info));
10181:   } else {
10182:     PetscCall(MatLUFactor(F->schur, NULL, NULL, &info));
10183:   }
10184:   PetscCall(PetscLogEventEnd(MAT_FactorFactS, F, 0, 0, 0));
10185:   F->schur_status = MAT_FACTOR_SCHUR_FACTORED;
10186:   PetscFunctionReturn(PETSC_SUCCESS);
10187: }

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

10192:   Neighbor-wise Collective

10194:   Input Parameters:
10195: + A     - the matrix
10196: . P     - the projection matrix
10197: . scall - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`
10198: - 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
10199:           if the result is a dense matrix this is irrelevant

10201:   Output Parameter:
10202: . C - the product matrix

10204:   Level: intermediate

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

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

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

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

10217: .seealso: [](ch_matrices), `Mat`, `MatProductCreate()`, `MatMatMult()`, `MatRARt()`
10218: @*/
10219: PetscErrorCode MatPtAP(Mat A, Mat P, MatReuse scall, PetscReal fill, Mat *C)
10220: {
10221:   PetscFunctionBegin;
10222:   if (scall == MAT_REUSE_MATRIX) MatCheckProduct(*C, 5);
10223:   PetscCheck(scall != MAT_INPLACE_MATRIX, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "Inplace product not supported");

10225:   if (scall == MAT_INITIAL_MATRIX) {
10226:     PetscCall(MatProductCreate(A, P, NULL, C));
10227:     PetscCall(MatProductSetType(*C, MATPRODUCT_PtAP));
10228:     PetscCall(MatProductSetAlgorithm(*C, "default"));
10229:     PetscCall(MatProductSetFill(*C, fill));

10231:     (*C)->product->api_user = PETSC_TRUE;
10232:     PetscCall(MatProductSetFromOptions(*C));
10233:     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);
10234:     PetscCall(MatProductSymbolic(*C));
10235:   } else { /* scall == MAT_REUSE_MATRIX */
10236:     PetscCall(MatProductReplaceMats(A, P, NULL, *C));
10237:   }

10239:   PetscCall(MatProductNumeric(*C));
10240:   if (A->symmetric == PETSC_BOOL3_TRUE) {
10241:     PetscCall(MatSetOption(*C, MAT_SYMMETRIC, PETSC_TRUE));
10242:     (*C)->spd = A->spd;
10243:   }
10244:   PetscFunctionReturn(PETSC_SUCCESS);
10245: }

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

10250:   Neighbor-wise Collective

10252:   Input Parameters:
10253: + A     - the matrix
10254: . R     - the projection matrix
10255: . scall - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`
10256: - fill  - expected fill as ratio of nnz(C)/nnz(A), use `PETSC_DETERMINE` or `PETSC_CURRENT` if you do not have a good estimate
10257:           if the result is a dense matrix this is irrelevant

10259:   Output Parameter:
10260: . C - the product matrix

10262:   Level: intermediate

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

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

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

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

10277: .seealso: [](ch_matrices), `Mat`, `MatProductCreate()`, `MatMatMult()`, `MatPtAP()`
10278: @*/
10279: PetscErrorCode MatRARt(Mat A, Mat R, MatReuse scall, PetscReal fill, Mat *C)
10280: {
10281:   PetscFunctionBegin;
10282:   if (scall == MAT_REUSE_MATRIX) MatCheckProduct(*C, 5);
10283:   PetscCheck(scall != MAT_INPLACE_MATRIX, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "Inplace product not supported");

10285:   if (scall == MAT_INITIAL_MATRIX) {
10286:     PetscCall(MatProductCreate(A, R, NULL, C));
10287:     PetscCall(MatProductSetType(*C, MATPRODUCT_RARt));
10288:     PetscCall(MatProductSetAlgorithm(*C, "default"));
10289:     PetscCall(MatProductSetFill(*C, fill));

10291:     (*C)->product->api_user = PETSC_TRUE;
10292:     PetscCall(MatProductSetFromOptions(*C));
10293:     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);
10294:     PetscCall(MatProductSymbolic(*C));
10295:   } else { /* scall == MAT_REUSE_MATRIX */
10296:     PetscCall(MatProductReplaceMats(A, R, NULL, *C));
10297:   }

10299:   PetscCall(MatProductNumeric(*C));
10300:   if (A->symmetric == PETSC_BOOL3_TRUE) PetscCall(MatSetOption(*C, MAT_SYMMETRIC, PETSC_TRUE));
10301:   PetscFunctionReturn(PETSC_SUCCESS);
10302: }

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

10308:   PetscFunctionBegin;
10309:   PetscCheck(scall != MAT_INPLACE_MATRIX, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "MAT_INPLACE_MATRIX product not supported");
10310:   if (scall == MAT_INITIAL_MATRIX) {
10311:     PetscCall(PetscInfo(A, "Calling MatProduct API with MAT_INITIAL_MATRIX and product type %s\n", MatProductTypes[ptype]));
10312:     PetscCall(MatProductCreate(A, B, NULL, C));
10313:     PetscCall(MatProductSetAlgorithm(*C, MATPRODUCTALGORITHMDEFAULT));
10314:     PetscCall(MatProductSetFill(*C, fill));
10315:   } else { /* scall == MAT_REUSE_MATRIX */
10316:     Mat_Product *product = (*C)->product;

10318:     PetscCall(PetscObjectBaseTypeCompareAny((PetscObject)*C, &flg, MATSEQDENSE, MATMPIDENSE, ""));
10319:     if (flg && product && product->type != ptype) {
10320:       PetscCall(MatProductClear(*C));
10321:       product = NULL;
10322:     }
10323:     PetscCall(PetscInfo(A, "Calling MatProduct API with MAT_REUSE_MATRIX %s product present and product type %s\n", product ? "with" : "without", MatProductTypes[ptype]));
10324:     if (!product) { /* user provide the dense matrix *C without calling MatProductCreate() or reusing it from previous calls */
10325:       PetscCheck(flg, PetscObjectComm((PetscObject)*C), PETSC_ERR_SUP, "Call MatProductCreate() first");
10326:       PetscCall(MatProductCreate_Private(A, B, NULL, *C));
10327:       product        = (*C)->product;
10328:       product->fill  = fill;
10329:       product->clear = PETSC_TRUE;
10330:     } else { /* user may change input matrices A or B when MAT_REUSE_MATRIX */
10331:       flg = PETSC_FALSE;
10332:       PetscCall(MatProductReplaceMats(A, B, NULL, *C));
10333:     }
10334:   }
10335:   if (flg) {
10336:     (*C)->product->api_user = PETSC_TRUE;
10337:     PetscCall(MatProductSetType(*C, ptype));
10338:     PetscCall(MatProductSetFromOptions(*C));
10339:     PetscCall(MatProductSymbolic(*C));
10340:   }
10341:   PetscCall(MatProductNumeric(*C));
10342:   PetscFunctionReturn(PETSC_SUCCESS);
10343: }

10345: /*@
10346:   MatMatMult - Performs matrix-matrix multiplication $ C=A*B $.

10348:   Neighbor-wise Collective

10350:   Input Parameters:
10351: + A     - the left matrix
10352: . B     - the right matrix
10353: . scall - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`
10354: - 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
10355:           if the result is a dense matrix this is irrelevant

10357:   Output Parameter:
10358: . C - the product matrix

10360:   Notes:
10361:   Unless scall is `MAT_REUSE_MATRIX` C will be created.

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

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

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

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

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

10376:   Example of Usage:
10377: .vb
10378:      MatProductCreate(A,B,NULL,&C);
10379:      MatProductSetType(C,MATPRODUCT_AB);
10380:      MatProductSymbolic(C);
10381:      MatProductNumeric(C); // compute C=A * B
10382:      MatProductReplaceMats(A1,B1,NULL,C); // compute C=A1 * B1
10383:      MatProductNumeric(C);
10384:      MatProductReplaceMats(A2,NULL,NULL,C); // compute C=A2 * B1
10385:      MatProductNumeric(C);
10386: .ve

10388:   Level: intermediate

10390: .seealso: [](ch_matrices), `Mat`, `MatProductType`, `MATPRODUCT_AB`, `MatTransposeMatMult()`, `MatMatTransposeMult()`, `MatPtAP()`, `MatProductCreate()`, `MatProductSymbolic()`, `MatProductReplaceMats()`, `MatProductNumeric()`
10391: @*/
10392: PetscErrorCode MatMatMult(Mat A, Mat B, MatReuse scall, PetscReal fill, Mat *C)
10393: {
10394:   PetscFunctionBegin;
10395:   PetscCall(MatProduct_Private(A, B, scall, fill, MATPRODUCT_AB, C));
10396:   PetscFunctionReturn(PETSC_SUCCESS);
10397: }

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

10402:   Neighbor-wise Collective

10404:   Input Parameters:
10405: + A     - the left matrix
10406: . B     - the right matrix
10407: . scall - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`
10408: - fill  - expected fill as ratio of nnz(C)/(nnz(A) + nnz(B)), use `PETSC_DETERMINE` or `PETSC_CURRENT` if not known

10410:   Output Parameter:
10411: . C - the product matrix

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

10418:   Level: intermediate

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

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

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

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

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

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

10436: .seealso: [](ch_matrices), `Mat`, `MatProductCreate()`, `MATPRODUCT_ABt`, `MatMatMult()`, `MatTransposeMatMult()`, `MatPtAP()`, `MatProductAlgorithm`, `MatProductType`
10437: @*/
10438: PetscErrorCode MatMatTransposeMult(Mat A, Mat B, MatReuse scall, PetscReal fill, Mat *C)
10439: {
10440:   PetscFunctionBegin;
10441:   PetscCall(MatProduct_Private(A, B, scall, fill, MATPRODUCT_ABt, C));
10442:   if (A == B) PetscCall(MatSetOption(*C, MAT_SYMMETRIC, PETSC_TRUE));
10443:   PetscFunctionReturn(PETSC_SUCCESS);
10444: }

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

10449:   Neighbor-wise Collective

10451:   Input Parameters:
10452: + A     - the left matrix
10453: . B     - the right matrix
10454: . scall - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`
10455: - fill  - expected fill as ratio of nnz(C)/(nnz(A) + nnz(B)), use `PETSC_DETERMINE` or `PETSC_CURRENT` if not known

10457:   Output Parameter:
10458: . C - the product matrix

10460:   Level: intermediate

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

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

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

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

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

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

10478: .seealso: [](ch_matrices), `Mat`, `MatProductCreate()`, `MATPRODUCT_AtB`, `MatMatMult()`, `MatMatTransposeMult()`, `MatPtAP()`
10479: @*/
10480: PetscErrorCode MatTransposeMatMult(Mat A, Mat B, MatReuse scall, PetscReal fill, Mat *C)
10481: {
10482:   PetscFunctionBegin;
10483:   PetscCall(MatProduct_Private(A, B, scall, fill, MATPRODUCT_AtB, C));
10484:   PetscFunctionReturn(PETSC_SUCCESS);
10485: }

10487: /*@
10488:   MatMatMatMult - Performs matrix-matrix-matrix multiplication D=A*B*C.

10490:   Neighbor-wise Collective

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

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

10503:   Level: intermediate

10505:   Notes:
10506:   Unless `scall` is `MAT_REUSE_MATRIX` `D` will be created.

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

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

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

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

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

10521: .seealso: [](ch_matrices), `Mat`, `MatProductCreate()`, `MATPRODUCT_ABC`, `MatMatMult`, `MatPtAP()`, `MatMatTransposeMult()`, `MatTransposeMatMult()`
10522: @*/
10523: PetscErrorCode MatMatMatMult(Mat A, Mat B, Mat C, MatReuse scall, PetscReal fill, Mat *D)
10524: {
10525:   PetscFunctionBegin;
10526:   if (scall == MAT_REUSE_MATRIX) MatCheckProduct(*D, 6);
10527:   PetscCheck(scall != MAT_INPLACE_MATRIX, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "Inplace product not supported");

10529:   if (scall == MAT_INITIAL_MATRIX) {
10530:     PetscCall(MatProductCreate(A, B, C, D));
10531:     PetscCall(MatProductSetType(*D, MATPRODUCT_ABC));
10532:     PetscCall(MatProductSetAlgorithm(*D, "default"));
10533:     PetscCall(MatProductSetFill(*D, fill));

10535:     (*D)->product->api_user = PETSC_TRUE;
10536:     PetscCall(MatProductSetFromOptions(*D));
10537:     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,
10538:                ((PetscObject)C)->type_name);
10539:     PetscCall(MatProductSymbolic(*D));
10540:   } else { /* user may change input matrices when REUSE */
10541:     PetscCall(MatProductReplaceMats(A, B, C, *D));
10542:   }
10543:   PetscCall(MatProductNumeric(*D));
10544:   PetscFunctionReturn(PETSC_SUCCESS);
10545: }

10547: /*@
10548:   MatCreateRedundantMatrix - Create redundant matrices and put them into processors of subcommunicators.

10550:   Collective

10552:   Input Parameters:
10553: + mat      - the matrix
10554: . nsubcomm - the number of subcommunicators (= number of redundant parallel or sequential matrices)
10555: . subcomm  - MPI communicator split from the communicator where mat resides in (or `MPI_COMM_NULL` if nsubcomm is used)
10556: - reuse    - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`

10558:   Output Parameter:
10559: . matredundant - redundant matrix

10561:   Level: advanced

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

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

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

10572: .seealso: [](ch_matrices), `Mat`, `MatDestroy()`, `PetscSubcommCreate()`, `PetscSubcomm`
10573: @*/
10574: PetscErrorCode MatCreateRedundantMatrix(Mat mat, PetscInt nsubcomm, MPI_Comm subcomm, MatReuse reuse, Mat *matredundant)
10575: {
10576:   MPI_Comm       comm;
10577:   PetscMPIInt    size;
10578:   PetscInt       mloc_sub, nloc_sub, rstart, rend, M = mat->rmap->N, N = mat->cmap->N, bs = mat->rmap->bs;
10579:   Mat_Redundant *redund     = NULL;
10580:   PetscSubcomm   psubcomm   = NULL;
10581:   MPI_Comm       subcomm_in = subcomm;
10582:   Mat           *matseq;
10583:   IS             isrow, iscol;
10584:   PetscBool      newsubcomm = PETSC_FALSE;

10586:   PetscFunctionBegin;
10588:   if (nsubcomm && reuse == MAT_REUSE_MATRIX) {
10589:     PetscAssertPointer(*matredundant, 5);
10591:   }

10593:   PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)mat), &size));
10594:   if (size == 1 || nsubcomm == 1) {
10595:     if (reuse == MAT_INITIAL_MATRIX) {
10596:       PetscCall(MatDuplicate(mat, MAT_COPY_VALUES, matredundant));
10597:     } else {
10598:       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");
10599:       PetscCall(MatCopy(mat, *matredundant, SAME_NONZERO_PATTERN));
10600:     }
10601:     PetscFunctionReturn(PETSC_SUCCESS);
10602:   }

10604:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
10605:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
10606:   MatCheckPreallocated(mat, 1);

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

10615:     PetscCall(PetscSubcommCreate(comm, &psubcomm));
10616:     PetscCall(PetscSubcommSetNumber(psubcomm, nsubcomm));
10617:     PetscCall(PetscSubcommSetType(psubcomm, PETSC_SUBCOMM_CONTIGUOUS));
10618:     PetscCall(PetscSubcommSetFromOptions(psubcomm));
10619:     PetscCall(PetscCommDuplicate(PetscSubcommChild(psubcomm), &subcomm, NULL));
10620:     newsubcomm = PETSC_TRUE;
10621:     PetscCall(PetscSubcommDestroy(&psubcomm));
10622:   }

10624:   /* get isrow, iscol and a local sequential matrix matseq[0] */
10625:   if (reuse == MAT_INITIAL_MATRIX) {
10626:     mloc_sub = PETSC_DECIDE;
10627:     nloc_sub = PETSC_DECIDE;
10628:     if (bs < 1) {
10629:       PetscCall(PetscSplitOwnership(subcomm, &mloc_sub, &M));
10630:       PetscCall(PetscSplitOwnership(subcomm, &nloc_sub, &N));
10631:     } else {
10632:       PetscCall(PetscSplitOwnershipBlock(subcomm, bs, &mloc_sub, &M));
10633:       PetscCall(PetscSplitOwnershipBlock(subcomm, bs, &nloc_sub, &N));
10634:     }
10635:     PetscCallMPI(MPI_Scan(&mloc_sub, &rend, 1, MPIU_INT, MPI_SUM, subcomm));
10636:     rstart = rend - mloc_sub;
10637:     PetscCall(ISCreateStride(PETSC_COMM_SELF, mloc_sub, rstart, 1, &isrow));
10638:     PetscCall(ISCreateStride(PETSC_COMM_SELF, N, 0, 1, &iscol));
10639:     PetscCall(ISSetIdentity(iscol));
10640:   } else { /* reuse == MAT_REUSE_MATRIX */
10641:     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");
10642:     /* retrieve subcomm */
10643:     PetscCall(PetscObjectGetComm((PetscObject)*matredundant, &subcomm));
10644:     redund = (*matredundant)->redundant;
10645:     isrow  = redund->isrow;
10646:     iscol  = redund->iscol;
10647:     matseq = redund->matseq;
10648:   }
10649:   PetscCall(MatCreateSubMatrices(mat, 1, &isrow, &iscol, reuse, &matseq));

10651:   /* get matredundant over subcomm */
10652:   if (reuse == MAT_INITIAL_MATRIX) {
10653:     PetscCall(MatCreateMPIMatConcatenateSeqMat(subcomm, matseq[0], nloc_sub, reuse, matredundant));

10655:     /* create a supporting struct and attach it to C for reuse */
10656:     PetscCall(PetscNew(&redund));
10657:     (*matredundant)->redundant = redund;
10658:     redund->isrow              = isrow;
10659:     redund->iscol              = iscol;
10660:     redund->matseq             = matseq;
10661:     if (newsubcomm) {
10662:       redund->subcomm = subcomm;
10663:     } else {
10664:       redund->subcomm = MPI_COMM_NULL;
10665:     }
10666:   } else {
10667:     PetscCall(MatCreateMPIMatConcatenateSeqMat(subcomm, matseq[0], PETSC_DECIDE, reuse, matredundant));
10668:   }
10669: #if defined(PETSC_HAVE_VIENNACL) || defined(PETSC_HAVE_CUDA) || defined(PETSC_HAVE_HIP)
10670:   if (matseq[0]->boundtocpu && matseq[0]->bindingpropagates) {
10671:     PetscCall(MatBindToCPU(*matredundant, PETSC_TRUE));
10672:     PetscCall(MatSetBindingPropagates(*matredundant, PETSC_TRUE));
10673:   }
10674: #endif
10675:   PetscCall(PetscLogEventEnd(MAT_RedundantMat, mat, 0, 0, 0));
10676:   PetscFunctionReturn(PETSC_SUCCESS);
10677: }

10679: /*@C
10680:   MatGetMultiProcBlock - Create multiple 'parallel submatrices' from
10681:   a given `Mat`. Each submatrix can span multiple procs.

10683:   Collective

10685:   Input Parameters:
10686: + mat     - the matrix
10687: . subComm - the sub communicator obtained as if by `MPI_Comm_split(PetscObjectComm((PetscObject)mat))`
10688: - scall   - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`

10690:   Output Parameter:
10691: . subMat - parallel sub-matrices each spanning a given `subcomm`

10693:   Level: advanced

10695:   Notes:
10696:   The submatrix partition across processors is dictated by `subComm` a
10697:   communicator obtained by `MPI_comm_split()` or via `PetscSubcommCreate()`. The `subComm`
10698:   is not restricted to be grouped with consecutive original MPI processes.

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

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

10709: .seealso: [](ch_matrices), `Mat`, `MatCreateRedundantMatrix()`, `MatCreateSubMatrices()`, `PCBJACOBI`
10710: @*/
10711: PetscErrorCode MatGetMultiProcBlock(Mat mat, MPI_Comm subComm, MatReuse scall, Mat *subMat)
10712: {
10713:   PetscMPIInt commsize, subCommSize;

10715:   PetscFunctionBegin;
10716:   PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)mat), &commsize));
10717:   PetscCallMPI(MPI_Comm_size(subComm, &subCommSize));
10718:   PetscCheck(subCommSize <= commsize, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_OUTOFRANGE, "CommSize %d < SubCommZize %d", commsize, subCommSize);

10720:   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");
10721:   PetscCall(PetscLogEventBegin(MAT_GetMultiProcBlock, mat, 0, 0, 0));
10722:   PetscUseTypeMethod(mat, getmultiprocblock, subComm, scall, subMat);
10723:   PetscCall(PetscLogEventEnd(MAT_GetMultiProcBlock, mat, 0, 0, 0));
10724:   PetscFunctionReturn(PETSC_SUCCESS);
10725: }

10727: /*@
10728:   MatGetLocalSubMatrix - Gets a reference to a submatrix specified in local numbering

10730:   Not Collective

10732:   Input Parameters:
10733: + mat   - matrix to extract local submatrix from
10734: . isrow - local row indices for submatrix
10735: - iscol - local column indices for submatrix

10737:   Output Parameter:
10738: . submat - the submatrix

10740:   Level: intermediate

10742:   Notes:
10743:   `submat` should be disposed of with `MatRestoreLocalSubMatrix()`.

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

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

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

10754: .seealso: [](ch_matrices), `Mat`, `MatRestoreLocalSubMatrix()`, `MatCreateLocalRef()`, `MatSetLocalToGlobalMapping()`
10755: @*/
10756: PetscErrorCode MatGetLocalSubMatrix(Mat mat, IS isrow, IS iscol, Mat *submat)
10757: {
10758:   PetscFunctionBegin;
10762:   PetscCheckSameComm(isrow, 2, iscol, 3);
10763:   PetscAssertPointer(submat, 4);
10764:   PetscCheck(mat->rmap->mapping, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Matrix must have local to global mapping provided before this call");

10766:   if (mat->ops->getlocalsubmatrix) {
10767:     PetscUseTypeMethod(mat, getlocalsubmatrix, isrow, iscol, submat);
10768:   } else {
10769:     PetscCall(MatCreateLocalRef(mat, isrow, iscol, submat));
10770:   }
10771:   (*submat)->assembled = mat->assembled;
10772:   PetscFunctionReturn(PETSC_SUCCESS);
10773: }

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

10778:   Not Collective

10780:   Input Parameters:
10781: + mat    - matrix to extract local submatrix from
10782: . isrow  - local row indices for submatrix
10783: . iscol  - local column indices for submatrix
10784: - submat - the submatrix

10786:   Level: intermediate

10788: .seealso: [](ch_matrices), `Mat`, `MatGetLocalSubMatrix()`
10789: @*/
10790: PetscErrorCode MatRestoreLocalSubMatrix(Mat mat, IS isrow, IS iscol, Mat *submat)
10791: {
10792:   PetscFunctionBegin;
10796:   PetscCheckSameComm(isrow, 2, iscol, 3);
10797:   PetscAssertPointer(submat, 4);

10800:   if (mat->ops->restorelocalsubmatrix) {
10801:     PetscUseTypeMethod(mat, restorelocalsubmatrix, isrow, iscol, submat);
10802:   } else {
10803:     PetscCall(MatDestroy(submat));
10804:   }
10805:   *submat = NULL;
10806:   PetscFunctionReturn(PETSC_SUCCESS);
10807: }

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

10812:   Collective

10814:   Input Parameter:
10815: . mat - the matrix

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

10820:   Level: developer

10822: .seealso: [](ch_matrices), `Mat`, `MatMultTranspose()`, `MatMultAdd()`, `MatMultTransposeAdd()`
10823: @*/
10824: PetscErrorCode MatFindZeroDiagonals(Mat mat, IS *is)
10825: {
10826:   PetscFunctionBegin;
10829:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
10830:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");

10832:   if (!mat->ops->findzerodiagonals) {
10833:     Vec                diag;
10834:     const PetscScalar *a;
10835:     PetscInt          *rows;
10836:     PetscInt           rStart, rEnd, r, nrow = 0;

10838:     PetscCall(MatCreateVecs(mat, &diag, NULL));
10839:     PetscCall(MatGetDiagonal(mat, diag));
10840:     PetscCall(MatGetOwnershipRange(mat, &rStart, &rEnd));
10841:     PetscCall(VecGetArrayRead(diag, &a));
10842:     for (r = 0; r < rEnd - rStart; ++r)
10843:       if (a[r] == 0.0) ++nrow;
10844:     PetscCall(PetscMalloc1(nrow, &rows));
10845:     nrow = 0;
10846:     for (r = 0; r < rEnd - rStart; ++r)
10847:       if (a[r] == 0.0) rows[nrow++] = r + rStart;
10848:     PetscCall(VecRestoreArrayRead(diag, &a));
10849:     PetscCall(VecDestroy(&diag));
10850:     PetscCall(ISCreateGeneral(PetscObjectComm((PetscObject)mat), nrow, rows, PETSC_OWN_POINTER, is));
10851:   } else {
10852:     PetscUseTypeMethod(mat, findzerodiagonals, is);
10853:   }
10854:   PetscFunctionReturn(PETSC_SUCCESS);
10855: }

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

10860:   Collective

10862:   Input Parameter:
10863: . mat - the matrix

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

10868:   Level: developer

10870: .seealso: [](ch_matrices), `Mat`, `MatMultTranspose()`, `MatMultAdd()`, `MatMultTransposeAdd()`
10871: @*/
10872: PetscErrorCode MatFindOffBlockDiagonalEntries(Mat mat, IS *is)
10873: {
10874:   PetscFunctionBegin;
10877:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
10878:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");

10880:   PetscUseTypeMethod(mat, findoffblockdiagonalentries, is);
10881:   PetscFunctionReturn(PETSC_SUCCESS);
10882: }

10884: /*@C
10885:   MatInvertBlockDiagonal - Inverts the block diagonal entries.

10887:   Collective; No Fortran Support

10889:   Input Parameter:
10890: . mat - the matrix

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

10895:   Level: advanced

10897:   Notes:
10898:   The size of the blocks is determined by the block size of the matrix.

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

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

10904: .seealso: [](ch_matrices), `Mat`, `MatInvertVariableBlockEnvelope()`, `MatInvertBlockDiagonalMat()`
10905: @*/
10906: PetscErrorCode MatInvertBlockDiagonal(Mat mat, const PetscScalar *values[])
10907: {
10908:   PetscFunctionBegin;
10910:   PetscCheck(mat->assembled, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
10911:   PetscCheck(!mat->factortype, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
10912:   PetscUseTypeMethod(mat, invertblockdiagonal, values);
10913:   PetscFunctionReturn(PETSC_SUCCESS);
10914: }

10916: /*@
10917:   MatInvertVariableBlockDiagonal - Inverts the point block diagonal entries.

10919:   Collective; No Fortran Support

10921:   Input Parameters:
10922: + mat     - the matrix
10923: . nblocks - the number of blocks on the process, set with `MatSetVariableBlockSizes()`
10924: - bsizes  - the size of each block on the process, set with `MatSetVariableBlockSizes()`

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

10929:   Level: advanced

10931:   Notes:
10932:   Use `MatInvertBlockDiagonal()` if all blocks have the same size

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

10936: .seealso: [](ch_matrices), `Mat`, `MatInvertBlockDiagonal()`, `MatSetVariableBlockSizes()`, `MatInvertVariableBlockEnvelope()`
10937: @*/
10938: PetscErrorCode MatInvertVariableBlockDiagonal(Mat mat, PetscInt nblocks, const PetscInt bsizes[], PetscScalar values[])
10939: {
10940:   PetscFunctionBegin;
10942:   PetscCheck(mat->assembled, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
10943:   PetscCheck(!mat->factortype, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
10944:   PetscUseTypeMethod(mat, invertvariableblockdiagonal, nblocks, bsizes, values);
10945:   PetscFunctionReturn(PETSC_SUCCESS);
10946: }

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

10951:   Collective

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

10957:   Level: advanced

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

10962: .seealso: [](ch_matrices), `Mat`, `MatInvertBlockDiagonal()`
10963: @*/
10964: PetscErrorCode MatInvertBlockDiagonalMat(Mat A, Mat C)
10965: {
10966:   const PetscScalar *vals;
10967:   PetscInt          *dnnz;
10968:   PetscInt           m, rstart, rend, bs, i, j;

10970:   PetscFunctionBegin;
10971:   PetscCall(MatInvertBlockDiagonal(A, &vals));
10972:   PetscCall(MatGetBlockSize(A, &bs));
10973:   PetscCall(MatGetLocalSize(A, &m, NULL));
10974:   PetscCall(MatSetLayouts(C, A->rmap, A->cmap));
10975:   PetscCall(MatSetBlockSizes(C, A->rmap->bs, A->cmap->bs));
10976:   PetscCall(PetscMalloc1(m / bs, &dnnz));
10977:   for (j = 0; j < m / bs; j++) dnnz[j] = 1;
10978:   PetscCall(MatXAIJSetPreallocation(C, bs, dnnz, NULL, NULL, NULL));
10979:   PetscCall(PetscFree(dnnz));
10980:   PetscCall(MatGetOwnershipRange(C, &rstart, &rend));
10981:   PetscCall(MatSetOption(C, MAT_ROW_ORIENTED, PETSC_FALSE));
10982:   for (i = rstart / bs; i < rend / bs; i++) PetscCall(MatSetValuesBlocked(C, 1, &i, 1, &i, &vals[(i - rstart / bs) * bs * bs], INSERT_VALUES));
10983:   PetscCall(MatSetOption(C, MAT_NO_OFF_PROC_ENTRIES, PETSC_TRUE));
10984:   PetscCall(MatAssemblyBegin(C, MAT_FINAL_ASSEMBLY));
10985:   PetscCall(MatAssemblyEnd(C, MAT_FINAL_ASSEMBLY));
10986:   PetscCall(MatSetOption(C, MAT_NO_OFF_PROC_ENTRIES, PETSC_FALSE));
10987:   PetscCall(MatSetOption(C, MAT_ROW_ORIENTED, PETSC_TRUE));
10988:   PetscFunctionReturn(PETSC_SUCCESS);
10989: }

10991: /*@
10992:   MatTransposeColoringDestroy - Destroys a coloring context for matrix product $C = A*B^T$ that was created
10993:   via `MatTransposeColoringCreate()`.

10995:   Collective

10997:   Input Parameter:
10998: . c - coloring context

11000:   Level: intermediate

11002: .seealso: [](ch_matrices), `Mat`, `MatTransposeColoringCreate()`
11003: @*/
11004: PetscErrorCode MatTransposeColoringDestroy(MatTransposeColoring *c)
11005: {
11006:   MatTransposeColoring matcolor = *c;

11008:   PetscFunctionBegin;
11009:   if (!matcolor) PetscFunctionReturn(PETSC_SUCCESS);
11010:   if (--((PetscObject)matcolor)->refct > 0) {
11011:     matcolor = NULL;
11012:     PetscFunctionReturn(PETSC_SUCCESS);
11013:   }

11015:   PetscCall(PetscFree3(matcolor->ncolumns, matcolor->nrows, matcolor->colorforrow));
11016:   PetscCall(PetscFree(matcolor->rows));
11017:   PetscCall(PetscFree(matcolor->den2sp));
11018:   PetscCall(PetscFree(matcolor->colorforcol));
11019:   PetscCall(PetscFree(matcolor->columns));
11020:   if (matcolor->brows > 0) PetscCall(PetscFree(matcolor->lstart));
11021:   PetscCall(PetscHeaderDestroy(c));
11022:   PetscFunctionReturn(PETSC_SUCCESS);
11023: }

11025: /*@
11026:   MatTransColoringApplySpToDen - Given a symbolic matrix product $C = A*B^T$ for which
11027:   a `MatTransposeColoring` context has been created, computes a dense $B^T$ by applying
11028:   `MatTransposeColoring` to sparse `B`.

11030:   Collective

11032:   Input Parameters:
11033: + coloring - coloring context created with `MatTransposeColoringCreate()`
11034: - B        - sparse matrix

11036:   Output Parameter:
11037: . Btdense - dense matrix $B^T$

11039:   Level: developer

11041:   Note:
11042:   These are used internally for some implementations of `MatRARt()`

11044: .seealso: [](ch_matrices), `Mat`, `MatTransposeColoringCreate()`, `MatTransposeColoringDestroy()`, `MatTransColoringApplyDenToSp()`
11045: @*/
11046: PetscErrorCode MatTransColoringApplySpToDen(MatTransposeColoring coloring, Mat B, Mat Btdense)
11047: {
11048:   PetscFunctionBegin;

11053:   PetscCall((*B->ops->transcoloringapplysptoden)(coloring, B, Btdense));
11054:   PetscFunctionReturn(PETSC_SUCCESS);
11055: }

11057: /*@
11058:   MatTransColoringApplyDenToSp - Given a symbolic matrix product $C_{sp} = A*B^T$ for which
11059:   a `MatTransposeColoring` context has been created and a dense matrix $C_{den} = A*B^T_{dense}$
11060:   in which `B^T_{dens}` is obtained from `MatTransColoringApplySpToDen()`, recover sparse matrix
11061:   $C_{sp}$ from $C_{den}$.

11063:   Collective

11065:   Input Parameters:
11066: + matcoloring - coloring context created with `MatTransposeColoringCreate()`
11067: - Cden        - matrix product of a sparse matrix and a dense matrix Btdense

11069:   Output Parameter:
11070: . Csp - sparse matrix

11072:   Level: developer

11074:   Note:
11075:   These are used internally for some implementations of `MatRARt()`

11077: .seealso: [](ch_matrices), `Mat`, `MatTransposeColoringCreate()`, `MatTransposeColoringDestroy()`, `MatTransColoringApplySpToDen()`
11078: @*/
11079: PetscErrorCode MatTransColoringApplyDenToSp(MatTransposeColoring matcoloring, Mat Cden, Mat Csp)
11080: {
11081:   PetscFunctionBegin;

11086:   PetscCall((*Csp->ops->transcoloringapplydentosp)(matcoloring, Cden, Csp));
11087:   PetscCall(MatAssemblyBegin(Csp, MAT_FINAL_ASSEMBLY));
11088:   PetscCall(MatAssemblyEnd(Csp, MAT_FINAL_ASSEMBLY));
11089:   PetscFunctionReturn(PETSC_SUCCESS);
11090: }

11092: /*@
11093:   MatTransposeColoringCreate - Creates a matrix coloring context for the matrix product $C = A*B^T$.

11095:   Collective

11097:   Input Parameters:
11098: + mat        - the matrix product C
11099: - iscoloring - the coloring of the matrix; usually obtained with `MatColoringCreate()` or `DMCreateColoring()`

11101:   Output Parameter:
11102: . color - the new coloring context

11104:   Level: intermediate

11106: .seealso: [](ch_matrices), `Mat`, `MatTransposeColoringDestroy()`, `MatTransColoringApplySpToDen()`,
11107:           `MatTransColoringApplyDenToSp()`
11108: @*/
11109: PetscErrorCode MatTransposeColoringCreate(Mat mat, ISColoring iscoloring, MatTransposeColoring *color)
11110: {
11111:   MatTransposeColoring c;
11112:   MPI_Comm             comm;

11114:   PetscFunctionBegin;
11115:   PetscAssertPointer(color, 3);

11117:   PetscCall(PetscLogEventBegin(MAT_TransposeColoringCreate, mat, 0, 0, 0));
11118:   PetscCall(PetscObjectGetComm((PetscObject)mat, &comm));
11119:   PetscCall(PetscHeaderCreate(c, MAT_TRANSPOSECOLORING_CLASSID, "MatTransposeColoring", "Matrix product C=A*B^T via coloring", "Mat", comm, MatTransposeColoringDestroy, NULL));
11120:   c->ctype = iscoloring->ctype;
11121:   PetscUseTypeMethod(mat, transposecoloringcreate, iscoloring, c);
11122:   *color = c;
11123:   PetscCall(PetscLogEventEnd(MAT_TransposeColoringCreate, mat, 0, 0, 0));
11124:   PetscFunctionReturn(PETSC_SUCCESS);
11125: }

11127: /*@
11128:   MatGetNonzeroState - Returns a 64-bit integer representing the current state of nonzeros in the matrix. If the
11129:   matrix has had new nonzero locations added to (or removed from) the matrix since the previous call, the value will be larger.

11131:   Not Collective

11133:   Input Parameter:
11134: . mat - the matrix

11136:   Output Parameter:
11137: . state - the current state

11139:   Level: intermediate

11141:   Notes:
11142:   You can only compare states from two different calls to the SAME matrix, you cannot compare calls between
11143:   different matrices

11145:   Use `PetscObjectStateGet()` to check for changes to the numerical values in a matrix

11147:   Use the result of `PetscObjectGetId()` to compare if a previously checked matrix is the same as the current matrix, do not compare object pointers.

11149: .seealso: [](ch_matrices), `Mat`, `PetscObjectStateGet()`, `PetscObjectGetId()`
11150: @*/
11151: PetscErrorCode MatGetNonzeroState(Mat mat, PetscObjectState *state)
11152: {
11153:   PetscFunctionBegin;
11155:   *state = mat->nonzerostate;
11156:   PetscFunctionReturn(PETSC_SUCCESS);
11157: }

11159: /*@
11160:   MatCreateMPIMatConcatenateSeqMat - Creates a single large PETSc matrix by concatenating sequential
11161:   matrices from each processor

11163:   Collective

11165:   Input Parameters:
11166: + comm   - the communicators the parallel matrix will live on
11167: . seqmat - the input sequential matrices
11168: . n      - number of local columns (or `PETSC_DECIDE`)
11169: - reuse  - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`

11171:   Output Parameter:
11172: . mpimat - the parallel matrix generated

11174:   Level: developer

11176:   Note:
11177:   The number of columns of the matrix in EACH processor MUST be the same.

11179: .seealso: [](ch_matrices), `Mat`
11180: @*/
11181: PetscErrorCode MatCreateMPIMatConcatenateSeqMat(MPI_Comm comm, Mat seqmat, PetscInt n, MatReuse reuse, Mat *mpimat)
11182: {
11183:   PetscMPIInt size;

11185:   PetscFunctionBegin;
11186:   PetscCallMPI(MPI_Comm_size(comm, &size));
11187:   if (size == 1) {
11188:     if (reuse == MAT_INITIAL_MATRIX) {
11189:       PetscCall(MatDuplicate(seqmat, MAT_COPY_VALUES, mpimat));
11190:     } else {
11191:       PetscCall(MatCopy(seqmat, *mpimat, SAME_NONZERO_PATTERN));
11192:     }
11193:     PetscFunctionReturn(PETSC_SUCCESS);
11194:   }

11196:   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");

11198:   PetscCall(PetscLogEventBegin(MAT_Merge, seqmat, 0, 0, 0));
11199:   PetscCall((*seqmat->ops->creatempimatconcatenateseqmat)(comm, seqmat, n, reuse, mpimat));
11200:   PetscCall(PetscLogEventEnd(MAT_Merge, seqmat, 0, 0, 0));
11201:   PetscFunctionReturn(PETSC_SUCCESS);
11202: }

11204: /*@
11205:   MatSubdomainsCreateCoalesce - Creates index subdomains by coalescing adjacent MPI processes' ownership ranges.

11207:   Collective

11209:   Input Parameters:
11210: + A - the matrix to create subdomains from
11211: - N - requested number of subdomains

11213:   Output Parameters:
11214: + n   - number of subdomains resulting on this MPI process
11215: - iss - `IS` list with indices of subdomains on this MPI process

11217:   Level: advanced

11219:   Note:
11220:   The number of subdomains must be smaller than the communicator size

11222: .seealso: [](ch_matrices), `Mat`, `IS`
11223: @*/
11224: PetscErrorCode MatSubdomainsCreateCoalesce(Mat A, PetscInt N, PetscInt *n, IS *iss[])
11225: {
11226:   MPI_Comm    comm, subcomm;
11227:   PetscMPIInt size, rank, color;
11228:   PetscInt    rstart, rend, k;

11230:   PetscFunctionBegin;
11231:   PetscCall(PetscObjectGetComm((PetscObject)A, &comm));
11232:   PetscCallMPI(MPI_Comm_size(comm, &size));
11233:   PetscCallMPI(MPI_Comm_rank(comm, &rank));
11234:   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);
11235:   *n    = 1;
11236:   k     = size / N + (size % N > 0); /* There are up to k ranks to a color */
11237:   color = rank / k;
11238:   PetscCallMPI(MPI_Comm_split(comm, color, rank, &subcomm));
11239:   PetscCall(PetscMalloc1(1, iss));
11240:   PetscCall(MatGetOwnershipRange(A, &rstart, &rend));
11241:   PetscCall(ISCreateStride(subcomm, rend - rstart, rstart, 1, iss[0]));
11242:   PetscCallMPI(MPI_Comm_free(&subcomm));
11243:   PetscFunctionReturn(PETSC_SUCCESS);
11244: }

11246: /*@
11247:   MatGalerkin - Constructs the coarse grid problem matrix via Galerkin projection.

11249:   If the interpolation and restriction operators are the same, uses `MatPtAP()`.
11250:   If they are not the same, uses `MatMatMatMult()`.

11252:   Once the coarse grid problem is constructed, correct for interpolation operators
11253:   that are not of full rank, which can legitimately happen in the case of non-nested
11254:   geometric multigrid.

11256:   Input Parameters:
11257: + restrct     - restriction operator
11258: . dA          - fine grid matrix
11259: . interpolate - interpolation operator
11260: . reuse       - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`
11261: - fill        - expected fill, use `PETSC_DETERMINE` or `PETSC_DETERMINE` if you do not have a good estimate

11263:   Output Parameter:
11264: . A - the Galerkin coarse matrix

11266:   Options Database Key:
11267: . -pc_mg_galerkin (both|pmat|mat|none) - for what matrices the Galerkin process should be used

11269:   Level: developer

11271:   Note:
11272:   The deprecated `PETSC_DEFAULT` in `fill` also means use the current value

11274: .seealso: [](ch_matrices), `Mat`, `MatPtAP()`, `MatMatMatMult()`
11275: @*/
11276: PetscErrorCode MatGalerkin(Mat restrct, Mat dA, Mat interpolate, MatReuse reuse, PetscReal fill, Mat *A)
11277: {
11278:   IS  zerorows;
11279:   Vec diag;

11281:   PetscFunctionBegin;
11282:   PetscCheck(reuse != MAT_INPLACE_MATRIX, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "Inplace product not supported");
11283:   /* Construct the coarse grid matrix */
11284:   if (interpolate == restrct) {
11285:     PetscCall(MatPtAP(dA, interpolate, reuse, fill, A));
11286:   } else {
11287:     PetscCall(MatMatMatMult(restrct, dA, interpolate, reuse, fill, A));
11288:   }

11290:   /* If the interpolation matrix is not of full rank, A will have zero rows.
11291:      This can legitimately happen in the case of non-nested geometric multigrid.
11292:      In that event, we set the rows of the matrix to the rows of the identity,
11293:      ignoring the equations (as the RHS will also be zero). */

11295:   PetscCall(MatFindZeroRows(*A, &zerorows));

11297:   if (zerorows != NULL) { /* if there are any zero rows */
11298:     PetscCall(MatCreateVecs(*A, &diag, NULL));
11299:     PetscCall(MatGetDiagonal(*A, diag));
11300:     PetscCall(VecISSet(diag, zerorows, 1.0));
11301:     PetscCall(MatDiagonalSet(*A, diag, INSERT_VALUES));
11302:     PetscCall(VecDestroy(&diag));
11303:     PetscCall(ISDestroy(&zerorows));
11304:   }
11305:   PetscFunctionReturn(PETSC_SUCCESS);
11306: }

11308: /*@C
11309:   MatSetOperation - Allows user to set a matrix operation for any matrix type

11311:   Logically Collective

11313:   Input Parameters:
11314: + mat - the matrix
11315: . op  - the name of the operation
11316: - f   - the function that provides the operation

11318:   Level: developer

11320:   Example Usage:
11321: .vb
11322:   extern PetscErrorCode usermult(Mat, Vec, Vec);

11324:   PetscCall(MatCreateXXX(comm, ..., &A));
11325:   PetscCall(MatSetOperation(A, MATOP_MULT, (PetscErrorCodeFn *)usermult));
11326: .ve

11328:   Notes:
11329:   See the file `include/petscmat.h` for a complete list of matrix
11330:   operations, which all have the form MATOP_<OPERATION>, where
11331:   <OPERATION> is the name (in all capital letters) of the
11332:   user interface routine (e.g., `MatMult()` -> `MATOP_MULT`).

11334:   All user-provided functions (except for `MATOP_DESTROY`) should have the same calling
11335:   sequence as the usual matrix interface routines, since they
11336:   are intended to be accessed via the usual matrix interface
11337:   routines, e.g.,
11338: .vb
11339:   MatMult(Mat, Vec, Vec) -> usermult(Mat, Vec, Vec)
11340: .ve

11342:   In particular each function MUST return `PETSC_SUCCESS` on success and
11343:   nonzero on failure.

11345:   This routine is distinct from `MatShellSetOperation()` in that it can be called on any matrix type.

11347: .seealso: [](ch_matrices), `Mat`, `MatGetOperation()`, `MatCreateShell()`, `MatShellSetContext()`, `MatShellSetOperation()`
11348: @*/
11349: PetscErrorCode MatSetOperation(Mat mat, MatOperation op, PetscErrorCodeFn *f)
11350: {
11351:   PetscFunctionBegin;
11353:   if (op == MATOP_VIEW && !mat->ops->viewnative && f != (PetscErrorCodeFn *)mat->ops->view) mat->ops->viewnative = mat->ops->view;
11354:   (((PetscErrorCodeFn **)mat->ops)[op]) = f;
11355:   PetscFunctionReturn(PETSC_SUCCESS);
11356: }

11358: /*@C
11359:   MatGetOperation - Gets a matrix operation for any matrix type.

11361:   Not Collective

11363:   Input Parameters:
11364: + mat - the matrix
11365: - op  - the name of the operation

11367:   Output Parameter:
11368: . f - the function that provides the operation

11370:   Level: developer

11372:   Example Usage:
11373: .vb
11374:   PetscErrorCode (*usermult)(Mat, Vec, Vec);

11376:   MatGetOperation(A, MATOP_MULT, (PetscErrorCodeFn **)&usermult);
11377: .ve

11379:   Notes:
11380:   See the file `include/petscmat.h` for a complete list of matrix
11381:   operations, which all have the form MATOP_<OPERATION>, where
11382:   <OPERATION> is the name (in all capital letters) of the
11383:   user interface routine (e.g., `MatMult()` -> `MATOP_MULT`).

11385:   This routine is distinct from `MatShellGetOperation()` in that it can be called on any matrix type.

11387: .seealso: [](ch_matrices), `Mat`, `MatSetOperation()`, `MatCreateShell()`, `MatShellGetContext()`, `MatShellGetOperation()`
11388: @*/
11389: PetscErrorCode MatGetOperation(Mat mat, MatOperation op, PetscErrorCodeFn **f)
11390: {
11391:   PetscFunctionBegin;
11393:   *f = (((PetscErrorCodeFn **)mat->ops)[op]);
11394:   PetscFunctionReturn(PETSC_SUCCESS);
11395: }

11397: /*@
11398:   MatHasOperation - Determines whether the given matrix supports the particular operation.

11400:   Not Collective

11402:   Input Parameters:
11403: + mat - the matrix
11404: - op  - the operation, for example, `MATOP_GET_DIAGONAL`

11406:   Output Parameter:
11407: . has - either `PETSC_TRUE` or `PETSC_FALSE`

11409:   Level: advanced

11411:   Note:
11412:   See `MatSetOperation()` for additional discussion on naming convention and usage of `op`.

11414: .seealso: [](ch_matrices), `Mat`, `MatCreateShell()`, `MatGetOperation()`, `MatSetOperation()`
11415: @*/
11416: PetscErrorCode MatHasOperation(Mat mat, MatOperation op, PetscBool *has)
11417: {
11418:   PetscFunctionBegin;
11420:   PetscAssertPointer(has, 3);
11421:   if (mat->ops->hasoperation) {
11422:     PetscUseTypeMethod(mat, hasoperation, op, has);
11423:   } else {
11424:     if (((void **)mat->ops)[op]) *has = PETSC_TRUE;
11425:     else {
11426:       *has = PETSC_FALSE;
11427:       if (op == MATOP_CREATE_SUBMATRIX) {
11428:         PetscMPIInt size;

11430:         PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)mat), &size));
11431:         if (size == 1) PetscCall(MatHasOperation(mat, MATOP_CREATE_SUBMATRICES, has));
11432:       }
11433:     }
11434:   }
11435:   PetscFunctionReturn(PETSC_SUCCESS);
11436: }

11438: /*@
11439:   MatHasCongruentLayouts - Determines whether the rows and columns layouts of the matrix are congruent

11441:   Collective

11443:   Input Parameter:
11444: . mat - the matrix

11446:   Output Parameter:
11447: . cong - either `PETSC_TRUE` or `PETSC_FALSE`

11449:   Level: beginner

11451: .seealso: [](ch_matrices), `Mat`, `MatCreate()`, `MatSetSizes()`, `PetscLayout`
11452: @*/
11453: PetscErrorCode MatHasCongruentLayouts(Mat mat, PetscBool *cong)
11454: {
11455:   PetscFunctionBegin;
11458:   PetscAssertPointer(cong, 2);
11459:   if (!mat->rmap || !mat->cmap) {
11460:     *cong = mat->rmap == mat->cmap ? PETSC_TRUE : PETSC_FALSE;
11461:     PetscFunctionReturn(PETSC_SUCCESS);
11462:   }
11463:   if (mat->congruentlayouts == PETSC_DECIDE) { /* first time we compare rows and cols layouts */
11464:     PetscCall(PetscLayoutSetUp(mat->rmap));
11465:     PetscCall(PetscLayoutSetUp(mat->cmap));
11466:     PetscCall(PetscLayoutCompare(mat->rmap, mat->cmap, cong));
11467:     if (*cong) mat->congruentlayouts = 1;
11468:     else mat->congruentlayouts = 0;
11469:   } else *cong = mat->congruentlayouts ? PETSC_TRUE : PETSC_FALSE;
11470:   PetscFunctionReturn(PETSC_SUCCESS);
11471: }

11473: PetscErrorCode MatSetInf(Mat A)
11474: {
11475:   PetscFunctionBegin;
11476:   PetscUseTypeMethod(A, setinf);
11477:   PetscFunctionReturn(PETSC_SUCCESS);
11478: }

11480: /*@
11481:   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
11482:   and possibly removes small values from the graph structure.

11484:   Collective

11486:   Input Parameters:
11487: + A       - the matrix
11488: . sym     - `PETSC_TRUE` indicates that the graph should be symmetrized
11489: . scale   - `PETSC_TRUE` indicates that the graph edge weights should be symmetrically scaled with the diagonal entry
11490: . filter  - filter value - < 0: does nothing; == 0: removes only 0.0 entries; otherwise: removes entries with abs(entries) <= value
11491: . num_idx - size of 'index' array
11492: - index   - array of block indices to use for graph strength of connection weight

11494:   Output Parameter:
11495: . graph - the resulting graph

11497:   Level: advanced

11499: .seealso: [](ch_matrices), `Mat`, `MatCreate()`, `PCGAMG`
11500: @*/
11501: PetscErrorCode MatCreateGraph(Mat A, PetscBool sym, PetscBool scale, PetscReal filter, PetscInt num_idx, PetscInt index[], Mat *graph)
11502: {
11503:   PetscFunctionBegin;
11507:   PetscAssertPointer(graph, 7);
11508:   PetscCall(PetscLogEventBegin(MAT_CreateGraph, A, 0, 0, 0));
11509:   PetscUseTypeMethod(A, creategraph, sym, scale, filter, num_idx, index, graph);
11510:   PetscCall(PetscLogEventEnd(MAT_CreateGraph, A, 0, 0, 0));
11511:   PetscFunctionReturn(PETSC_SUCCESS);
11512: }

11514: /*@
11515:   MatEliminateZeros - eliminate the nondiagonal zero entries in place from the nonzero structure of a sparse `Mat` in place,
11516:   meaning the same memory is used for the matrix, and no new memory is allocated.

11518:   Collective

11520:   Input Parameters:
11521: + A    - the matrix
11522: - 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

11524:   Level: intermediate

11526:   Developer Note:
11527:   The entries in the sparse matrix data structure are shifted to fill in the unneeded locations in the data. Thus the end
11528:   of the arrays in the data structure are unneeded.

11530: .seealso: [](ch_matrices), `Mat`, `MatCreate()`, `MatCreateGraph()`, `MatFilter()`
11531: @*/
11532: PetscErrorCode MatEliminateZeros(Mat A, PetscBool keep)
11533: {
11534:   PetscFunctionBegin;
11536:   PetscUseTypeMethod(A, eliminatezeros, keep);
11537:   PetscFunctionReturn(PETSC_SUCCESS);
11538: }

11540: /*@C
11541:   MatGetCurrentMemType - Get the memory location of the matrix

11543:   Not Collective, but the result will be the same on all MPI processes

11545:   Input Parameter:
11546: . A - the matrix whose memory type we are checking

11548:   Output Parameter:
11549: . m - the memory type

11551:   Level: intermediate

11553: .seealso: [](ch_matrices), `Mat`, `MatBoundToCPU()`, `PetscMemType`
11554: @*/
11555: PetscErrorCode MatGetCurrentMemType(Mat A, PetscMemType *m)
11556: {
11557:   PetscFunctionBegin;
11559:   PetscAssertPointer(m, 2);
11560:   if (A->ops->getcurrentmemtype) PetscUseTypeMethod(A, getcurrentmemtype, m);
11561:   else *m = PETSC_MEMTYPE_HOST;
11562:   PetscFunctionReturn(PETSC_SUCCESS);
11563: }