Actual source code: matrix.c

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

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

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

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

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

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

 55:   Logically Collective

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

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

 69:   Level: intermediate

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

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

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

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

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

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

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

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

111:   Logically Collective

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

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

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

125:   Level: advanced

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

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

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

143:   Logically Collective

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

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

153:   Level: advanced

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

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

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

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

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

180:   Logically Collective

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

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

188:   Level: advanced

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

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

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

208:   Logically Collective

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

213:   Level: developer

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

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

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

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

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

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

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

297:   Level: intermediate

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

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

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

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

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

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

330:   Level: intermediate

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

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

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

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

363:   Not Collective

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

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

371:   Level: advanced

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

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

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

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

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

401:   Collective

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

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

409:   Level: advanced

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

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

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

430:   Logically Collective

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

435:   Level: advanced

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

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

454:   Collective

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

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

463:   Level: advanced

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

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

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

488:   Logically Collective

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

493:   Level: advanced

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

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

515:   Not Collective

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

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

526:   Level: advanced

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

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

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

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

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

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

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

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

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

566:   PetscFunctionBegin;
569:   PetscCheck(mat->assembled, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
570:   PetscCheck(!mat->factortype, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
571:   MatCheckPreallocated(mat, 1);
572:   PetscCheck(row >= mat->rmap->rstart && row < mat->rmap->rend, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Only for local rows, %" PetscInt_FMT " not in [%" PetscInt_FMT ",%" PetscInt_FMT ")", row, mat->rmap->rstart, mat->rmap->rend);
573:   PetscCall(PetscLogEventBegin(MAT_GetRow, mat, 0, 0, 0));
574:   PetscUseTypeMethod(mat, getrow, row, &incols, (PetscInt **)cols, (PetscScalar **)vals);
575:   if (ncols) *ncols = incols;
576:   PetscCall(PetscLogEventEnd(MAT_GetRow, mat, 0, 0, 0));
577:   PetscFunctionReturn(PETSC_SUCCESS);
578: }

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

583:   Logically Collective

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

588:   Level: advanced

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

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

607:   Not Collective

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

616:   Level: advanced

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

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

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

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

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

650:   Not Collective

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

655:   Level: advanced

657:   Note:
658:   The flag is to ensure that users are aware that `MatGetRow()` only provides the upper triangular part of the row for the matrices in `MATSBAIJ` format.

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

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

677:   Not Collective

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

682:   Level: advanced

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

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

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

705:   Logically Collective

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

711:   Level: advanced

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

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

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

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

736:   Logically Collective

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

742:   Level: developer

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

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

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

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

772:   Logically Collective

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

778:   Level: developer

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

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

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

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

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

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

816:   Logically Collective

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

822:   Level: advanced

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

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

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

843:   Not Collective

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

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

851:   Level: advanced

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

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

867:   Not Collective

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

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

875:   Level: advanced

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

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

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

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

898:   Collective

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

903:   Level: beginner

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

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

912:   Currently only supported for  `MATAIJ` matrices.

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

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

928:   Collective

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

933:   Level: intermediate

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

938:   Currently only supported for `MATAIJ` matrices.

940: .seealso: [](ch_matrices), `Mat`, `MatResetPreallocation()`
941: @*/
942: PetscErrorCode MatResetHash(Mat A)
943: {
944:   PetscFunctionBegin;
947:   PetscCheck(A->insertmode == NOT_SET_VALUES, PETSC_COMM_SELF, PETSC_ERR_SUP, "Cannot reset to hash state after setting some values but not yet calling MatAssemblyBegin()/MatAssemblyEnd()");
948:   if (A->num_ass == 0) PetscFunctionReturn(PETSC_SUCCESS);
949:   PetscUseMethod(A, "MatResetHash_C", (Mat), (A));
950:   /* These flags are used to determine whether certain setups occur */
951:   A->was_assembled = PETSC_FALSE;
952:   A->assembled     = PETSC_FALSE;
953:   /* Log that the state of this object has changed; this will help guarantee that preconditioners get re-setup */
954:   PetscCall(PetscObjectStateIncrease((PetscObject)A));
955:   PetscFunctionReturn(PETSC_SUCCESS);
956: }

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

961:   Collective

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

966:   Level: advanced

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

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

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

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

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

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

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

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

1009:   Collective

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

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

1019:   Level: intermediate

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

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

1037:   Collective on viewer

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

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

1057:   Level: beginner

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

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

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

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

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

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

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

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

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

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

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

1122: #if !defined(PETSC_HAVE_THREADSAFETY)
1123:   insidematview++;
1124: #endif
1125:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERSTRING, &isstring));
1126:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERASCII, &isascii));
1127:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERSAWS, &issaws));
1128:   PetscCheck((isascii && (format == PETSC_VIEWER_ASCII_INFO || format == PETSC_VIEWER_ASCII_INFO_DETAIL)) || !mat->factortype, PetscObjectComm((PetscObject)viewer), PETSC_ERR_ARG_WRONGSTATE, "No viewers for factored matrix except ASCII, info, or info_detail");

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

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

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

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

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

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

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

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

1250:   Collective

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

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

1260:   Level: beginner

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

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

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

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

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

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

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

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

1312: .vb
1313:     PetscInt    MAT_FILE_CLASSID
1314:     PetscInt    number of rows
1315:     PetscInt    number of columns
1316:     PetscInt    total number of nonzeros
1317:     PetscInt    *number nonzeros in each row
1318:     PetscInt    *column indices of all nonzeros (starting index is zero)
1319:     PetscScalar *values of all nonzeros
1320: .ve
1321:   If PETSc was not configured with `--with-64-bit-indices` then only `MATMPIAIJ` matrices with more than `PETSC_INT_MAX` non-zeros can be
1322:   stored or loaded (each MPI process part of the matrix must have less than `PETSC_INT_MAX` nonzeros). Since the total nonzero count in this
1323:   case will not fit in a (32-bit) `PetscInt` the value `PETSC_INT_MAX` is used for the header entry `total number of nonzeros`.

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

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

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

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

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

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

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

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

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

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

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

1369:   PetscFunctionBegin;

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

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

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

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

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

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

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

1421:   Collective

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

1426:   Level: beginner

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

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

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

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

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

1476:   Not Collective

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

1488:   Level: beginner

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

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

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

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

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

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

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

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

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

1535:   if (PetscDefined(USE_DEBUG)) {
1536:     PetscInt i, j;

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

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

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

1571:   Not Collective

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

1581:   Level: beginner

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

1586:   Calls to `MatSetValues()` with the `INSERT_VALUES` and `ADD_VALUES`
1587:   options cannot be mixed without intervening calls to the assembly
1588:   routines.

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

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

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

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

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

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

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

1627: /*@
1628:   MatSetValuesRowLocal - Inserts a row (block row for `MATBAIJ` matrices) of nonzero
1629:   values into a matrix

1631:   Not Collective

1633:   Input Parameters:
1634: + mat - the matrix
1635: . row - the (block) row to set
1636: - 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.
1637:         See `MAT_ROW_ORIENTED` in `MatSetOption()` for how to use column-major order.

1639:   Level: intermediate

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

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

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

1648:   `row` must belong to this MPI process

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

1653: .seealso: [](ch_matrices), `Mat`, `MatSetOption()`, `MatAssemblyBegin()`, `MatAssemblyEnd()`, `MatSetValuesBlocked()`, `MatSetValuesLocal()`,
1654:           `InsertMode`, `INSERT_VALUES`, `ADD_VALUES`, `MatSetValues()`, `MatSetValuesRow()`, `MatSetLocalToGlobalMapping()`
1655: @*/
1656: PetscErrorCode MatSetValuesRowLocal(Mat mat, PetscInt row, const PetscScalar v[])
1657: {
1658:   PetscInt globalrow;

1660:   PetscFunctionBegin;
1663:   PetscAssertPointer(v, 3);
1664:   PetscCall(ISLocalToGlobalMappingApply(mat->rmap->mapping, 1, &row, &globalrow));
1665:   PetscCall(MatSetValuesRow(mat, globalrow, v));
1666:   PetscFunctionReturn(PETSC_SUCCESS);
1667: }

1669: /*@
1670:   MatSetValuesRow - Inserts a row (block row for `MATBAIJ` matrices) of nonzero
1671:   values into a matrix

1673:   Not Collective

1675:   Input Parameters:
1676: + mat - the matrix
1677: . row - the (block) row to set
1678: - 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

1680:   Level: advanced

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

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

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

1689:   `row` must belong to this process

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

1705:   if (mat->assembled) {
1706:     mat->was_assembled = PETSC_TRUE;
1707:     mat->assembled     = PETSC_FALSE;
1708:   }
1709:   PetscCall(PetscLogEventBegin(MAT_SetValues, mat, 0, 0, 0));
1710:   PetscUseTypeMethod(mat, setvaluesrow, row, v);
1711:   PetscCall(PetscLogEventEnd(MAT_SetValues, mat, 0, 0, 0));
1712:   PetscFunctionReturn(PETSC_SUCCESS);
1713: }

1715: // PetscClangLinter pragma disable: -fdoc-section-header-unknown
1716: /*@
1717:   MatSetValuesStencil - Inserts or adds a block of values into a matrix.
1718:   Using structured grid indexing

1720:   Not Collective

1722:   Input Parameters:
1723: + mat  - the matrix
1724: . m    - number of rows being entered
1725: . idxm - grid coordinates (and component number when dof > 1) for matrix rows being entered
1726: . n    - number of columns being entered
1727: . idxn - grid coordinates (and component number when dof > 1) for matrix columns being entered
1728: . v    - a one-dimensional array that contains the values implicitly stored as a two-dimensional array, by default in row-major order.
1729:          See `MAT_ROW_ORIENTED` in `MatSetOption()` for how to use column-major order.
1730: - addv - either `ADD_VALUES` to add to existing entries at that location or `INSERT_VALUES` to replace existing entries with new values

1732:   Level: beginner

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

1737:   Calls to `MatSetValuesStencil()` with the `INSERT_VALUES` and `ADD_VALUES`
1738:   options cannot be mixed without intervening calls to the assembly
1739:   routines.

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

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

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

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

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

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

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

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

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

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

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

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

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

1824: /*@
1825:   MatSetValuesBlockedStencil - Inserts or adds a block of values into a matrix.
1826:   Using structured grid indexing

1828:   Not Collective

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

1840:   Level: beginner

1842:   Notes:
1843:   By default the values, `v`, are row-oriented and unsorted.
1844:   See `MatSetOption()` for other options.

1846:   Calls to `MatSetValuesBlockedStencil()` with the `INSERT_VALUES` and `ADD_VALUES`
1847:   options cannot be mixed without intervening calls to the assembly
1848:   routines.

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

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

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

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

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

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

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

1874:   Fortran Notes:
1875:   `idxm` and `idxn` should be declared as
1876: .vb
1877:     MatStencil idxm(4,m),idxn(4,n)
1878: .ve
1879:   and the values inserted using
1880: .vb
1881:     idxm(MatStencil_i,1) = i
1882:     idxm(MatStencil_j,1) = j
1883:     idxm(MatStencil_k,1) = k
1884:    etc
1885: .ve

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

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

1899:   PetscFunctionBegin;
1900:   if (!m || !n) PetscFunctionReturn(PETSC_SUCCESS); /* no values to insert */
1903:   PetscAssertPointer(idxm, 3);
1904:   PetscAssertPointer(idxn, 5);
1905:   PetscAssertPointer(v, 6);

1907:   if ((m + n) <= (PetscInt)PETSC_STATIC_ARRAY_LENGTH(buf)) {
1908:     jdxm = buf;
1909:     jdxn = buf + m;
1910:   } else {
1911:     PetscCall(PetscMalloc2(m, &bufm, n, &bufn));
1912:     jdxm = bufm;
1913:     jdxn = bufn;
1914:   }
1915:   for (i = 0; i < m; i++) {
1916:     for (j = 0; j < 3 - sdim; j++) dxm++;
1917:     tmp = *dxm++ - starts[0];
1918:     for (j = 0; j < sdim - 1; j++) {
1919:       if ((*dxm++ - starts[j + 1]) < 0 || tmp < 0) tmp = -1;
1920:       else tmp = tmp * dims[j] + *(dxm - 1) - starts[j + 1];
1921:     }
1922:     dxm++;
1923:     jdxm[i] = tmp;
1924:   }
1925:   for (i = 0; i < n; i++) {
1926:     for (j = 0; j < 3 - sdim; j++) dxn++;
1927:     tmp = *dxn++ - starts[0];
1928:     for (j = 0; j < sdim - 1; j++) {
1929:       if ((*dxn++ - starts[j + 1]) < 0 || tmp < 0) tmp = -1;
1930:       else tmp = tmp * dims[j] + *(dxn - 1) - starts[j + 1];
1931:     }
1932:     dxn++;
1933:     jdxn[i] = tmp;
1934:   }
1935:   PetscCall(MatSetValuesBlockedLocal(mat, m, jdxm, n, jdxn, v, addv));
1936:   PetscCall(PetscFree2(bufm, bufn));
1937:   PetscFunctionReturn(PETSC_SUCCESS);
1938: }

1940: /*@
1941:   MatSetStencil - Sets the grid information for setting values into a matrix via
1942:   `MatSetValuesStencil()`

1944:   Not Collective

1946:   Input Parameters:
1947: + mat    - the matrix
1948: . dim    - dimension of the grid 1, 2, or 3
1949: . dims   - number of grid points in x, y, and z direction, including ghost points on your processor
1950: . starts - starting point of ghost nodes on your processor in x, y, and z direction
1951: - dof    - number of degrees of freedom per node

1953:   Level: beginner

1955:   Notes:
1956:   Inspired by the structured grid interface to the HYPRE package
1957:   (www.llnl.gov/CASC/hyper)

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

1962: .seealso: [](ch_matrices), `Mat`, `MatStencil`, `MatSetOption()`, `MatAssemblyBegin()`, `MatAssemblyEnd()`, `MatSetValuesBlocked()`, `MatSetValuesLocal()`,
1963:           `MatSetValues()`, `MatSetValuesBlockedStencil()`, `MatSetValuesStencil()`
1964: @*/
1965: PetscErrorCode MatSetStencil(Mat mat, PetscInt dim, const PetscInt dims[], const PetscInt starts[], PetscInt dof)
1966: {
1967:   PetscFunctionBegin;
1969:   PetscAssertPointer(dims, 3);
1970:   PetscAssertPointer(starts, 4);

1972:   mat->stencil.dim = dim + (dof > 1);
1973:   for (PetscInt i = 0; i < dim; i++) {
1974:     mat->stencil.dims[i]   = dims[dim - i - 1]; /* copy the values in backwards */
1975:     mat->stencil.starts[i] = starts[dim - i - 1];
1976:   }
1977:   mat->stencil.dims[dim]   = dof;
1978:   mat->stencil.starts[dim] = 0;
1979:   mat->stencil.noc         = (PetscBool)(dof == 1);
1980:   PetscFunctionReturn(PETSC_SUCCESS);
1981: }

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

1986:   Not Collective

1988:   Input Parameters:
1989: + mat  - the matrix
1990: . m    - the number of block rows
1991: . idxm - the global block indices
1992: . n    - the number of block columns
1993: . idxn - the global block indices
1994: . v    - a one-dimensional array that contains the values implicitly stored as a two-dimensional array, by default in row-major order.
1995:          See `MAT_ROW_ORIENTED` in `MatSetOption()` for how to use column-major order.
1996: - addv - either `ADD_VALUES` to add values to any existing entries, or `INSERT_VALUES` replaces existing entries with new values

1998:   Level: intermediate

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

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

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

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

2015:   Calls to `MatSetValuesBlocked()` with the `INSERT_VALUES` and `ADD_VALUES`
2016:   options cannot be mixed without intervening calls to the assembly
2017:   routines.

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

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

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

2033:   Example:
2034: .vb
2035:    Suppose m=n=2 and block size(bs) = 2 The array is

2037:    1  2  | 3  4
2038:    5  6  | 7  8
2039:    - - - | - - -
2040:    9  10 | 11 12
2041:    13 14 | 15 16

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

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

2050:   Fortran Notes:
2051:   If any of `idmx`, `idxn`, and `v` are scalars pass them using, for example,
2052: .vb
2053:   call MatSetValuesBlocked(mat, one, [idxm], one, [idxn], [v], INSERT_VALUES, ierr)
2054: .ve

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

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

2093:     PetscCall(MatGetBlockSizes(mat, &bs, &cbs));
2094:     if ((m * bs + n * cbs) <= (PetscInt)PETSC_STATIC_ARRAY_LENGTH(buf)) {
2095:       iidxm = buf;
2096:       iidxn = buf + m * bs;
2097:     } else {
2098:       PetscCall(PetscMalloc2(m * bs, &bufr, n * cbs, &bufc));
2099:       iidxm = bufr;
2100:       iidxn = bufc;
2101:     }
2102:     for (i = 0; i < m; i++) {
2103:       for (j = 0; j < bs; j++) iidxm[i * bs + j] = bs * idxm[i] + j;
2104:     }
2105:     if (m != n || bs != cbs || idxm != idxn) {
2106:       for (i = 0; i < n; i++) {
2107:         for (j = 0; j < cbs; j++) iidxn[i * cbs + j] = cbs * idxn[i] + j;
2108:       }
2109:     } else iidxn = iidxm;
2110:     PetscCall(MatSetValues(mat, m * bs, iidxm, n * cbs, iidxn, v, addv));
2111:     PetscCall(PetscFree2(bufr, bufc));
2112:   }
2113:   PetscCall(PetscLogEventEnd(MAT_SetValues, mat, 0, 0, 0));
2114:   PetscFunctionReturn(PETSC_SUCCESS);
2115: }

2117: /*@
2118:   MatGetValues - Gets a block of local values from a matrix.

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

2122:   Input Parameters:
2123: + mat  - the matrix
2124: . v    - a logically two-dimensional array for storing the values
2125: . m    - the number of rows
2126: . idxm - the  global indices of the rows
2127: . n    - the number of columns
2128: - idxn - the global indices of the columns

2130:   Level: advanced

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

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

2140:   `MatGetValues()` requires that the matrix has been assembled
2141:   with `MatAssemblyBegin()`/`MatAssemblyEnd()`.  Thus, calls to
2142:   `MatSetValues()` and `MatGetValues()` CANNOT be made in succession
2143:   without intermediate matrix assembly.

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

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

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

2167:   PetscCall(PetscLogEventBegin(MAT_GetValues, mat, 0, 0, 0));
2168:   PetscUseTypeMethod(mat, getvalues, m, idxm, n, idxn, v);
2169:   PetscCall(PetscLogEventEnd(MAT_GetValues, mat, 0, 0, 0));
2170:   PetscFunctionReturn(PETSC_SUCCESS);
2171: }

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

2177:   Not Collective

2179:   Input Parameters:
2180: + mat  - the matrix
2181: . nrow - number of rows
2182: . irow - the row local indices
2183: . ncol - number of columns
2184: - icol - the column local indices

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

2190:   Level: advanced

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

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

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

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

2244:   Not Collective

2246:   Input Parameters:
2247: + mat  - the matrix
2248: . nb   - the number of blocks
2249: . bs   - the number of rows (and columns) in each block
2250: . rows - a concatenation of the rows for each block
2251: - v    - a concatenation of logically two-dimensional arrays of values

2253:   Level: advanced

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

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

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

2272:   PetscCall(PetscLogEventBegin(MAT_SetValuesBatch, mat, 0, 0, 0));
2273:   for (PetscInt b = 0; b < nb; ++b) PetscCall(MatSetValues(mat, bs, &rows[b * bs], bs, &rows[b * bs], &v[b * bs * bs], ADD_VALUES));
2274:   PetscCall(PetscLogEventEnd(MAT_SetValuesBatch, mat, 0, 0, 0));
2275:   PetscFunctionReturn(PETSC_SUCCESS);
2276: }

2278: /*@
2279:   MatSetLocalToGlobalMapping - Sets a local-to-global numbering for use by
2280:   the routine `MatSetValuesLocal()` to allow users to insert matrix entries
2281:   using a local (per-processor) numbering.

2283:   Not Collective

2285:   Input Parameters:
2286: + x        - the matrix
2287: . rmapping - row mapping created with `ISLocalToGlobalMappingCreate()` or `ISLocalToGlobalMappingCreateIS()`
2288: - cmapping - column mapping

2290:   Level: intermediate

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

2295: .seealso: [](ch_matrices), `Mat`, `DM`, `DMCreateMatrix()`, `MatGetLocalToGlobalMapping()`, `MatAssemblyBegin()`, `MatAssemblyEnd()`, `MatSetValues()`, `MatSetValuesLocal()`, `MatGetValuesLocal()`
2296: @*/
2297: PetscErrorCode MatSetLocalToGlobalMapping(Mat x, ISLocalToGlobalMapping rmapping, ISLocalToGlobalMapping cmapping)
2298: {
2299:   PetscFunctionBegin;
2304:   if (x->ops->setlocaltoglobalmapping) PetscUseTypeMethod(x, setlocaltoglobalmapping, rmapping, cmapping);
2305:   else {
2306:     PetscCall(PetscLayoutSetISLocalToGlobalMapping(x->rmap, rmapping));
2307:     PetscCall(PetscLayoutSetISLocalToGlobalMapping(x->cmap, cmapping));
2308:   }
2309:   PetscFunctionReturn(PETSC_SUCCESS);
2310: }

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

2315:   Not Collective

2317:   Input Parameter:
2318: . A - the matrix

2320:   Output Parameters:
2321: + rmapping - row mapping
2322: - cmapping - column mapping

2324:   Level: advanced

2326: .seealso: [](ch_matrices), `Mat`, `MatSetLocalToGlobalMapping()`, `MatSetValuesLocal()`
2327: @*/
2328: PetscErrorCode MatGetLocalToGlobalMapping(Mat A, ISLocalToGlobalMapping *rmapping, ISLocalToGlobalMapping *cmapping)
2329: {
2330:   PetscFunctionBegin;
2333:   if (rmapping) {
2334:     PetscAssertPointer(rmapping, 2);
2335:     *rmapping = A->rmap->mapping;
2336:   }
2337:   if (cmapping) {
2338:     PetscAssertPointer(cmapping, 3);
2339:     *cmapping = A->cmap->mapping;
2340:   }
2341:   PetscFunctionReturn(PETSC_SUCCESS);
2342: }

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

2347:   Logically Collective

2349:   Input Parameters:
2350: + A    - the matrix
2351: . rmap - row layout
2352: - cmap - column layout

2354:   Level: advanced

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

2359: .seealso: [](ch_matrices), `Mat`, `PetscLayout`, `MatCreateVecs()`, `MatGetLocalToGlobalMapping()`, `MatGetLayouts()`
2360: @*/
2361: PetscErrorCode MatSetLayouts(Mat A, PetscLayout rmap, PetscLayout cmap)
2362: {
2363:   PetscFunctionBegin;
2365:   PetscCall(PetscLayoutReference(rmap, &A->rmap));
2366:   PetscCall(PetscLayoutReference(cmap, &A->cmap));
2367:   PetscFunctionReturn(PETSC_SUCCESS);
2368: }

2370: /*@
2371:   MatGetLayouts - Gets the `PetscLayout` objects for rows and columns

2373:   Not Collective

2375:   Input Parameter:
2376: . A - the matrix

2378:   Output Parameters:
2379: + rmap - row layout
2380: - cmap - column layout

2382:   Level: advanced

2384: .seealso: [](ch_matrices), `Mat`, [Matrix Layouts](sec_matlayout), `PetscLayout`, `MatCreateVecs()`, `MatGetLocalToGlobalMapping()`, `MatSetLayouts()`
2385: @*/
2386: PetscErrorCode MatGetLayouts(Mat A, PetscLayout *rmap, PetscLayout *cmap)
2387: {
2388:   PetscFunctionBegin;
2391:   if (rmap) {
2392:     PetscAssertPointer(rmap, 2);
2393:     *rmap = A->rmap;
2394:   }
2395:   if (cmap) {
2396:     PetscAssertPointer(cmap, 3);
2397:     *cmap = A->cmap;
2398:   }
2399:   PetscFunctionReturn(PETSC_SUCCESS);
2400: }

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

2406:   Not Collective

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

2418:   Level: intermediate

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

2423:   Calls to `MatSetValuesLocal()` with the `INSERT_VALUES` and `ADD_VALUES`
2424:   options cannot be mixed without intervening calls to the assembly
2425:   routines.

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

2430:   Fortran Notes:
2431:   If any of `irow`, `icol`, and `y` are scalars pass them using, for example,
2432: .vb
2433:   call MatSetValuesLocal(mat, one, [irow], one, [icol], [y], INSERT_VALUES, ierr)
2434: .ve

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

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

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

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

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

2494:   Not Collective

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

2506:   Level: intermediate

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

2512:   Calls to `MatSetValuesBlockedLocal()` with the `INSERT_VALUES` and `ADD_VALUES`
2513:   options cannot be mixed without intervening calls to the assembly
2514:   routines.

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

2519:   Fortran Notes:
2520:   If any of `irow`, `icol`, and `y` are scalars pass them using, for example,
2521: .vb
2522:   call MatSetValuesBlockedLocal(mat, one, [irow], one, [icol], [y], INSERT_VALUES, ierr)
2523: .ve

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

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

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

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

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

2594:   Collective

2596:   Input Parameters:
2597: + mat - the matrix
2598: - x   - the vector to be multiplied

2600:   Output Parameter:
2601: . y - the result

2603:   Level: developer

2605:   Note:
2606:   The vectors `x` and `y` cannot be the same.  I.e., one cannot
2607:   call `MatMultDiagonalBlock`(A,y,y).

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

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

2624:   PetscUseTypeMethod(mat, multdiagonalblock, x, y);
2625:   PetscCall(PetscObjectStateIncrease((PetscObject)y));
2626:   PetscFunctionReturn(PETSC_SUCCESS);
2627: }

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

2632:   Neighbor-wise Collective

2634:   Input Parameters:
2635: + mat - the matrix
2636: - x   - the vector to be multiplied

2638:   Output Parameter:
2639: . y - the result

2641:   Level: beginner

2643:   Note:
2644:   The vectors `x` and `y` cannot be the same.  I.e., one cannot
2645:   call `MatMult`(A,y,y).

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

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

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

2680:   Neighbor-wise Collective

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

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

2689:   Level: beginner

2691:   Notes:
2692:   The vectors `x` and `y` cannot be the same.  I.e., one cannot
2693:   call `MatMultTranspose`(A,y,y).

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

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

2704:   PetscFunctionBegin;
2708:   VecCheckAssembled(x);

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

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

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

2738:   Neighbor-wise Collective

2740:   Input Parameters:
2741: + mat - the matrix
2742: - x   - the vector to be multiplied

2744:   Output Parameter:
2745: . y - the result

2747:   Level: beginner

2749:   Notes:
2750:   The vectors `x` and `y` cannot be the same.  I.e., one cannot
2751:   call `MatMultHermitianTranspose`(A,y,y).

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

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

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

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

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

2800: /*@
2801:   MatMultAdd -  Computes $v3 = v2 + A * v1$.

2803:   Neighbor-wise Collective

2805:   Input Parameters:
2806: + mat - the matrix
2807: . v1  - the vector to be multiplied by `mat`
2808: - v2  - the vector to be added to the result

2810:   Output Parameter:
2811: . v3 - the result

2813:   Level: beginner

2815:   Note:
2816:   The vectors `v1` and `v3` cannot be the same.  I.e., one cannot
2817:   call `MatMultAdd`(A,v1,v2,v1).

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

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

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

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

2852:   Neighbor-wise Collective

2854:   Input Parameters:
2855: + mat - the matrix
2856: . v1  - the vector to be multiplied by the transpose of the matrix
2857: - v2  - the vector to be added to the result

2859:   Output Parameter:
2860: . v3 - the result

2862:   Level: beginner

2864:   Note:
2865:   The vectors `v1` and `v3` cannot be the same.  I.e., one cannot
2866:   call `MatMultTransposeAdd`(A,v1,v2,v1).

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

2874:   PetscFunctionBegin;

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

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

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

2902:   Neighbor-wise Collective

2904:   Input Parameters:
2905: + mat - the matrix
2906: . v1  - the vector to be multiplied by the Hermitian transpose
2907: - v2  - the vector to be added to the result

2909:   Output Parameter:
2910: . v3 - the result

2912:   Level: beginner

2914:   Note:
2915:   The vectors `v1` and `v3` cannot be the same.  I.e., one cannot
2916:   call `MatMultHermitianTransposeAdd`(A,v1,v2,v1).

2918: .seealso: [](ch_matrices), `Mat`, `MatMultHermitianTranspose()`, `MatMultTranspose()`, `MatMultAdd()`, `MatMult()`
2919: @*/
2920: PetscErrorCode MatMultHermitianTransposeAdd(Mat mat, Vec v1, Vec v2, Vec v3)
2921: {
2922:   PetscFunctionBegin;

2929:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
2930:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
2931:   PetscCheck(v1 != v3, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_IDN, "v1 and v3 must be different vectors");
2932:   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);
2933:   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);
2934:   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);
2935:   MatCheckPreallocated(mat, 1);

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

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

2968: PetscErrorCode MatANorm_Default(Mat mat, Vec x, PetscReal *val)
2969: {
2970:   PetscScalar sval;

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

2980: /*@
2981:   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)
2982:   positive definite.

2984:   Collective

2986:   Input Parameters:
2987: + mat - matrix used to define the inner product
2988: . x   - first vector
2989: - y   - second vector

2991:   Output Parameter:
2992: . val - the dot product with respect to `A`

2994:   Level: intermediate

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

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

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

3038: /*@
3039:   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)
3040:   positive definite.

3042:   Collective

3044:   Input Parameters:
3045: + mat - matrix used to define norm
3046: - x   - the vector to compute the norm of

3048:   Output Parameter:
3049: . val - the norm with respect to `A`

3051:   Level: intermediate

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

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

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

3088: /*@
3089:   MatGetFactorType - gets the type of factorization a matrix is

3091:   Not Collective

3093:   Input Parameter:
3094: . mat - the matrix

3096:   Output Parameter:
3097: . 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`

3099:   Level: intermediate

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

3114: /*@
3115:   MatSetFactorType - sets the type of factorization a matrix is

3117:   Logically Collective

3119:   Input Parameters:
3120: + mat - the matrix
3121: - 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`

3123:   Level: intermediate

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

3137: /*@
3138:   MatGetInfo - Returns information about matrix storage (number of
3139:   nonzeros, memory, etc.).

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

3143:   Input Parameters:
3144: + mat  - the matrix
3145: - 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)

3147:   Output Parameter:
3148: . info - matrix information context

3150:   Options Database Key:
3151: . -mat_view ::ascii_info - print matrix info to `PETSC_STDOUT`

3153:   Level: intermediate

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

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

3170:       MatGetInfo(A, MAT_LOCAL, &info);
3171:       mal  = info.mallocs;
3172:       nz_a = info.nz_allocated;
3173: .ve

3175: .seealso: [](ch_matrices), `Mat`, `MatInfo`, `MatStashGetInfo()`
3176: @*/
3177: PetscErrorCode MatGetInfo(Mat mat, MatInfoType flag, MatInfo *info)
3178: {
3179:   PetscFunctionBegin;
3182:   PetscAssertPointer(info, 3);
3183:   MatCheckPreallocated(mat, 1);
3184:   PetscUseTypeMethod(mat, getinfo, flag, info);
3185:   PetscFunctionReturn(PETSC_SUCCESS);
3186: }

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

3199: /*@
3200:   MatLUFactor - Performs in-place LU factorization of matrix.

3202:   Collective

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

3215:   Level: developer

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

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

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

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

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

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

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

3259: /*@
3260:   MatILUFactor - Performs in-place ILU factorization of matrix.

3262:   Collective

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

3276:   Level: developer

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

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

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

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

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

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

3316:   Collective

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

3329:   Level: developer

3331:   Notes:
3332:   See [Matrix Factorization](sec_matfactor) for additional information about factorizations

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

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

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

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

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

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

3374:   Collective

3376:   Input Parameters:
3377: + fact - the factor matrix obtained with `MatGetFactor()`
3378: . mat  - the matrix
3379: - info - options for factorization

3381:   Level: developer

3383:   Notes:
3384:   See `MatLUFactor()` for in-place factorization.  See
3385:   `MatCholeskyFactorNumeric()` for the symmetric, positive definite case.

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

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

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

3400:   PetscFunctionBegin;
3405:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
3406:   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,
3407:              mat->rmap->N, (fact)->rmap->N, mat->cmap->N, (fact)->cmap->N);

3409:   MatCheckPreallocated(mat, 2);
3410:   if (!info) {
3411:     PetscCall(MatFactorInfoInitialize(&tinfo));
3412:     info = &tinfo;
3413:   }

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

3425: /*@
3426:   MatCholeskyFactor - Performs in-place Cholesky factorization of a
3427:   symmetric matrix.

3429:   Collective

3431:   Input Parameters:
3432: + mat  - the matrix
3433: . perm - row and column permutations
3434: - info - expected fill as ratio of original fill

3436:   Level: developer

3438:   Notes:
3439:   See `MatLUFactor()` for the nonsymmetric case.  See also `MatGetFactor()`,
3440:   `MatCholeskyFactorSymbolic()`, and `MatCholeskyFactorNumeric()`.

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

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

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

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

3470:   PetscCall(PetscLogEventBegin(MAT_CholeskyFactor, mat, perm, 0, 0));
3471:   PetscUseTypeMethod(mat, choleskyfactor, perm, info);
3472:   PetscCall(PetscLogEventEnd(MAT_CholeskyFactor, mat, perm, 0, 0));
3473:   PetscCall(PetscObjectStateIncrease((PetscObject)mat));
3474:   PetscFunctionReturn(PETSC_SUCCESS);
3475: }

3477: /*@
3478:   MatCholeskyFactorSymbolic - Performs symbolic Cholesky factorization
3479:   of a symmetric matrix.

3481:   Collective

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

3494:   Level: developer

3496:   Notes:
3497:   See `MatLUFactorSymbolic()` for the nonsymmetric case.  See also
3498:   `MatCholeskyFactor()` and `MatCholeskyFactorNumeric()`.

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

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

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

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

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

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

3542:   Collective

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

3549:   Level: developer

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

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

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

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

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

3589: /*@
3590:   MatQRFactor - Performs in-place QR factorization of matrix.

3592:   Collective

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

3604:   Level: developer

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

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

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

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

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

3641:   Collective

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

3654:   Level: developer

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

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

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

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

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

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

3696:   Collective

3698:   Input Parameters:
3699: + fact - the factor matrix obtained with `MatGetFactor()`
3700: . mat  - the matrix
3701: - info - options for factorization

3703:   Level: developer

3705:   Notes:
3706:   See `MatQRFactor()` for in-place factorization.

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

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

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

3721:   PetscFunctionBegin;
3726:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
3727:   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,
3728:              mat->rmap->N, (fact)->rmap->N, mat->cmap->N, (fact)->cmap->N);

3730:   MatCheckPreallocated(mat, 2);
3731:   if (!info) {
3732:     PetscCall(MatFactorInfoInitialize(&tinfo));
3733:     info = &tinfo;
3734:   }

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

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

3749:   Neighbor-wise Collective

3751:   Input Parameters:
3752: + mat - the factored matrix
3753: - b   - the right-hand-side vector

3755:   Output Parameter:
3756: . x - the result vector

3758:   Level: developer

3760:   Notes:
3761:   The vectors `b` and `x` cannot be the same.  I.e., one cannot
3762:   call `MatSolve`(A,x,x).

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

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

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

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

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

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

3838:   Neighbor-wise Collective

3840:   Input Parameters:
3841: + A - the factored matrix
3842: - B - the right-hand-side matrix `MATDENSE` (or sparse `MATAIJ`-- when using MUMPS)

3844:   Output Parameter:
3845: . X - the result matrix (dense matrix)

3847:   Level: developer

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

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

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

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

3883:   Neighbor-wise Collective

3885:   Input Parameters:
3886: + A - the factored matrix
3887: - B - the right-hand-side matrix  (`MATDENSE` matrix)

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

3892:   Level: developer

3894:   Note:
3895:   The matrices `B` and `X` cannot be the same.  I.e., one cannot
3896:   call `MatMatSolveTranspose`(A,X,X).

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

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

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

3930:   Neighbor-wise Collective

3932:   Input Parameters:
3933: + A  - the factored matrix
3934: - Bt - the transpose of right-hand-side matrix as a `MATDENSE`

3936:   Output Parameter:
3937: . X - the result matrix (dense matrix)

3939:   Level: developer

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

3945: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatMatSolve()`, `MatMatSolveTranspose()`, `MatLUFactor()`, `MatCholeskyFactor()`
3946: @*/
3947: PetscErrorCode MatMatTransposeSolve(Mat A, Mat Bt, Mat X)
3948: {
3949:   PetscFunctionBegin;
3954:   PetscCheckSameComm(A, 1, Bt, 2);
3955:   PetscCheckSameComm(A, 1, X, 3);

3957:   PetscCheck(X != Bt, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_IDN, "X and B must be different matrices");
3958:   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);
3959:   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);
3960:   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");
3961:   if (!A->rmap->N && !A->cmap->N) PetscFunctionReturn(PETSC_SUCCESS);
3962:   PetscCheck(A->factortype, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_WRONGSTATE, "Unfactored matrix");
3963:   MatCheckPreallocated(A, 1);

3965:   PetscCall(PetscLogEventBegin(MAT_MatTrSolve, A, Bt, X, 0));
3966:   PetscUseTypeMethod(A, mattransposesolve, Bt, X);
3967:   PetscCall(PetscLogEventEnd(MAT_MatTrSolve, A, Bt, X, 0));
3968:   PetscCall(PetscObjectStateIncrease((PetscObject)X));
3969:   PetscFunctionReturn(PETSC_SUCCESS);
3970: }

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

3976:   Neighbor-wise Collective

3978:   Input Parameters:
3979: + mat - the factored matrix
3980: - b   - the right-hand-side vector

3982:   Output Parameter:
3983: . x - the result vector

3985:   Level: developer

3987:   Notes:
3988:   `MatSolve()` should be used for most applications, as it performs
3989:   a forward solve followed by a backward solve.

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

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

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

4018:   PetscCall(PetscLogEventBegin(MAT_ForwardSolve, mat, b, x, 0));
4019:   PetscUseTypeMethod(mat, forwardsolve, b, x);
4020:   PetscCall(PetscLogEventEnd(MAT_ForwardSolve, mat, b, x, 0));
4021:   PetscCall(PetscObjectStateIncrease((PetscObject)x));
4022:   PetscFunctionReturn(PETSC_SUCCESS);
4023: }

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

4029:   Neighbor-wise Collective

4031:   Input Parameters:
4032: + mat - the factored matrix
4033: - b   - the right-hand-side vector

4035:   Output Parameter:
4036: . x - the result vector

4038:   Level: developer

4040:   Notes:
4041:   `MatSolve()` should be used for most applications, as it performs
4042:   a forward solve followed by a backward solve.

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

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

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

4071:   PetscCall(PetscLogEventBegin(MAT_BackwardSolve, mat, b, x, 0));
4072:   PetscUseTypeMethod(mat, backwardsolve, b, x);
4073:   PetscCall(PetscLogEventEnd(MAT_BackwardSolve, mat, b, x, 0));
4074:   PetscCall(PetscObjectStateIncrease((PetscObject)x));
4075:   PetscFunctionReturn(PETSC_SUCCESS);
4076: }

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

4081:   Neighbor-wise Collective

4083:   Input Parameters:
4084: + mat - the factored matrix
4085: . b   - the right-hand-side vector
4086: - y   - the vector to be added to

4088:   Output Parameter:
4089: . x - the result vector

4091:   Level: developer

4093:   Note:
4094:   The vectors `b` and `x` cannot be the same.  I.e., one cannot
4095:   call `MatSolveAdd`(A,x,y,x).

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

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

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

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

4149:   Neighbor-wise Collective

4151:   Input Parameters:
4152: + mat - the factored matrix
4153: - b   - the right-hand-side vector

4155:   Output Parameter:
4156: . x - the result vector

4158:   Level: developer

4160:   Notes:
4161:   The vectors `b` and `x` cannot be the same.  I.e., one cannot
4162:   call `MatSolveTranspose`(A,x,x).

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

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

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

4199: /*@
4200:   MatSolveTransposeAdd - Computes $x = y + A^{-T} b$
4201:   factored matrix.

4203:   Neighbor-wise Collective

4205:   Input Parameters:
4206: + mat - the factored matrix
4207: . b   - the right-hand-side vector
4208: - y   - the vector to be added to

4210:   Output Parameter:
4211: . x - the result vector

4213:   Level: developer

4215:   Note:
4216:   The vectors `b` and `x` cannot be the same.  I.e., one cannot
4217:   call `MatSolveTransposeAdd`(A,x,y,x).

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

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

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

4268: // PetscClangLinter pragma disable: -fdoc-section-header-unknown
4269: /*@
4270:   MatSOR - Computes relaxation (SOR, Gauss-Seidel) sweeps.

4272:   Neighbor-wise Collective

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

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

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

4297:   Level: developer

4299:   Notes:
4300:   `SOR_LOCAL_FORWARD_SWEEP`, `SOR_LOCAL_BACKWARD_SWEEP`, and
4301:   `SOR_LOCAL_SYMMETRIC_SWEEP` perform separate independent smoothings
4302:   on each processor.

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

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

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

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

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

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

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

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

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

4373: /*@
4374:   MatCopy - Copies a matrix to another matrix.

4376:   Collective

4378:   Input Parameters:
4379: + A   - the matrix
4380: - str - `SAME_NONZERO_PATTERN` or `DIFFERENT_NONZERO_PATTERN`

4382:   Output Parameter:
4383: . B - where the copy is put

4385:   Level: intermediate

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

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

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

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

4414:   PetscCall(PetscLogEventBegin(MAT_Copy, A, B, 0, 0));
4415:   if (A->ops->copy) PetscUseTypeMethod(A, copy, B, str);
4416:   else PetscCall(MatCopy_Basic(A, B, str));

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

4425:   PetscCall(PetscLogEventEnd(MAT_Copy, A, B, 0, 0));
4426:   PetscCall(PetscObjectStateIncrease((PetscObject)B));
4427:   PetscFunctionReturn(PETSC_SUCCESS);
4428: }

4430: /*@
4431:   MatConvert - Converts a matrix to another matrix, either of the same
4432:   or different type.

4434:   Collective

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

4444:   Output Parameter:
4445: . M - pointer to place new matrix

4447:   Level: intermediate

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

4454:   Cannot be used to convert a sequential matrix to parallel or parallel to sequential,
4455:   the MPI communicator of the generated matrix is always the same as the communicator
4456:   of the input matrix.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

4612: /*@
4613:   MatFactorGetSolverType - Returns name of the package providing the factorization routines

4615:   Not Collective

4617:   Input Parameter:
4618: . mat - the matrix, must be a factored matrix

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

4623:   Level: intermediate

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

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

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

4650: typedef struct _MatSolverTypeHolder *MatSolverTypeHolder;
4651: struct _MatSolverTypeHolder {
4652:   char                       *name;
4653:   MatSolverTypeForSpecifcType handlers;
4654:   MatSolverTypeHolder         next;
4655: };

4657: static MatSolverTypeHolder MatSolverTypeHolders = NULL;

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

4662:   Logically Collective, No Fortran Support

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

4670:   Level: developer

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

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

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

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

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

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

4739:   Level: developer

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

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

4755:   PetscFunctionBegin;
4756:   if (foundtype) *foundtype = PETSC_FALSE;
4757:   if (foundmtype) *foundmtype = PETSC_FALSE;
4758:   if (createfactor) *createfactor = NULL;

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

4813: PetscErrorCode MatSolverTypeDestroy(void)
4814: {
4815:   MatSolverTypeHolder         next = MatSolverTypeHolders, prev;
4816:   MatSolverTypeForSpecifcType inext, iprev;

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

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

4839:   Logically Collective

4841:   Input Parameter:
4842: . mat - the matrix

4844:   Output Parameter:
4845: . flg - `PETSC_TRUE` if uses the ordering

4847:   Level: developer

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

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

4862: /*@
4863:   MatFactorGetPreferredOrdering - The preferred ordering for a particular matrix factor object

4865:   Logically Collective

4867:   Input Parameters:
4868: + mat   - the matrix obtained with `MatGetFactor()`
4869: - ftype - the factorization type to be used

4871:   Output Parameter:
4872: . otype - the preferred ordering type

4874:   Level: developer

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

4886: /*@
4887:   MatGetFactor - Returns a matrix suitable to calls to routines such as `MatLUFactorSymbolic()`, `MatCholeskyFactorSymbolic()`, `MatILUFactorSymbolic()`,
4888:   `MatICCFactorSymbolic()`, `MatLUFactorNumeric()`, `MatCholeskyFactorNumeric()`, `MatILUFactorNumeric()`, and
4889:   `MatICCFactorNumeric()`

4891:   Collective

4893:   Input Parameters:
4894: + mat   - the matrix
4895: . 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
4896:           the other criteria is returned
4897: - ftype - factor type, `MAT_FACTOR_LU`, `MAT_FACTOR_CHOLESKY`, `MAT_FACTOR_ICC`, `MAT_FACTOR_ILU`, `MAT_FACTOR_QR`

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

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

4907:   Level: intermediate

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

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

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

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

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

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

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

4944:   PetscFunctionBegin;

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

4951:   PetscCall(MatIsShell(mat, &shell));
4952:   if (shell) PetscCall(MatHasOperation(mat, MATOP_GET_FACTOR, &hasop));
4953:   if (hasop) {
4954:     PetscUseTypeMethod(mat, getfactor, type, ftype, f);
4955:     PetscFunctionReturn(PETSC_SUCCESS);
4956:   }

4958:   PetscCall(MatSolverTypeGet(type, ((PetscObject)mat)->type_name, ftype, &foundtype, &foundmtype, &conv));
4959:   if (!foundtype) {
4960:     if (type) {
4961:       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],
4962:               ((PetscObject)mat)->type_name, type);
4963:     } else {
4964:       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);
4965:     }
4966:   }
4967:   PetscCheck(foundmtype, PetscObjectComm((PetscObject)mat), PETSC_ERR_MISSING_FACTOR, "MatSolverType %s does not support matrix type %s", type, ((PetscObject)mat)->type_name);
4968:   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);

4970:   PetscCall((*conv)(mat, ftype, f));
4971:   if (mat->factorprefix) PetscCall(MatSetOptionsPrefix(*f, mat->factorprefix));
4972:   PetscFunctionReturn(PETSC_SUCCESS);
4973: }

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

4978:   Not Collective

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

4985:   Output Parameter:
4986: . flg - PETSC_TRUE if the factorization is available

4988:   Level: intermediate

4990:   Notes:
4991:   Some PETSc matrix formats have alternative solvers available that are contained in alternative packages
4992:   such as pastix, superlu, mumps etc.

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

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

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

5006:   PetscFunctionBegin;
5008:   PetscAssertPointer(flg, 4);

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

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

5016:   PetscCall(MatSolverTypeGet(type, ((PetscObject)mat)->type_name, ftype, NULL, NULL, &gconv));
5017:   *flg = gconv ? PETSC_TRUE : PETSC_FALSE;
5018:   PetscFunctionReturn(PETSC_SUCCESS);
5019: }

5021: /*@
5022:   MatDuplicate - Duplicates a matrix including the non-zero structure.

5024:   Collective

5026:   Input Parameters:
5027: + mat - the matrix
5028: - op  - One of `MAT_DO_NOT_COPY_VALUES`, `MAT_COPY_VALUES`, or `MAT_SHARE_NONZERO_PATTERN`.
5029:         See the manual page for `MatDuplicateOption()` for an explanation of these options.

5031:   Output Parameter:
5032: . M - pointer to place new matrix

5034:   Level: intermediate

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

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

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

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

5047: .seealso: [](ch_matrices), `Mat`, `MatCopy()`, `MatConvert()`, `MatDuplicateOption`
5048: @*/
5049: PetscErrorCode MatDuplicate(Mat mat, MatDuplicateOption op, Mat *M)
5050: {
5051:   Mat               B;
5052:   VecType           vtype;
5053:   PetscInt          i;
5054:   PetscObject       dm, container_h, container_d;
5055:   PetscErrorCodeFn *viewf;

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

5065:   PetscCall(PetscLogEventBegin(MAT_Convert, mat, 0, 0, 0));
5066:   PetscUseTypeMethod(mat, duplicate, op, M);
5067:   PetscCall(PetscLogEventEnd(MAT_Convert, mat, 0, 0, 0));
5068:   B = *M;

5070:   PetscCall(MatGetOperation(mat, MATOP_VIEW, &viewf));
5071:   if (viewf) PetscCall(MatSetOperation(B, MATOP_VIEW, viewf));
5072:   PetscCall(MatGetVecType(mat, &vtype));
5073:   PetscCall(MatSetVecType(B, vtype));

5075:   B->stencil.dim = mat->stencil.dim;
5076:   B->stencil.noc = mat->stencil.noc;
5077:   for (i = 0; i <= mat->stencil.dim + (mat->stencil.noc ? 0 : -1); i++) {
5078:     B->stencil.dims[i]   = mat->stencil.dims[i];
5079:     B->stencil.starts[i] = mat->stencil.starts[i];
5080:   }

5082:   B->nooffproczerorows = mat->nooffproczerorows;
5083:   B->nooffprocentries  = mat->nooffprocentries;

5085:   PetscCall(PetscObjectQuery((PetscObject)mat, "__PETSc_dm", &dm));
5086:   if (dm) PetscCall(PetscObjectCompose((PetscObject)B, "__PETSc_dm", dm));
5087:   PetscCall(PetscObjectQuery((PetscObject)mat, "__PETSc_MatCOOStruct_Host", &container_h));
5088:   if (container_h) PetscCall(PetscObjectCompose((PetscObject)B, "__PETSc_MatCOOStruct_Host", container_h));
5089:   PetscCall(PetscObjectQuery((PetscObject)mat, "__PETSc_MatCOOStruct_Device", &container_d));
5090:   if (container_d) PetscCall(PetscObjectCompose((PetscObject)B, "__PETSc_MatCOOStruct_Device", container_d));
5091:   if (op == MAT_COPY_VALUES) PetscCall(MatPropagateSymmetryOptions(mat, B));
5092:   PetscCall(PetscObjectStateIncrease((PetscObject)B));
5093:   PetscFunctionReturn(PETSC_SUCCESS);
5094: }

5096: /*@
5097:   MatGetDiagonal - Gets the diagonal of a matrix as a `Vec`

5099:   Logically Collective

5101:   Input Parameter:
5102: . mat - the matrix

5104:   Output Parameter:
5105: . v - the diagonal of the matrix

5107:   Level: intermediate

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

5114:   Currently only correct in parallel for square matrices.

5116: .seealso: [](ch_matrices), `Mat`, `Vec`, `MatGetRow()`, `MatCreateSubMatrices()`, `MatCreateSubMatrix()`, `MatGetRowMaxAbs()`
5117: @*/
5118: PetscErrorCode MatGetDiagonal(Mat mat, Vec v)
5119: {
5120:   PetscFunctionBegin;
5124:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
5125:   MatCheckPreallocated(mat, 1);
5126:   if (PetscDefined(USE_DEBUG)) {
5127:     PetscInt nv, row, col, ndiag;

5129:     PetscCall(VecGetLocalSize(v, &nv));
5130:     PetscCall(MatGetLocalSize(mat, &row, &col));
5131:     ndiag = PetscMin(row, col);
5132:     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);
5133:   }

5135:   PetscUseTypeMethod(mat, getdiagonal, v);
5136:   PetscCall(PetscObjectStateIncrease((PetscObject)v));
5137:   PetscFunctionReturn(PETSC_SUCCESS);
5138: }

5140: /*@
5141:   MatGetRowMin - Gets the minimum value (of the real part) of each
5142:   row of the matrix

5144:   Logically Collective

5146:   Input Parameter:
5147: . mat - the matrix

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

5153:   Level: intermediate

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

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

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

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

5186: /*@
5187:   MatGetRowMinAbs - Gets the minimum value (in absolute value) of each
5188:   row of the matrix

5190:   Logically Collective

5192:   Input Parameter:
5193: . mat - the matrix

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

5199:   Level: intermediate

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

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

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

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

5233: /*@
5234:   MatGetRowMax - Gets the maximum value (of the real part) of each
5235:   row of the matrix

5237:   Logically Collective

5239:   Input Parameter:
5240: . mat - the matrix

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

5246:   Level: intermediate

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

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

5254: .seealso: [](ch_matrices), `Mat`, `MatGetDiagonal()`, `MatCreateSubMatrices()`, `MatCreateSubMatrix()`, `MatGetRowMaxAbs()`, `MatGetRowMin()`, `MatGetRowMinAbs()`
5255: @*/
5256: PetscErrorCode MatGetRowMax(Mat mat, Vec v, PetscInt idx[])
5257: {
5258:   PetscFunctionBegin;
5262:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");

5264:   if (!mat->cmap->N) {
5265:     PetscCall(VecSet(v, PETSC_MIN_REAL));
5266:     if (idx) {
5267:       PetscInt i, m = mat->rmap->n;
5268:       for (i = 0; i < m; i++) idx[i] = -1;
5269:     }
5270:   } else {
5271:     MatCheckPreallocated(mat, 1);
5272:     PetscUseTypeMethod(mat, getrowmax, v, idx);
5273:   }
5274:   PetscCall(PetscObjectStateIncrease((PetscObject)v));
5275:   PetscFunctionReturn(PETSC_SUCCESS);
5276: }

5278: /*@
5279:   MatGetRowMaxAbs - Gets the maximum value (in absolute value) of each
5280:   row of the matrix

5282:   Logically Collective

5284:   Input Parameter:
5285: . mat - the matrix

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

5291:   Level: intermediate

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

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

5299: .seealso: [](ch_matrices), `Mat`, `MatGetDiagonal()`, `MatCreateSubMatrices()`, `MatCreateSubMatrix()`, `MatGetRowSum()`, `MatGetRowMin()`, `MatGetRowMinAbs()`
5300: @*/
5301: PetscErrorCode MatGetRowMaxAbs(Mat mat, Vec v, PetscInt idx[])
5302: {
5303:   PetscFunctionBegin;
5307:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");

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

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

5327:   Logically Collective

5329:   Input Parameter:
5330: . mat - the matrix

5332:   Output Parameter:
5333: . v - the vector for storing the sum

5335:   Level: intermediate

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

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

5349:   if (!mat->cmap->N) PetscCall(VecSet(v, 0.0));
5350:   else {
5351:     MatCheckPreallocated(mat, 1);
5352:     PetscUseTypeMethod(mat, getrowsumabs, v);
5353:   }
5354:   PetscCall(PetscObjectStateIncrease((PetscObject)v));
5355:   PetscFunctionReturn(PETSC_SUCCESS);
5356: }

5358: /*@
5359:   MatGetRowSum - Gets the sum of each row of the matrix

5361:   Logically or Neighborhood Collective

5363:   Input Parameter:
5364: . mat - the matrix

5366:   Output Parameter:
5367: . v - the vector for storing the sum of rows

5369:   Level: intermediate

5371:   Note:
5372:   This code is slow since it is not currently specialized for different formats

5374: .seealso: [](ch_matrices), `Mat`, `MatGetDiagonal()`, `MatCreateSubMatrices()`, `MatCreateSubMatrix()`, `MatGetRowMax()`, `MatGetRowMin()`, `MatGetRowMaxAbs()`, `MatGetRowMinAbs()`, `MatGetRowSumAbs()`
5375: @*/
5376: PetscErrorCode MatGetRowSum(Mat mat, Vec v)
5377: {
5378:   Vec ones;

5380:   PetscFunctionBegin;
5384:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
5385:   MatCheckPreallocated(mat, 1);
5386:   PetscCall(MatCreateVecs(mat, &ones, NULL));
5387:   PetscCall(VecSet(ones, 1.));
5388:   PetscCall(MatMult(mat, ones, v));
5389:   PetscCall(VecDestroy(&ones));
5390:   PetscFunctionReturn(PETSC_SUCCESS);
5391: }

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

5397:   Collective

5399:   Input Parameter:
5400: . mat - the matrix to provide the transpose

5402:   Output Parameter:
5403: . 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

5405:   Level: advanced

5407:   Note:
5408:   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
5409:   routine allows bypassing that call.

5411: .seealso: [](ch_matrices), `Mat`, `MatTransposeSymbolic()`, `MatTranspose()`, `MatMultTranspose()`, `MatMultTransposeAdd()`, `MatIsTranspose()`, `MatReuse`, `MAT_INITIAL_MATRIX`, `MAT_REUSE_MATRIX`, `MAT_INPLACE_MATRIX`
5412: @*/
5413: PetscErrorCode MatTransposeSetPrecursor(Mat mat, Mat B)
5414: {
5415:   MatParentState *rb = NULL;

5417:   PetscFunctionBegin;
5418:   PetscCall(PetscNew(&rb));
5419:   rb->id    = ((PetscObject)mat)->id;
5420:   rb->state = 0;
5421:   PetscCall(MatGetNonzeroState(mat, &rb->nonzerostate));
5422:   PetscCall(PetscObjectContainerCompose((PetscObject)B, "MatTransposeParent", rb, PetscCtxDestroyDefault));
5423:   PetscFunctionReturn(PETSC_SUCCESS);
5424: }

5426: static PetscErrorCode MatTranspose_Private(Mat mat, MatReuse reuse, Mat *B, PetscBool conjugate)
5427: {
5428:   PetscContainer  rB                        = NULL;
5429:   MatParentState *rb                        = NULL;
5430:   PetscErrorCode (*f)(Mat, MatReuse, Mat *) = NULL;

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

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

5462:   if (reuse == MAT_INITIAL_MATRIX) PetscCall(MatTransposeSetPrecursor(mat, *B));
5463:   if (reuse != MAT_INPLACE_MATRIX) {
5464:     PetscCall(PetscObjectQuery((PetscObject)*B, "MatTransposeParent", (PetscObject *)&rB));
5465:     PetscCall(PetscContainerGetPointer(rB, &rb));
5466:     rb->state        = ((PetscObject)mat)->state;
5467:     rb->nonzerostate = mat->nonzerostate;
5468:   }
5469:   PetscFunctionReturn(PETSC_SUCCESS);
5470: }

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

5475:   Collective

5477:   Input Parameters:
5478: + mat   - the matrix to transpose
5479: - reuse - either `MAT_INITIAL_MATRIX`, `MAT_REUSE_MATRIX`, or `MAT_INPLACE_MATRIX`

5481:   Output Parameter:
5482: . B - the transpose of the matrix

5484:   Level: intermediate

5486:   Notes:
5487:   If you use `MAT_INPLACE_MATRIX` then you must pass in `&mat` for `B`

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

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

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

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

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

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

5511: /*@
5512:   MatTransposeSymbolic - Computes the symbolic part of the transpose of a matrix.

5514:   Collective

5516:   Input Parameter:
5517: . A - the matrix to transpose

5519:   Output Parameter:
5520: . 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
5521:       numerical portion.

5523:   Level: intermediate

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

5528: .seealso: [](ch_matrices), `Mat`, `MatTransposeSetPrecursor()`, `MatTranspose()`, `MatMultTranspose()`, `MatMultTransposeAdd()`, `MatIsTranspose()`, `MatReuse`, `MAT_INITIAL_MATRIX`, `MAT_REUSE_MATRIX`, `MAT_INPLACE_MATRIX`
5529: @*/
5530: PetscErrorCode MatTransposeSymbolic(Mat A, Mat *B)
5531: {
5532:   PetscFunctionBegin;
5535:   PetscCheck(A->assembled, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
5536:   PetscCheck(!A->factortype, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
5537:   PetscCall(PetscLogEventBegin(MAT_Transpose, A, 0, 0, 0));
5538:   PetscUseTypeMethod(A, transposesymbolic, B);
5539:   PetscCall(PetscLogEventEnd(MAT_Transpose, A, 0, 0, 0));

5541:   PetscCall(MatTransposeSetPrecursor(A, *B));
5542:   PetscFunctionReturn(PETSC_SUCCESS);
5543: }

5545: PetscErrorCode MatTransposeCheckNonzeroState_Private(Mat A, Mat B)
5546: {
5547:   PetscContainer  rB;
5548:   MatParentState *rb;

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

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

5567:   Collective

5569:   Input Parameters:
5570: + A   - the matrix to test
5571: . B   - the matrix to test against, this can equal the first parameter
5572: - tol - tolerance, differences between entries smaller than this are counted as zero

5574:   Output Parameter:
5575: . flg - the result

5577:   Level: intermediate

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

5583: .seealso: [](ch_matrices), `Mat`, `MatTranspose()`, `MatIsSymmetric()`, `MatIsHermitian()`
5584: @*/
5585: PetscErrorCode MatIsTranspose(Mat A, Mat B, PetscReal tol, PetscBool *flg)
5586: {
5587:   PetscErrorCode (*f)(Mat, Mat, PetscReal, PetscBool *), (*g)(Mat, Mat, PetscReal, PetscBool *);

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

5602:     PetscCall(MatGetType(f ? B : A, &mattype));
5603:     SETERRQ(PETSC_COMM_SELF, PETSC_ERR_SUP, "Matrix of type %s does not support checking for transpose", mattype);
5604:   }
5605:   PetscFunctionReturn(PETSC_SUCCESS);
5606: }

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

5611:   Collective

5613:   Input Parameters:
5614: + mat   - the matrix to transpose and complex conjugate
5615: - reuse - either `MAT_INITIAL_MATRIX`, `MAT_REUSE_MATRIX`, or `MAT_INPLACE_MATRIX`

5617:   Output Parameter:
5618: . B - the Hermitian transpose

5620:   Level: intermediate

5622: .seealso: [](ch_matrices), `Mat`, `MatTranspose()`, `MatMultTranspose()`, `MatMultTransposeAdd()`, `MatIsTranspose()`, `MatReuse`
5623: @*/
5624: PetscErrorCode MatHermitianTranspose(Mat mat, MatReuse reuse, Mat *B)
5625: {
5626:   PetscFunctionBegin;
5627:   PetscCall(MatTranspose_Private(mat, reuse, B, PETSC_TRUE));
5628:   PetscFunctionReturn(PETSC_SUCCESS);
5629: }

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

5634:   Collective

5636:   Input Parameters:
5637: + A   - the matrix to test
5638: . B   - the matrix to test against, this can equal the first parameter
5639: - tol - tolerance, differences between entries smaller than this are counted as zero

5641:   Output Parameter:
5642: . flg - the result

5644:   Level: intermediate

5646:   Notes:
5647:   Only available for `MATAIJ` matrices.

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

5653: .seealso: [](ch_matrices), `Mat`, `MatTranspose()`, `MatIsSymmetric()`, `MatIsHermitian()`, `MatIsTranspose()`
5654: @*/
5655: PetscErrorCode MatIsHermitianTranspose(Mat A, Mat B, PetscReal tol, PetscBool *flg)
5656: {
5657:   PetscErrorCode (*f)(Mat, Mat, PetscReal, PetscBool *), (*g)(Mat, Mat, PetscReal, PetscBool *);

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

5671:     PetscCall(MatGetType(f ? B : A, &mattype));
5672:     SETERRQ(PETSC_COMM_SELF, PETSC_ERR_SUP, "Matrix of type %s does not support checking for Hermitian transpose", mattype);
5673:   }
5674:   PetscFunctionReturn(PETSC_SUCCESS);
5675: }

5677: /*@
5678:   MatPermute - Creates a new matrix with rows and columns permuted from the
5679:   original.

5681:   Collective

5683:   Input Parameters:
5684: + mat - the matrix to permute
5685: . row - row permutation, each processor supplies only the permutation for its rows
5686: - col - column permutation, each processor supplies only the permutation for its columns

5688:   Output Parameter:
5689: . B - the permuted matrix

5691:   Level: advanced

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

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

5702: .seealso: [](ch_matrices), `Mat`, `MatGetOrdering()`, `ISAllGather()`, `MatCreateSubMatrix()`
5703: @*/
5704: PetscErrorCode MatPermute(Mat mat, IS row, IS col, Mat *B)
5705: {
5706:   PetscFunctionBegin;
5711:   PetscAssertPointer(B, 4);
5712:   PetscCheckSameComm(mat, 1, row, 2);
5713:   if (row != col) PetscCheckSameComm(row, 2, col, 3);
5714:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
5715:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
5716:   PetscCheck(mat->ops->permute || mat->ops->createsubmatrix, PETSC_COMM_SELF, PETSC_ERR_SUP, "MatPermute not available for Mat type %s", ((PetscObject)mat)->type_name);
5717:   MatCheckPreallocated(mat, 1);

5719:   if (mat->ops->permute) {
5720:     PetscUseTypeMethod(mat, permute, row, col, B);
5721:     PetscCall(PetscObjectStateIncrease((PetscObject)*B));
5722:   } else {
5723:     PetscCall(MatCreateSubMatrix(mat, row, col, MAT_INITIAL_MATRIX, B));
5724:   }
5725:   PetscFunctionReturn(PETSC_SUCCESS);
5726: }

5728: /*@
5729:   MatEqual - Compares two matrices.

5731:   Collective

5733:   Input Parameters:
5734: + A - the first matrix
5735: - B - the second matrix

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

5740:   Level: intermediate

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

5746: .seealso: [](ch_matrices), `Mat`, `MatMultEqual()`
5747: @*/
5748: PetscErrorCode MatEqual(Mat A, Mat B, PetscBool *flg)
5749: {
5750:   PetscFunctionBegin;
5755:   PetscAssertPointer(flg, 3);
5756:   PetscCheckSameComm(A, 1, B, 2);
5757:   MatCheckPreallocated(A, 1);
5758:   MatCheckPreallocated(B, 2);
5759:   PetscCheck(A->assembled, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
5760:   PetscCheck(B->assembled, PetscObjectComm((PetscObject)B), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
5761:   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,
5762:              B->cmap->N);
5763:   if (A->ops->equal && A->ops->equal == B->ops->equal) PetscUseTypeMethod(A, equal, B, flg);
5764:   else PetscCall(MatMultEqual(A, B, 10, flg));
5765:   PetscFunctionReturn(PETSC_SUCCESS);
5766: }

5768: /*@
5769:   MatDiagonalScale - Scales a matrix on the left and right by diagonal
5770:   matrices that are stored as vectors.  Either of the two scaling
5771:   matrices can be `NULL`.

5773:   Collective

5775:   Input Parameters:
5776: + mat - the matrix to be scaled
5777: . l   - the left scaling vector (or `NULL`)
5778: - r   - the right scaling vector (or `NULL`)

5780:   Level: intermediate

5782:   Note:
5783:   `MatDiagonalScale()` computes $A = LAR$, where
5784:   L = a diagonal matrix (stored as a vector), R = a diagonal matrix (stored as a vector)
5785:   The L scales the rows of the matrix, the R scales the columns of the matrix.

5787: .seealso: [](ch_matrices), `Mat`, `MatScale()`, `MatShift()`, `MatDiagonalSet()`
5788: @*/
5789: PetscErrorCode MatDiagonalScale(Mat mat, Vec l, Vec r)
5790: {
5791:   PetscBool flg = PETSC_FALSE;

5793:   PetscFunctionBegin;
5796:   if (l) {
5798:     PetscCheckSameComm(mat, 1, l, 2);
5799:   }
5800:   if (r) {
5802:     PetscCheckSameComm(mat, 1, r, 3);
5803:   }
5804:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
5805:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
5806:   MatCheckPreallocated(mat, 1);
5807:   if (!l && !r) PetscFunctionReturn(PETSC_SUCCESS);

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

5829:         PetscCall(VecDuplicate(l, &conjugate));
5830:         PetscCall(VecCopy(l, conjugate));
5831:         PetscCall(VecConjugate(conjugate));
5832:         PetscCall(VecEqual(conjugate, r, &flg));
5833:         PetscCall(VecDestroy(&conjugate));
5834:       }
5835:       if (!flg) {
5836:         PetscCall(PetscObjectTypeCompareAny((PetscObject)mat, &flg, MATSEQSBAIJ, MATMPISBAIJ, ""));
5837:         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");
5838:         mat->hermitian = PETSC_BOOL3_FALSE;
5839:         mat->symmetric = mat->spd = PETSC_BOOL3_UNKNOWN;
5840:       }
5841:     }
5842:   }
5843:   PetscFunctionReturn(PETSC_SUCCESS);
5844: }

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

5849:   Logically Collective

5851:   Input Parameters:
5852: + mat - the matrix to be scaled
5853: - a   - the scaling value

5855:   Level: intermediate

5857: .seealso: [](ch_matrices), `Mat`, `MatDiagonalScale()`
5858: @*/
5859: PetscErrorCode MatScale(Mat mat, PetscScalar a)
5860: {
5861:   PetscFunctionBegin;
5864:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
5865:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
5867:   MatCheckPreallocated(mat, 1);

5869:   PetscCall(PetscLogEventBegin(MAT_Scale, mat, 0, 0, 0));
5870:   if (a != (PetscScalar)1.0) {
5871:     PetscUseTypeMethod(mat, scale, a);
5872:     PetscCall(PetscObjectStateIncrease((PetscObject)mat));
5873:   }
5874:   PetscCall(PetscLogEventEnd(MAT_Scale, mat, 0, 0, 0));
5875:   PetscFunctionReturn(PETSC_SUCCESS);
5876: }

5878: /*@
5879:   MatNorm - Calculates various norms of a matrix.

5881:   Collective

5883:   Input Parameters:
5884: + mat  - the matrix
5885: - type - the type of norm, `NORM_1`, `NORM_FROBENIUS`, `NORM_INFINITY`

5887:   Output Parameter:
5888: . nrm - the resulting norm

5890:   Level: intermediate

5892: .seealso: [](ch_matrices), `Mat`
5893: @*/
5894: PetscErrorCode MatNorm(Mat mat, NormType type, PetscReal *nrm)
5895: {
5896:   PetscFunctionBegin;
5899:   PetscAssertPointer(nrm, 3);

5901:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
5902:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
5903:   MatCheckPreallocated(mat, 1);

5905:   PetscUseTypeMethod(mat, norm, type, nrm);
5906:   PetscFunctionReturn(PETSC_SUCCESS);
5907: }

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

5918:   Collective

5920:   Input Parameters:
5921: + mat  - the matrix
5922: - type - type of assembly, either `MAT_FLUSH_ASSEMBLY` or `MAT_FINAL_ASSEMBLY`

5924:   Level: beginner

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

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

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

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

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

5956:   if (!MatAssemblyEnd_InUse) {
5957:     PetscCall(PetscLogEventBegin(MAT_AssemblyBegin, mat, 0, 0, 0));
5958:     PetscTryTypeMethod(mat, assemblybegin, type);
5959:     PetscCall(PetscLogEventEnd(MAT_AssemblyBegin, mat, 0, 0, 0));
5960:   } else PetscTryTypeMethod(mat, assemblybegin, type);
5961:   PetscFunctionReturn(PETSC_SUCCESS);
5962: }

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

5968:   Not Collective

5970:   Input Parameter:
5971: . mat - the matrix

5973:   Output Parameter:
5974: . assembled - `PETSC_TRUE` or `PETSC_FALSE`

5976:   Level: advanced

5978: .seealso: [](ch_matrices), `Mat`, `MatAssemblyEnd()`, `MatSetValues()`, `MatAssemblyBegin()`
5979: @*/
5980: PetscErrorCode MatAssembled(Mat mat, PetscBool *assembled)
5981: {
5982:   PetscFunctionBegin;
5984:   PetscAssertPointer(assembled, 2);
5985:   *assembled = mat->assembled;
5986:   PetscFunctionReturn(PETSC_SUCCESS);
5987: }

5989: /*@
5990:   MatAssemblyEnd - Completes assembling the matrix.  This routine should
5991:   be called after `MatAssemblyBegin()`.

5993:   Collective

5995:   Input Parameters:
5996: + mat  - the matrix
5997: - type - type of assembly, either `MAT_FLUSH_ASSEMBLY` or `MAT_FINAL_ASSEMBLY`

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

6002:   Level: beginner

6004: .seealso: [](ch_matrices), `Mat`, `MatAssemblyBegin()`, `MatSetValues()`, `PetscDrawOpenX()`, `PetscDrawCreate()`, `MatView()`, `MatAssembled()`, `PetscViewerSocketOpen()`,
6005:           `MatViewFromOptions()`, `PetscObjectViewFromOptions()`
6006: @*/
6007: PetscErrorCode MatAssemblyEnd(Mat mat, MatAssemblyType type)
6008: {
6009:   static PetscInt inassm = 0;
6010:   PetscBool       flg    = PETSC_FALSE;

6012:   PetscFunctionBegin;

6016:   inassm++;
6017:   MatAssemblyEnd_InUse++;
6018:   if (MatAssemblyEnd_InUse == 1) { /* Do the logging only the first time through */
6019:     PetscCall(PetscLogEventBegin(MAT_AssemblyEnd, mat, 0, 0, 0));
6020:     PetscTryTypeMethod(mat, assemblyend, type);
6021:     PetscCall(PetscLogEventEnd(MAT_AssemblyEnd, mat, 0, 0, 0));
6022:   } else PetscTryTypeMethod(mat, assemblyend, type);

6024:   /* Flush assembly is not a true assembly */
6025:   if (type != MAT_FLUSH_ASSEMBLY) {
6026:     if (mat->num_ass) {
6027:       if (!mat->symmetry_eternal) {
6028:         mat->symmetric = PETSC_BOOL3_UNKNOWN;
6029:         mat->hermitian = PETSC_BOOL3_UNKNOWN;
6030:       }
6031:       if (!mat->structural_symmetry_eternal && mat->ass_nonzerostate != mat->nonzerostate) mat->structurally_symmetric = PETSC_BOOL3_UNKNOWN;
6032:       if (!mat->spd_eternal) mat->spd = PETSC_BOOL3_UNKNOWN;
6033:     }
6034:     mat->num_ass++;
6035:     mat->assembled        = PETSC_TRUE;
6036:     mat->ass_nonzerostate = mat->nonzerostate;
6037:   }

6039:   mat->insertmode = NOT_SET_VALUES;
6040:   MatAssemblyEnd_InUse--;
6041:   PetscCall(PetscObjectStateIncrease((PetscObject)mat));
6042:   if (inassm == 1 && type != MAT_FLUSH_ASSEMBLY) {
6043:     PetscCall(MatViewFromOptions(mat, NULL, "-mat_view"));

6045:     if (mat->checksymmetryonassembly) {
6046:       PetscCall(MatIsSymmetric(mat, mat->checksymmetrytol, &flg));
6047:       if (flg) {
6048:         PetscCall(PetscPrintf(PetscObjectComm((PetscObject)mat), "Matrix is symmetric (tolerance %g)\n", (double)mat->checksymmetrytol));
6049:       } else {
6050:         PetscCall(PetscPrintf(PetscObjectComm((PetscObject)mat), "Matrix is not symmetric (tolerance %g)\n", (double)mat->checksymmetrytol));
6051:       }
6052:     }
6053:     if (mat->nullsp && mat->checknullspaceonassembly) PetscCall(MatNullSpaceTest(mat->nullsp, mat, NULL));
6054:   }
6055:   inassm--;
6056:   PetscFunctionReturn(PETSC_SUCCESS);
6057: }

6059: // PetscClangLinter pragma disable: -fdoc-section-header-unknown
6060: /*@
6061:   MatSetOption - Sets a parameter option for a matrix. Some options
6062:   may be specific to certain storage formats.  Some options
6063:   determine how values will be inserted (or added). Sorted,
6064:   row-oriented input will generally assemble the fastest. The default
6065:   is row-oriented.

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

6069:   Input Parameters:
6070: + mat - the matrix
6071: . op  - the option, one of those listed below (and possibly others),
6072: - flg - turn the option on (`PETSC_TRUE`) or off (`PETSC_FALSE`)

6074:   Options Describing Matrix Structure:
6075: + `MAT_SPD`                         - symmetric positive definite
6076: . `MAT_SYMMETRIC`                   - symmetric in terms of both structure and value
6077: . `MAT_HERMITIAN`                   - transpose is the complex conjugation
6078: . `MAT_STRUCTURALLY_SYMMETRIC`      - symmetric nonzero structure
6079: . `MAT_SYMMETRY_ETERNAL`            - indicates the symmetry (or Hermitian structure) or its absence will persist through any changes to the matrix
6080: . `MAT_STRUCTURAL_SYMMETRY_ETERNAL` - indicates the structural symmetry or its absence will persist through any changes to the matrix
6081: . `MAT_SPD_ETERNAL`                 - indicates the value of `MAT_SPD` (true or false) will persist through any changes to the matrix

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

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

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

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

6108:   Level: intermediate

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

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

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

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

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

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

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

6144:   `MAT_USE_HASH_TABLE` indicates that a hash table be used to improve the
6145:   searches during matrix assembly. When this flag is set, the hash table
6146:   is created during the first matrix assembly. This hash table is
6147:   used the next time through, during `MatSetValues()`/`MatSetValuesBlocked()`
6148:   to improve the searching of indices. `MAT_NEW_NONZERO_LOCATIONS` flag
6149:   should be used with `MAT_USE_HASH_TABLE` flag. This option is currently
6150:   supported by `MATMPIBAIJ` format only.

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

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

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

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

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

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

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

6176: .seealso: [](ch_matrices), `MatOption`, `Mat`, `MatGetOption()`
6177: @*/
6178: PetscErrorCode MatSetOption(Mat mat, MatOption op, PetscBool flg)
6179: {
6180:   PetscFunctionBegin;
6182:   if (op > 0) {
6185:   }

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

6189:   switch (op) {
6190:   case MAT_FORCE_DIAGONAL_ENTRIES:
6191:     mat->force_diagonals = flg;
6192:     PetscFunctionReturn(PETSC_SUCCESS);
6193:   case MAT_NO_OFF_PROC_ENTRIES:
6194:     mat->nooffprocentries = flg;
6195:     PetscFunctionReturn(PETSC_SUCCESS);
6196:   case MAT_SUBSET_OFF_PROC_ENTRIES:
6197:     mat->assembly_subset = flg;
6198:     if (!mat->assembly_subset) { /* See the same logic in VecAssembly wrt VEC_SUBSET_OFF_PROC_ENTRIES */
6199: #if !defined(PETSC_HAVE_MPIUNI)
6200:       PetscCall(MatStashScatterDestroy_BTS(&mat->stash));
6201: #endif
6202:       mat->stash.first_assembly_done = PETSC_FALSE;
6203:     }
6204:     PetscFunctionReturn(PETSC_SUCCESS);
6205:   case MAT_NO_OFF_PROC_ZERO_ROWS:
6206:     mat->nooffproczerorows = flg;
6207:     PetscFunctionReturn(PETSC_SUCCESS);
6208:   case MAT_SPD:
6209:     if (flg) {
6210:       mat->spd                    = PETSC_BOOL3_TRUE;
6211:       mat->symmetric              = PETSC_BOOL3_TRUE;
6212:       mat->structurally_symmetric = PETSC_BOOL3_TRUE;
6213: #if !defined(PETSC_USE_COMPLEX)
6214:       mat->hermitian = PETSC_BOOL3_TRUE;
6215: #endif
6216:     } else {
6217:       mat->spd = PETSC_BOOL3_FALSE;
6218:     }
6219:     break;
6220:   case MAT_SYMMETRIC:
6221:     mat->symmetric = PetscBoolToBool3(flg);
6222:     if (flg) mat->structurally_symmetric = PETSC_BOOL3_TRUE;
6223: #if !defined(PETSC_USE_COMPLEX)
6224:     mat->hermitian = PetscBoolToBool3(flg);
6225: #endif
6226:     break;
6227:   case MAT_HERMITIAN:
6228:     mat->hermitian = PetscBoolToBool3(flg);
6229:     if (flg) mat->structurally_symmetric = PETSC_BOOL3_TRUE;
6230: #if !defined(PETSC_USE_COMPLEX)
6231:     mat->symmetric = PetscBoolToBool3(flg);
6232: #endif
6233:     break;
6234:   case MAT_STRUCTURALLY_SYMMETRIC:
6235:     mat->structurally_symmetric = PetscBoolToBool3(flg);
6236:     break;
6237:   case MAT_SYMMETRY_ETERNAL:
6238:     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");
6239:     mat->symmetry_eternal = flg;
6240:     if (flg) mat->structural_symmetry_eternal = PETSC_TRUE;
6241:     break;
6242:   case MAT_STRUCTURAL_SYMMETRY_ETERNAL:
6243:     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");
6244:     mat->structural_symmetry_eternal = flg;
6245:     break;
6246:   case MAT_SPD_ETERNAL:
6247:     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");
6248:     mat->spd_eternal = flg;
6249:     if (flg) {
6250:       mat->structural_symmetry_eternal = PETSC_TRUE;
6251:       mat->symmetry_eternal            = PETSC_TRUE;
6252:     }
6253:     break;
6254:   case MAT_STRUCTURE_ONLY:
6255:     mat->structure_only = flg;
6256:     break;
6257:   case MAT_SORTED_FULL:
6258:     mat->sortedfull = flg;
6259:     break;
6260:   default:
6261:     break;
6262:   }
6263:   PetscTryTypeMethod(mat, setoption, op, flg);
6264:   PetscFunctionReturn(PETSC_SUCCESS);
6265: }

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

6270:   Logically Collective

6272:   Input Parameters:
6273: + mat - the matrix
6274: - op  - the option, this only responds to certain options, check the code for which ones

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

6279:   Level: intermediate

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

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

6287: .seealso: [](ch_matrices), `Mat`, `MatOption`, `MatSetOption()`, `MatIsSymmetric()`, `MatIsHermitian()`, `MatIsStructurallySymmetric()`,
6288:     `MatIsSymmetricKnown()`, `MatIsHermitianKnown()`, `MatIsStructurallySymmetricKnown()`
6289: @*/
6290: PetscErrorCode MatGetOption(Mat mat, MatOption op, PetscBool *flg)
6291: {
6292:   PetscFunctionBegin;

6296:   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);
6297:   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()");

6299:   switch (op) {
6300:   case MAT_NO_OFF_PROC_ENTRIES:
6301:     *flg = mat->nooffprocentries;
6302:     break;
6303:   case MAT_NO_OFF_PROC_ZERO_ROWS:
6304:     *flg = mat->nooffproczerorows;
6305:     break;
6306:   case MAT_SYMMETRIC:
6307:     SETERRQ(PetscObjectComm((PetscObject)mat), PETSC_ERR_SUP, "Use MatIsSymmetric() or MatIsSymmetricKnown()");
6308:     break;
6309:   case MAT_HERMITIAN:
6310:     SETERRQ(PetscObjectComm((PetscObject)mat), PETSC_ERR_SUP, "Use MatIsHermitian() or MatIsHermitianKnown()");
6311:     break;
6312:   case MAT_STRUCTURALLY_SYMMETRIC:
6313:     SETERRQ(PetscObjectComm((PetscObject)mat), PETSC_ERR_SUP, "Use MatIsStructurallySymmetric() or MatIsStructurallySymmetricKnown()");
6314:     break;
6315:   case MAT_SPD:
6316:     SETERRQ(PetscObjectComm((PetscObject)mat), PETSC_ERR_SUP, "Use MatIsSPDKnown()");
6317:     break;
6318:   case MAT_SYMMETRY_ETERNAL:
6319:     *flg = mat->symmetry_eternal;
6320:     break;
6321:   case MAT_STRUCTURAL_SYMMETRY_ETERNAL:
6322:     *flg = mat->symmetry_eternal;
6323:     break;
6324:   default:
6325:     break;
6326:   }
6327:   PetscFunctionReturn(PETSC_SUCCESS);
6328: }

6330: /*@
6331:   MatZeroEntries - Zeros all entries of a matrix.  For sparse matrices
6332:   this routine retains the old nonzero structure.

6334:   Logically Collective

6336:   Input Parameter:
6337: . mat - the matrix

6339:   Level: intermediate

6341:   Note:
6342:   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.
6343:   See the Performance chapter of the users manual for information on preallocating matrices.

6345: .seealso: [](ch_matrices), `Mat`, `MatZeroRows()`, `MatZeroRowsColumns()`
6346: @*/
6347: PetscErrorCode MatZeroEntries(Mat mat)
6348: {
6349:   PetscFunctionBegin;
6352:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
6353:   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");
6354:   MatCheckPreallocated(mat, 1);

6356:   PetscCall(PetscLogEventBegin(MAT_ZeroEntries, mat, 0, 0, 0));
6357:   PetscUseTypeMethod(mat, zeroentries);
6358:   PetscCall(PetscLogEventEnd(MAT_ZeroEntries, mat, 0, 0, 0));
6359:   PetscCall(PetscObjectStateIncrease((PetscObject)mat));
6360:   PetscFunctionReturn(PETSC_SUCCESS);
6361: }

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

6367:   Collective

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

6377:   Level: intermediate

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

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

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

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

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

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

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

6402: .seealso: [](ch_matrices), `Mat`, `MatZeroRowsIS()`, `MatZeroRows()`, `MatZeroRowsLocalIS()`, `MatZeroRowsStencil()`, `MatZeroEntries()`, `MatZeroRowsLocal()`, `MatSetOption()`,
6403:           `MatZeroRowsColumnsLocal()`, `MatZeroRowsColumnsLocalIS()`, `MatZeroRowsColumnsIS()`, `MatZeroRowsColumnsStencil()`
6404: @*/
6405: PetscErrorCode MatZeroRowsColumns(Mat mat, PetscInt numRows, const PetscInt rows[], PetscScalar diag, Vec x, Vec b)
6406: {
6407:   PetscFunctionBegin;
6410:   if (numRows) PetscAssertPointer(rows, 3);
6411:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
6412:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
6413:   MatCheckPreallocated(mat, 1);

6415:   PetscUseTypeMethod(mat, zerorowscolumns, numRows, rows, diag, x, b);
6416:   PetscCall(MatViewFromOptions(mat, NULL, "-mat_view"));
6417:   PetscCall(PetscObjectStateIncrease((PetscObject)mat));
6418:   PetscFunctionReturn(PETSC_SUCCESS);
6419: }

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

6425:   Collective

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

6434:   Level: intermediate

6436:   Note:
6437:   See `MatZeroRowsColumns()` for details on how this routine operates.

6439: .seealso: [](ch_matrices), `Mat`, `MatZeroRowsIS()`, `MatZeroRowsColumns()`, `MatZeroRowsLocalIS()`, `MatZeroRowsStencil()`, `MatZeroEntries()`, `MatZeroRowsLocal()`, `MatSetOption()`,
6440:           `MatZeroRowsColumnsLocal()`, `MatZeroRowsColumnsLocalIS()`, `MatZeroRows()`, `MatZeroRowsColumnsStencil()`
6441: @*/
6442: PetscErrorCode MatZeroRowsColumnsIS(Mat mat, IS is, PetscScalar diag, Vec x, Vec b)
6443: {
6444:   PetscInt        numRows;
6445:   const PetscInt *rows;

6447:   PetscFunctionBegin;
6452:   PetscCall(ISGetLocalSize(is, &numRows));
6453:   PetscCall(ISGetIndices(is, &rows));
6454:   PetscCall(MatZeroRowsColumns(mat, numRows, rows, diag, x, b));
6455:   PetscCall(ISRestoreIndices(is, &rows));
6456:   PetscFunctionReturn(PETSC_SUCCESS);
6457: }

6459: /*@
6460:   MatZeroRows - Zeros all entries (except possibly the main diagonal)
6461:   of a set of rows of a matrix.

6463:   Collective

6465:   Input Parameters:
6466: + mat     - the matrix
6467: . numRows - the number of rows to zero
6468: . rows    - the global row indices
6469: . diag    - value put in the diagonal of the zeroed rows
6470: . x       - optional vector of solutions for zeroed rows (other entries in vector are not used), these must be set before this call
6471: - b       - optional vector of right-hand side, that will be adjusted by provided solution entries

6473:   Level: intermediate

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

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

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

6483:   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)
6484:   from the matrix.

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

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

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

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

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

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

6509: .seealso: [](ch_matrices), `Mat`, `MatZeroRowsIS()`, `MatZeroRowsColumns()`, `MatZeroRowsLocalIS()`, `MatZeroRowsStencil()`, `MatZeroEntries()`, `MatZeroRowsLocal()`, `MatSetOption()`,
6510:           `MatZeroRowsColumnsLocal()`, `MatZeroRowsColumnsLocalIS()`, `MatZeroRowsColumnsIS()`, `MatZeroRowsColumnsStencil()`, `PCREDISTRIBUTE`, `MAT_KEEP_NONZERO_PATTERN`
6511: @*/
6512: PetscErrorCode MatZeroRows(Mat mat, PetscInt numRows, const PetscInt rows[], PetscScalar diag, Vec x, Vec b)
6513: {
6514:   PetscFunctionBegin;
6517:   if (numRows) PetscAssertPointer(rows, 3);
6518:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
6519:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
6520:   MatCheckPreallocated(mat, 1);

6522:   PetscUseTypeMethod(mat, zerorows, numRows, rows, diag, x, b);
6523:   PetscCall(MatViewFromOptions(mat, NULL, "-mat_view"));
6524:   PetscCall(PetscObjectStateIncrease((PetscObject)mat));
6525:   PetscFunctionReturn(PETSC_SUCCESS);
6526: }

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

6532:   Collective

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

6541:   Level: intermediate

6543:   Note:
6544:   See `MatZeroRows()` for details on how this routine operates.

6546: .seealso: [](ch_matrices), `Mat`, `MatZeroRows()`, `MatZeroRowsColumns()`, `MatZeroRowsLocalIS()`, `MatZeroRowsStencil()`, `MatZeroEntries()`, `MatZeroRowsLocal()`, `MatSetOption()`,
6547:           `MatZeroRowsColumnsLocal()`, `MatZeroRowsColumnsLocalIS()`, `MatZeroRowsColumnsIS()`, `MatZeroRowsColumnsStencil()`, `IS`
6548: @*/
6549: PetscErrorCode MatZeroRowsIS(Mat mat, IS is, PetscScalar diag, Vec x, Vec b)
6550: {
6551:   PetscInt        numRows = 0;
6552:   const PetscInt *rows    = NULL;

6554:   PetscFunctionBegin;
6557:   if (is) {
6559:     PetscCall(ISGetLocalSize(is, &numRows));
6560:     PetscCall(ISGetIndices(is, &rows));
6561:   }
6562:   PetscCall(MatZeroRows(mat, numRows, rows, diag, x, b));
6563:   if (is) PetscCall(ISRestoreIndices(is, &rows));
6564:   PetscFunctionReturn(PETSC_SUCCESS);
6565: }

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

6571:   Collective

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

6581:   Level: intermediate

6583:   Notes:
6584:   See `MatZeroRows()` for details on how this routine operates.

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

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

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

6596:   Fortran Note:
6597:   `idxm` and `idxn` should be declared as
6598: .vb
6599:     MatStencil idxm(4, m)
6600: .ve
6601:   and the values inserted using
6602: .vb
6603:     idxm(MatStencil_i, 1) = i
6604:     idxm(MatStencil_j, 1) = j
6605:     idxm(MatStencil_k, 1) = k
6606:     idxm(MatStencil_c, 1) = c
6607:    etc
6608: .ve

6610: .seealso: [](ch_matrices), `Mat`, `MatStencil`, `MatZeroRowsIS()`, `MatZeroRowsColumns()`, `MatZeroRowsLocalIS()`, `MatZeroRows()`, `MatZeroEntries()`, `MatZeroRowsLocal()`, `MatSetOption()`,
6611:           `MatZeroRowsColumnsLocal()`, `MatZeroRowsColumnsLocalIS()`, `MatZeroRowsColumnsIS()`, `MatZeroRowsColumnsStencil()`
6612: @*/
6613: PetscErrorCode MatZeroRowsStencil(Mat mat, PetscInt numRows, const MatStencil rows[], PetscScalar diag, Vec x, Vec b)
6614: {
6615:   PetscInt  dim    = mat->stencil.dim;
6616:   PetscInt  sdim   = dim - (1 - (PetscInt)mat->stencil.noc);
6617:   PetscInt *dims   = mat->stencil.dims + 1;
6618:   PetscInt *starts = mat->stencil.starts;
6619:   PetscInt *dxm    = (PetscInt *)rows;
6620:   PetscInt *jdxm, i, j, tmp, numNewRows = 0;

6622:   PetscFunctionBegin;
6625:   if (numRows) PetscAssertPointer(rows, 3);

6627:   PetscCall(PetscMalloc1(numRows, &jdxm));
6628:   for (i = 0; i < numRows; ++i) {
6629:     /* Skip unused dimensions (they are ordered k, j, i, c) */
6630:     for (j = 0; j < 3 - sdim; ++j) dxm++;
6631:     /* Local index in X dir */
6632:     tmp = *dxm++ - starts[0];
6633:     /* Loop over remaining dimensions */
6634:     for (j = 0; j < dim - 1; ++j) {
6635:       /* If nonlocal, set index to be negative */
6636:       if ((*dxm++ - starts[j + 1]) < 0 || tmp < 0) tmp = PETSC_INT_MIN;
6637:       /* Update local index */
6638:       else tmp = tmp * dims[j] + *(dxm - 1) - starts[j + 1];
6639:     }
6640:     /* Skip component slot if necessary */
6641:     if (mat->stencil.noc) dxm++;
6642:     /* Local row number */
6643:     if (tmp >= 0) jdxm[numNewRows++] = tmp;
6644:   }
6645:   PetscCall(MatZeroRowsLocal(mat, numNewRows, jdxm, diag, x, b));
6646:   PetscCall(PetscFree(jdxm));
6647:   PetscFunctionReturn(PETSC_SUCCESS);
6648: }

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

6654:   Collective

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

6664:   Level: intermediate

6666:   Notes:
6667:   See `MatZeroRowsColumns()` for details on how this routine operates.

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

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

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

6679:   Fortran Note:
6680:   `idxm` and `idxn` should be declared as
6681: .vb
6682:     MatStencil idxm(4, m)
6683: .ve
6684:   and the values inserted using
6685: .vb
6686:     idxm(MatStencil_i, 1) = i
6687:     idxm(MatStencil_j, 1) = j
6688:     idxm(MatStencil_k, 1) = k
6689:     idxm(MatStencil_c, 1) = c
6690:     etc
6691: .ve

6693: .seealso: [](ch_matrices), `Mat`, `MatZeroRowsIS()`, `MatZeroRowsColumns()`, `MatZeroRowsLocalIS()`, `MatZeroRowsStencil()`, `MatZeroEntries()`, `MatZeroRowsLocal()`, `MatSetOption()`,
6694:           `MatZeroRowsColumnsLocal()`, `MatZeroRowsColumnsLocalIS()`, `MatZeroRowsColumnsIS()`, `MatZeroRows()`
6695: @*/
6696: PetscErrorCode MatZeroRowsColumnsStencil(Mat mat, PetscInt numRows, const MatStencil rows[], PetscScalar diag, Vec x, Vec b)
6697: {
6698:   PetscInt  dim    = mat->stencil.dim;
6699:   PetscInt  sdim   = dim - (1 - (PetscInt)mat->stencil.noc);
6700:   PetscInt *dims   = mat->stencil.dims + 1;
6701:   PetscInt *starts = mat->stencil.starts;
6702:   PetscInt *dxm    = (PetscInt *)rows;
6703:   PetscInt *jdxm, i, j, tmp, numNewRows = 0;

6705:   PetscFunctionBegin;
6708:   if (numRows) PetscAssertPointer(rows, 3);

6710:   PetscCall(PetscMalloc1(numRows, &jdxm));
6711:   for (i = 0; i < numRows; ++i) {
6712:     /* Skip unused dimensions (they are ordered k, j, i, c) */
6713:     for (j = 0; j < 3 - sdim; ++j) dxm++;
6714:     /* Local index in X dir */
6715:     tmp = *dxm++ - starts[0];
6716:     /* Loop over remaining dimensions */
6717:     for (j = 0; j < dim - 1; ++j) {
6718:       /* If nonlocal, set index to be negative */
6719:       if ((*dxm++ - starts[j + 1]) < 0 || tmp < 0) tmp = PETSC_INT_MIN;
6720:       /* Update local index */
6721:       else tmp = tmp * dims[j] + *(dxm - 1) - starts[j + 1];
6722:     }
6723:     /* Skip component slot if necessary */
6724:     if (mat->stencil.noc) dxm++;
6725:     /* Local row number */
6726:     if (tmp >= 0) jdxm[numNewRows++] = tmp;
6727:   }
6728:   PetscCall(MatZeroRowsColumnsLocal(mat, numNewRows, jdxm, diag, x, b));
6729:   PetscCall(PetscFree(jdxm));
6730:   PetscFunctionReturn(PETSC_SUCCESS);
6731: }

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

6737:   Collective

6739:   Input Parameters:
6740: + mat     - the matrix
6741: . numRows - the number of rows to remove
6742: . rows    - the local row indices
6743: . diag    - value put in all diagonals of eliminated rows
6744: . x       - optional vector of solutions for zeroed rows (other entries in vector are not used)
6745: - b       - optional vector of right-hand side, that will be adjusted by provided solution

6747:   Level: intermediate

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

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

6755: .seealso: [](ch_matrices), `Mat`, `MatZeroRowsIS()`, `MatZeroRowsColumns()`, `MatZeroRowsLocalIS()`, `MatZeroRowsStencil()`, `MatZeroEntries()`, `MatZeroRows()`, `MatSetOption()`,
6756:           `MatZeroRowsColumnsLocal()`, `MatZeroRowsColumnsLocalIS()`, `MatZeroRowsColumnsIS()`, `MatZeroRowsColumnsStencil()`
6757: @*/
6758: PetscErrorCode MatZeroRowsLocal(Mat mat, PetscInt numRows, const PetscInt rows[], PetscScalar diag, Vec x, Vec b)
6759: {
6760:   PetscFunctionBegin;
6763:   if (numRows) PetscAssertPointer(rows, 3);
6764:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
6765:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
6766:   MatCheckPreallocated(mat, 1);

6768:   if (mat->ops->zerorowslocal) {
6769:     PetscUseTypeMethod(mat, zerorowslocal, numRows, rows, diag, x, b);
6770:   } else {
6771:     IS        is, newis;
6772:     PetscInt *newRows, nl = 0;

6774:     PetscCheck(mat->rmap->mapping, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Need to provide local to global mapping to matrix first");
6775:     PetscCall(ISCreateGeneral(PETSC_COMM_SELF, numRows, rows, PETSC_USE_POINTER, &is));
6776:     PetscCall(ISLocalToGlobalMappingApplyIS(mat->rmap->mapping, is, &newis));
6777:     PetscCall(ISGetIndices(newis, (const PetscInt **)&newRows));
6778:     for (PetscInt i = 0; i < numRows; i++)
6779:       if (newRows[i] > -1) newRows[nl++] = newRows[i];
6780:     PetscUseTypeMethod(mat, zerorows, nl, newRows, diag, x, b);
6781:     PetscCall(ISRestoreIndices(newis, (const PetscInt **)&newRows));
6782:     PetscCall(ISDestroy(&newis));
6783:     PetscCall(ISDestroy(&is));
6784:   }
6785:   PetscCall(PetscObjectStateIncrease((PetscObject)mat));
6786:   PetscFunctionReturn(PETSC_SUCCESS);
6787: }

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

6793:   Collective

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

6802:   Level: intermediate

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

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

6810: .seealso: [](ch_matrices), `Mat`, `MatZeroRowsIS()`, `MatZeroRowsColumns()`, `MatZeroRows()`, `MatZeroRowsStencil()`, `MatZeroEntries()`, `MatZeroRowsLocal()`, `MatSetOption()`,
6811:           `MatZeroRowsColumnsLocal()`, `MatZeroRowsColumnsLocalIS()`, `MatZeroRowsColumnsIS()`, `MatZeroRowsColumnsStencil()`
6812: @*/
6813: PetscErrorCode MatZeroRowsLocalIS(Mat mat, IS is, PetscScalar diag, Vec x, Vec b)
6814: {
6815:   PetscInt        numRows;
6816:   const PetscInt *rows;

6818:   PetscFunctionBegin;
6822:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
6823:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
6824:   MatCheckPreallocated(mat, 1);

6826:   PetscCall(ISGetLocalSize(is, &numRows));
6827:   PetscCall(ISGetIndices(is, &rows));
6828:   PetscCall(MatZeroRowsLocal(mat, numRows, rows, diag, x, b));
6829:   PetscCall(ISRestoreIndices(is, &rows));
6830:   PetscFunctionReturn(PETSC_SUCCESS);
6831: }

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

6837:   Collective

6839:   Input Parameters:
6840: + mat     - the matrix
6841: . numRows - the number of rows to remove
6842: . rows    - the global row indices
6843: . diag    - value put in all diagonals of eliminated rows
6844: . x       - optional vector of solutions for zeroed rows (other entries in vector are not used)
6845: - b       - optional vector of right-hand side, that will be adjusted by provided solution

6847:   Level: intermediate

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

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

6855: .seealso: [](ch_matrices), `Mat`, `MatZeroRowsIS()`, `MatZeroRowsColumns()`, `MatZeroRowsLocalIS()`, `MatZeroRowsStencil()`, `MatZeroEntries()`, `MatZeroRowsLocal()`, `MatSetOption()`,
6856:           `MatZeroRows()`, `MatZeroRowsColumnsLocalIS()`, `MatZeroRowsColumnsIS()`, `MatZeroRowsColumnsStencil()`
6857: @*/
6858: PetscErrorCode MatZeroRowsColumnsLocal(Mat mat, PetscInt numRows, const PetscInt rows[], PetscScalar diag, Vec x, Vec b)
6859: {
6860:   PetscFunctionBegin;
6863:   if (numRows) PetscAssertPointer(rows, 3);
6864:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
6865:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
6866:   MatCheckPreallocated(mat, 1);

6868:   if (mat->ops->zerorowscolumnslocal) {
6869:     PetscUseTypeMethod(mat, zerorowscolumnslocal, numRows, rows, diag, x, b);
6870:   } else {
6871:     IS        is, newis;
6872:     PetscInt *newRows, nl = 0;

6874:     PetscCheck(mat->rmap->mapping, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Need to provide local to global mapping to matrix first");
6875:     PetscCall(ISCreateGeneral(PETSC_COMM_SELF, numRows, rows, PETSC_USE_POINTER, &is));
6876:     PetscCall(ISLocalToGlobalMappingApplyIS(mat->rmap->mapping, is, &newis));
6877:     PetscCall(ISGetIndices(newis, (const PetscInt **)&newRows));
6878:     for (PetscInt i = 0; i < numRows; i++)
6879:       if (newRows[i] > -1) newRows[nl++] = newRows[i];
6880:     PetscUseTypeMethod(mat, zerorowscolumns, nl, newRows, diag, x, b);
6881:     PetscCall(ISRestoreIndices(newis, (const PetscInt **)&newRows));
6882:     PetscCall(ISDestroy(&newis));
6883:     PetscCall(ISDestroy(&is));
6884:   }
6885:   PetscCall(PetscObjectStateIncrease((PetscObject)mat));
6886:   PetscFunctionReturn(PETSC_SUCCESS);
6887: }

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

6893:   Collective

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

6902:   Level: intermediate

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

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

6910: .seealso: [](ch_matrices), `Mat`, `MatZeroRowsIS()`, `MatZeroRowsColumns()`, `MatZeroRowsLocalIS()`, `MatZeroRowsStencil()`, `MatZeroEntries()`, `MatZeroRowsLocal()`, `MatSetOption()`,
6911:           `MatZeroRowsColumnsLocal()`, `MatZeroRows()`, `MatZeroRowsColumnsIS()`, `MatZeroRowsColumnsStencil()`
6912: @*/
6913: PetscErrorCode MatZeroRowsColumnsLocalIS(Mat mat, IS is, PetscScalar diag, Vec x, Vec b)
6914: {
6915:   PetscInt        numRows;
6916:   const PetscInt *rows;

6918:   PetscFunctionBegin;
6922:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
6923:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
6924:   MatCheckPreallocated(mat, 1);

6926:   PetscCall(ISGetLocalSize(is, &numRows));
6927:   PetscCall(ISGetIndices(is, &rows));
6928:   PetscCall(MatZeroRowsColumnsLocal(mat, numRows, rows, diag, x, b));
6929:   PetscCall(ISRestoreIndices(is, &rows));
6930:   PetscFunctionReturn(PETSC_SUCCESS);
6931: }

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

6936:   Not Collective

6938:   Input Parameter:
6939: . mat - the matrix

6941:   Output Parameters:
6942: + m - the number of global rows
6943: - n - the number of global columns

6945:   Level: beginner

6947:   Note:
6948:   Both output parameters can be `NULL` on input.

6950: .seealso: [](ch_matrices), `Mat`, `MatSetSizes()`, `MatGetLocalSize()`
6951: @*/
6952: PetscErrorCode MatGetSize(Mat mat, PetscInt *m, PetscInt *n)
6953: {
6954:   PetscFunctionBegin;
6956:   if (m) *m = mat->rmap->N;
6957:   if (n) *n = mat->cmap->N;
6958:   PetscFunctionReturn(PETSC_SUCCESS);
6959: }

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

6965:   Not Collective

6967:   Input Parameter:
6968: . mat - the matrix

6970:   Output Parameters:
6971: + m - the number of local rows, use `NULL` to not obtain this value
6972: - n - the number of local columns, use `NULL` to not obtain this value

6974:   Level: beginner

6976: .seealso: [](ch_matrices), `Mat`, `MatSetSizes()`, `MatGetSize()`
6977: @*/
6978: PetscErrorCode MatGetLocalSize(Mat mat, PetscInt *m, PetscInt *n)
6979: {
6980:   PetscFunctionBegin;
6982:   if (m) PetscAssertPointer(m, 2);
6983:   if (n) PetscAssertPointer(n, 3);
6984:   if (m) *m = mat->rmap->n;
6985:   if (n) *n = mat->cmap->n;
6986:   PetscFunctionReturn(PETSC_SUCCESS);
6987: }

6989: /*@
6990:   MatGetOwnershipRangeColumn - Returns the range of matrix columns associated with rows of a
6991:   vector one multiplies this matrix by that are owned by this processor.

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

6995:   Input Parameter:
6996: . mat - the matrix

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

7002:   Level: developer

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

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

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

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

7016: .seealso: [](ch_matrices), `Mat`, `MatGetOwnershipRange()`, `MatGetOwnershipRanges()`, `MatGetOwnershipRangesColumn()`, `PetscLayout`,
7017:           `MatSetSizes()`, `MatCreateAIJ()`, `DMDAGetGhostCorners()`, `DM`
7018: @*/
7019: PetscErrorCode MatGetOwnershipRangeColumn(Mat mat, PetscInt *m, PetscInt *n)
7020: {
7021:   PetscFunctionBegin;
7024:   if (m) PetscAssertPointer(m, 2);
7025:   if (n) PetscAssertPointer(n, 3);
7026:   MatCheckPreallocated(mat, 1);
7027:   if (m) *m = mat->cmap->rstart;
7028:   if (n) *n = mat->cmap->rend;
7029:   PetscFunctionReturn(PETSC_SUCCESS);
7030: }

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

7036:   Not Collective

7038:   Input Parameter:
7039: . mat - the matrix

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

7045:   Level: beginner

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

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

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

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

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

7062: .seealso: [](ch_matrices), `Mat`, `MatGetOwnershipRanges()`, `MatGetOwnershipRangeColumn()`, `MatGetOwnershipRangesColumn()`, `PetscSplitOwnership()`,
7063:           `PetscSplitOwnershipBlock()`, `PetscLayout`, `MatSetSizes()`, `MatCreateAIJ()`, `DMDAGetGhostCorners()`, `DM`
7064: @*/
7065: PetscErrorCode MatGetOwnershipRange(Mat mat, PetscInt *m, PetscInt *n)
7066: {
7067:   PetscFunctionBegin;
7070:   if (m) PetscAssertPointer(m, 2);
7071:   if (n) PetscAssertPointer(n, 3);
7072:   MatCheckPreallocated(mat, 1);
7073:   if (m) *m = mat->rmap->rstart;
7074:   if (n) *n = mat->rmap->rend;
7075:   PetscFunctionReturn(PETSC_SUCCESS);
7076: }

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

7082:   Not Collective, unless matrix has not been allocated

7084:   Input Parameter:
7085: . mat - the matrix

7087:   Output Parameter:
7088: . ranges - start of each processors portion plus one more than the total length at the end, of length `size` + 1
7089:            where `size` is the number of MPI processes used by `mat`

7091:   Level: beginner

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

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

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

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

7106: .seealso: [](ch_matrices), `Mat`, `MatGetOwnershipRange()`, `MatGetOwnershipRangeColumn()`, `MatGetOwnershipRangesColumn()`, `PetscLayout`,
7107:           `PetscSplitOwnership()`, `PetscSplitOwnershipBlock()`, `MatSetSizes()`, `MatCreateAIJ()`,
7108:           `DMDAGetGhostCorners()`, `DM`
7109: @*/
7110: PetscErrorCode MatGetOwnershipRanges(Mat mat, const PetscInt *ranges[])
7111: {
7112:   PetscFunctionBegin;
7115:   MatCheckPreallocated(mat, 1);
7116:   PetscCall(PetscLayoutGetRanges(mat->rmap, ranges));
7117:   PetscFunctionReturn(PETSC_SUCCESS);
7118: }

7120: /*@C
7121:   MatGetOwnershipRangesColumn - Returns the ranges of matrix columns associated with rows of a
7122:   vector one multiplies this vector by that are owned by each processor.

7124:   Not Collective, unless matrix has not been allocated

7126:   Input Parameter:
7127: . mat - the matrix

7129:   Output Parameter:
7130: . ranges - start of each processors portion plus one more than the total length at the end

7132:   Level: beginner

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

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

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

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

7146: .seealso: [](ch_matrices), `Mat`, `MatGetOwnershipRange()`, `MatGetOwnershipRangeColumn()`, `MatGetOwnershipRanges()`,
7147:           `PetscSplitOwnership()`, `PetscSplitOwnershipBlock()`, `PetscLayout`, `MatSetSizes()`, `MatCreateAIJ()`,
7148:           `DMDAGetGhostCorners()`, `DM`
7149: @*/
7150: PetscErrorCode MatGetOwnershipRangesColumn(Mat mat, const PetscInt *ranges[])
7151: {
7152:   PetscFunctionBegin;
7155:   MatCheckPreallocated(mat, 1);
7156:   PetscCall(PetscLayoutGetRanges(mat->cmap, ranges));
7157:   PetscFunctionReturn(PETSC_SUCCESS);
7158: }

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

7163:   Not Collective

7165:   Input Parameter:
7166: . A - matrix

7168:   Output Parameters:
7169: + rows - rows in which this process owns elements, , use `NULL` to not obtain this value
7170: - cols - columns in which this process owns elements, use `NULL` to not obtain this value

7172:   Level: intermediate

7174:   Note:
7175:   You should call `ISDestroy()` on the returned `IS`

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

7182: .seealso: [](ch_matrices), `IS`, `Mat`, `MatGetOwnershipRanges()`, `MatSetValues()`, `MATELEMENTAL`, `MATSCALAPACK`
7183: @*/
7184: PetscErrorCode MatGetOwnershipIS(Mat A, IS *rows, IS *cols)
7185: {
7186:   PetscErrorCode (*f)(Mat, IS *, IS *);

7188:   PetscFunctionBegin;
7191:   MatCheckPreallocated(A, 1);
7192:   PetscCall(PetscObjectQueryFunction((PetscObject)A, "MatGetOwnershipIS_C", &f));
7193:   if (f) {
7194:     PetscCall((*f)(A, rows, cols));
7195:   } else { /* Create a standard row-based partition, each process is responsible for ALL columns in their row block */
7196:     if (rows) PetscCall(ISCreateStride(PETSC_COMM_SELF, A->rmap->n, A->rmap->rstart, 1, rows));
7197:     if (cols) PetscCall(ISCreateStride(PETSC_COMM_SELF, A->cmap->N, 0, 1, cols));
7198:   }
7199:   PetscFunctionReturn(PETSC_SUCCESS);
7200: }

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

7207:   Collective

7209:   Input Parameters:
7210: + fact - the factorized matrix obtained with `MatGetFactor()`
7211: . mat  - the matrix
7212: . row  - row permutation
7213: . col  - column permutation
7214: - info - structure containing
7215: .vb
7216:       levels - number of levels of fill.
7217:       expected fill - as ratio of original fill.
7218:       1 or 0 - indicating force fill on diagonal (improves robustness for matrices
7219:                 missing diagonal entries)
7220: .ve

7222:   Level: developer

7224:   Notes:
7225:   See [Matrix Factorization](sec_matfactor) for additional information.

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

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

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

7236: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatGetFactor()`, `MatLUFactorSymbolic()`, `MatLUFactorNumeric()`, `MatCholeskyFactor()`,
7237:           `MatGetOrdering()`, `MatFactorInfo`
7238: @*/
7239: PetscErrorCode MatILUFactorSymbolic(Mat fact, Mat mat, IS row, IS col, const MatFactorInfo *info)
7240: {
7241:   PetscFunctionBegin;
7246:   PetscAssertPointer(info, 5);
7247:   PetscAssertPointer(fact, 1);
7248:   PetscCheck(info->levels >= 0, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_OUTOFRANGE, "Levels of fill negative %" PetscInt_FMT, (PetscInt)info->levels);
7249:   PetscCheck(info->fill >= 1.0, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_OUTOFRANGE, "Expected fill less than 1.0 %g", (double)info->fill);
7250:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
7251:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
7252:   MatCheckPreallocated(mat, 2);

7254:   if (!fact->trivialsymbolic) PetscCall(PetscLogEventBegin(MAT_ILUFactorSymbolic, mat, row, col, 0));
7255:   PetscUseTypeMethod(fact, ilufactorsymbolic, mat, row, col, info);
7256:   if (!fact->trivialsymbolic) PetscCall(PetscLogEventEnd(MAT_ILUFactorSymbolic, mat, row, col, 0));
7257:   PetscFunctionReturn(PETSC_SUCCESS);
7258: }

7260: /*@
7261:   MatICCFactorSymbolic - Performs symbolic incomplete
7262:   Cholesky factorization for a symmetric matrix.  Use
7263:   `MatCholeskyFactorNumeric()` to complete the factorization.

7265:   Collective

7267:   Input Parameters:
7268: + fact - the factorized matrix obtained with `MatGetFactor()`
7269: . mat  - the matrix to be factored
7270: . perm - row and column permutation
7271: - info - structure containing
7272: .vb
7273:       levels - number of levels of fill.
7274:       expected fill - as ratio of original fill.
7275: .ve

7277:   Level: developer

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

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

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

7289: .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatCholeskyFactorNumeric()`, `MatCholeskyFactor()`, `MatFactorInfo`
7290: @*/
7291: PetscErrorCode MatICCFactorSymbolic(Mat fact, Mat mat, IS perm, const MatFactorInfo *info)
7292: {
7293:   PetscFunctionBegin;
7297:   PetscAssertPointer(info, 4);
7298:   PetscAssertPointer(fact, 1);
7299:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
7300:   PetscCheck(info->levels >= 0, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_OUTOFRANGE, "Levels negative %" PetscInt_FMT, (PetscInt)info->levels);
7301:   PetscCheck(info->fill >= 1.0, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_OUTOFRANGE, "Expected fill less than 1.0 %g", (double)info->fill);
7302:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
7303:   MatCheckPreallocated(mat, 2);

7305:   if (!fact->trivialsymbolic) PetscCall(PetscLogEventBegin(MAT_ICCFactorSymbolic, mat, perm, 0, 0));
7306:   PetscUseTypeMethod(fact, iccfactorsymbolic, mat, perm, info);
7307:   if (!fact->trivialsymbolic) PetscCall(PetscLogEventEnd(MAT_ICCFactorSymbolic, mat, perm, 0, 0));
7308:   PetscFunctionReturn(PETSC_SUCCESS);
7309: }

7311: /*@C
7312:   MatCreateSubMatrices - Extracts several submatrices from a matrix. If submat
7313:   points to an array of valid matrices, they may be reused to store the new
7314:   submatrices.

7316:   Collective

7318:   Input Parameters:
7319: + mat   - the matrix
7320: . n     - the number of submatrixes to be extracted (on this processor, may be zero)
7321: . irow  - index set of rows to extract
7322: . icol  - index set of columns to extract
7323: - scall - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`

7325:   Output Parameter:
7326: . submat - the array of submatrices

7328:   Level: advanced

7330:   Notes:
7331:   `MatCreateSubMatrices()` can extract ONLY sequential submatrices
7332:   (from both sequential and parallel matrices). Use `MatCreateSubMatrix()`
7333:   to extract a parallel submatrix.

7335:   Some matrix types place restrictions on the row and column
7336:   indices, such as that they be sorted or that they be equal to each other.

7338:   The index sets may not have duplicate entries.

7340:   When extracting submatrices from a parallel matrix, each processor can
7341:   form a different submatrix by setting the rows and columns of its
7342:   individual index sets according to the local submatrix desired.

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

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

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

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

7358:   Fortran Note:
7359: .vb
7360:   Mat, pointer :: submat(:)
7361: .ve

7363: .seealso: [](ch_matrices), `Mat`, `MatDestroySubMatrices()`, `MatCreateSubMatrix()`, `MatGetRow()`, `MatGetDiagonal()`, `MatReuse`
7364: @*/
7365: PetscErrorCode MatCreateSubMatrices(Mat mat, PetscInt n, const IS irow[], const IS icol[], MatReuse scall, Mat *submat[])
7366: {
7367:   PetscInt  i;
7368:   PetscBool eq;

7370:   PetscFunctionBegin;
7373:   if (n) {
7374:     PetscAssertPointer(irow, 3);
7376:     PetscAssertPointer(icol, 4);
7378:   }
7379:   PetscAssertPointer(submat, 6);
7380:   if (n && scall == MAT_REUSE_MATRIX) {
7381:     PetscAssertPointer(*submat, 6);
7383:   }
7384:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
7385:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
7386:   MatCheckPreallocated(mat, 1);
7387:   PetscCall(PetscLogEventBegin(MAT_CreateSubMats, mat, 0, 0, 0));
7388:   PetscUseTypeMethod(mat, createsubmatrices, n, irow, icol, scall, submat);
7389:   PetscCall(PetscLogEventEnd(MAT_CreateSubMats, mat, 0, 0, 0));
7390:   for (i = 0; i < n; i++) {
7391:     (*submat)[i]->factortype = MAT_FACTOR_NONE; /* in case in place factorization was previously done on submatrix */
7392:     PetscCall(ISEqualUnsorted(irow[i], icol[i], &eq));
7393:     if (eq) PetscCall(MatPropagateSymmetryOptions(mat, (*submat)[i]));
7394: #if defined(PETSC_HAVE_VIENNACL) || defined(PETSC_HAVE_CUDA) || defined(PETSC_HAVE_HIP)
7395:     if (mat->boundtocpu && mat->bindingpropagates) {
7396:       PetscCall(MatBindToCPU((*submat)[i], PETSC_TRUE));
7397:       PetscCall(MatSetBindingPropagates((*submat)[i], PETSC_TRUE));
7398:     }
7399: #endif
7400:   }
7401:   PetscFunctionReturn(PETSC_SUCCESS);
7402: }

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

7407:   Collective

7409:   Input Parameters:
7410: + mat   - the matrix
7411: . n     - the number of submatrixes to be extracted
7412: . irow  - index set of rows to extract
7413: . icol  - index set of columns to extract
7414: - scall - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`

7416:   Output Parameter:
7417: . submat - the array of submatrices

7419:   Level: advanced

7421:   Note:
7422:   This is used by `PCGASM`

7424: .seealso: [](ch_matrices), `Mat`, `PCGASM`, `MatCreateSubMatrices()`, `MatCreateSubMatrix()`, `MatGetRow()`, `MatGetDiagonal()`, `MatReuse`
7425: @*/
7426: PetscErrorCode MatCreateSubMatricesMPI(Mat mat, PetscInt n, const IS irow[], const IS icol[], MatReuse scall, Mat *submat[])
7427: {
7428:   PetscInt  i;
7429:   PetscBool eq;

7431:   PetscFunctionBegin;
7434:   if (n) {
7435:     PetscAssertPointer(irow, 3);
7437:     PetscAssertPointer(icol, 4);
7439:   }
7440:   PetscAssertPointer(submat, 6);
7441:   if (n && scall == MAT_REUSE_MATRIX) {
7442:     PetscAssertPointer(*submat, 6);
7444:   }
7445:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
7446:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
7447:   MatCheckPreallocated(mat, 1);

7449:   PetscCall(PetscLogEventBegin(MAT_CreateSubMats, mat, 0, 0, 0));
7450:   PetscUseTypeMethod(mat, createsubmatricesmpi, n, irow, icol, scall, submat);
7451:   PetscCall(PetscLogEventEnd(MAT_CreateSubMats, mat, 0, 0, 0));
7452:   for (i = 0; i < n; i++) {
7453:     PetscCall(ISEqualUnsorted(irow[i], icol[i], &eq));
7454:     if (eq) PetscCall(MatPropagateSymmetryOptions(mat, (*submat)[i]));
7455:   }
7456:   PetscFunctionReturn(PETSC_SUCCESS);
7457: }

7459: /*@C
7460:   MatDestroyMatrices - Destroys an array of matrices

7462:   Collective

7464:   Input Parameters:
7465: + n   - the number of local matrices
7466: - mat - the matrices (this is a pointer to the array of matrices)

7468:   Level: advanced

7470:   Notes:
7471:   Frees not only the matrices, but also the array that contains the matrices

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

7475: .seealso: [](ch_matrices), `Mat`, `MatCreateSubMatrices()`, `MatDestroySubMatrices()`
7476: @*/
7477: PetscErrorCode MatDestroyMatrices(PetscInt n, Mat *mat[])
7478: {
7479:   PetscInt i;

7481:   PetscFunctionBegin;
7482:   if (!*mat) PetscFunctionReturn(PETSC_SUCCESS);
7483:   PetscCheck(n >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Trying to destroy negative number of matrices %" PetscInt_FMT, n);
7484:   PetscAssertPointer(mat, 2);

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

7488:   /* memory is allocated even if n = 0 */
7489:   PetscCall(PetscFree(*mat));
7490:   PetscFunctionReturn(PETSC_SUCCESS);
7491: }

7493: /*@C
7494:   MatDestroySubMatrices - Destroys a set of matrices obtained with `MatCreateSubMatrices()`.

7496:   Collective

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

7502:   Level: advanced

7504:   Note:
7505:   Frees not only the matrices, but also the array that contains the matrices

7507: .seealso: [](ch_matrices), `Mat`, `MatCreateSubMatrices()`, `MatDestroyMatrices()`
7508: @*/
7509: PetscErrorCode MatDestroySubMatrices(PetscInt n, Mat *mat[])
7510: {
7511:   Mat mat0;

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

7519:   mat0 = (*mat)[0];
7520:   if (mat0 && mat0->ops->destroysubmatrices) {
7521:     PetscCall((*mat0->ops->destroysubmatrices)(n, mat));
7522:   } else {
7523:     PetscCall(MatDestroyMatrices(n, mat));
7524:   }
7525:   PetscFunctionReturn(PETSC_SUCCESS);
7526: }

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

7531:   Collective

7533:   Input Parameter:
7534: . mat - the matrix

7536:   Output Parameter:
7537: . matstruct - the sequential matrix with the nonzero structure of `mat`

7539:   Level: developer

7541: .seealso: [](ch_matrices), `Mat`, `MatDestroySeqNonzeroStructure()`, `MatCreateSubMatrices()`, `MatDestroyMatrices()`
7542: @*/
7543: PetscErrorCode MatGetSeqNonzeroStructure(Mat mat, Mat *matstruct)
7544: {
7545:   PetscFunctionBegin;
7547:   PetscAssertPointer(matstruct, 2);

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

7553:   PetscCall(PetscLogEventBegin(MAT_GetSeqNonzeroStructure, mat, 0, 0, 0));
7554:   PetscUseTypeMethod(mat, getseqnonzerostructure, matstruct);
7555:   PetscCall(PetscLogEventEnd(MAT_GetSeqNonzeroStructure, mat, 0, 0, 0));
7556:   PetscFunctionReturn(PETSC_SUCCESS);
7557: }

7559: /*@C
7560:   MatDestroySeqNonzeroStructure - Destroys matrix obtained with `MatGetSeqNonzeroStructure()`.

7562:   Collective

7564:   Input Parameter:
7565: . mat - the matrix

7567:   Level: advanced

7569:   Note:
7570:   This is not needed, one can just call `MatDestroy()`

7572: .seealso: [](ch_matrices), `Mat`, `MatGetSeqNonzeroStructure()`
7573: @*/
7574: PetscErrorCode MatDestroySeqNonzeroStructure(Mat *mat)
7575: {
7576:   PetscFunctionBegin;
7577:   PetscAssertPointer(mat, 1);
7578:   PetscCall(MatDestroy(mat));
7579:   PetscFunctionReturn(PETSC_SUCCESS);
7580: }

7582: /*@
7583:   MatIncreaseOverlap - Given a set of submatrices indicated by index sets,
7584:   replaces the index sets by larger ones that represent submatrices with
7585:   additional overlap.

7587:   Collective

7589:   Input Parameters:
7590: + mat - the matrix
7591: . n   - the number of index sets
7592: . is  - the array of index sets (these index sets will changed during the call)
7593: - ov  - the additional overlap requested

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

7598:   Level: developer

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

7605: .seealso: [](ch_matrices), `Mat`, `PCASM`, `MatSetBlockSize()`, `MatIncreaseOverlapSplit()`, `MatCreateSubMatrices()`
7606: @*/
7607: PetscErrorCode MatIncreaseOverlap(Mat mat, PetscInt n, IS is[], PetscInt ov)
7608: {
7609:   PetscInt i, bs, cbs;

7611:   PetscFunctionBegin;
7615:   PetscCheck(n >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Must have one or more domains, you have %" PetscInt_FMT, n);
7616:   if (n) {
7617:     PetscAssertPointer(is, 3);
7619:   }
7620:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
7621:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
7622:   MatCheckPreallocated(mat, 1);

7624:   if (!ov || !n) PetscFunctionReturn(PETSC_SUCCESS);
7625:   PetscCall(PetscLogEventBegin(MAT_IncreaseOverlap, mat, 0, 0, 0));
7626:   PetscUseTypeMethod(mat, increaseoverlap, n, is, ov);
7627:   PetscCall(PetscLogEventEnd(MAT_IncreaseOverlap, mat, 0, 0, 0));
7628:   PetscCall(MatGetBlockSizes(mat, &bs, &cbs));
7629:   if (bs == cbs) {
7630:     for (i = 0; i < n; i++) PetscCall(ISSetBlockSize(is[i], bs));
7631:   }
7632:   PetscFunctionReturn(PETSC_SUCCESS);
7633: }

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

7637: /*@
7638:   MatIncreaseOverlapSplit - Given a set of submatrices indicated by index sets across
7639:   a sub communicator, replaces the index sets by larger ones that represent submatrices with
7640:   additional overlap.

7642:   Collective

7644:   Input Parameters:
7645: + mat - the matrix
7646: . n   - the number of index sets
7647: . is  - the array of index sets (these index sets will changed during the call)
7648: - ov  - the additional overlap requested

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

7653:   Level: developer

7655: .seealso: [](ch_matrices), `Mat`, `MatCreateSubMatrices()`, `MatIncreaseOverlap()`
7656: @*/
7657: PetscErrorCode MatIncreaseOverlapSplit(Mat mat, PetscInt n, IS is[], PetscInt ov)
7658: {
7659:   PetscInt i;

7661:   PetscFunctionBegin;
7664:   PetscCheck(n >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Must have one or more domains, you have %" PetscInt_FMT, n);
7665:   if (n) {
7666:     PetscAssertPointer(is, 3);
7668:   }
7669:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
7670:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
7671:   MatCheckPreallocated(mat, 1);
7672:   if (!ov) PetscFunctionReturn(PETSC_SUCCESS);
7673:   PetscCall(PetscLogEventBegin(MAT_IncreaseOverlap, mat, 0, 0, 0));
7674:   for (i = 0; i < n; i++) PetscCall(MatIncreaseOverlapSplit_Single(mat, &is[i], ov));
7675:   PetscCall(PetscLogEventEnd(MAT_IncreaseOverlap, mat, 0, 0, 0));
7676:   PetscFunctionReturn(PETSC_SUCCESS);
7677: }

7679: /*@
7680:   MatGetBlockSize - Returns the matrix block size.

7682:   Not Collective

7684:   Input Parameter:
7685: . mat - the matrix

7687:   Output Parameter:
7688: . bs - block size

7690:   Level: intermediate

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

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

7697: .seealso: [](ch_matrices), `Mat`, `MATBAIJ`, `MATSBAIJ`, `MatCreateSeqBAIJ()`, `MatCreateBAIJ()`, `MatGetBlockSizes()`
7698: @*/
7699: PetscErrorCode MatGetBlockSize(Mat mat, PetscInt *bs)
7700: {
7701:   PetscFunctionBegin;
7703:   PetscAssertPointer(bs, 2);
7704:   *bs = mat->rmap->bs;
7705:   PetscFunctionReturn(PETSC_SUCCESS);
7706: }

7708: /*@
7709:   MatGetBlockSizes - Returns the matrix block row and column sizes.

7711:   Not Collective

7713:   Input Parameter:
7714: . mat - the matrix

7716:   Output Parameters:
7717: + rbs - row block size
7718: - cbs - column block size

7720:   Level: intermediate

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

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

7728: .seealso: [](ch_matrices), `Mat`, `MATBAIJ`, `MATSBAIJ`, `MatCreateSeqBAIJ()`, `MatCreateBAIJ()`, `MatGetBlockSize()`, `MatSetBlockSize()`, `MatSetBlockSizes()`
7729: @*/
7730: PetscErrorCode MatGetBlockSizes(Mat mat, PetscInt *rbs, PetscInt *cbs)
7731: {
7732:   PetscFunctionBegin;
7734:   if (rbs) PetscAssertPointer(rbs, 2);
7735:   if (cbs) PetscAssertPointer(cbs, 3);
7736:   if (rbs) *rbs = mat->rmap->bs;
7737:   if (cbs) *cbs = mat->cmap->bs;
7738:   PetscFunctionReturn(PETSC_SUCCESS);
7739: }

7741: /*@
7742:   MatSetBlockSize - Sets the matrix block size.

7744:   Logically Collective

7746:   Input Parameters:
7747: + mat - the matrix
7748: - bs  - block size

7750:   Level: intermediate

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

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

7759: .seealso: [](ch_matrices), `Mat`, `MATBAIJ`, `MATSBAIJ`, `MATAIJ`, `MatCreateSeqBAIJ()`, `MatCreateBAIJ()`, `MatGetBlockSize()`, `MatSetBlockSizes()`, `MatGetBlockSizes()`
7760: @*/
7761: PetscErrorCode MatSetBlockSize(Mat mat, PetscInt bs)
7762: {
7763:   PetscFunctionBegin;
7766:   PetscCall(MatSetBlockSizes(mat, bs, bs));
7767:   PetscFunctionReturn(PETSC_SUCCESS);
7768: }

7770: typedef struct {
7771:   PetscInt         n;
7772:   IS              *is;
7773:   Mat             *mat;
7774:   PetscObjectState nonzerostate;
7775:   Mat              C;
7776: } EnvelopeData;

7778: static PetscErrorCode EnvelopeDataDestroy(PetscCtxRt ptr)
7779: {
7780:   EnvelopeData *edata = *(EnvelopeData **)ptr;

7782:   PetscFunctionBegin;
7783:   for (PetscInt i = 0; i < edata->n; i++) PetscCall(ISDestroy(&edata->is[i]));
7784:   PetscCall(PetscFree(edata->is));
7785:   PetscCall(PetscFree(edata));
7786:   PetscFunctionReturn(PETSC_SUCCESS);
7787: }

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

7793:   Collective

7795:   Input Parameter:
7796: . mat - the matrix

7798:   Level: intermediate

7800:   Notes:
7801:   There can be zeros within the blocks

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

7805: .seealso: [](ch_matrices), `Mat`, `MatInvertVariableBlockEnvelope()`, `MatSetVariableBlockSizes()`
7806: @*/
7807: PetscErrorCode MatComputeVariableBlockEnvelope(Mat mat)
7808: {
7809:   PetscInt           n, *sizes, *starts, i = 0, env = 0, tbs = 0, lblocks = 0, rstart, II, ln = 0, cnt = 0, cstart, cend;
7810:   PetscInt          *diag, *odiag, sc;
7811:   VecScatter         scatter;
7812:   PetscScalar       *seqv;
7813:   const PetscScalar *parv;
7814:   const PetscInt    *ia, *ja;
7815:   PetscBool          set, flag, done;
7816:   Mat                AA = mat, A;
7817:   MPI_Comm           comm;
7818:   PetscMPIInt        rank, size, tag;
7819:   MPI_Status         status;
7820:   PetscContainer     container;
7821:   EnvelopeData      *edata;
7822:   Vec                seq, par;
7823:   IS                 isglobal;

7825:   PetscFunctionBegin;
7827:   PetscCall(MatIsSymmetricKnown(mat, &set, &flag));
7828:   if (!set || !flag) {
7829:     /* TODO: only needs nonzero structure of transpose */
7830:     PetscCall(MatTranspose(mat, MAT_INITIAL_MATRIX, &AA));
7831:     PetscCall(MatAXPY(AA, 1.0, mat, DIFFERENT_NONZERO_PATTERN));
7832:   }
7833:   PetscCall(MatAIJGetLocalMat(AA, &A));
7834:   PetscCall(MatGetRowIJ(A, 0, PETSC_FALSE, PETSC_FALSE, &n, &ia, &ja, &done));
7835:   PetscCheck(done, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "Unable to get IJ structure from matrix");

7837:   PetscCall(MatGetLocalSize(mat, &n, NULL));
7838:   PetscCall(PetscObjectGetNewTag((PetscObject)mat, &tag));
7839:   PetscCall(PetscObjectGetComm((PetscObject)mat, &comm));
7840:   PetscCallMPI(MPI_Comm_size(comm, &size));
7841:   PetscCallMPI(MPI_Comm_rank(comm, &rank));

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

7845:   if (rank > 0) {
7846:     PetscCallMPI(MPI_Recv(&env, 1, MPIU_INT, rank - 1, tag, comm, &status));
7847:     PetscCallMPI(MPI_Recv(&tbs, 1, MPIU_INT, rank - 1, tag, comm, &status));
7848:   }
7849:   PetscCall(MatGetOwnershipRange(mat, &rstart, NULL));
7850:   for (i = 0; i < n; i++) {
7851:     env = PetscMax(env, ja[ia[i + 1] - 1]);
7852:     II  = rstart + i;
7853:     if (env == II) {
7854:       starts[lblocks]  = tbs;
7855:       sizes[lblocks++] = 1 + II - tbs;
7856:       tbs              = 1 + II;
7857:     }
7858:   }
7859:   if (rank < size - 1) {
7860:     PetscCallMPI(MPI_Send(&env, 1, MPIU_INT, rank + 1, tag, comm));
7861:     PetscCallMPI(MPI_Send(&tbs, 1, MPIU_INT, rank + 1, tag, comm));
7862:   }

7864:   PetscCall(MatRestoreRowIJ(A, 0, PETSC_FALSE, PETSC_FALSE, &n, &ia, &ja, &done));
7865:   if (!set || !flag) PetscCall(MatDestroy(&AA));
7866:   PetscCall(MatDestroy(&A));

7868:   PetscCall(PetscNew(&edata));
7869:   PetscCall(MatGetNonzeroState(mat, &edata->nonzerostate));
7870:   edata->n = lblocks;
7871:   /* create IS needed for extracting blocks from the original matrix */
7872:   PetscCall(PetscMalloc1(lblocks, &edata->is));
7873:   for (PetscInt i = 0; i < lblocks; i++) PetscCall(ISCreateStride(PETSC_COMM_SELF, sizes[i], starts[i], 1, &edata->is[i]));

7875:   /* Create the resulting inverse matrix nonzero structure with preallocation information */
7876:   PetscCall(MatCreate(PetscObjectComm((PetscObject)mat), &edata->C));
7877:   PetscCall(MatSetSizes(edata->C, mat->rmap->n, mat->cmap->n, mat->rmap->N, mat->cmap->N));
7878:   PetscCall(MatSetBlockSizesFromMats(edata->C, mat, mat));
7879:   PetscCall(MatSetType(edata->C, MATAIJ));

7881:   /* Communicate the start and end of each row, from each block to the correct rank */
7882:   /* TODO: Use PetscSF instead of VecScatter */
7883:   for (PetscInt i = 0; i < lblocks; i++) ln += sizes[i];
7884:   PetscCall(VecCreateSeq(PETSC_COMM_SELF, 2 * ln, &seq));
7885:   PetscCall(VecGetArrayWrite(seq, &seqv));
7886:   for (PetscInt i = 0; i < lblocks; i++) {
7887:     for (PetscInt j = 0; j < sizes[i]; j++) {
7888:       seqv[cnt]     = starts[i];
7889:       seqv[cnt + 1] = starts[i] + sizes[i];
7890:       cnt += 2;
7891:     }
7892:   }
7893:   PetscCall(VecRestoreArrayWrite(seq, &seqv));
7894:   PetscCallMPI(MPI_Scan(&cnt, &sc, 1, MPIU_INT, MPI_SUM, PetscObjectComm((PetscObject)mat)));
7895:   sc -= cnt;
7896:   PetscCall(VecCreateMPI(PetscObjectComm((PetscObject)mat), 2 * mat->rmap->n, 2 * mat->rmap->N, &par));
7897:   PetscCall(ISCreateStride(PETSC_COMM_SELF, cnt, sc, 1, &isglobal));
7898:   PetscCall(VecScatterCreate(seq, NULL, par, isglobal, &scatter));
7899:   PetscCall(ISDestroy(&isglobal));
7900:   PetscCall(VecScatterBegin(scatter, seq, par, INSERT_VALUES, SCATTER_FORWARD));
7901:   PetscCall(VecScatterEnd(scatter, seq, par, INSERT_VALUES, SCATTER_FORWARD));
7902:   PetscCall(VecScatterDestroy(&scatter));
7903:   PetscCall(VecDestroy(&seq));
7904:   PetscCall(MatGetOwnershipRangeColumn(mat, &cstart, &cend));
7905:   PetscCall(PetscMalloc2(mat->rmap->n, &diag, mat->rmap->n, &odiag));
7906:   PetscCall(VecGetArrayRead(par, &parv));
7907:   cnt = 0;
7908:   PetscCall(MatGetSize(mat, NULL, &n));
7909:   for (PetscInt i = 0; i < mat->rmap->n; i++) {
7910:     PetscInt start, end, d = 0, od = 0;

7912:     start = (PetscInt)PetscRealPart(parv[cnt]);
7913:     end   = (PetscInt)PetscRealPart(parv[cnt + 1]);
7914:     cnt += 2;

7916:     if (start < cstart) {
7917:       od += cstart - start + n - cend;
7918:       d += cend - cstart;
7919:     } else if (start < cend) {
7920:       od += n - cend;
7921:       d += cend - start;
7922:     } else od += n - start;
7923:     if (end <= cstart) {
7924:       od -= cstart - end + n - cend;
7925:       d -= cend - cstart;
7926:     } else if (end < cend) {
7927:       od -= n - cend;
7928:       d -= cend - end;
7929:     } else od -= n - end;

7931:     odiag[i] = od;
7932:     diag[i]  = d;
7933:   }
7934:   PetscCall(VecRestoreArrayRead(par, &parv));
7935:   PetscCall(VecDestroy(&par));
7936:   PetscCall(MatXAIJSetPreallocation(edata->C, mat->rmap->bs, diag, odiag, NULL, NULL));
7937:   PetscCall(PetscFree2(diag, odiag));
7938:   PetscCall(PetscFree2(sizes, starts));

7940:   PetscCall(PetscContainerCreate(PETSC_COMM_SELF, &container));
7941:   PetscCall(PetscContainerSetPointer(container, edata));
7942:   PetscCall(PetscContainerSetCtxDestroy(container, EnvelopeDataDestroy));
7943:   PetscCall(PetscObjectCompose((PetscObject)mat, "EnvelopeData", (PetscObject)container));
7944:   PetscCall(PetscObjectDereference((PetscObject)container));
7945:   PetscFunctionReturn(PETSC_SUCCESS);
7946: }

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

7951:   Collective

7953:   Input Parameters:
7954: + A     - the matrix
7955: - reuse - indicates if the `C` matrix was obtained from a previous call to this routine

7957:   Output Parameter:
7958: . C - matrix with inverted block diagonal of `A`

7960:   Level: advanced

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

7965: .seealso: [](ch_matrices), `Mat`, `MatInvertBlockDiagonal()`, `MatComputeBlockDiagonal()`
7966: @*/
7967: PetscErrorCode MatInvertVariableBlockEnvelope(Mat A, MatReuse reuse, Mat *C)
7968: {
7969:   PetscContainer   container;
7970:   EnvelopeData    *edata;
7971:   PetscObjectState nonzerostate;

7973:   PetscFunctionBegin;
7974:   PetscCall(PetscObjectQuery((PetscObject)A, "EnvelopeData", (PetscObject *)&container));
7975:   if (!container) {
7976:     PetscCall(MatComputeVariableBlockEnvelope(A));
7977:     PetscCall(PetscObjectQuery((PetscObject)A, "EnvelopeData", (PetscObject *)&container));
7978:   }
7979:   PetscCall(PetscContainerGetPointer(container, &edata));
7980:   PetscCall(MatGetNonzeroState(A, &nonzerostate));
7981:   PetscCheck(nonzerostate <= edata->nonzerostate, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "Cannot handle changes to matrix nonzero structure");
7982:   PetscCheck(reuse != MAT_REUSE_MATRIX || *C == edata->C, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "C matrix must be the same as previously output");

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

7987:   for (PetscInt i = 0; i < edata->n; i++) {
7988:     Mat          D;
7989:     PetscScalar *dvalues;

7991:     PetscCall(MatConvert(edata->mat[i], MATSEQDENSE, MAT_INITIAL_MATRIX, &D));
7992:     PetscCall(MatSetOption(*C, MAT_ROW_ORIENTED, PETSC_FALSE));
7993:     PetscCall(MatSeqDenseInvert(D));
7994:     PetscCall(MatDenseGetArray(D, &dvalues));
7995:     PetscCall(MatSetValuesIS(*C, edata->is[i], edata->is[i], dvalues, INSERT_VALUES));
7996:     PetscCall(MatDestroy(&D));
7997:   }
7998:   PetscCall(MatDestroySubMatrices(edata->n, &edata->mat));
7999:   PetscCall(MatAssemblyBegin(*C, MAT_FINAL_ASSEMBLY));
8000:   PetscCall(MatAssemblyEnd(*C, MAT_FINAL_ASSEMBLY));
8001:   PetscFunctionReturn(PETSC_SUCCESS);
8002: }

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

8007:   Not Collective

8009:   Input Parameters:
8010: + mat     - the matrix
8011: . nblocks - the number of blocks on this process, each block can only exist on a single process
8012: - bsizes  - the block sizes

8014:   Level: intermediate

8016:   Notes:
8017:   Currently used by `PCVPBJACOBI` for `MATAIJ` matrices

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

8021: .seealso: [](ch_matrices), `Mat`, `MatCreateSeqBAIJ()`, `MatCreateBAIJ()`, `MatGetBlockSize()`, `MatSetBlockSizes()`, `MatGetBlockSizes()`, `MatGetVariableBlockSizes()`,
8022:           `MatComputeVariableBlockEnvelope()`, `PCVPBJACOBI`
8023: @*/
8024: PetscErrorCode MatSetVariableBlockSizes(Mat mat, PetscInt nblocks, const PetscInt bsizes[])
8025: {
8026:   PetscInt ncnt = 0, nlocal;

8028:   PetscFunctionBegin;
8030:   PetscCall(MatGetLocalSize(mat, &nlocal, NULL));
8031:   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);
8032:   for (PetscInt i = 0; i < nblocks; i++) ncnt += bsizes[i];
8033:   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);
8034:   PetscCall(PetscFree(mat->bsizes));
8035:   mat->nblocks = nblocks;
8036:   PetscCall(PetscMalloc1(nblocks, &mat->bsizes));
8037:   PetscCall(PetscArraycpy(mat->bsizes, bsizes, nblocks));
8038:   PetscFunctionReturn(PETSC_SUCCESS);
8039: }

8041: /*@C
8042:   MatGetVariableBlockSizes - Gets a diagonal blocks of the matrix that need not be of the same size

8044:   Not Collective; No Fortran Support

8046:   Input Parameter:
8047: . mat - the matrix

8049:   Output Parameters:
8050: + nblocks - the number of blocks on this process
8051: - bsizes  - the block sizes

8053:   Level: intermediate

8055: .seealso: [](ch_matrices), `Mat`, `MatCreateSeqBAIJ()`, `MatCreateBAIJ()`, `MatGetBlockSize()`, `MatSetBlockSizes()`, `MatGetBlockSizes()`, `MatSetVariableBlockSizes()`, `MatComputeVariableBlockEnvelope()`
8056: @*/
8057: PetscErrorCode MatGetVariableBlockSizes(Mat mat, PetscInt *nblocks, const PetscInt *bsizes[])
8058: {
8059:   PetscFunctionBegin;
8061:   if (nblocks) *nblocks = mat->nblocks;
8062:   if (bsizes) *bsizes = mat->bsizes;
8063:   PetscFunctionReturn(PETSC_SUCCESS);
8064: }

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

8069:   Not Collective

8071:   Input Parameter:
8072: + subA  - the submatrix
8073: . A     - the original matrix
8074: - isrow - The `IS` of selected rows for the submatrix, must be sorted

8076:   Level: developer

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

8081: .seealso: [](ch_matrices), `Mat`, `MatSetVariableBlockSizes()`, `MatComputeVariableBlockEnvelope()`
8082: @*/
8083: PetscErrorCode MatSelectVariableBlockSizes(Mat subA, Mat A, IS isrow)
8084: {
8085:   const PetscInt *rows;
8086:   PetscInt        n, rStart, rEnd, Nb = 0;
8087:   PetscBool       flg = A->bsizes ? PETSC_TRUE : PETSC_FALSE;

8089:   PetscFunctionBegin;
8090:   // The code for block size extraction does not support an unsorted IS
8091:   if (flg) PetscCall(ISSorted(isrow, &flg));
8092:   // We don't support originally off-diagonal blocks
8093:   if (flg) {
8094:     PetscCall(MatGetOwnershipRange(A, &rStart, &rEnd));
8095:     PetscCall(ISGetLocalSize(isrow, &n));
8096:     PetscCall(ISGetIndices(isrow, &rows));
8097:     for (PetscInt i = 0; i < n && flg; ++i) {
8098:       if (rows[i] < rStart || rows[i] >= rEnd) flg = PETSC_FALSE;
8099:     }
8100:     PetscCall(ISRestoreIndices(isrow, &rows));
8101:   }
8102:   // quiet return if we can't extract block size
8103:   PetscCallMPI(MPIU_Allreduce(MPI_IN_PLACE, &flg, 1, MPI_C_BOOL, MPI_LAND, PetscObjectComm((PetscObject)subA)));
8104:   if (!flg) PetscFunctionReturn(PETSC_SUCCESS);

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

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

8114:       if (i == n) break;
8115:       if (rows[i] == row) {
8116:         occupied = PETSC_TRUE;
8117:         ++i;
8118:       }
8119:       while (i < n && rows[i] < row) ++i;
8120:     }
8121:     gr += A->bsizes[b];
8122:     if (occupied) ++Nb;
8123:   }
8124:   subA->nblocks = Nb;
8125:   PetscCall(PetscFree(subA->bsizes));
8126:   PetscCall(PetscMalloc1(subA->nblocks, &subA->bsizes));
8127:   PetscInt sb = 0;
8128:   for (PetscInt b = 0, gr = rStart, i = 0; b < A->nblocks; ++b) {
8129:     if (sb < subA->nblocks) subA->bsizes[sb] = 0;
8130:     for (PetscInt br = 0; br < A->bsizes[b]; ++br) {
8131:       const PetscInt row = gr + br;

8133:       if (i == n) break;
8134:       if (rows[i] == row) {
8135:         ++subA->bsizes[sb];
8136:         ++i;
8137:       }
8138:       while (i < n && rows[i] < row) ++i;
8139:     }
8140:     gr += A->bsizes[b];
8141:     if (sb < subA->nblocks && subA->bsizes[sb]) ++sb;
8142:   }
8143:   PetscCheck(sb == subA->nblocks, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Invalid number of blocks %" PetscInt_FMT " != %" PetscInt_FMT, sb, subA->nblocks);
8144:   PetscInt nlocal, ncnt = 0;
8145:   PetscCall(MatGetLocalSize(subA, &nlocal, NULL));
8146:   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);
8147:   for (PetscInt i = 0; i < subA->nblocks; i++) ncnt += subA->bsizes[i];
8148:   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);
8149:   PetscCall(ISRestoreIndices(isrow, &rows));
8150:   PetscFunctionReturn(PETSC_SUCCESS);
8151: }

8153: /*@
8154:   MatSetBlockSizes - Sets the matrix block row and column sizes.

8156:   Logically Collective

8158:   Input Parameters:
8159: + mat - the matrix
8160: . rbs - row block size
8161: - cbs - column block size

8163:   Level: intermediate

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

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

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

8175: .seealso: [](ch_matrices), `Mat`, `MatCreateSeqBAIJ()`, `MatCreateBAIJ()`, `MatGetBlockSize()`, `MatSetBlockSize()`, `MatGetBlockSizes()`
8176: @*/
8177: PetscErrorCode MatSetBlockSizes(Mat mat, PetscInt rbs, PetscInt cbs)
8178: {
8179:   PetscFunctionBegin;
8183:   PetscTryTypeMethod(mat, setblocksizes, rbs, cbs);
8184:   if (mat->rmap->refcnt) {
8185:     ISLocalToGlobalMapping l2g  = NULL;
8186:     PetscLayout            nmap = NULL;

8188:     PetscCall(PetscLayoutDuplicate(mat->rmap, &nmap));
8189:     if (mat->rmap->mapping) PetscCall(ISLocalToGlobalMappingDuplicate(mat->rmap->mapping, &l2g));
8190:     PetscCall(PetscLayoutDestroy(&mat->rmap));
8191:     mat->rmap          = nmap;
8192:     mat->rmap->mapping = l2g;
8193:   }
8194:   if (mat->cmap->refcnt) {
8195:     ISLocalToGlobalMapping l2g  = NULL;
8196:     PetscLayout            nmap = NULL;

8198:     PetscCall(PetscLayoutDuplicate(mat->cmap, &nmap));
8199:     if (mat->cmap->mapping) PetscCall(ISLocalToGlobalMappingDuplicate(mat->cmap->mapping, &l2g));
8200:     PetscCall(PetscLayoutDestroy(&mat->cmap));
8201:     mat->cmap          = nmap;
8202:     mat->cmap->mapping = l2g;
8203:   }
8204:   PetscCall(PetscLayoutSetBlockSize(mat->rmap, rbs));
8205:   PetscCall(PetscLayoutSetBlockSize(mat->cmap, cbs));
8206:   PetscFunctionReturn(PETSC_SUCCESS);
8207: }

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

8212:   Logically Collective

8214:   Input Parameters:
8215: + mat     - the matrix
8216: . fromRow - matrix from which to copy row block size
8217: - fromCol - matrix from which to copy column block size (can be same as `fromRow`)

8219:   Level: developer

8221: .seealso: [](ch_matrices), `Mat`, `MatCreateSeqBAIJ()`, `MatCreateBAIJ()`, `MatGetBlockSize()`, `MatSetBlockSizes()`
8222: @*/
8223: PetscErrorCode MatSetBlockSizesFromMats(Mat mat, Mat fromRow, Mat fromCol)
8224: {
8225:   PetscFunctionBegin;
8229:   PetscTryTypeMethod(mat, setblocksizes, fromRow->rmap->bs, fromCol->cmap->bs);
8230:   PetscCall(PetscLayoutSetBlockSize(mat->rmap, fromRow->rmap->bs));
8231:   PetscCall(PetscLayoutSetBlockSize(mat->cmap, fromCol->cmap->bs));
8232:   PetscFunctionReturn(PETSC_SUCCESS);
8233: }

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

8238:   Collective

8240:   Input Parameters:
8241: + mat - the matrix
8242: . b   - the right-hand-side
8243: - x   - the approximate solution

8245:   Output Parameter:
8246: . r - location to store the residual

8248:   Level: developer

8250: .seealso: [](ch_matrices), `Mat`, `MatMult()`, `MatMultAdd()`, `PCMGSetResidual()`
8251: @*/
8252: PetscErrorCode MatResidual(Mat mat, Vec b, Vec x, Vec r)
8253: {
8254:   PetscFunctionBegin;
8260:   MatCheckPreallocated(mat, 1);
8261:   PetscCall(PetscLogEventBegin(MAT_Residual, mat, 0, 0, 0));
8262:   if (!mat->ops->residual) {
8263:     PetscCall(MatMult(mat, x, r));
8264:     PetscCall(VecAYPX(r, -1.0, b));
8265:   } else {
8266:     PetscUseTypeMethod(mat, residual, b, x, r);
8267:   }
8268:   PetscCall(PetscLogEventEnd(MAT_Residual, mat, 0, 0, 0));
8269:   PetscFunctionReturn(PETSC_SUCCESS);
8270: }

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

8275:   Collective

8277:   Input Parameters:
8278: + mat             - the matrix
8279: . shift           - 0 or 1 indicating we want the indices starting at 0 or 1
8280: . symmetric       - `PETSC_TRUE` or `PETSC_FALSE` indicating the matrix data structure should be symmetrized
8281: - inodecompressed - `PETSC_TRUE` or `PETSC_FALSE`  indicating if the nonzero structure of the
8282:                  inodes or the nonzero elements is wanted. For `MATBAIJ` matrices the compressed version is
8283:                  always used.

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

8292:   Level: developer

8294:   Notes:
8295:   You CANNOT change any of the ia[] or ja[] values.

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

8299:   Fortran Notes:
8300:   Use
8301: .vb
8302:     PetscInt, pointer :: ia(:),ja(:)
8303:     call MatGetRowIJ(mat,shift,symmetric,inodecompressed,n,ia,ja,done,ierr)
8304:     ! Access the ith and jth entries via ia(i) and ja(j)
8305: .ve

8307: .seealso: [](ch_matrices), `Mat`, `MATAIJ`, `MatGetColumnIJ()`, `MatRestoreRowIJ()`, `MatSeqAIJGetArray()`
8308: @*/
8309: PetscErrorCode MatGetRowIJ(Mat mat, PetscInt shift, PetscBool symmetric, PetscBool inodecompressed, PetscInt *n, const PetscInt *ia[], const PetscInt *ja[], PetscBool *done)
8310: {
8311:   PetscFunctionBegin;
8314:   if (n) PetscAssertPointer(n, 5);
8315:   if (ia) PetscAssertPointer(ia, 6);
8316:   if (ja) PetscAssertPointer(ja, 7);
8317:   if (done) PetscAssertPointer(done, 8);
8318:   MatCheckPreallocated(mat, 1);
8319:   if (!mat->ops->getrowij && done) *done = PETSC_FALSE;
8320:   else {
8321:     if (done) *done = PETSC_TRUE;
8322:     PetscCall(PetscLogEventBegin(MAT_GetRowIJ, mat, 0, 0, 0));
8323:     PetscUseTypeMethod(mat, getrowij, shift, symmetric, inodecompressed, n, ia, ja, done);
8324:     PetscCall(PetscLogEventEnd(MAT_GetRowIJ, mat, 0, 0, 0));
8325:   }
8326:   PetscFunctionReturn(PETSC_SUCCESS);
8327: }

8329: /*@C
8330:   MatGetColumnIJ - Returns the compressed column storage i and j indices for sequential matrices.

8332:   Collective

8334:   Input Parameters:
8335: + mat             - the matrix
8336: . shift           - 1 or zero indicating we want the indices starting at 0 or 1
8337: . symmetric       - `PETSC_TRUE` or `PETSC_FALSE` indicating the matrix data structure should be
8338:                 symmetrized
8339: - inodecompressed - `PETSC_TRUE` or `PETSC_FALSE` indicating if the nonzero structure of the
8340:                  inodes or the nonzero elements is wanted. For `MATBAIJ` matrices the compressed version is
8341:                  always used.

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

8349:   Level: developer

8351: .seealso: [](ch_matrices), `Mat`, `MatGetRowIJ()`, `MatRestoreColumnIJ()`
8352: @*/
8353: PetscErrorCode MatGetColumnIJ(Mat mat, PetscInt shift, PetscBool symmetric, PetscBool inodecompressed, PetscInt *n, const PetscInt *ia[], const PetscInt *ja[], PetscBool *done)
8354: {
8355:   PetscFunctionBegin;
8358:   PetscAssertPointer(n, 5);
8359:   if (ia) PetscAssertPointer(ia, 6);
8360:   if (ja) PetscAssertPointer(ja, 7);
8361:   PetscAssertPointer(done, 8);
8362:   MatCheckPreallocated(mat, 1);
8363:   if (!mat->ops->getcolumnij) *done = PETSC_FALSE;
8364:   else {
8365:     *done = PETSC_TRUE;
8366:     PetscUseTypeMethod(mat, getcolumnij, shift, symmetric, inodecompressed, n, ia, ja, done);
8367:   }
8368:   PetscFunctionReturn(PETSC_SUCCESS);
8369: }

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

8374:   Collective

8376:   Input Parameters:
8377: + mat             - the matrix
8378: . shift           - 1 or zero indicating we want the indices starting at 0 or 1
8379: . symmetric       - `PETSC_TRUE` or `PETSC_FALSE` indicating the matrix data structure should be symmetrized
8380: . inodecompressed - `PETSC_TRUE` or `PETSC_FALSE` indicating if the nonzero structure of the
8381:                     inodes or the nonzero elements is wanted. For `MATBAIJ` matrices the compressed version is
8382:                     always used.
8383: . n               - size of (possibly compressed) matrix
8384: . ia              - the row pointers
8385: - ja              - the column indices

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

8390:   Level: developer

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

8397: .seealso: [](ch_matrices), `Mat`, `MatGetRowIJ()`, `MatRestoreColumnIJ()`
8398: @*/
8399: PetscErrorCode MatRestoreRowIJ(Mat mat, PetscInt shift, PetscBool symmetric, PetscBool inodecompressed, PetscInt *n, const PetscInt *ia[], const PetscInt *ja[], PetscBool *done)
8400: {
8401:   PetscFunctionBegin;
8404:   if (ia) PetscAssertPointer(ia, 6);
8405:   if (ja) PetscAssertPointer(ja, 7);
8406:   if (done) PetscAssertPointer(done, 8);
8407:   MatCheckPreallocated(mat, 1);

8409:   if (!mat->ops->restorerowij && done) *done = PETSC_FALSE;
8410:   else {
8411:     if (done) *done = PETSC_TRUE;
8412:     PetscUseTypeMethod(mat, restorerowij, shift, symmetric, inodecompressed, n, ia, ja, done);
8413:     if (n) *n = 0;
8414:     if (ia) *ia = NULL;
8415:     if (ja) *ja = NULL;
8416:   }
8417:   PetscFunctionReturn(PETSC_SUCCESS);
8418: }

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

8423:   Collective

8425:   Input Parameters:
8426: + mat             - the matrix
8427: . shift           - 1 or zero indicating we want the indices starting at 0 or 1
8428: . symmetric       - `PETSC_TRUE` or `PETSC_FALSE` indicating the matrix data structure should be symmetrized
8429: - inodecompressed - `PETSC_TRUE` or `PETSC_FALSE` indicating if the nonzero structure of the
8430:                     inodes or the nonzero elements is wanted. For `MATBAIJ` matrices the compressed version is
8431:                     always used.

8433:   Output Parameters:
8434: + n    - size of (possibly compressed) matrix
8435: . ia   - the column pointers
8436: . ja   - the row indices
8437: - done - `PETSC_TRUE` or `PETSC_FALSE` indicated that the values have been returned

8439:   Level: developer

8441: .seealso: [](ch_matrices), `Mat`, `MatGetColumnIJ()`, `MatRestoreRowIJ()`
8442: @*/
8443: PetscErrorCode MatRestoreColumnIJ(Mat mat, PetscInt shift, PetscBool symmetric, PetscBool inodecompressed, PetscInt *n, const PetscInt *ia[], const PetscInt *ja[], PetscBool *done)
8444: {
8445:   PetscFunctionBegin;
8448:   if (ia) PetscAssertPointer(ia, 6);
8449:   if (ja) PetscAssertPointer(ja, 7);
8450:   PetscAssertPointer(done, 8);
8451:   MatCheckPreallocated(mat, 1);

8453:   if (!mat->ops->restorecolumnij) *done = PETSC_FALSE;
8454:   else {
8455:     *done = PETSC_TRUE;
8456:     PetscUseTypeMethod(mat, restorecolumnij, shift, symmetric, inodecompressed, n, ia, ja, done);
8457:     if (n) *n = 0;
8458:     if (ia) *ia = NULL;
8459:     if (ja) *ja = NULL;
8460:   }
8461:   PetscFunctionReturn(PETSC_SUCCESS);
8462: }

8464: /*@
8465:   MatColoringPatch - Used inside matrix coloring routines that use `MatGetRowIJ()` and/or
8466:   `MatGetColumnIJ()`.

8468:   Collective

8470:   Input Parameters:
8471: + mat        - the matrix
8472: . ncolors    - maximum color value
8473: . n          - number of entries in colorarray
8474: - colorarray - array indicating color for each column

8476:   Output Parameter:
8477: . iscoloring - coloring generated using colorarray information

8479:   Level: developer

8481: .seealso: [](ch_matrices), `Mat`, `MatGetRowIJ()`, `MatGetColumnIJ()`
8482: @*/
8483: PetscErrorCode MatColoringPatch(Mat mat, PetscInt ncolors, PetscInt n, ISColoringValue colorarray[], ISColoring *iscoloring)
8484: {
8485:   PetscFunctionBegin;
8488:   PetscAssertPointer(colorarray, 4);
8489:   PetscAssertPointer(iscoloring, 5);
8490:   MatCheckPreallocated(mat, 1);

8492:   if (!mat->ops->coloringpatch) {
8493:     PetscCall(ISColoringCreate(PetscObjectComm((PetscObject)mat), ncolors, n, colorarray, PETSC_OWN_POINTER, iscoloring));
8494:   } else {
8495:     PetscUseTypeMethod(mat, coloringpatch, ncolors, n, colorarray, iscoloring);
8496:   }
8497:   PetscFunctionReturn(PETSC_SUCCESS);
8498: }

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

8503:   Logically Collective

8505:   Input Parameter:
8506: . mat - the factored matrix to be reset

8508:   Level: developer

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

8517:   One can specify in-place ILU(0) factorization by calling
8518: .vb
8519:      PCType(pc,PCILU);
8520:      PCFactorSeUseInPlace(pc);
8521: .ve
8522:   or by using the options -pc_type ilu -pc_factor_in_place

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

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

8533: .seealso: [](ch_matrices), `Mat`, `PCFactorSetUseInPlace()`, `PCFactorGetUseInPlace()`
8534: @*/
8535: PetscErrorCode MatSetUnfactored(Mat mat)
8536: {
8537:   PetscFunctionBegin;
8540:   MatCheckPreallocated(mat, 1);
8541:   mat->factortype = MAT_FACTOR_NONE;
8542:   if (!mat->ops->setunfactored) PetscFunctionReturn(PETSC_SUCCESS);
8543:   PetscUseTypeMethod(mat, setunfactored);
8544:   PetscFunctionReturn(PETSC_SUCCESS);
8545: }

8547: /*@
8548:   MatCreateSubMatrix - Gets a single submatrix on the same number of processors
8549:   as the original matrix.

8551:   Collective

8553:   Input Parameters:
8554: + mat   - the original matrix
8555: . isrow - parallel `IS` containing the rows this processor should obtain
8556: . 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.
8557: - cll   - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`

8559:   Output Parameter:
8560: . newmat - the new submatrix, of the same type as the original matrix

8562:   Level: advanced

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

8567:   Some matrix types place restrictions on the row and column indices, such
8568:   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;
8569:   for example, if the block size is 3 one cannot select the 0 and 2 rows without selecting the 1 row.

8571:   The index sets may not have duplicate entries.

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

8579:   The communicator of the newly obtained matrix is ALWAYS the same as the communicator of
8580:   the input matrix.

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

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

8587:   Example usage:
8588:   Consider the following 8x8 matrix with 34 non-zero values, that is
8589:   assembled across 3 processors. Let's assume that proc0 owns 3 rows,
8590:   proc1 owns 3 rows, proc2 owns 2 rows. This division can be shown
8591:   as follows
8592: .vb
8593:             1  2  0  |  0  3  0  |  0  4
8594:     Proc0   0  5  6  |  7  0  0  |  8  0
8595:             9  0 10  | 11  0  0  | 12  0
8596:     -------------------------------------
8597:            13  0 14  | 15 16 17  |  0  0
8598:     Proc1   0 18  0  | 19 20 21  |  0  0
8599:             0  0  0  | 22 23  0  | 24  0
8600:     -------------------------------------
8601:     Proc2  25 26 27  |  0  0 28  | 29  0
8602:            30  0  0  | 31 32 33  |  0 34
8603: .ve

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

8607: .vb
8608:             2  0  |  0  3  0  |  0
8609:     Proc0   5  6  |  7  0  0  |  8
8610:     -------------------------------
8611:     Proc1  18  0  | 19 20 21  |  0
8612:     -------------------------------
8613:     Proc2  26 27  |  0  0 28  | 29
8614:             0  0  | 31 32 33  |  0
8615: .ve

8617: .seealso: [](ch_matrices), `Mat`, `MatCreateSubMatrices()`, `MatCreateSubMatricesMPI()`, `MatCreateSubMatrixVirtual()`, `MatSubMatrixVirtualUpdate()`
8618: @*/
8619: PetscErrorCode MatCreateSubMatrix(Mat mat, IS isrow, IS iscol, MatReuse cll, Mat *newmat)
8620: {
8621:   PetscMPIInt size;
8622:   Mat        *local;
8623:   IS          iscoltmp;
8624:   PetscBool   flg;

8626:   PetscFunctionBegin;
8630:   PetscAssertPointer(newmat, 5);
8633:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
8634:   PetscCheck(cll != MAT_IGNORE_MATRIX, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Cannot use MAT_IGNORE_MATRIX");
8635:   PetscCheck(cll != MAT_INPLACE_MATRIX, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Cannot use MAT_INPLACE_MATRIX");

8637:   MatCheckPreallocated(mat, 1);
8638:   PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)mat), &size));

8640:   if (!iscol || isrow == iscol) {
8641:     PetscBool   stride;
8642:     PetscMPIInt grabentirematrix = 0, grab;
8643:     PetscCall(PetscObjectTypeCompare((PetscObject)isrow, ISSTRIDE, &stride));
8644:     if (stride) {
8645:       PetscInt first, step, n, rstart, rend;
8646:       PetscCall(ISStrideGetInfo(isrow, &first, &step));
8647:       if (step == 1) {
8648:         PetscCall(MatGetOwnershipRange(mat, &rstart, &rend));
8649:         if (rstart == first) {
8650:           PetscCall(ISGetLocalSize(isrow, &n));
8651:           if (n == rend - rstart) grabentirematrix = 1;
8652:         }
8653:       }
8654:     }
8655:     PetscCallMPI(MPIU_Allreduce(&grabentirematrix, &grab, 1, MPI_INT, MPI_MIN, PetscObjectComm((PetscObject)mat)));
8656:     if (grab) {
8657:       PetscCall(PetscInfo(mat, "Getting entire matrix as submatrix\n"));
8658:       if (cll == MAT_INITIAL_MATRIX) {
8659:         *newmat = mat;
8660:         PetscCall(PetscObjectReference((PetscObject)mat));
8661:       }
8662:       PetscFunctionReturn(PETSC_SUCCESS);
8663:     }
8664:   }

8666:   if (!iscol) {
8667:     PetscCall(ISCreateStride(PetscObjectComm((PetscObject)mat), mat->cmap->n, mat->cmap->rstart, 1, &iscoltmp));
8668:   } else {
8669:     iscoltmp = iscol;
8670:   }

8672:   /* if original matrix is on just one processor then use submatrix generated */
8673:   if (mat->ops->createsubmatrices && !mat->ops->createsubmatrix && size == 1 && cll == MAT_REUSE_MATRIX) {
8674:     PetscCall(MatCreateSubMatrices(mat, 1, &isrow, &iscoltmp, MAT_REUSE_MATRIX, &newmat));
8675:     goto setproperties;
8676:   } else if (mat->ops->createsubmatrices && !mat->ops->createsubmatrix && size == 1) {
8677:     PetscCall(MatCreateSubMatrices(mat, 1, &isrow, &iscoltmp, MAT_INITIAL_MATRIX, &local));
8678:     *newmat = *local;
8679:     PetscCall(PetscFree(local));
8680:     goto setproperties;
8681:   } else if (!mat->ops->createsubmatrix) {
8682:     /* Create a new matrix type that implements the operation using the full matrix */
8683:     PetscCall(PetscLogEventBegin(MAT_CreateSubMat, mat, 0, 0, 0));
8684:     switch (cll) {
8685:     case MAT_INITIAL_MATRIX:
8686:       PetscCall(MatCreateSubMatrixVirtual(mat, isrow, iscoltmp, newmat));
8687:       break;
8688:     case MAT_REUSE_MATRIX:
8689:       PetscCall(MatSubMatrixVirtualUpdate(*newmat, mat, isrow, iscoltmp));
8690:       break;
8691:     default:
8692:       SETERRQ(PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_OUTOFRANGE, "Invalid MatReuse, must be either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX");
8693:     }
8694:     PetscCall(PetscLogEventEnd(MAT_CreateSubMat, mat, 0, 0, 0));
8695:     goto setproperties;
8696:   }

8698:   PetscCall(PetscLogEventBegin(MAT_CreateSubMat, mat, 0, 0, 0));
8699:   PetscUseTypeMethod(mat, createsubmatrix, isrow, iscoltmp, cll, newmat);
8700:   PetscCall(PetscLogEventEnd(MAT_CreateSubMat, mat, 0, 0, 0));

8702: setproperties:
8703:   if ((*newmat)->symmetric == PETSC_BOOL3_UNKNOWN && (*newmat)->structurally_symmetric == PETSC_BOOL3_UNKNOWN && (*newmat)->spd == PETSC_BOOL3_UNKNOWN && (*newmat)->hermitian == PETSC_BOOL3_UNKNOWN) {
8704:     PetscCall(ISEqualUnsorted(isrow, iscoltmp, &flg));
8705:     if (flg) PetscCall(MatPropagateSymmetryOptions(mat, *newmat));
8706:   }
8707:   if (!iscol) PetscCall(ISDestroy(&iscoltmp));
8708:   if (*newmat && cll == MAT_INITIAL_MATRIX) PetscCall(PetscObjectStateIncrease((PetscObject)*newmat));
8709:   if (!iscol || isrow == iscol) PetscCall(MatSelectVariableBlockSizes(*newmat, mat, isrow));
8710:   PetscFunctionReturn(PETSC_SUCCESS);
8711: }

8713: /*@
8714:   MatPropagateSymmetryOptions - Propagates symmetry options set on a matrix to another matrix

8716:   Not Collective

8718:   Input Parameters:
8719: + A - the matrix we wish to propagate options from
8720: - B - the matrix we wish to propagate options to

8722:   Level: beginner

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

8727: .seealso: [](ch_matrices), `Mat`, `MatSetOption()`, `MatIsSymmetricKnown()`, `MatIsSPDKnown()`, `MatIsHermitianKnown()`, `MatIsStructurallySymmetricKnown()`
8728: @*/
8729: PetscErrorCode MatPropagateSymmetryOptions(Mat A, Mat B)
8730: {
8731:   PetscFunctionBegin;
8734:   B->symmetry_eternal            = A->symmetry_eternal;
8735:   B->structural_symmetry_eternal = A->structural_symmetry_eternal;
8736:   B->symmetric                   = A->symmetric;
8737:   B->structurally_symmetric      = A->structurally_symmetric;
8738:   B->spd                         = A->spd;
8739:   B->hermitian                   = A->hermitian;
8740:   PetscFunctionReturn(PETSC_SUCCESS);
8741: }

8743: /*@
8744:   MatStashSetInitialSize - sets the sizes of the matrix stash, that is
8745:   used during the assembly process to store values that belong to
8746:   other processors.

8748:   Not Collective

8750:   Input Parameters:
8751: + mat   - the matrix
8752: . size  - the initial size of the stash.
8753: - bsize - the initial size of the block-stash(if used).

8755:   Options Database Keys:
8756: + -matstash_initial_size size or size0,size1,...,sizep-1            - set initial size
8757: - -matstash_block_initial_size bsize  or bsize0,bsize1,...,bsizep-1 - set initial block size

8759:   Level: intermediate

8761:   Notes:
8762:   The block-stash is used for values set with `MatSetValuesBlocked()` while
8763:   the stash is used for values set with `MatSetValues()`

8765:   Run with the option -info and look for output of the form
8766:   MatAssemblyBegin_MPIXXX:Stash has MM entries, uses nn mallocs.
8767:   to determine the appropriate value, MM, to use for size and
8768:   MatAssemblyBegin_MPIXXX:Block-Stash has BMM entries, uses nn mallocs.
8769:   to determine the value, BMM to use for bsize

8771: .seealso: [](ch_matrices), `MatAssemblyBegin()`, `MatAssemblyEnd()`, `Mat`, `MatStashGetInfo()`
8772: @*/
8773: PetscErrorCode MatStashSetInitialSize(Mat mat, PetscInt size, PetscInt bsize)
8774: {
8775:   PetscFunctionBegin;
8778:   PetscCall(MatStashSetInitialSize_Private(&mat->stash, size));
8779:   PetscCall(MatStashSetInitialSize_Private(&mat->bstash, bsize));
8780:   PetscFunctionReturn(PETSC_SUCCESS);
8781: }

8783: /*@
8784:   MatInterpolateAdd - $w = y + A*x$ or $A^T*x$ depending on the shape of
8785:   the matrix

8787:   Neighbor-wise Collective

8789:   Input Parameters:
8790: + A - the matrix
8791: . x - the vector to be multiplied by the interpolation operator
8792: - y - the vector to be added to the result

8794:   Output Parameter:
8795: . w - the resulting vector

8797:   Level: intermediate

8799:   Notes:
8800:   `w` may be the same vector as `y`.

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

8805: .seealso: [](ch_matrices), `Mat`, `MatMultAdd()`, `MatMultTransposeAdd()`, `MatRestrict()`, `PCMG`
8806: @*/
8807: PetscErrorCode MatInterpolateAdd(Mat A, Vec x, Vec y, Vec w)
8808: {
8809:   PetscInt M, N, Ny;

8811:   PetscFunctionBegin;
8816:   PetscCall(MatGetSize(A, &M, &N));
8817:   PetscCall(VecGetSize(y, &Ny));
8818:   if (M == Ny) PetscCall(MatMultAdd(A, x, y, w));
8819:   else PetscCall(MatMultTransposeAdd(A, x, y, w));
8820:   PetscFunctionReturn(PETSC_SUCCESS);
8821: }

8823: /*@
8824:   MatInterpolate - $y = A*x$ or $A^T*x$ depending on the shape of
8825:   the matrix

8827:   Neighbor-wise Collective

8829:   Input Parameters:
8830: + A - the matrix
8831: - x - the vector to be interpolated

8833:   Output Parameter:
8834: . y - the resulting vector

8836:   Level: intermediate

8838:   Note:
8839:   This allows one to use either the restriction or interpolation (its transpose)
8840:   matrix to do the interpolation

8842: .seealso: [](ch_matrices), `Mat`, `MatMultAdd()`, `MatMultTransposeAdd()`, `MatRestrict()`, `PCMG`
8843: @*/
8844: PetscErrorCode MatInterpolate(Mat A, Vec x, Vec y)
8845: {
8846:   PetscInt M, N, Ny;

8848:   PetscFunctionBegin;
8852:   PetscCall(MatGetSize(A, &M, &N));
8853:   PetscCall(VecGetSize(y, &Ny));
8854:   if (M == Ny) PetscCall(MatMult(A, x, y));
8855:   else PetscCall(MatMultTranspose(A, x, y));
8856:   PetscFunctionReturn(PETSC_SUCCESS);
8857: }

8859: /*@
8860:   MatRestrict - $y = A*x$ or $A^T*x$

8862:   Neighbor-wise Collective

8864:   Input Parameters:
8865: + A - the matrix
8866: - x - the vector to be restricted

8868:   Output Parameter:
8869: . y - the resulting vector

8871:   Level: intermediate

8873:   Note:
8874:   This allows one to use either the restriction or interpolation (its transpose)
8875:   matrix to do the restriction

8877: .seealso: [](ch_matrices), `Mat`, `MatMultAdd()`, `MatMultTransposeAdd()`, `MatInterpolate()`, `PCMG`
8878: @*/
8879: PetscErrorCode MatRestrict(Mat A, Vec x, Vec y)
8880: {
8881:   PetscInt M, N, Nx;

8883:   PetscFunctionBegin;
8887:   PetscCall(MatGetSize(A, &M, &N));
8888:   PetscCall(VecGetSize(x, &Nx));
8889:   if (M == Nx) PetscCall(MatMultTranspose(A, x, y));
8890:   else PetscCall(MatMult(A, x, y));
8891:   PetscFunctionReturn(PETSC_SUCCESS);
8892: }

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

8897:   Neighbor-wise Collective

8899:   Input Parameters:
8900: + A - the matrix
8901: . x - the input dense matrix to be multiplied
8902: - w - the input dense matrix to be added to the result

8904:   Output Parameter:
8905: . y - the output dense matrix

8907:   Level: intermediate

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

8914: .seealso: [](ch_matrices), `Mat`, `MatInterpolateAdd()`, `MatMatInterpolate()`, `MatMatRestrict()`, `PCMG`
8915: @*/
8916: PetscErrorCode MatMatInterpolateAdd(Mat A, Mat x, Mat w, Mat *y)
8917: {
8918:   PetscInt  M, N, Mx, Nx, Mo, My = 0, Ny = 0;
8919:   PetscBool trans = PETSC_TRUE;
8920:   MatReuse  reuse = MAT_INITIAL_MATRIX;

8922:   PetscFunctionBegin;
8928:   PetscCall(MatGetSize(A, &M, &N));
8929:   PetscCall(MatGetSize(x, &Mx, &Nx));
8930:   if (N == Mx) trans = PETSC_FALSE;
8931:   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);
8932:   Mo = trans ? N : M;
8933:   if (*y) {
8934:     PetscCall(MatGetSize(*y, &My, &Ny));
8935:     if (Mo == My && Nx == Ny) reuse = MAT_REUSE_MATRIX;
8936:     else {
8937:       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);
8938:       PetscCall(MatDestroy(y));
8939:     }
8940:   }

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

8945:     PetscCall(PetscObjectQuery((PetscObject)*y, "__MatMatIntAdd_w", (PetscObject *)&w));
8946:     if (w) {
8947:       PetscInt My, Ny, Mw, Nw;

8949:       PetscCall(PetscObjectTypeCompare((PetscObject)*y, ((PetscObject)w)->type_name, &flg));
8950:       PetscCall(MatGetSize(*y, &My, &Ny));
8951:       PetscCall(MatGetSize(w, &Mw, &Nw));
8952:       if (!flg || My != Mw || Ny != Nw) w = NULL;
8953:     }
8954:     if (!w) {
8955:       PetscCall(MatDuplicate(*y, MAT_COPY_VALUES, &w));
8956:       PetscCall(PetscObjectCompose((PetscObject)*y, "__MatMatIntAdd_w", (PetscObject)w));
8957:       PetscCall(PetscObjectDereference((PetscObject)w));
8958:     } else PetscCall(MatCopy(*y, w, UNKNOWN_NONZERO_PATTERN));
8959:   }
8960:   if (!trans) PetscCall(MatMatMult(A, x, reuse, PETSC_DETERMINE, y));
8961:   else PetscCall(MatTransposeMatMult(A, x, reuse, PETSC_DETERMINE, y));
8962:   if (w) PetscCall(MatAXPY(*y, 1.0, w, UNKNOWN_NONZERO_PATTERN));
8963:   PetscFunctionReturn(PETSC_SUCCESS);
8964: }

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

8969:   Neighbor-wise Collective

8971:   Input Parameters:
8972: + A - the matrix
8973: - x - the input dense matrix

8975:   Output Parameter:
8976: . y - the output dense matrix

8978:   Level: intermediate

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

8985: .seealso: [](ch_matrices), `Mat`, `MatInterpolate()`, `MatRestrict()`, `MatMatRestrict()`, `PCMG`
8986: @*/
8987: PetscErrorCode MatMatInterpolate(Mat A, Mat x, Mat *y)
8988: {
8989:   PetscFunctionBegin;
8990:   PetscCall(MatMatInterpolateAdd(A, x, NULL, y));
8991:   PetscFunctionReturn(PETSC_SUCCESS);
8992: }

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

8997:   Neighbor-wise Collective

8999:   Input Parameters:
9000: + A - the matrix
9001: - x - the input dense matrix

9003:   Output Parameter:
9004: . y - the output dense matrix

9006:   Level: intermediate

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

9013: .seealso: [](ch_matrices), `Mat`, `MatRestrict()`, `MatInterpolate()`, `MatMatInterpolate()`, `PCMG`
9014: @*/
9015: PetscErrorCode MatMatRestrict(Mat A, Mat x, Mat *y)
9016: {
9017:   PetscFunctionBegin;
9018:   PetscCall(MatMatInterpolateAdd(A, x, NULL, y));
9019:   PetscFunctionReturn(PETSC_SUCCESS);
9020: }

9022: /*@
9023:   MatGetNullSpace - retrieves the null space of a matrix.

9025:   Logically Collective

9027:   Input Parameters:
9028: + mat    - the matrix
9029: - nullsp - the null space object

9031:   Level: developer

9033: .seealso: [](ch_matrices), `Mat`, `MatCreate()`, `MatNullSpaceCreate()`, `MatSetNearNullSpace()`, `MatSetNullSpace()`, `MatNullSpace`
9034: @*/
9035: PetscErrorCode MatGetNullSpace(Mat mat, MatNullSpace *nullsp)
9036: {
9037:   PetscFunctionBegin;
9039:   PetscAssertPointer(nullsp, 2);
9040:   *nullsp = (mat->symmetric == PETSC_BOOL3_TRUE && !mat->nullsp) ? mat->transnullsp : mat->nullsp;
9041:   PetscFunctionReturn(PETSC_SUCCESS);
9042: }

9044: /*@C
9045:   MatGetNullSpaces - gets the null spaces, transpose null spaces, and near null spaces from an array of matrices

9047:   Logically Collective

9049:   Input Parameters:
9050: + n   - the number of matrices
9051: - mat - the array of matrices

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

9056:   Level: developer

9058:   Note:
9059:   Call `MatRestoreNullspaces()` to provide these to another array of matrices

9061: .seealso: [](ch_matrices), `Mat`, `MatCreate()`, `MatNullSpaceCreate()`, `MatSetNearNullSpace()`, `MatGetNullSpace()`, `MatSetTransposeNullSpace()`, `MatGetTransposeNullSpace()`,
9062:           `MatNullSpaceRemove()`, `MatRestoreNullSpaces()`
9063: @*/
9064: PetscErrorCode MatGetNullSpaces(PetscInt n, Mat mat[], MatNullSpace *nullsp[])
9065: {
9066:   PetscFunctionBegin;
9067:   PetscCheck(n >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Number of matrices %" PetscInt_FMT " must be non-negative", n);
9068:   PetscAssertPointer(mat, 2);
9069:   PetscAssertPointer(nullsp, 3);

9071:   PetscCall(PetscCalloc1(3 * n, nullsp));
9072:   for (PetscInt i = 0; i < n; i++) {
9074:     (*nullsp)[i] = mat[i]->nullsp;
9075:     PetscCall(PetscObjectReference((PetscObject)(*nullsp)[i]));
9076:     (*nullsp)[n + i] = mat[i]->nearnullsp;
9077:     PetscCall(PetscObjectReference((PetscObject)(*nullsp)[n + i]));
9078:     (*nullsp)[2 * n + i] = mat[i]->transnullsp;
9079:     PetscCall(PetscObjectReference((PetscObject)(*nullsp)[2 * n + i]));
9080:   }
9081:   PetscFunctionReturn(PETSC_SUCCESS);
9082: }

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

9087:   Logically Collective

9089:   Input Parameters:
9090: + n      - the number of matrices
9091: . mat    - the array of matrices
9092: - nullsp - an array of null spaces

9094:   Level: developer

9096:   Note:
9097:   Call `MatGetNullSpaces()` to create `nullsp`

9099: .seealso: [](ch_matrices), `Mat`, `MatCreate()`, `MatNullSpaceCreate()`, `MatSetNearNullSpace()`, `MatGetNullSpace()`, `MatSetTransposeNullSpace()`, `MatGetTransposeNullSpace()`,
9100:           `MatNullSpaceRemove()`, `MatGetNullSpaces()`
9101: @*/
9102: PetscErrorCode MatRestoreNullSpaces(PetscInt n, Mat mat[], MatNullSpace *nullsp[])
9103: {
9104:   PetscFunctionBegin;
9105:   PetscCheck(n >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Number of matrices %" PetscInt_FMT " must be non-negative", n);
9106:   PetscAssertPointer(mat, 2);
9107:   PetscAssertPointer(nullsp, 3);
9108:   PetscAssertPointer(*nullsp, 3);

9110:   for (PetscInt i = 0; i < n; i++) {
9112:     PetscCall(MatSetNullSpace(mat[i], (*nullsp)[i]));
9113:     PetscCall(PetscObjectDereference((PetscObject)(*nullsp)[i]));
9114:     PetscCall(MatSetNearNullSpace(mat[i], (*nullsp)[n + i]));
9115:     PetscCall(PetscObjectDereference((PetscObject)(*nullsp)[n + i]));
9116:     PetscCall(MatSetTransposeNullSpace(mat[i], (*nullsp)[2 * n + i]));
9117:     PetscCall(PetscObjectDereference((PetscObject)(*nullsp)[2 * n + i]));
9118:   }
9119:   PetscCall(PetscFree(*nullsp));
9120:   PetscFunctionReturn(PETSC_SUCCESS);
9121: }

9123: /*@
9124:   MatSetNullSpace - attaches a null space to a matrix.

9126:   Logically Collective

9128:   Input Parameters:
9129: + mat    - the matrix
9130: - nullsp - the null space object

9132:   Level: advanced

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

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

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

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

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

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

9155: .seealso: [](ch_matrices), `Mat`, `MatCreate()`, `MatNullSpaceCreate()`, `MatSetNearNullSpace()`, `MatGetNullSpace()`, `MatSetTransposeNullSpace()`, `MatGetTransposeNullSpace()`, `MatNullSpaceRemove()`,
9156:           `KSPSetPCSide()`
9157: @*/
9158: PetscErrorCode MatSetNullSpace(Mat mat, MatNullSpace nullsp)
9159: {
9160:   PetscFunctionBegin;
9163:   PetscCall(PetscObjectReference((PetscObject)nullsp));
9164:   PetscCall(MatNullSpaceDestroy(&mat->nullsp));
9165:   mat->nullsp = nullsp;
9166:   if (mat->symmetric == PETSC_BOOL3_TRUE) PetscCall(MatSetTransposeNullSpace(mat, nullsp));
9167:   PetscFunctionReturn(PETSC_SUCCESS);
9168: }

9170: /*@
9171:   MatGetTransposeNullSpace - retrieves the null space of the transpose of a matrix.

9173:   Logically Collective

9175:   Input Parameters:
9176: + mat    - the matrix
9177: - nullsp - the null space object

9179:   Level: developer

9181: .seealso: [](ch_matrices), `Mat`, `MatNullSpace`, `MatCreate()`, `MatNullSpaceCreate()`, `MatSetNearNullSpace()`, `MatSetTransposeNullSpace()`, `MatSetNullSpace()`, `MatGetNullSpace()`
9182: @*/
9183: PetscErrorCode MatGetTransposeNullSpace(Mat mat, MatNullSpace *nullsp)
9184: {
9185:   PetscFunctionBegin;
9188:   PetscAssertPointer(nullsp, 2);
9189:   *nullsp = (mat->symmetric == PETSC_BOOL3_TRUE && !mat->transnullsp) ? mat->nullsp : mat->transnullsp;
9190:   PetscFunctionReturn(PETSC_SUCCESS);
9191: }

9193: /*@
9194:   MatSetTransposeNullSpace - attaches the null space of a transpose of a matrix to the matrix

9196:   Logically Collective

9198:   Input Parameters:
9199: + mat    - the matrix
9200: - nullsp - the null space object

9202:   Level: advanced

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

9207:   See `MatSetNullSpace()`

9209: .seealso: [](ch_matrices), `Mat`, `MatNullSpace`, `MatCreate()`, `MatNullSpaceCreate()`, `MatSetNearNullSpace()`, `MatGetNullSpace()`, `MatSetNullSpace()`, `MatGetTransposeNullSpace()`, `MatNullSpaceRemove()`, `KSPSetPCSide()`
9210: @*/
9211: PetscErrorCode MatSetTransposeNullSpace(Mat mat, MatNullSpace nullsp)
9212: {
9213:   PetscFunctionBegin;
9216:   PetscCall(PetscObjectReference((PetscObject)nullsp));
9217:   PetscCall(MatNullSpaceDestroy(&mat->transnullsp));
9218:   mat->transnullsp = nullsp;
9219:   PetscFunctionReturn(PETSC_SUCCESS);
9220: }

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

9226:   Logically Collective

9228:   Input Parameters:
9229: + mat    - the matrix
9230: - nullsp - the null space object

9232:   Level: advanced

9234:   Notes:
9235:   Overwrites any previous near null space that may have been attached

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

9239: .seealso: [](ch_matrices), `Mat`, `MatNullSpace`, `MatCreate()`, `MatNullSpaceCreate()`, `MatSetNullSpace()`, `MatNullSpaceCreateRigidBody()`, `MatGetNearNullSpace()`
9240: @*/
9241: PetscErrorCode MatSetNearNullSpace(Mat mat, MatNullSpace nullsp)
9242: {
9243:   PetscFunctionBegin;
9247:   MatCheckPreallocated(mat, 1);
9248:   PetscCall(PetscObjectReference((PetscObject)nullsp));
9249:   PetscCall(MatNullSpaceDestroy(&mat->nearnullsp));
9250:   mat->nearnullsp = nullsp;
9251:   PetscFunctionReturn(PETSC_SUCCESS);
9252: }

9254: /*@
9255:   MatGetNearNullSpace - Get null space attached with `MatSetNearNullSpace()`

9257:   Not Collective

9259:   Input Parameter:
9260: . mat - the matrix

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

9265:   Level: advanced

9267: .seealso: [](ch_matrices), `Mat`, `MatNullSpace`, `MatSetNearNullSpace()`, `MatGetNullSpace()`, `MatNullSpaceCreate()`
9268: @*/
9269: PetscErrorCode MatGetNearNullSpace(Mat mat, MatNullSpace *nullsp)
9270: {
9271:   PetscFunctionBegin;
9274:   PetscAssertPointer(nullsp, 2);
9275:   MatCheckPreallocated(mat, 1);
9276:   *nullsp = mat->nearnullsp;
9277:   PetscFunctionReturn(PETSC_SUCCESS);
9278: }

9280: /*@
9281:   MatICCFactor - Performs in-place incomplete Cholesky factorization of matrix.

9283:   Collective

9285:   Input Parameters:
9286: + mat  - the matrix
9287: . row  - row/column permutation
9288: - info - information on desired factorization process

9290:   Level: developer

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

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

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

9303: .seealso: [](ch_matrices), `Mat`, `MatFactorInfo`, `MatGetFactor()`, `MatICCFactorSymbolic()`, `MatLUFactorNumeric()`, `MatCholeskyFactor()`
9304: @*/
9305: PetscErrorCode MatICCFactor(Mat mat, IS row, const MatFactorInfo *info)
9306: {
9307:   PetscFunctionBegin;
9311:   PetscAssertPointer(info, 3);
9312:   PetscCheck(mat->rmap->N == mat->cmap->N, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONG, "matrix must be square");
9313:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
9314:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
9315:   MatCheckPreallocated(mat, 1);
9316:   PetscUseTypeMethod(mat, iccfactor, row, info);
9317:   PetscCall(PetscObjectStateIncrease((PetscObject)mat));
9318:   PetscFunctionReturn(PETSC_SUCCESS);
9319: }

9321: /*@
9322:   MatDiagonalScaleLocal - Scales columns of a matrix given the scaling values including the
9323:   ghosted ones.

9325:   Not Collective

9327:   Input Parameters:
9328: + mat  - the matrix
9329: - diag - the diagonal values, including ghost ones

9331:   Level: developer

9333:   Notes:
9334:   Works only for `MATMPIAIJ` and `MATMPIBAIJ` matrices

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

9338: .seealso: [](ch_matrices), `Mat`, `MatDiagonalScale()`
9339: @*/
9340: PetscErrorCode MatDiagonalScaleLocal(Mat mat, Vec diag)
9341: {
9342:   PetscMPIInt size;

9344:   PetscFunctionBegin;

9349:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Matrix must be already assembled");
9350:   PetscCall(PetscLogEventBegin(MAT_Scale, mat, 0, 0, 0));
9351:   PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)mat), &size));
9352:   if (size == 1) {
9353:     PetscInt n, m;
9354:     PetscCall(VecGetSize(diag, &n));
9355:     PetscCall(MatGetSize(mat, NULL, &m));
9356:     PetscCheck(m == n, PETSC_COMM_SELF, PETSC_ERR_SUP, "Only supported for sequential matrices when no ghost points/periodic conditions");
9357:     PetscCall(MatDiagonalScale(mat, NULL, diag));
9358:   } else PetscUseMethod(mat, "MatDiagonalScaleLocal_C", (Mat, Vec), (mat, diag));
9359:   PetscCall(PetscLogEventEnd(MAT_Scale, mat, 0, 0, 0));
9360:   PetscCall(PetscObjectStateIncrease((PetscObject)mat));
9361:   PetscFunctionReturn(PETSC_SUCCESS);
9362: }

9364: /*@
9365:   MatGetInertia - Gets the inertia from a factored matrix

9367:   Collective

9369:   Input Parameter:
9370: . mat - the matrix

9372:   Output Parameters:
9373: + nneg  - number of negative eigenvalues
9374: . nzero - number of zero eigenvalues
9375: - npos  - number of positive eigenvalues

9377:   Level: advanced

9379:   Note:
9380:   Matrix must have been factored by `MatCholeskyFactor()`

9382: .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatCholeskyFactor()`
9383: @*/
9384: PetscErrorCode MatGetInertia(Mat mat, PetscInt *nneg, PetscInt *nzero, PetscInt *npos)
9385: {
9386:   PetscFunctionBegin;
9389:   PetscCheck(mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Unfactored matrix");
9390:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Numeric factor mat is not assembled");
9391:   PetscUseTypeMethod(mat, getinertia, nneg, nzero, npos);
9392:   PetscFunctionReturn(PETSC_SUCCESS);
9393: }

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

9398:   Neighbor-wise Collective

9400:   Input Parameters:
9401: + mat - the factored matrix obtained with `MatGetFactor()`
9402: - b   - the right-hand-side vectors

9404:   Output Parameter:
9405: . x - the result vectors

9407:   Level: developer

9409:   Note:
9410:   The vectors `b` and `x` cannot be the same.  I.e., one cannot
9411:   call `MatSolves`(A,x,x).

9413: .seealso: [](ch_matrices), `Mat`, `Vecs`, `MatSolveAdd()`, `MatSolveTranspose()`, `MatSolveTransposeAdd()`, `MatSolve()`
9414: @*/
9415: PetscErrorCode MatSolves(Mat mat, Vecs b, Vecs x)
9416: {
9417:   PetscFunctionBegin;
9420:   PetscCheck(x != b, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_IDN, "x and b must be different vectors");
9421:   PetscCheck(mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Unfactored matrix");
9422:   if (!mat->rmap->N && !mat->cmap->N) PetscFunctionReturn(PETSC_SUCCESS);

9424:   MatCheckPreallocated(mat, 1);
9425:   PetscCall(PetscLogEventBegin(MAT_Solves, mat, 0, 0, 0));
9426:   PetscUseTypeMethod(mat, solves, b, x);
9427:   PetscCall(PetscLogEventEnd(MAT_Solves, mat, 0, 0, 0));
9428:   PetscFunctionReturn(PETSC_SUCCESS);
9429: }

9431: /*@
9432:   MatIsSymmetric - Test whether a matrix is symmetric

9434:   Collective

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

9440:   Output Parameter:
9441: . flg - the result

9443:   Level: intermediate

9445:   Notes:
9446:   For real numbers `MatIsSymmetric()` and `MatIsHermitian()` return identical results

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

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

9453: .seealso: [](ch_matrices), `Mat`, `MatTranspose()`, `MatIsTranspose()`, `MatIsHermitian()`, `MatIsStructurallySymmetric()`, `MatSetOption()`, `MatIsSymmetricKnown()`,
9454:           `MAT_SYMMETRIC`, `MAT_SYMMETRY_ETERNAL`
9455: @*/
9456: PetscErrorCode MatIsSymmetric(Mat A, PetscReal tol, PetscBool *flg)
9457: {
9458:   PetscFunctionBegin;
9460:   PetscAssertPointer(flg, 3);
9461:   if (A->symmetric != PETSC_BOOL3_UNKNOWN && !tol) *flg = PetscBool3ToBool(A->symmetric);
9462:   else {
9463:     if (A->ops->issymmetric) PetscUseTypeMethod(A, issymmetric, tol, flg);
9464:     else PetscCall(MatIsTranspose(A, A, tol, flg));
9465:     if (!tol) PetscCall(MatSetOption(A, MAT_SYMMETRIC, *flg));
9466:   }
9467:   PetscFunctionReturn(PETSC_SUCCESS);
9468: }

9470: /*@
9471:   MatIsHermitian - Test whether a matrix is Hermitian

9473:   Collective

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

9479:   Output Parameter:
9480: . flg - the result

9482:   Level: intermediate

9484:   Notes:
9485:   For real numbers `MatIsSymmetric()` and `MatIsHermitian()` return identical results

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

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

9492: .seealso: [](ch_matrices), `Mat`, `MatTranspose()`, `MatIsTranspose()`, `MatIsHermitianKnown()`, `MatIsStructurallySymmetric()`, `MatSetOption()`,
9493:           `MatIsSymmetricKnown()`, `MatIsSymmetric()`, `MAT_HERMITIAN`, `MAT_SYMMETRY_ETERNAL`
9494: @*/
9495: PetscErrorCode MatIsHermitian(Mat A, PetscReal tol, PetscBool *flg)
9496: {
9497:   PetscFunctionBegin;
9499:   PetscAssertPointer(flg, 3);
9500:   if (A->hermitian != PETSC_BOOL3_UNKNOWN && !tol) *flg = PetscBool3ToBool(A->hermitian);
9501:   else {
9502:     if (A->ops->ishermitian) PetscUseTypeMethod(A, ishermitian, tol, flg);
9503:     else PetscCall(MatIsHermitianTranspose(A, A, tol, flg));
9504:     if (!tol) PetscCall(MatSetOption(A, MAT_HERMITIAN, *flg));
9505:   }
9506:   PetscFunctionReturn(PETSC_SUCCESS);
9507: }

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

9512:   Not Collective

9514:   Input Parameter:
9515: . A - the matrix to check

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

9521:   Level: advanced

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

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

9530: .seealso: [](ch_matrices), `Mat`, `MAT_SYMMETRY_ETERNAL`, `MatTranspose()`, `MatIsTranspose()`, `MatIsHermitian()`, `MatIsStructurallySymmetric()`, `MatSetOption()`, `MatIsSymmetric()`, `MatIsHermitianKnown()`
9531: @*/
9532: PetscErrorCode MatIsSymmetricKnown(Mat A, PetscBool *set, PetscBool *flg)
9533: {
9534:   PetscFunctionBegin;
9536:   PetscAssertPointer(set, 2);
9537:   PetscAssertPointer(flg, 3);
9538:   if (A->symmetric != PETSC_BOOL3_UNKNOWN) {
9539:     *set = PETSC_TRUE;
9540:     *flg = PetscBool3ToBool(A->symmetric);
9541:   } else *set = PETSC_FALSE;
9542:   PetscFunctionReturn(PETSC_SUCCESS);
9543: }

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

9548:   Not Collective

9550:   Input Parameter:
9551: . A - the matrix to check

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

9557:   Level: advanced

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

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

9565: .seealso: [](ch_matrices), `Mat`, `MAT_SPD_ETERNAL`, `MAT_SPD`, `MatTranspose()`, `MatIsTranspose()`, `MatIsHermitian()`, `MatIsStructurallySymmetric()`, `MatSetOption()`, `MatIsSymmetric()`, `MatIsHermitianKnown()`
9566: @*/
9567: PetscErrorCode MatIsSPDKnown(Mat A, PetscBool *set, PetscBool *flg)
9568: {
9569:   PetscFunctionBegin;
9571:   PetscAssertPointer(set, 2);
9572:   PetscAssertPointer(flg, 3);
9573:   if (A->spd != PETSC_BOOL3_UNKNOWN) {
9574:     *set = PETSC_TRUE;
9575:     *flg = PetscBool3ToBool(A->spd);
9576:   } else *set = PETSC_FALSE;
9577:   PetscFunctionReturn(PETSC_SUCCESS);
9578: }

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

9583:   Not Collective

9585:   Input Parameter:
9586: . A - the matrix to check

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

9592:   Level: advanced

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

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

9601: .seealso: [](ch_matrices), `Mat`, `MAT_SYMMETRY_ETERNAL`, `MAT_HERMITIAN`, `MatTranspose()`, `MatIsTranspose()`, `MatIsHermitian()`, `MatIsStructurallySymmetric()`, `MatSetOption()`, `MatIsSymmetric()`
9602: @*/
9603: PetscErrorCode MatIsHermitianKnown(Mat A, PetscBool *set, PetscBool *flg)
9604: {
9605:   PetscFunctionBegin;
9607:   PetscAssertPointer(set, 2);
9608:   PetscAssertPointer(flg, 3);
9609:   if (A->hermitian != PETSC_BOOL3_UNKNOWN) {
9610:     *set = PETSC_TRUE;
9611:     *flg = PetscBool3ToBool(A->hermitian);
9612:   } else *set = PETSC_FALSE;
9613:   PetscFunctionReturn(PETSC_SUCCESS);
9614: }

9616: /*@
9617:   MatIsStructurallySymmetric - Test whether a matrix is structurally symmetric

9619:   Collective

9621:   Input Parameter:
9622: . A - the matrix to test

9624:   Output Parameter:
9625: . flg - the result

9627:   Level: intermediate

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

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

9635: .seealso: [](ch_matrices), `Mat`, `MAT_STRUCTURALLY_SYMMETRIC`, `MAT_STRUCTURAL_SYMMETRY_ETERNAL`, `MatTranspose()`, `MatIsTranspose()`, `MatIsHermitian()`, `MatIsSymmetric()`, `MatSetOption()`, `MatIsStructurallySymmetricKnown()`
9636: @*/
9637: PetscErrorCode MatIsStructurallySymmetric(Mat A, PetscBool *flg)
9638: {
9639:   PetscFunctionBegin;
9641:   PetscAssertPointer(flg, 2);
9642:   if (A->structurally_symmetric != PETSC_BOOL3_UNKNOWN) *flg = PetscBool3ToBool(A->structurally_symmetric);
9643:   else {
9644:     PetscUseTypeMethod(A, isstructurallysymmetric, flg);
9645:     PetscCall(MatSetOption(A, MAT_STRUCTURALLY_SYMMETRIC, *flg));
9646:   }
9647:   PetscFunctionReturn(PETSC_SUCCESS);
9648: }

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

9653:   Not Collective

9655:   Input Parameter:
9656: . A - the matrix to check

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

9662:   Level: advanced

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

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

9670: .seealso: [](ch_matrices), `Mat`, `MAT_STRUCTURALLY_SYMMETRIC`, `MatTranspose()`, `MatIsTranspose()`, `MatIsHermitian()`, `MatIsStructurallySymmetric()`, `MatSetOption()`, `MatIsSymmetric()`, `MatIsHermitianKnown()`
9671: @*/
9672: PetscErrorCode MatIsStructurallySymmetricKnown(Mat A, PetscBool *set, PetscBool *flg)
9673: {
9674:   PetscFunctionBegin;
9676:   PetscAssertPointer(set, 2);
9677:   PetscAssertPointer(flg, 3);
9678:   if (A->structurally_symmetric != PETSC_BOOL3_UNKNOWN) {
9679:     *set = PETSC_TRUE;
9680:     *flg = PetscBool3ToBool(A->structurally_symmetric);
9681:   } else *set = PETSC_FALSE;
9682:   PetscFunctionReturn(PETSC_SUCCESS);
9683: }

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

9689:   Not Collective

9691:   Input Parameter:
9692: . mat - the matrix

9694:   Output Parameters:
9695: + nstash    - the size of the stash
9696: . reallocs  - the number of additional mallocs incurred.
9697: . bnstash   - the size of the block stash
9698: - breallocs - the number of additional mallocs incurred.in the block stash

9700:   Level: advanced

9702: .seealso: [](ch_matrices), `MatAssemblyBegin()`, `MatAssemblyEnd()`, `Mat`, `MatStashSetInitialSize()`
9703: @*/
9704: PetscErrorCode MatStashGetInfo(Mat mat, PetscInt *nstash, PetscInt *reallocs, PetscInt *bnstash, PetscInt *breallocs)
9705: {
9706:   PetscFunctionBegin;
9707:   PetscCall(MatStashGetInfo_Private(&mat->stash, nstash, reallocs));
9708:   PetscCall(MatStashGetInfo_Private(&mat->bstash, bnstash, breallocs));
9709:   PetscFunctionReturn(PETSC_SUCCESS);
9710: }

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

9716:   Collective

9718:   Input Parameter:
9719: . mat - the matrix

9721:   Output Parameters:
9722: + right - (optional) vector that the matrix can be multiplied against
9723: - left  - (optional) vector that the matrix vector product can be stored in

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

9728:   Level: advanced

9730:   Notes:
9731:   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()`.

9733:   The `VecType` of the created vectors is determined by the `MatType` of `mat`. This can be overridden by using `MatSetVecType()` or the option `-mat_vec_type`.

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

9737: .seealso: [](ch_matrices), `Mat`, `Vec`, `VecCreate()`, `VecDestroy()`, `DMCreateGlobalVector()`, `MatSetVecType()`
9738: @*/
9739: PetscErrorCode MatCreateVecs(Mat mat, Vec *right, Vec *left)
9740: {
9741:   PetscFunctionBegin;
9744:   if (mat->ops->getvecs) {
9745:     PetscUseTypeMethod(mat, getvecs, right, left);
9746:   } else {
9747:     if (right) {
9748:       PetscCheck(mat->cmap->n >= 0, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "PetscLayout for columns not yet setup");
9749:       PetscCall(VecCreateWithLayout_Private(mat->cmap, right));
9750:       PetscCall(VecSetType(*right, mat->defaultvectype));
9751: #if defined(PETSC_HAVE_VIENNACL) || defined(PETSC_HAVE_CUDA) || defined(PETSC_HAVE_HIP)
9752:       if (mat->boundtocpu && mat->bindingpropagates) {
9753:         PetscCall(VecSetBindingPropagates(*right, PETSC_TRUE));
9754:         PetscCall(VecBindToCPU(*right, PETSC_TRUE));
9755:       }
9756: #endif
9757:     }
9758:     if (left) {
9759:       PetscCheck(mat->rmap->n >= 0, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "PetscLayout for rows not yet setup");
9760:       PetscCall(VecCreateWithLayout_Private(mat->rmap, left));
9761:       PetscCall(VecSetType(*left, mat->defaultvectype));
9762: #if defined(PETSC_HAVE_VIENNACL) || defined(PETSC_HAVE_CUDA) || defined(PETSC_HAVE_HIP)
9763:       if (mat->boundtocpu && mat->bindingpropagates) {
9764:         PetscCall(VecSetBindingPropagates(*left, PETSC_TRUE));
9765:         PetscCall(VecBindToCPU(*left, PETSC_TRUE));
9766:       }
9767: #endif
9768:     }
9769:   }
9770:   PetscFunctionReturn(PETSC_SUCCESS);
9771: }

9773: /*@
9774:   MatFactorInfoInitialize - Initializes a `MatFactorInfo` data structure
9775:   with default values.

9777:   Not Collective

9779:   Input Parameter:
9780: . info - the `MatFactorInfo` data structure

9782:   Level: developer

9784:   Notes:
9785:   The solvers are generally used through the `KSP` and `PC` objects, for example
9786:   `PCLU`, `PCILU`, `PCCHOLESKY`, `PCICC`

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

9790: .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatFactorInfo`
9791: @*/
9792: PetscErrorCode MatFactorInfoInitialize(MatFactorInfo *info)
9793: {
9794:   PetscFunctionBegin;
9795:   PetscCall(PetscMemzero(info, sizeof(MatFactorInfo)));
9796:   PetscFunctionReturn(PETSC_SUCCESS);
9797: }

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

9802:   Collective

9804:   Input Parameters:
9805: + mat - the factored matrix
9806: - is  - the index set defining the Schur indices (0-based)

9808:   Level: advanced

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

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

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

9817: .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatFactorGetSchurComplement()`, `MatFactorRestoreSchurComplement()`, `MatFactorCreateSchurComplement()`, `MatFactorSolveSchurComplement()`,
9818:           `MatFactorSolveSchurComplementTranspose()`, `MATSOLVERMUMPS`, `MATSOLVERMKL_PARDISO`
9819: @*/
9820: PetscErrorCode MatFactorSetSchurIS(Mat mat, IS is)
9821: {
9822:   PetscErrorCode (*f)(Mat, IS);

9824:   PetscFunctionBegin;
9829:   PetscCheckSameComm(mat, 1, is, 2);
9830:   PetscCheck(mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Only for factored matrix");
9831:   PetscCall(PetscObjectQueryFunction((PetscObject)mat, "MatFactorSetSchurIS_C", &f));
9832:   PetscCheck(f, PetscObjectComm((PetscObject)mat), PETSC_ERR_SUP, "The selected MatSolverType does not support Schur complement computation. You should use MATSOLVERMUMPS or MATSOLVERMKL_PARDISO");
9833:   PetscCall(MatDestroy(&mat->schur));
9834:   PetscCall((*f)(mat, is));
9835:   PetscCheck(mat->schur, PetscObjectComm((PetscObject)mat), PETSC_ERR_PLIB, "Schur complement has not been created");
9836:   PetscFunctionReturn(PETSC_SUCCESS);
9837: }

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

9842:   Logically Collective

9844:   Input Parameters:
9845: + F      - the factored matrix obtained by calling `MatGetFactor()`
9846: . S      - location where to return the Schur complement, can be `NULL`
9847: - status - the status of the Schur complement matrix, can be `NULL`

9849:   Level: advanced

9851:   Notes:
9852:   You must call `MatFactorSetSchurIS()` before calling this routine.

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

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

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

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

9864:   Developer Note:
9865:   The reason this routine exists is because the representation of the Schur complement within the factor matrix may be different than a standard PETSc
9866:   matrix representation and we normally do not want to use the time or memory to make a copy as a regular PETSc matrix.

9868: .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatFactorSetSchurIS()`, `MatFactorGetSchurComplement()`, `MatFactorSchurStatus`, `MATSOLVERMUMPS`, `MATSOLVERMKL_PARDISO`
9869: @*/
9870: PetscErrorCode MatFactorCreateSchurComplement(Mat F, Mat *S, MatFactorSchurStatus *status)
9871: {
9872:   PetscFunctionBegin;
9874:   if (S) PetscAssertPointer(S, 2);
9875:   if (status) PetscAssertPointer(status, 3);
9876:   if (S) {
9877:     PetscErrorCode (*f)(Mat, Mat *);

9879:     PetscCall(PetscObjectQueryFunction((PetscObject)F, "MatFactorCreateSchurComplement_C", &f));
9880:     if (f) PetscCall((*f)(F, S));
9881:     else PetscCall(MatDuplicate(F->schur, MAT_COPY_VALUES, S));
9882:   }
9883:   if (status) *status = F->schur_status;
9884:   PetscFunctionReturn(PETSC_SUCCESS);
9885: }

9887: /*@
9888:   MatFactorGetSchurComplement - Gets access to a Schur complement matrix using the current Schur data within a factored matrix

9890:   Logically Collective

9892:   Input Parameters:
9893: + F      - the factored matrix obtained by calling `MatGetFactor()`
9894: . S      - location where to return the Schur complement, can be `NULL`
9895: - status - the status of the Schur complement matrix, can be `NULL`

9897:   Level: advanced

9899:   Notes:
9900:   You must call `MatFactorSetSchurIS()` before calling this routine.

9902:   Schur complement mode is currently implemented for sequential matrices with factor type of `MATSOLVERMUMPS`

9904:   The routine returns a the Schur Complement stored within the data structures of the solver.

9906:   If `MatFactorInvertSchurComplement()` has previously been called, the returned matrix is actually the inverse of the Schur complement.

9908:   The returned matrix should not be destroyed; the caller should call `MatFactorRestoreSchurComplement()` when the object is no longer needed.

9910:   Use `MatFactorCreateSchurComplement()` to create a copy of the Schur complement matrix that is within a factored matrix

9912:   See `MatCreateSchurComplement()` or `MatGetSchurComplement()` for ways to create virtual or approximate Schur complements.

9914: .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatFactorSetSchurIS()`, `MatFactorRestoreSchurComplement()`, `MatFactorCreateSchurComplement()`, `MatFactorSchurStatus`
9915: @*/
9916: PetscErrorCode MatFactorGetSchurComplement(Mat F, Mat *S, MatFactorSchurStatus *status)
9917: {
9918:   PetscFunctionBegin;
9920:   if (S) {
9921:     PetscAssertPointer(S, 2);
9922:     *S = F->schur;
9923:   }
9924:   if (status) {
9925:     PetscAssertPointer(status, 3);
9926:     *status = F->schur_status;
9927:   }
9928:   PetscFunctionReturn(PETSC_SUCCESS);
9929: }

9931: static PetscErrorCode MatFactorUpdateSchurStatus_Private(Mat F)
9932: {
9933:   Mat S = F->schur;

9935:   PetscFunctionBegin;
9936:   switch (F->schur_status) {
9937:   case MAT_FACTOR_SCHUR_UNFACTORED: // fall-through
9938:   case MAT_FACTOR_SCHUR_INVERTED:
9939:     if (S) {
9940:       S->ops->solve             = NULL;
9941:       S->ops->matsolve          = NULL;
9942:       S->ops->solvetranspose    = NULL;
9943:       S->ops->matsolvetranspose = NULL;
9944:       S->ops->solveadd          = NULL;
9945:       S->ops->solvetransposeadd = NULL;
9946:       S->factortype             = MAT_FACTOR_NONE;
9947:       PetscCall(PetscFree(S->solvertype));
9948:     }
9949:   case MAT_FACTOR_SCHUR_FACTORED: // fall-through
9950:     break;
9951:   default:
9952:     SETERRQ(PetscObjectComm((PetscObject)F), PETSC_ERR_SUP, "Unhandled MatFactorSchurStatus %d", F->schur_status);
9953:   }
9954:   PetscFunctionReturn(PETSC_SUCCESS);
9955: }

9957: /*@
9958:   MatFactorRestoreSchurComplement - Restore the Schur complement matrix object obtained from a call to `MatFactorGetSchurComplement()`

9960:   Logically Collective

9962:   Input Parameters:
9963: + F      - the factored matrix obtained by calling `MatGetFactor()`
9964: . S      - location where the Schur complement is stored
9965: - status - the status of the Schur complement matrix (see `MatFactorSchurStatus`)

9967:   Level: advanced

9969: .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatFactorSetSchurIS()`, `MatFactorCreateSchurComplement()`, `MatFactorSchurStatus`
9970: @*/
9971: PetscErrorCode MatFactorRestoreSchurComplement(Mat F, Mat *S, MatFactorSchurStatus status)
9972: {
9973:   PetscFunctionBegin;
9975:   if (S) {
9977:     *S = NULL;
9978:   }
9979:   F->schur_status = status;
9980:   PetscCall(MatFactorUpdateSchurStatus_Private(F));
9981:   PetscFunctionReturn(PETSC_SUCCESS);
9982: }

9984: /*@
9985:   MatFactorSolveSchurComplementTranspose - Solve the transpose of the Schur complement system computed during the factorization step

9987:   Logically Collective

9989:   Input Parameters:
9990: + F   - the factored matrix obtained by calling `MatGetFactor()`
9991: . rhs - location where the right-hand side of the Schur complement system is stored
9992: - sol - location where the solution of the Schur complement system has to be returned

9994:   Level: advanced

9996:   Notes:
9997:   The sizes of the vectors should match the size of the Schur complement

9999:   Must be called after `MatFactorSetSchurIS()`

10001: .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatFactorSetSchurIS()`, `MatFactorSolveSchurComplement()`
10002: @*/
10003: PetscErrorCode MatFactorSolveSchurComplementTranspose(Mat F, Vec rhs, Vec sol)
10004: {
10005:   PetscFunctionBegin;
10012:   PetscCheckSameComm(F, 1, rhs, 2);
10013:   PetscCheckSameComm(F, 1, sol, 3);
10014:   PetscCall(MatFactorFactorizeSchurComplement(F));
10015:   switch (F->schur_status) {
10016:   case MAT_FACTOR_SCHUR_FACTORED:
10017:     PetscCall(MatSolveTranspose(F->schur, rhs, sol));
10018:     break;
10019:   case MAT_FACTOR_SCHUR_INVERTED:
10020:     PetscCall(MatMultTranspose(F->schur, rhs, sol));
10021:     break;
10022:   default:
10023:     SETERRQ(PetscObjectComm((PetscObject)F), PETSC_ERR_SUP, "Unhandled MatFactorSchurStatus %d", F->schur_status);
10024:   }
10025:   PetscFunctionReturn(PETSC_SUCCESS);
10026: }

10028: /*@
10029:   MatFactorSolveSchurComplement - Solve the Schur complement system computed during the factorization step

10031:   Logically Collective

10033:   Input Parameters:
10034: + F   - the factored matrix obtained by calling `MatGetFactor()`
10035: . rhs - location where the right-hand side of the Schur complement system is stored
10036: - sol - location where the solution of the Schur complement system has to be returned

10038:   Level: advanced

10040:   Notes:
10041:   The sizes of the vectors should match the size of the Schur complement

10043:   Must be called after `MatFactorSetSchurIS()`

10045: .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatFactorSetSchurIS()`, `MatFactorSolveSchurComplementTranspose()`
10046: @*/
10047: PetscErrorCode MatFactorSolveSchurComplement(Mat F, Vec rhs, Vec sol)
10048: {
10049:   PetscFunctionBegin;
10056:   PetscCheckSameComm(F, 1, rhs, 2);
10057:   PetscCheckSameComm(F, 1, sol, 3);
10058:   PetscCall(MatFactorFactorizeSchurComplement(F));
10059:   switch (F->schur_status) {
10060:   case MAT_FACTOR_SCHUR_FACTORED:
10061:     PetscCall(MatSolve(F->schur, rhs, sol));
10062:     break;
10063:   case MAT_FACTOR_SCHUR_INVERTED:
10064:     PetscCall(MatMult(F->schur, rhs, sol));
10065:     break;
10066:   default:
10067:     SETERRQ(PetscObjectComm((PetscObject)F), PETSC_ERR_SUP, "Unhandled MatFactorSchurStatus %d", F->schur_status);
10068:   }
10069:   PetscFunctionReturn(PETSC_SUCCESS);
10070: }

10072: PETSC_SINGLE_LIBRARY_INTERN PetscErrorCode MatSeqDenseInvertFactors_Private(Mat);
10073: #if PetscDefined(HAVE_CUDA)
10074: PETSC_SINGLE_LIBRARY_INTERN PetscErrorCode MatSeqDenseCUDAInvertFactors_Internal(Mat);
10075: #endif

10077: /* Schur status updated in the interface */
10078: static PetscErrorCode MatFactorInvertSchurComplement_Private(Mat F)
10079: {
10080:   Mat S = F->schur;

10082:   PetscFunctionBegin;
10083:   if (S) {
10084:     PetscMPIInt size;
10085:     PetscBool   isdense, isdensecuda;

10087:     PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)S), &size));
10088:     PetscCheck(size <= 1, PetscObjectComm((PetscObject)S), PETSC_ERR_SUP, "Not yet implemented");
10089:     PetscCall(PetscObjectTypeCompare((PetscObject)S, MATSEQDENSE, &isdense));
10090:     PetscCall(PetscObjectTypeCompare((PetscObject)S, MATSEQDENSECUDA, &isdensecuda));
10091:     PetscCheck(isdense || isdensecuda, PetscObjectComm((PetscObject)S), PETSC_ERR_SUP, "Not implemented for type %s", ((PetscObject)S)->type_name);
10092:     PetscCall(PetscLogEventBegin(MAT_FactorInvS, F, 0, 0, 0));
10093:     if (isdense) {
10094:       PetscCall(MatSeqDenseInvertFactors_Private(S));
10095:     } else if (isdensecuda) {
10096: #if defined(PETSC_HAVE_CUDA)
10097:       PetscCall(MatSeqDenseCUDAInvertFactors_Internal(S));
10098: #endif
10099:     }
10100:     // HIP??????????????
10101:     PetscCall(PetscLogEventEnd(MAT_FactorInvS, F, 0, 0, 0));
10102:   }
10103:   PetscFunctionReturn(PETSC_SUCCESS);
10104: }

10106: /*@
10107:   MatFactorInvertSchurComplement - Invert the Schur complement matrix computed during the factorization step

10109:   Logically Collective

10111:   Input Parameter:
10112: . F - the factored matrix obtained by calling `MatGetFactor()`

10114:   Level: advanced

10116:   Notes:
10117:   Must be called after `MatFactorSetSchurIS()`.

10119:   Call `MatFactorGetSchurComplement()` or  `MatFactorCreateSchurComplement()` AFTER this call to actually compute the inverse and get access to it.

10121: .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatFactorSetSchurIS()`, `MatFactorGetSchurComplement()`, `MatFactorCreateSchurComplement()`
10122: @*/
10123: PetscErrorCode MatFactorInvertSchurComplement(Mat F)
10124: {
10125:   PetscFunctionBegin;
10128:   if (F->schur_status == MAT_FACTOR_SCHUR_INVERTED) PetscFunctionReturn(PETSC_SUCCESS);
10129:   PetscCall(MatFactorFactorizeSchurComplement(F));
10130:   PetscCall(MatFactorInvertSchurComplement_Private(F));
10131:   F->schur_status = MAT_FACTOR_SCHUR_INVERTED;
10132:   PetscFunctionReturn(PETSC_SUCCESS);
10133: }

10135: /*@
10136:   MatFactorFactorizeSchurComplement - Factorize the Schur complement matrix computed during the factorization step

10138:   Logically Collective

10140:   Input Parameter:
10141: . F - the factored matrix obtained by calling `MatGetFactor()`

10143:   Level: advanced

10145:   Note:
10146:   Must be called after `MatFactorSetSchurIS()`

10148: .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatFactorSetSchurIS()`, `MatFactorInvertSchurComplement()`
10149: @*/
10150: PetscErrorCode MatFactorFactorizeSchurComplement(Mat F)
10151: {
10152:   MatFactorInfo info;

10154:   PetscFunctionBegin;
10157:   if (F->schur_status == MAT_FACTOR_SCHUR_INVERTED || F->schur_status == MAT_FACTOR_SCHUR_FACTORED) PetscFunctionReturn(PETSC_SUCCESS);
10158:   PetscCall(PetscLogEventBegin(MAT_FactorFactS, F, 0, 0, 0));
10159:   PetscCall(PetscMemzero(&info, sizeof(MatFactorInfo)));
10160:   if (F->factortype == MAT_FACTOR_CHOLESKY) { /* LDL^t regarded as Cholesky */
10161:     PetscCall(MatCholeskyFactor(F->schur, NULL, &info));
10162:   } else {
10163:     PetscCall(MatLUFactor(F->schur, NULL, NULL, &info));
10164:   }
10165:   PetscCall(PetscLogEventEnd(MAT_FactorFactS, F, 0, 0, 0));
10166:   F->schur_status = MAT_FACTOR_SCHUR_FACTORED;
10167:   PetscFunctionReturn(PETSC_SUCCESS);
10168: }

10170: /*@
10171:   MatPtAP - Creates the matrix product $C = P^T * A * P$

10173:   Neighbor-wise Collective

10175:   Input Parameters:
10176: + A     - the matrix
10177: . P     - the projection matrix
10178: . scall - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`
10179: - 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
10180:           if the result is a dense matrix this is irrelevant

10182:   Output Parameter:
10183: . C - the product matrix

10185:   Level: intermediate

10187:   Notes:
10188:   `C` will be created and must be destroyed by the user with `MatDestroy()`.

10190:   This is a convenience routine that wraps the use of the `MatProductCreate()` with a `MatProductType` of `MATPRODUCT_PtAP`
10191:   functionality into a single function call. For more involved matrix-matrix operations see `MatProductCreate()`.

10193:   The deprecated `PETSC_DEFAULT` in `fill` also means use the current value

10195:   Developer Note:
10196:   For matrix types without special implementation the function fallbacks to `MatMatMult()` followed by `MatTransposeMatMult()`.

10198: .seealso: [](ch_matrices), `Mat`, `MatProductCreate()`, `MatMatMult()`, `MatRARt()`
10199: @*/
10200: PetscErrorCode MatPtAP(Mat A, Mat P, MatReuse scall, PetscReal fill, Mat *C)
10201: {
10202:   PetscFunctionBegin;
10203:   if (scall == MAT_REUSE_MATRIX) MatCheckProduct(*C, 5);
10204:   PetscCheck(scall != MAT_INPLACE_MATRIX, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "Inplace product not supported");

10206:   if (scall == MAT_INITIAL_MATRIX) {
10207:     PetscCall(MatProductCreate(A, P, NULL, C));
10208:     PetscCall(MatProductSetType(*C, MATPRODUCT_PtAP));
10209:     PetscCall(MatProductSetAlgorithm(*C, "default"));
10210:     PetscCall(MatProductSetFill(*C, fill));

10212:     (*C)->product->api_user = PETSC_TRUE;
10213:     PetscCall(MatProductSetFromOptions(*C));
10214:     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);
10215:     PetscCall(MatProductSymbolic(*C));
10216:   } else { /* scall == MAT_REUSE_MATRIX */
10217:     PetscCall(MatProductReplaceMats(A, P, NULL, *C));
10218:   }

10220:   PetscCall(MatProductNumeric(*C));
10221:   if (A->symmetric == PETSC_BOOL3_TRUE) {
10222:     PetscCall(MatSetOption(*C, MAT_SYMMETRIC, PETSC_TRUE));
10223:     (*C)->spd = A->spd;
10224:   }
10225:   PetscFunctionReturn(PETSC_SUCCESS);
10226: }

10228: /*@
10229:   MatRARt - Creates the matrix product $C = R * A * R^T$

10231:   Neighbor-wise Collective

10233:   Input Parameters:
10234: + A     - the matrix
10235: . R     - the projection matrix
10236: . scall - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`
10237: - fill  - expected fill as ratio of nnz(C)/nnz(A), use `PETSC_DETERMINE` or `PETSC_CURRENT` if you do not have a good estimate
10238:           if the result is a dense matrix this is irrelevant

10240:   Output Parameter:
10241: . C - the product matrix

10243:   Level: intermediate

10245:   Notes:
10246:   `C` will be created and must be destroyed by the user with `MatDestroy()`.

10248:   This is a convenience routine that wraps the use of the `MatProductCreate()` with a `MatProductType` of `MATPRODUCT_RARt`
10249:   functionality into a single function call. For more involved matrix-matrix operations see `MatProductCreate()`.

10251:   This routine is currently only implemented for pairs of `MATAIJ` matrices and classes
10252:   which inherit from `MATAIJ`. Due to PETSc sparse matrix block row distribution among processes,
10253:   the parallel `MatRARt()` is implemented computing the explicit transpose of `R`, which can be very expensive.
10254:   We recommend using `MatPtAP()` when possible.

10256:   The deprecated `PETSC_DEFAULT` in `fill` also means use the current value

10258: .seealso: [](ch_matrices), `Mat`, `MatProductCreate()`, `MatMatMult()`, `MatPtAP()`
10259: @*/
10260: PetscErrorCode MatRARt(Mat A, Mat R, MatReuse scall, PetscReal fill, Mat *C)
10261: {
10262:   PetscFunctionBegin;
10263:   if (scall == MAT_REUSE_MATRIX) MatCheckProduct(*C, 5);
10264:   PetscCheck(scall != MAT_INPLACE_MATRIX, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "Inplace product not supported");

10266:   if (scall == MAT_INITIAL_MATRIX) {
10267:     PetscCall(MatProductCreate(A, R, NULL, C));
10268:     PetscCall(MatProductSetType(*C, MATPRODUCT_RARt));
10269:     PetscCall(MatProductSetAlgorithm(*C, "default"));
10270:     PetscCall(MatProductSetFill(*C, fill));

10272:     (*C)->product->api_user = PETSC_TRUE;
10273:     PetscCall(MatProductSetFromOptions(*C));
10274:     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);
10275:     PetscCall(MatProductSymbolic(*C));
10276:   } else { /* scall == MAT_REUSE_MATRIX */
10277:     PetscCall(MatProductReplaceMats(A, R, NULL, *C));
10278:   }

10280:   PetscCall(MatProductNumeric(*C));
10281:   if (A->symmetric == PETSC_BOOL3_TRUE) PetscCall(MatSetOption(*C, MAT_SYMMETRIC, PETSC_TRUE));
10282:   PetscFunctionReturn(PETSC_SUCCESS);
10283: }

10285: static PetscErrorCode MatProduct_Private(Mat A, Mat B, MatReuse scall, PetscReal fill, MatProductType ptype, Mat *C)
10286: {
10287:   PetscBool flg = PETSC_TRUE;

10289:   PetscFunctionBegin;
10290:   PetscCheck(scall != MAT_INPLACE_MATRIX, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "MAT_INPLACE_MATRIX product not supported");
10291:   if (scall == MAT_INITIAL_MATRIX) {
10292:     PetscCall(PetscInfo(A, "Calling MatProduct API with MAT_INITIAL_MATRIX and product type %s\n", MatProductTypes[ptype]));
10293:     PetscCall(MatProductCreate(A, B, NULL, C));
10294:     PetscCall(MatProductSetAlgorithm(*C, MATPRODUCTALGORITHMDEFAULT));
10295:     PetscCall(MatProductSetFill(*C, fill));
10296:   } else { /* scall == MAT_REUSE_MATRIX */
10297:     Mat_Product *product = (*C)->product;

10299:     PetscCall(PetscObjectBaseTypeCompareAny((PetscObject)*C, &flg, MATSEQDENSE, MATMPIDENSE, ""));
10300:     if (flg && product && product->type != ptype) {
10301:       PetscCall(MatProductClear(*C));
10302:       product = NULL;
10303:     }
10304:     PetscCall(PetscInfo(A, "Calling MatProduct API with MAT_REUSE_MATRIX %s product present and product type %s\n", product ? "with" : "without", MatProductTypes[ptype]));
10305:     if (!product) { /* user provide the dense matrix *C without calling MatProductCreate() or reusing it from previous calls */
10306:       PetscCheck(flg, PetscObjectComm((PetscObject)*C), PETSC_ERR_SUP, "Call MatProductCreate() first");
10307:       PetscCall(MatProductCreate_Private(A, B, NULL, *C));
10308:       product        = (*C)->product;
10309:       product->fill  = fill;
10310:       product->clear = PETSC_TRUE;
10311:     } else { /* user may change input matrices A or B when MAT_REUSE_MATRIX */
10312:       flg = PETSC_FALSE;
10313:       PetscCall(MatProductReplaceMats(A, B, NULL, *C));
10314:     }
10315:   }
10316:   if (flg) {
10317:     (*C)->product->api_user = PETSC_TRUE;
10318:     PetscCall(MatProductSetType(*C, ptype));
10319:     PetscCall(MatProductSetFromOptions(*C));
10320:     PetscCall(MatProductSymbolic(*C));
10321:   }
10322:   PetscCall(MatProductNumeric(*C));
10323:   PetscFunctionReturn(PETSC_SUCCESS);
10324: }

10326: /*@
10327:   MatMatMult - Performs matrix-matrix multiplication $ C=A*B $.

10329:   Neighbor-wise Collective

10331:   Input Parameters:
10332: + A     - the left matrix
10333: . B     - the right matrix
10334: . scall - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`
10335: - 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
10336:           if the result is a dense matrix this is irrelevant

10338:   Output Parameter:
10339: . C - the product matrix

10341:   Notes:
10342:   Unless scall is `MAT_REUSE_MATRIX` C will be created.

10344:   `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
10345:   call to this function with `MAT_INITIAL_MATRIX`.

10347:   To determine the correct fill value, run with `-info` and search for the string "Fill ratio" to see the value actually needed.

10349:   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`,
10350:   rather than first having `MatMatMult()` create it for you. You can NEVER do this if the matrix `C` is sparse.

10352:   The deprecated `PETSC_DEFAULT` in `fill` also means use the current value

10354:   This is a convenience routine that wraps the use of the `MatProductCreate()` with a `MatProductType` of `MATPRODUCT_AB`
10355:   functionality into a single function call. For more involved matrix-matrix operations see `MatProductCreate()`.

10357:   Example of Usage:
10358: .vb
10359:      MatProductCreate(A,B,NULL,&C);
10360:      MatProductSetType(C,MATPRODUCT_AB);
10361:      MatProductSymbolic(C);
10362:      MatProductNumeric(C); // compute C=A * B
10363:      MatProductReplaceMats(A1,B1,NULL,C); // compute C=A1 * B1
10364:      MatProductNumeric(C);
10365:      MatProductReplaceMats(A2,NULL,NULL,C); // compute C=A2 * B1
10366:      MatProductNumeric(C);
10367: .ve

10369:   Level: intermediate

10371: .seealso: [](ch_matrices), `Mat`, `MatProductType`, `MATPRODUCT_AB`, `MatTransposeMatMult()`, `MatMatTransposeMult()`, `MatPtAP()`, `MatProductCreate()`, `MatProductSymbolic()`, `MatProductReplaceMats()`, `MatProductNumeric()`
10372: @*/
10373: PetscErrorCode MatMatMult(Mat A, Mat B, MatReuse scall, PetscReal fill, Mat *C)
10374: {
10375:   PetscFunctionBegin;
10376:   PetscCall(MatProduct_Private(A, B, scall, fill, MATPRODUCT_AB, C));
10377:   PetscFunctionReturn(PETSC_SUCCESS);
10378: }

10380: /*@
10381:   MatMatTransposeMult - Performs matrix-matrix multiplication $C = A*B^T$.

10383:   Neighbor-wise Collective

10385:   Input Parameters:
10386: + A     - the left matrix
10387: . B     - the right matrix
10388: . scall - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`
10389: - fill  - expected fill as ratio of nnz(C)/(nnz(A) + nnz(B)), use `PETSC_DETERMINE` or `PETSC_CURRENT` if not known

10391:   Output Parameter:
10392: . C - the product matrix

10394:   Options Database Key:
10395: . -matmattransmult_mpidense_mpidense_via {allgatherv,cyclic} - Choose between algorithms for `MATMPIDENSE` matrices: the
10396:               first redundantly copies the transposed `B` matrix on each process and requires O(log P) communication complexity;
10397:               the second never stores more than one portion of the `B` matrix at a time but requires O(P) communication complexity.

10399:   Level: intermediate

10401:   Notes:
10402:   C will be created if `MAT_INITIAL_MATRIX` and must be destroyed by the user with `MatDestroy()`.

10404:   `MAT_REUSE_MATRIX` can only be used if the matrices A and B have the same nonzero pattern as in the previous call

10406:   To determine the correct fill value, run with -info and search for the string "Fill ratio" to see the value
10407:   actually needed.

10409:   This routine is currently only implemented for pairs of `MATSEQAIJ` matrices, for the `MATSEQDENSE` class,
10410:   and for pairs of `MATMPIDENSE` matrices.

10412:   This is a convenience routine that wraps the use of the `MatProductCreate()` with a `MatProductType` of `MATPRODUCT_ABt`
10413:   functionality into a single function call. For more involved matrix-matrix operations see `MatProductCreate()`.

10415:   The deprecated `PETSC_DEFAULT` in `fill` also means use the current value

10417: .seealso: [](ch_matrices), `Mat`, `MatProductCreate()`, `MATPRODUCT_ABt`, `MatMatMult()`, `MatTransposeMatMult()`, `MatPtAP()`, `MatProductAlgorithm`, `MatProductType`
10418: @*/
10419: PetscErrorCode MatMatTransposeMult(Mat A, Mat B, MatReuse scall, PetscReal fill, Mat *C)
10420: {
10421:   PetscFunctionBegin;
10422:   PetscCall(MatProduct_Private(A, B, scall, fill, MATPRODUCT_ABt, C));
10423:   if (A == B) PetscCall(MatSetOption(*C, MAT_SYMMETRIC, PETSC_TRUE));
10424:   PetscFunctionReturn(PETSC_SUCCESS);
10425: }

10427: /*@
10428:   MatTransposeMatMult - Performs matrix-matrix multiplication $C = A^T*B$.

10430:   Neighbor-wise Collective

10432:   Input Parameters:
10433: + A     - the left matrix
10434: . B     - the right matrix
10435: . scall - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`
10436: - fill  - expected fill as ratio of nnz(C)/(nnz(A) + nnz(B)), use `PETSC_DETERMINE` or `PETSC_CURRENT` if not known

10438:   Output Parameter:
10439: . C - the product matrix

10441:   Level: intermediate

10443:   Notes:
10444:   `C` will be created if `MAT_INITIAL_MATRIX` and must be destroyed by the user with `MatDestroy()`.

10446:   `MAT_REUSE_MATRIX` can only be used if `A` and `B` have the same nonzero pattern as in the previous call.

10448:   This is a convenience routine that wraps the use of `MatProductCreate()` with a `MatProductType` of `MATPRODUCT_AtB`
10449:   functionality into a single function call. For more involved matrix-matrix operations see `MatProductCreate()`.

10451:   To determine the correct fill value, run with -info and search for the string "Fill ratio" to see the value
10452:   actually needed.

10454:   This routine is currently implemented for pairs of `MATAIJ` matrices and pairs of `MATSEQDENSE` matrices and classes
10455:   which inherit from `MATSEQAIJ`.  `C` will be of the same type as the input matrices.

10457:   The deprecated `PETSC_DEFAULT` in `fill` also means use the current value

10459: .seealso: [](ch_matrices), `Mat`, `MatProductCreate()`, `MATPRODUCT_AtB`, `MatMatMult()`, `MatMatTransposeMult()`, `MatPtAP()`
10460: @*/
10461: PetscErrorCode MatTransposeMatMult(Mat A, Mat B, MatReuse scall, PetscReal fill, Mat *C)
10462: {
10463:   PetscFunctionBegin;
10464:   PetscCall(MatProduct_Private(A, B, scall, fill, MATPRODUCT_AtB, C));
10465:   PetscFunctionReturn(PETSC_SUCCESS);
10466: }

10468: /*@
10469:   MatMatMatMult - Performs matrix-matrix-matrix multiplication D=A*B*C.

10471:   Neighbor-wise Collective

10473:   Input Parameters:
10474: + A     - the left matrix
10475: . B     - the middle matrix
10476: . C     - the right matrix
10477: . scall - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`
10478: - 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
10479:           if the result is a dense matrix this is irrelevant

10481:   Output Parameter:
10482: . D - the product matrix

10484:   Level: intermediate

10486:   Notes:
10487:   Unless `scall` is `MAT_REUSE_MATRIX` `D` will be created.

10489:   `MAT_REUSE_MATRIX` can only be used if the matrices `A`, `B`, and `C` have the same nonzero pattern as in the previous call

10491:   This is a convenience routine that wraps the use of the `MatProductCreate()` with a `MatProductType` of `MATPRODUCT_ABC`
10492:   functionality into a single function call. For more involved matrix-matrix operations see `MatProductCreate()`.

10494:   To determine the correct fill value, run with `-info` and search for the string "Fill ratio" to see the value
10495:   actually needed.

10497:   If you have many matrices with the same non-zero structure to multiply, you
10498:   should use `MAT_REUSE_MATRIX` in all calls but the first

10500:   The deprecated `PETSC_DEFAULT` in `fill` also means use the current value

10502: .seealso: [](ch_matrices), `Mat`, `MatProductCreate()`, `MATPRODUCT_ABC`, `MatMatMult`, `MatPtAP()`, `MatMatTransposeMult()`, `MatTransposeMatMult()`
10503: @*/
10504: PetscErrorCode MatMatMatMult(Mat A, Mat B, Mat C, MatReuse scall, PetscReal fill, Mat *D)
10505: {
10506:   PetscFunctionBegin;
10507:   if (scall == MAT_REUSE_MATRIX) MatCheckProduct(*D, 6);
10508:   PetscCheck(scall != MAT_INPLACE_MATRIX, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "Inplace product not supported");

10510:   if (scall == MAT_INITIAL_MATRIX) {
10511:     PetscCall(MatProductCreate(A, B, C, D));
10512:     PetscCall(MatProductSetType(*D, MATPRODUCT_ABC));
10513:     PetscCall(MatProductSetAlgorithm(*D, "default"));
10514:     PetscCall(MatProductSetFill(*D, fill));

10516:     (*D)->product->api_user = PETSC_TRUE;
10517:     PetscCall(MatProductSetFromOptions(*D));
10518:     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,
10519:                ((PetscObject)C)->type_name);
10520:     PetscCall(MatProductSymbolic(*D));
10521:   } else { /* user may change input matrices when REUSE */
10522:     PetscCall(MatProductReplaceMats(A, B, C, *D));
10523:   }
10524:   PetscCall(MatProductNumeric(*D));
10525:   PetscFunctionReturn(PETSC_SUCCESS);
10526: }

10528: /*@
10529:   MatCreateRedundantMatrix - Create redundant matrices and put them into processors of subcommunicators.

10531:   Collective

10533:   Input Parameters:
10534: + mat      - the matrix
10535: . nsubcomm - the number of subcommunicators (= number of redundant parallel or sequential matrices)
10536: . subcomm  - MPI communicator split from the communicator where mat resides in (or `MPI_COMM_NULL` if nsubcomm is used)
10537: - reuse    - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`

10539:   Output Parameter:
10540: . matredundant - redundant matrix

10542:   Level: advanced

10544:   Notes:
10545:   `MAT_REUSE_MATRIX` can only be used when the nonzero structure of the
10546:   original matrix has not changed from that last call to `MatCreateRedundantMatrix()`.

10548:   This routine creates the duplicated matrices in the subcommunicators; you should NOT create them before
10549:   calling it.

10551:   `PetscSubcommCreate()` can be used to manage the creation of the subcomm but need not be.

10553: .seealso: [](ch_matrices), `Mat`, `MatDestroy()`, `PetscSubcommCreate()`, `PetscSubcomm`
10554: @*/
10555: PetscErrorCode MatCreateRedundantMatrix(Mat mat, PetscInt nsubcomm, MPI_Comm subcomm, MatReuse reuse, Mat *matredundant)
10556: {
10557:   MPI_Comm       comm;
10558:   PetscMPIInt    size;
10559:   PetscInt       mloc_sub, nloc_sub, rstart, rend, M = mat->rmap->N, N = mat->cmap->N, bs = mat->rmap->bs;
10560:   Mat_Redundant *redund     = NULL;
10561:   PetscSubcomm   psubcomm   = NULL;
10562:   MPI_Comm       subcomm_in = subcomm;
10563:   Mat           *matseq;
10564:   IS             isrow, iscol;
10565:   PetscBool      newsubcomm = PETSC_FALSE;

10567:   PetscFunctionBegin;
10569:   if (nsubcomm && reuse == MAT_REUSE_MATRIX) {
10570:     PetscAssertPointer(*matredundant, 5);
10572:   }

10574:   PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)mat), &size));
10575:   if (size == 1 || nsubcomm == 1) {
10576:     if (reuse == MAT_INITIAL_MATRIX) {
10577:       PetscCall(MatDuplicate(mat, MAT_COPY_VALUES, matredundant));
10578:     } else {
10579:       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");
10580:       PetscCall(MatCopy(mat, *matredundant, SAME_NONZERO_PATTERN));
10581:     }
10582:     PetscFunctionReturn(PETSC_SUCCESS);
10583:   }

10585:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
10586:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
10587:   MatCheckPreallocated(mat, 1);

10589:   PetscCall(PetscLogEventBegin(MAT_RedundantMat, mat, 0, 0, 0));
10590:   if (subcomm_in == MPI_COMM_NULL && reuse == MAT_INITIAL_MATRIX) { /* get subcomm if user does not provide subcomm */
10591:     /* create psubcomm, then get subcomm */
10592:     PetscCall(PetscObjectGetComm((PetscObject)mat, &comm));
10593:     PetscCallMPI(MPI_Comm_size(comm, &size));
10594:     PetscCheck(nsubcomm >= 1 && nsubcomm <= size, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "nsubcomm must between 1 and %d", size);

10596:     PetscCall(PetscSubcommCreate(comm, &psubcomm));
10597:     PetscCall(PetscSubcommSetNumber(psubcomm, nsubcomm));
10598:     PetscCall(PetscSubcommSetType(psubcomm, PETSC_SUBCOMM_CONTIGUOUS));
10599:     PetscCall(PetscSubcommSetFromOptions(psubcomm));
10600:     PetscCall(PetscCommDuplicate(PetscSubcommChild(psubcomm), &subcomm, NULL));
10601:     newsubcomm = PETSC_TRUE;
10602:     PetscCall(PetscSubcommDestroy(&psubcomm));
10603:   }

10605:   /* get isrow, iscol and a local sequential matrix matseq[0] */
10606:   if (reuse == MAT_INITIAL_MATRIX) {
10607:     mloc_sub = PETSC_DECIDE;
10608:     nloc_sub = PETSC_DECIDE;
10609:     if (bs < 1) {
10610:       PetscCall(PetscSplitOwnership(subcomm, &mloc_sub, &M));
10611:       PetscCall(PetscSplitOwnership(subcomm, &nloc_sub, &N));
10612:     } else {
10613:       PetscCall(PetscSplitOwnershipBlock(subcomm, bs, &mloc_sub, &M));
10614:       PetscCall(PetscSplitOwnershipBlock(subcomm, bs, &nloc_sub, &N));
10615:     }
10616:     PetscCallMPI(MPI_Scan(&mloc_sub, &rend, 1, MPIU_INT, MPI_SUM, subcomm));
10617:     rstart = rend - mloc_sub;
10618:     PetscCall(ISCreateStride(PETSC_COMM_SELF, mloc_sub, rstart, 1, &isrow));
10619:     PetscCall(ISCreateStride(PETSC_COMM_SELF, N, 0, 1, &iscol));
10620:     PetscCall(ISSetIdentity(iscol));
10621:   } else { /* reuse == MAT_REUSE_MATRIX */
10622:     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");
10623:     /* retrieve subcomm */
10624:     PetscCall(PetscObjectGetComm((PetscObject)*matredundant, &subcomm));
10625:     redund = (*matredundant)->redundant;
10626:     isrow  = redund->isrow;
10627:     iscol  = redund->iscol;
10628:     matseq = redund->matseq;
10629:   }
10630:   PetscCall(MatCreateSubMatrices(mat, 1, &isrow, &iscol, reuse, &matseq));

10632:   /* get matredundant over subcomm */
10633:   if (reuse == MAT_INITIAL_MATRIX) {
10634:     PetscCall(MatCreateMPIMatConcatenateSeqMat(subcomm, matseq[0], nloc_sub, reuse, matredundant));

10636:     /* create a supporting struct and attach it to C for reuse */
10637:     PetscCall(PetscNew(&redund));
10638:     (*matredundant)->redundant = redund;
10639:     redund->isrow              = isrow;
10640:     redund->iscol              = iscol;
10641:     redund->matseq             = matseq;
10642:     if (newsubcomm) {
10643:       redund->subcomm = subcomm;
10644:     } else {
10645:       redund->subcomm = MPI_COMM_NULL;
10646:     }
10647:   } else {
10648:     PetscCall(MatCreateMPIMatConcatenateSeqMat(subcomm, matseq[0], PETSC_DECIDE, reuse, matredundant));
10649:   }
10650: #if defined(PETSC_HAVE_VIENNACL) || defined(PETSC_HAVE_CUDA) || defined(PETSC_HAVE_HIP)
10651:   if (matseq[0]->boundtocpu && matseq[0]->bindingpropagates) {
10652:     PetscCall(MatBindToCPU(*matredundant, PETSC_TRUE));
10653:     PetscCall(MatSetBindingPropagates(*matredundant, PETSC_TRUE));
10654:   }
10655: #endif
10656:   PetscCall(PetscLogEventEnd(MAT_RedundantMat, mat, 0, 0, 0));
10657:   PetscFunctionReturn(PETSC_SUCCESS);
10658: }

10660: /*@C
10661:   MatGetMultiProcBlock - Create multiple 'parallel submatrices' from
10662:   a given `Mat`. Each submatrix can span multiple procs.

10664:   Collective

10666:   Input Parameters:
10667: + mat     - the matrix
10668: . subComm - the sub communicator obtained as if by `MPI_Comm_split(PetscObjectComm((PetscObject)mat))`
10669: - scall   - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`

10671:   Output Parameter:
10672: . subMat - parallel sub-matrices each spanning a given `subcomm`

10674:   Level: advanced

10676:   Notes:
10677:   The submatrix partition across processors is dictated by `subComm` a
10678:   communicator obtained by `MPI_comm_split()` or via `PetscSubcommCreate()`. The `subComm`
10679:   is not restricted to be grouped with consecutive original MPI processes.

10681:   Due the `MPI_Comm_split()` usage, the parallel layout of the submatrices
10682:   map directly to the layout of the original matrix [wrt the local
10683:   row,col partitioning]. So the original 'DiagonalMat' naturally maps
10684:   into the 'DiagonalMat' of the `subMat`, hence it is used directly from
10685:   the `subMat`. However the offDiagMat looses some columns - and this is
10686:   reconstructed with `MatSetValues()`

10688:   This is used by `PCBJACOBI` when a single block spans multiple MPI processes.

10690: .seealso: [](ch_matrices), `Mat`, `MatCreateRedundantMatrix()`, `MatCreateSubMatrices()`, `PCBJACOBI`
10691: @*/
10692: PetscErrorCode MatGetMultiProcBlock(Mat mat, MPI_Comm subComm, MatReuse scall, Mat *subMat)
10693: {
10694:   PetscMPIInt commsize, subCommSize;

10696:   PetscFunctionBegin;
10697:   PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)mat), &commsize));
10698:   PetscCallMPI(MPI_Comm_size(subComm, &subCommSize));
10699:   PetscCheck(subCommSize <= commsize, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_OUTOFRANGE, "CommSize %d < SubCommZize %d", commsize, subCommSize);

10701:   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");
10702:   PetscCall(PetscLogEventBegin(MAT_GetMultiProcBlock, mat, 0, 0, 0));
10703:   PetscUseTypeMethod(mat, getmultiprocblock, subComm, scall, subMat);
10704:   PetscCall(PetscLogEventEnd(MAT_GetMultiProcBlock, mat, 0, 0, 0));
10705:   PetscFunctionReturn(PETSC_SUCCESS);
10706: }

10708: /*@
10709:   MatGetLocalSubMatrix - Gets a reference to a submatrix specified in local numbering

10711:   Not Collective

10713:   Input Parameters:
10714: + mat   - matrix to extract local submatrix from
10715: . isrow - local row indices for submatrix
10716: - iscol - local column indices for submatrix

10718:   Output Parameter:
10719: . submat - the submatrix

10721:   Level: intermediate

10723:   Notes:
10724:   `submat` should be disposed of with `MatRestoreLocalSubMatrix()`.

10726:   Depending on the format of `mat`, the returned `submat` may not implement `MatMult()`.  Its communicator may be
10727:   the same as `mat`, it may be `PETSC_COMM_SELF`, or some other sub-communictor of `mat`'s.

10729:   `submat` always implements `MatSetValuesLocal()`.  If `isrow` and `iscol` have the same block size, then
10730:   `MatSetValuesBlockedLocal()` will also be implemented.

10732:   `mat` must have had a `ISLocalToGlobalMapping` provided to it with `MatSetLocalToGlobalMapping()`.
10733:   Matrices obtained with `DMCreateMatrix()` generally already have the local to global mapping provided.

10735: .seealso: [](ch_matrices), `Mat`, `MatRestoreLocalSubMatrix()`, `MatCreateLocalRef()`, `MatSetLocalToGlobalMapping()`
10736: @*/
10737: PetscErrorCode MatGetLocalSubMatrix(Mat mat, IS isrow, IS iscol, Mat *submat)
10738: {
10739:   PetscFunctionBegin;
10743:   PetscCheckSameComm(isrow, 2, iscol, 3);
10744:   PetscAssertPointer(submat, 4);
10745:   PetscCheck(mat->rmap->mapping, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Matrix must have local to global mapping provided before this call");

10747:   if (mat->ops->getlocalsubmatrix) {
10748:     PetscUseTypeMethod(mat, getlocalsubmatrix, isrow, iscol, submat);
10749:   } else {
10750:     PetscCall(MatCreateLocalRef(mat, isrow, iscol, submat));
10751:   }
10752:   (*submat)->assembled = mat->assembled;
10753:   PetscFunctionReturn(PETSC_SUCCESS);
10754: }

10756: /*@
10757:   MatRestoreLocalSubMatrix - Restores a reference to a submatrix specified in local numbering obtained with `MatGetLocalSubMatrix()`

10759:   Not Collective

10761:   Input Parameters:
10762: + mat    - matrix to extract local submatrix from
10763: . isrow  - local row indices for submatrix
10764: . iscol  - local column indices for submatrix
10765: - submat - the submatrix

10767:   Level: intermediate

10769: .seealso: [](ch_matrices), `Mat`, `MatGetLocalSubMatrix()`
10770: @*/
10771: PetscErrorCode MatRestoreLocalSubMatrix(Mat mat, IS isrow, IS iscol, Mat *submat)
10772: {
10773:   PetscFunctionBegin;
10777:   PetscCheckSameComm(isrow, 2, iscol, 3);
10778:   PetscAssertPointer(submat, 4);

10781:   if (mat->ops->restorelocalsubmatrix) {
10782:     PetscUseTypeMethod(mat, restorelocalsubmatrix, isrow, iscol, submat);
10783:   } else {
10784:     PetscCall(MatDestroy(submat));
10785:   }
10786:   *submat = NULL;
10787:   PetscFunctionReturn(PETSC_SUCCESS);
10788: }

10790: /*@
10791:   MatFindZeroDiagonals - Finds all the rows of a matrix that have zero or no diagonal entry in the matrix

10793:   Collective

10795:   Input Parameter:
10796: . mat - the matrix

10798:   Output Parameter:
10799: . is - if any rows have zero diagonals this contains the list of them

10801:   Level: developer

10803: .seealso: [](ch_matrices), `Mat`, `MatMultTranspose()`, `MatMultAdd()`, `MatMultTransposeAdd()`
10804: @*/
10805: PetscErrorCode MatFindZeroDiagonals(Mat mat, IS *is)
10806: {
10807:   PetscFunctionBegin;
10810:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
10811:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");

10813:   if (!mat->ops->findzerodiagonals) {
10814:     Vec                diag;
10815:     const PetscScalar *a;
10816:     PetscInt          *rows;
10817:     PetscInt           rStart, rEnd, r, nrow = 0;

10819:     PetscCall(MatCreateVecs(mat, &diag, NULL));
10820:     PetscCall(MatGetDiagonal(mat, diag));
10821:     PetscCall(MatGetOwnershipRange(mat, &rStart, &rEnd));
10822:     PetscCall(VecGetArrayRead(diag, &a));
10823:     for (r = 0; r < rEnd - rStart; ++r)
10824:       if (a[r] == 0.0) ++nrow;
10825:     PetscCall(PetscMalloc1(nrow, &rows));
10826:     nrow = 0;
10827:     for (r = 0; r < rEnd - rStart; ++r)
10828:       if (a[r] == 0.0) rows[nrow++] = r + rStart;
10829:     PetscCall(VecRestoreArrayRead(diag, &a));
10830:     PetscCall(VecDestroy(&diag));
10831:     PetscCall(ISCreateGeneral(PetscObjectComm((PetscObject)mat), nrow, rows, PETSC_OWN_POINTER, is));
10832:   } else {
10833:     PetscUseTypeMethod(mat, findzerodiagonals, is);
10834:   }
10835:   PetscFunctionReturn(PETSC_SUCCESS);
10836: }

10838: /*@
10839:   MatFindOffBlockDiagonalEntries - Finds all the rows of a matrix that have entries outside of the main diagonal block (defined by the matrix block size)

10841:   Collective

10843:   Input Parameter:
10844: . mat - the matrix

10846:   Output Parameter:
10847: . is - contains the list of rows with off block diagonal entries

10849:   Level: developer

10851: .seealso: [](ch_matrices), `Mat`, `MatMultTranspose()`, `MatMultAdd()`, `MatMultTransposeAdd()`
10852: @*/
10853: PetscErrorCode MatFindOffBlockDiagonalEntries(Mat mat, IS *is)
10854: {
10855:   PetscFunctionBegin;
10858:   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
10859:   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");

10861:   PetscUseTypeMethod(mat, findoffblockdiagonalentries, is);
10862:   PetscFunctionReturn(PETSC_SUCCESS);
10863: }

10865: /*@C
10866:   MatInvertBlockDiagonal - Inverts the block diagonal entries.

10868:   Collective; No Fortran Support

10870:   Input Parameter:
10871: . mat - the matrix

10873:   Output Parameter:
10874: . values - the block inverses in column major order (FORTRAN-like)

10876:   Level: advanced

10878:   Notes:
10879:   The size of the blocks is determined by the block size of the matrix.

10881:   The blocks never overlap between two MPI processes, use `MatInvertVariableBlockEnvelope()` for that case

10883:   The blocks all have the same size, use `MatInvertVariableBlockDiagonal()` for variable block size

10885: .seealso: [](ch_matrices), `Mat`, `MatInvertVariableBlockEnvelope()`, `MatInvertBlockDiagonalMat()`
10886: @*/
10887: PetscErrorCode MatInvertBlockDiagonal(Mat mat, const PetscScalar *values[])
10888: {
10889:   PetscFunctionBegin;
10891:   PetscCheck(mat->assembled, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
10892:   PetscCheck(!mat->factortype, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
10893:   PetscUseTypeMethod(mat, invertblockdiagonal, values);
10894:   PetscFunctionReturn(PETSC_SUCCESS);
10895: }

10897: /*@
10898:   MatInvertVariableBlockDiagonal - Inverts the point block diagonal entries.

10900:   Collective; No Fortran Support

10902:   Input Parameters:
10903: + mat     - the matrix
10904: . nblocks - the number of blocks on the process, set with `MatSetVariableBlockSizes()`
10905: - bsizes  - the size of each block on the process, set with `MatSetVariableBlockSizes()`

10907:   Output Parameter:
10908: . values - the block inverses in column major order (FORTRAN-like)

10910:   Level: advanced

10912:   Notes:
10913:   Use `MatInvertBlockDiagonal()` if all blocks have the same size

10915:   The blocks never overlap between two MPI processes, use `MatInvertVariableBlockEnvelope()` for that case

10917: .seealso: [](ch_matrices), `Mat`, `MatInvertBlockDiagonal()`, `MatSetVariableBlockSizes()`, `MatInvertVariableBlockEnvelope()`
10918: @*/
10919: PetscErrorCode MatInvertVariableBlockDiagonal(Mat mat, PetscInt nblocks, const PetscInt bsizes[], PetscScalar values[])
10920: {
10921:   PetscFunctionBegin;
10923:   PetscCheck(mat->assembled, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
10924:   PetscCheck(!mat->factortype, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
10925:   PetscUseTypeMethod(mat, invertvariableblockdiagonal, nblocks, bsizes, values);
10926:   PetscFunctionReturn(PETSC_SUCCESS);
10927: }

10929: /*@
10930:   MatInvertBlockDiagonalMat - set the values of matrix C to be the inverted block diagonal of matrix A

10932:   Collective

10934:   Input Parameters:
10935: + A - the matrix
10936: - C - matrix with inverted block diagonal of `A`.  This matrix should be created and may have its type set.

10938:   Level: advanced

10940:   Note:
10941:   The blocksize of the matrix is used to determine the blocks on the diagonal of `C`

10943: .seealso: [](ch_matrices), `Mat`, `MatInvertBlockDiagonal()`
10944: @*/
10945: PetscErrorCode MatInvertBlockDiagonalMat(Mat A, Mat C)
10946: {
10947:   const PetscScalar *vals;
10948:   PetscInt          *dnnz;
10949:   PetscInt           m, rstart, rend, bs, i, j;

10951:   PetscFunctionBegin;
10952:   PetscCall(MatInvertBlockDiagonal(A, &vals));
10953:   PetscCall(MatGetBlockSize(A, &bs));
10954:   PetscCall(MatGetLocalSize(A, &m, NULL));
10955:   PetscCall(MatSetLayouts(C, A->rmap, A->cmap));
10956:   PetscCall(MatSetBlockSizes(C, A->rmap->bs, A->cmap->bs));
10957:   PetscCall(PetscMalloc1(m / bs, &dnnz));
10958:   for (j = 0; j < m / bs; j++) dnnz[j] = 1;
10959:   PetscCall(MatXAIJSetPreallocation(C, bs, dnnz, NULL, NULL, NULL));
10960:   PetscCall(PetscFree(dnnz));
10961:   PetscCall(MatGetOwnershipRange(C, &rstart, &rend));
10962:   PetscCall(MatSetOption(C, MAT_ROW_ORIENTED, PETSC_FALSE));
10963:   for (i = rstart / bs; i < rend / bs; i++) PetscCall(MatSetValuesBlocked(C, 1, &i, 1, &i, &vals[(i - rstart / bs) * bs * bs], INSERT_VALUES));
10964:   PetscCall(MatSetOption(C, MAT_NO_OFF_PROC_ENTRIES, PETSC_TRUE));
10965:   PetscCall(MatAssemblyBegin(C, MAT_FINAL_ASSEMBLY));
10966:   PetscCall(MatAssemblyEnd(C, MAT_FINAL_ASSEMBLY));
10967:   PetscCall(MatSetOption(C, MAT_NO_OFF_PROC_ENTRIES, PETSC_FALSE));
10968:   PetscCall(MatSetOption(C, MAT_ROW_ORIENTED, PETSC_TRUE));
10969:   PetscFunctionReturn(PETSC_SUCCESS);
10970: }

10972: /*@
10973:   MatTransposeColoringDestroy - Destroys a coloring context for matrix product $C = A*B^T$ that was created
10974:   via `MatTransposeColoringCreate()`.

10976:   Collective

10978:   Input Parameter:
10979: . c - coloring context

10981:   Level: intermediate

10983: .seealso: [](ch_matrices), `Mat`, `MatTransposeColoringCreate()`
10984: @*/
10985: PetscErrorCode MatTransposeColoringDestroy(MatTransposeColoring *c)
10986: {
10987:   MatTransposeColoring matcolor = *c;

10989:   PetscFunctionBegin;
10990:   if (!matcolor) PetscFunctionReturn(PETSC_SUCCESS);
10991:   if (--((PetscObject)matcolor)->refct > 0) {
10992:     matcolor = NULL;
10993:     PetscFunctionReturn(PETSC_SUCCESS);
10994:   }

10996:   PetscCall(PetscFree3(matcolor->ncolumns, matcolor->nrows, matcolor->colorforrow));
10997:   PetscCall(PetscFree(matcolor->rows));
10998:   PetscCall(PetscFree(matcolor->den2sp));
10999:   PetscCall(PetscFree(matcolor->colorforcol));
11000:   PetscCall(PetscFree(matcolor->columns));
11001:   if (matcolor->brows > 0) PetscCall(PetscFree(matcolor->lstart));
11002:   PetscCall(PetscHeaderDestroy(c));
11003:   PetscFunctionReturn(PETSC_SUCCESS);
11004: }

11006: /*@
11007:   MatTransColoringApplySpToDen - Given a symbolic matrix product $C = A*B^T$ for which
11008:   a `MatTransposeColoring` context has been created, computes a dense $B^T$ by applying
11009:   `MatTransposeColoring` to sparse `B`.

11011:   Collective

11013:   Input Parameters:
11014: + coloring - coloring context created with `MatTransposeColoringCreate()`
11015: - B        - sparse matrix

11017:   Output Parameter:
11018: . Btdense - dense matrix $B^T$

11020:   Level: developer

11022:   Note:
11023:   These are used internally for some implementations of `MatRARt()`

11025: .seealso: [](ch_matrices), `Mat`, `MatTransposeColoringCreate()`, `MatTransposeColoringDestroy()`, `MatTransColoringApplyDenToSp()`
11026: @*/
11027: PetscErrorCode MatTransColoringApplySpToDen(MatTransposeColoring coloring, Mat B, Mat Btdense)
11028: {
11029:   PetscFunctionBegin;

11034:   PetscCall((*B->ops->transcoloringapplysptoden)(coloring, B, Btdense));
11035:   PetscFunctionReturn(PETSC_SUCCESS);
11036: }

11038: /*@
11039:   MatTransColoringApplyDenToSp - Given a symbolic matrix product $C_{sp} = A*B^T$ for which
11040:   a `MatTransposeColoring` context has been created and a dense matrix $C_{den} = A*B^T_{dense}$
11041:   in which `B^T_{dens}` is obtained from `MatTransColoringApplySpToDen()`, recover sparse matrix
11042:   $C_{sp}$ from $C_{den}$.

11044:   Collective

11046:   Input Parameters:
11047: + matcoloring - coloring context created with `MatTransposeColoringCreate()`
11048: - Cden        - matrix product of a sparse matrix and a dense matrix Btdense

11050:   Output Parameter:
11051: . Csp - sparse matrix

11053:   Level: developer

11055:   Note:
11056:   These are used internally for some implementations of `MatRARt()`

11058: .seealso: [](ch_matrices), `Mat`, `MatTransposeColoringCreate()`, `MatTransposeColoringDestroy()`, `MatTransColoringApplySpToDen()`
11059: @*/
11060: PetscErrorCode MatTransColoringApplyDenToSp(MatTransposeColoring matcoloring, Mat Cden, Mat Csp)
11061: {
11062:   PetscFunctionBegin;

11067:   PetscCall((*Csp->ops->transcoloringapplydentosp)(matcoloring, Cden, Csp));
11068:   PetscCall(MatAssemblyBegin(Csp, MAT_FINAL_ASSEMBLY));
11069:   PetscCall(MatAssemblyEnd(Csp, MAT_FINAL_ASSEMBLY));
11070:   PetscFunctionReturn(PETSC_SUCCESS);
11071: }

11073: /*@
11074:   MatTransposeColoringCreate - Creates a matrix coloring context for the matrix product $C = A*B^T$.

11076:   Collective

11078:   Input Parameters:
11079: + mat        - the matrix product C
11080: - iscoloring - the coloring of the matrix; usually obtained with `MatColoringCreate()` or `DMCreateColoring()`

11082:   Output Parameter:
11083: . color - the new coloring context

11085:   Level: intermediate

11087: .seealso: [](ch_matrices), `Mat`, `MatTransposeColoringDestroy()`, `MatTransColoringApplySpToDen()`,
11088:           `MatTransColoringApplyDenToSp()`
11089: @*/
11090: PetscErrorCode MatTransposeColoringCreate(Mat mat, ISColoring iscoloring, MatTransposeColoring *color)
11091: {
11092:   MatTransposeColoring c;
11093:   MPI_Comm             comm;

11095:   PetscFunctionBegin;
11096:   PetscAssertPointer(color, 3);

11098:   PetscCall(PetscLogEventBegin(MAT_TransposeColoringCreate, mat, 0, 0, 0));
11099:   PetscCall(PetscObjectGetComm((PetscObject)mat, &comm));
11100:   PetscCall(PetscHeaderCreate(c, MAT_TRANSPOSECOLORING_CLASSID, "MatTransposeColoring", "Matrix product C=A*B^T via coloring", "Mat", comm, MatTransposeColoringDestroy, NULL));
11101:   c->ctype = iscoloring->ctype;
11102:   PetscUseTypeMethod(mat, transposecoloringcreate, iscoloring, c);
11103:   *color = c;
11104:   PetscCall(PetscLogEventEnd(MAT_TransposeColoringCreate, mat, 0, 0, 0));
11105:   PetscFunctionReturn(PETSC_SUCCESS);
11106: }

11108: /*@
11109:   MatGetNonzeroState - Returns a 64-bit integer representing the current state of nonzeros in the matrix. If the
11110:   matrix has had new nonzero locations added to (or removed from) the matrix since the previous call, the value will be larger.

11112:   Not Collective

11114:   Input Parameter:
11115: . mat - the matrix

11117:   Output Parameter:
11118: . state - the current state

11120:   Level: intermediate

11122:   Notes:
11123:   You can only compare states from two different calls to the SAME matrix, you cannot compare calls between
11124:   different matrices

11126:   Use `PetscObjectStateGet()` to check for changes to the numerical values in a matrix

11128:   Use the result of `PetscObjectGetId()` to compare if a previously checked matrix is the same as the current matrix, do not compare object pointers.

11130: .seealso: [](ch_matrices), `Mat`, `PetscObjectStateGet()`, `PetscObjectGetId()`
11131: @*/
11132: PetscErrorCode MatGetNonzeroState(Mat mat, PetscObjectState *state)
11133: {
11134:   PetscFunctionBegin;
11136:   *state = mat->nonzerostate;
11137:   PetscFunctionReturn(PETSC_SUCCESS);
11138: }

11140: /*@
11141:   MatCreateMPIMatConcatenateSeqMat - Creates a single large PETSc matrix by concatenating sequential
11142:   matrices from each processor

11144:   Collective

11146:   Input Parameters:
11147: + comm   - the communicators the parallel matrix will live on
11148: . seqmat - the input sequential matrices
11149: . n      - number of local columns (or `PETSC_DECIDE`)
11150: - reuse  - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`

11152:   Output Parameter:
11153: . mpimat - the parallel matrix generated

11155:   Level: developer

11157:   Note:
11158:   The number of columns of the matrix in EACH processor MUST be the same.

11160: .seealso: [](ch_matrices), `Mat`
11161: @*/
11162: PetscErrorCode MatCreateMPIMatConcatenateSeqMat(MPI_Comm comm, Mat seqmat, PetscInt n, MatReuse reuse, Mat *mpimat)
11163: {
11164:   PetscMPIInt size;

11166:   PetscFunctionBegin;
11167:   PetscCallMPI(MPI_Comm_size(comm, &size));
11168:   if (size == 1) {
11169:     if (reuse == MAT_INITIAL_MATRIX) {
11170:       PetscCall(MatDuplicate(seqmat, MAT_COPY_VALUES, mpimat));
11171:     } else {
11172:       PetscCall(MatCopy(seqmat, *mpimat, SAME_NONZERO_PATTERN));
11173:     }
11174:     PetscFunctionReturn(PETSC_SUCCESS);
11175:   }

11177:   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");

11179:   PetscCall(PetscLogEventBegin(MAT_Merge, seqmat, 0, 0, 0));
11180:   PetscCall((*seqmat->ops->creatempimatconcatenateseqmat)(comm, seqmat, n, reuse, mpimat));
11181:   PetscCall(PetscLogEventEnd(MAT_Merge, seqmat, 0, 0, 0));
11182:   PetscFunctionReturn(PETSC_SUCCESS);
11183: }

11185: /*@
11186:   MatSubdomainsCreateCoalesce - Creates index subdomains by coalescing adjacent MPI processes' ownership ranges.

11188:   Collective

11190:   Input Parameters:
11191: + A - the matrix to create subdomains from
11192: - N - requested number of subdomains

11194:   Output Parameters:
11195: + n   - number of subdomains resulting on this MPI process
11196: - iss - `IS` list with indices of subdomains on this MPI process

11198:   Level: advanced

11200:   Note:
11201:   The number of subdomains must be smaller than the communicator size

11203: .seealso: [](ch_matrices), `Mat`, `IS`
11204: @*/
11205: PetscErrorCode MatSubdomainsCreateCoalesce(Mat A, PetscInt N, PetscInt *n, IS *iss[])
11206: {
11207:   MPI_Comm    comm, subcomm;
11208:   PetscMPIInt size, rank, color;
11209:   PetscInt    rstart, rend, k;

11211:   PetscFunctionBegin;
11212:   PetscCall(PetscObjectGetComm((PetscObject)A, &comm));
11213:   PetscCallMPI(MPI_Comm_size(comm, &size));
11214:   PetscCallMPI(MPI_Comm_rank(comm, &rank));
11215:   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);
11216:   *n    = 1;
11217:   k     = size / N + (size % N > 0); /* There are up to k ranks to a color */
11218:   color = rank / k;
11219:   PetscCallMPI(MPI_Comm_split(comm, color, rank, &subcomm));
11220:   PetscCall(PetscMalloc1(1, iss));
11221:   PetscCall(MatGetOwnershipRange(A, &rstart, &rend));
11222:   PetscCall(ISCreateStride(subcomm, rend - rstart, rstart, 1, iss[0]));
11223:   PetscCallMPI(MPI_Comm_free(&subcomm));
11224:   PetscFunctionReturn(PETSC_SUCCESS);
11225: }

11227: /*@
11228:   MatGalerkin - Constructs the coarse grid problem matrix via Galerkin projection.

11230:   If the interpolation and restriction operators are the same, uses `MatPtAP()`.
11231:   If they are not the same, uses `MatMatMatMult()`.

11233:   Once the coarse grid problem is constructed, correct for interpolation operators
11234:   that are not of full rank, which can legitimately happen in the case of non-nested
11235:   geometric multigrid.

11237:   Input Parameters:
11238: + restrct     - restriction operator
11239: . dA          - fine grid matrix
11240: . interpolate - interpolation operator
11241: . reuse       - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`
11242: - fill        - expected fill, use `PETSC_DETERMINE` or `PETSC_DETERMINE` if you do not have a good estimate

11244:   Output Parameter:
11245: . A - the Galerkin coarse matrix

11247:   Options Database Key:
11248: . -pc_mg_galerkin (both|pmat|mat|none) - for what matrices the Galerkin process should be used

11250:   Level: developer

11252:   Note:
11253:   The deprecated `PETSC_DEFAULT` in `fill` also means use the current value

11255: .seealso: [](ch_matrices), `Mat`, `MatPtAP()`, `MatMatMatMult()`
11256: @*/
11257: PetscErrorCode MatGalerkin(Mat restrct, Mat dA, Mat interpolate, MatReuse reuse, PetscReal fill, Mat *A)
11258: {
11259:   IS  zerorows;
11260:   Vec diag;

11262:   PetscFunctionBegin;
11263:   PetscCheck(reuse != MAT_INPLACE_MATRIX, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "Inplace product not supported");
11264:   /* Construct the coarse grid matrix */
11265:   if (interpolate == restrct) {
11266:     PetscCall(MatPtAP(dA, interpolate, reuse, fill, A));
11267:   } else {
11268:     PetscCall(MatMatMatMult(restrct, dA, interpolate, reuse, fill, A));
11269:   }

11271:   /* If the interpolation matrix is not of full rank, A will have zero rows.
11272:      This can legitimately happen in the case of non-nested geometric multigrid.
11273:      In that event, we set the rows of the matrix to the rows of the identity,
11274:      ignoring the equations (as the RHS will also be zero). */

11276:   PetscCall(MatFindZeroRows(*A, &zerorows));

11278:   if (zerorows != NULL) { /* if there are any zero rows */
11279:     PetscCall(MatCreateVecs(*A, &diag, NULL));
11280:     PetscCall(MatGetDiagonal(*A, diag));
11281:     PetscCall(VecISSet(diag, zerorows, 1.0));
11282:     PetscCall(MatDiagonalSet(*A, diag, INSERT_VALUES));
11283:     PetscCall(VecDestroy(&diag));
11284:     PetscCall(ISDestroy(&zerorows));
11285:   }
11286:   PetscFunctionReturn(PETSC_SUCCESS);
11287: }

11289: /*@C
11290:   MatSetOperation - Allows user to set a matrix operation for any matrix type

11292:   Logically Collective

11294:   Input Parameters:
11295: + mat - the matrix
11296: . op  - the name of the operation
11297: - f   - the function that provides the operation

11299:   Level: developer

11301:   Example Usage:
11302: .vb
11303:   extern PetscErrorCode usermult(Mat, Vec, Vec);

11305:   PetscCall(MatCreateXXX(comm, ..., &A));
11306:   PetscCall(MatSetOperation(A, MATOP_MULT, (PetscErrorCodeFn *)usermult));
11307: .ve

11309:   Notes:
11310:   See the file `include/petscmat.h` for a complete list of matrix
11311:   operations, which all have the form MATOP_<OPERATION>, where
11312:   <OPERATION> is the name (in all capital letters) of the
11313:   user interface routine (e.g., `MatMult()` -> `MATOP_MULT`).

11315:   All user-provided functions (except for `MATOP_DESTROY`) should have the same calling
11316:   sequence as the usual matrix interface routines, since they
11317:   are intended to be accessed via the usual matrix interface
11318:   routines, e.g.,
11319: .vb
11320:   MatMult(Mat, Vec, Vec) -> usermult(Mat, Vec, Vec)
11321: .ve

11323:   In particular each function MUST return `PETSC_SUCCESS` on success and
11324:   nonzero on failure.

11326:   This routine is distinct from `MatShellSetOperation()` in that it can be called on any matrix type.

11328: .seealso: [](ch_matrices), `Mat`, `MatGetOperation()`, `MatCreateShell()`, `MatShellSetContext()`, `MatShellSetOperation()`
11329: @*/
11330: PetscErrorCode MatSetOperation(Mat mat, MatOperation op, PetscErrorCodeFn *f)
11331: {
11332:   PetscFunctionBegin;
11334:   if (op == MATOP_VIEW && !mat->ops->viewnative && f != (PetscErrorCodeFn *)mat->ops->view) mat->ops->viewnative = mat->ops->view;
11335:   (((PetscErrorCodeFn **)mat->ops)[op]) = f;
11336:   PetscFunctionReturn(PETSC_SUCCESS);
11337: }

11339: /*@C
11340:   MatGetOperation - Gets a matrix operation for any matrix type.

11342:   Not Collective

11344:   Input Parameters:
11345: + mat - the matrix
11346: - op  - the name of the operation

11348:   Output Parameter:
11349: . f - the function that provides the operation

11351:   Level: developer

11353:   Example Usage:
11354: .vb
11355:   PetscErrorCode (*usermult)(Mat, Vec, Vec);

11357:   MatGetOperation(A, MATOP_MULT, (PetscErrorCodeFn **)&usermult);
11358: .ve

11360:   Notes:
11361:   See the file `include/petscmat.h` for a complete list of matrix
11362:   operations, which all have the form MATOP_<OPERATION>, where
11363:   <OPERATION> is the name (in all capital letters) of the
11364:   user interface routine (e.g., `MatMult()` -> `MATOP_MULT`).

11366:   This routine is distinct from `MatShellGetOperation()` in that it can be called on any matrix type.

11368: .seealso: [](ch_matrices), `Mat`, `MatSetOperation()`, `MatCreateShell()`, `MatShellGetContext()`, `MatShellGetOperation()`
11369: @*/
11370: PetscErrorCode MatGetOperation(Mat mat, MatOperation op, PetscErrorCodeFn **f)
11371: {
11372:   PetscFunctionBegin;
11374:   *f = (((PetscErrorCodeFn **)mat->ops)[op]);
11375:   PetscFunctionReturn(PETSC_SUCCESS);
11376: }

11378: /*@
11379:   MatHasOperation - Determines whether the given matrix supports the particular operation.

11381:   Not Collective

11383:   Input Parameters:
11384: + mat - the matrix
11385: - op  - the operation, for example, `MATOP_GET_DIAGONAL`

11387:   Output Parameter:
11388: . has - either `PETSC_TRUE` or `PETSC_FALSE`

11390:   Level: advanced

11392:   Note:
11393:   See `MatSetOperation()` for additional discussion on naming convention and usage of `op`.

11395: .seealso: [](ch_matrices), `Mat`, `MatCreateShell()`, `MatGetOperation()`, `MatSetOperation()`
11396: @*/
11397: PetscErrorCode MatHasOperation(Mat mat, MatOperation op, PetscBool *has)
11398: {
11399:   PetscFunctionBegin;
11401:   PetscAssertPointer(has, 3);
11402:   if (mat->ops->hasoperation) {
11403:     PetscUseTypeMethod(mat, hasoperation, op, has);
11404:   } else {
11405:     if (((void **)mat->ops)[op]) *has = PETSC_TRUE;
11406:     else {
11407:       *has = PETSC_FALSE;
11408:       if (op == MATOP_CREATE_SUBMATRIX) {
11409:         PetscMPIInt size;

11411:         PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)mat), &size));
11412:         if (size == 1) PetscCall(MatHasOperation(mat, MATOP_CREATE_SUBMATRICES, has));
11413:       }
11414:     }
11415:   }
11416:   PetscFunctionReturn(PETSC_SUCCESS);
11417: }

11419: /*@
11420:   MatHasCongruentLayouts - Determines whether the rows and columns layouts of the matrix are congruent

11422:   Collective

11424:   Input Parameter:
11425: . mat - the matrix

11427:   Output Parameter:
11428: . cong - either `PETSC_TRUE` or `PETSC_FALSE`

11430:   Level: beginner

11432: .seealso: [](ch_matrices), `Mat`, `MatCreate()`, `MatSetSizes()`, `PetscLayout`
11433: @*/
11434: PetscErrorCode MatHasCongruentLayouts(Mat mat, PetscBool *cong)
11435: {
11436:   PetscFunctionBegin;
11439:   PetscAssertPointer(cong, 2);
11440:   if (!mat->rmap || !mat->cmap) {
11441:     *cong = mat->rmap == mat->cmap ? PETSC_TRUE : PETSC_FALSE;
11442:     PetscFunctionReturn(PETSC_SUCCESS);
11443:   }
11444:   if (mat->congruentlayouts == PETSC_DECIDE) { /* first time we compare rows and cols layouts */
11445:     PetscCall(PetscLayoutSetUp(mat->rmap));
11446:     PetscCall(PetscLayoutSetUp(mat->cmap));
11447:     PetscCall(PetscLayoutCompare(mat->rmap, mat->cmap, cong));
11448:     if (*cong) mat->congruentlayouts = 1;
11449:     else mat->congruentlayouts = 0;
11450:   } else *cong = mat->congruentlayouts ? PETSC_TRUE : PETSC_FALSE;
11451:   PetscFunctionReturn(PETSC_SUCCESS);
11452: }

11454: PetscErrorCode MatSetInf(Mat A)
11455: {
11456:   PetscFunctionBegin;
11457:   PetscUseTypeMethod(A, setinf);
11458:   PetscFunctionReturn(PETSC_SUCCESS);
11459: }

11461: /*@
11462:   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
11463:   and possibly removes small values from the graph structure.

11465:   Collective

11467:   Input Parameters:
11468: + A       - the matrix
11469: . sym     - `PETSC_TRUE` indicates that the graph should be symmetrized
11470: . scale   - `PETSC_TRUE` indicates that the graph edge weights should be symmetrically scaled with the diagonal entry
11471: . filter  - filter value - < 0: does nothing; == 0: removes only 0.0 entries; otherwise: removes entries with abs(entries) <= value
11472: . num_idx - size of 'index' array
11473: - index   - array of block indices to use for graph strength of connection weight

11475:   Output Parameter:
11476: . graph - the resulting graph

11478:   Level: advanced

11480: .seealso: [](ch_matrices), `Mat`, `MatCreate()`, `PCGAMG`
11481: @*/
11482: PetscErrorCode MatCreateGraph(Mat A, PetscBool sym, PetscBool scale, PetscReal filter, PetscInt num_idx, PetscInt index[], Mat *graph)
11483: {
11484:   PetscFunctionBegin;
11488:   PetscAssertPointer(graph, 7);
11489:   PetscCall(PetscLogEventBegin(MAT_CreateGraph, A, 0, 0, 0));
11490:   PetscUseTypeMethod(A, creategraph, sym, scale, filter, num_idx, index, graph);
11491:   PetscCall(PetscLogEventEnd(MAT_CreateGraph, A, 0, 0, 0));
11492:   PetscFunctionReturn(PETSC_SUCCESS);
11493: }

11495: /*@
11496:   MatEliminateZeros - eliminate the nondiagonal zero entries in place from the nonzero structure of a sparse `Mat` in place,
11497:   meaning the same memory is used for the matrix, and no new memory is allocated.

11499:   Collective

11501:   Input Parameters:
11502: + A    - the matrix
11503: - 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

11505:   Level: intermediate

11507:   Developer Note:
11508:   The entries in the sparse matrix data structure are shifted to fill in the unneeded locations in the data. Thus the end
11509:   of the arrays in the data structure are unneeded.

11511: .seealso: [](ch_matrices), `Mat`, `MatCreate()`, `MatCreateGraph()`, `MatFilter()`
11512: @*/
11513: PetscErrorCode MatEliminateZeros(Mat A, PetscBool keep)
11514: {
11515:   PetscFunctionBegin;
11517:   PetscUseTypeMethod(A, eliminatezeros, keep);
11518:   PetscFunctionReturn(PETSC_SUCCESS);
11519: }

11521: /*@C
11522:   MatGetCurrentMemType - Get the memory location of the matrix

11524:   Not Collective, but the result will be the same on all MPI processes

11526:   Input Parameter:
11527: . A - the matrix whose memory type we are checking

11529:   Output Parameter:
11530: . m - the memory type

11532:   Level: intermediate

11534: .seealso: [](ch_matrices), `Mat`, `MatBoundToCPU()`, `PetscMemType`
11535: @*/
11536: PetscErrorCode MatGetCurrentMemType(Mat A, PetscMemType *m)
11537: {
11538:   PetscFunctionBegin;
11540:   PetscAssertPointer(m, 2);
11541:   if (A->ops->getcurrentmemtype) PetscUseTypeMethod(A, getcurrentmemtype, m);
11542:   else *m = PETSC_MEMTYPE_HOST;
11543:   PetscFunctionReturn(PETSC_SUCCESS);
11544: }