xref: /petsc/src/mat/interface/matrix.c (revision 5d83a8b16d06840f96948f1a43aa9c83c769a60a)
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 */
6 
7 #include <petsc/private/matimpl.h> /*I "petscmat.h" I*/
8 #include <petsc/private/isimpl.h>
9 #include <petsc/private/vecimpl.h>
10 
11 /* Logging support */
12 PetscClassId MAT_CLASSID;
13 PetscClassId MAT_COLORING_CLASSID;
14 PetscClassId MAT_FDCOLORING_CLASSID;
15 PetscClassId MAT_TRANSPOSECOLORING_CLASSID;
16 
17 PetscLogEvent MAT_Mult, MAT_MultAdd, MAT_MultTranspose;
18 PetscLogEvent MAT_MultTransposeAdd, MAT_Solve, MAT_Solves, MAT_SolveAdd, MAT_SolveTranspose, MAT_MatSolve, MAT_MatTrSolve;
19 PetscLogEvent MAT_SolveTransposeAdd, MAT_SOR, MAT_ForwardSolve, MAT_BackwardSolve, MAT_LUFactor, MAT_LUFactorSymbolic;
20 PetscLogEvent MAT_LUFactorNumeric, MAT_CholeskyFactor, MAT_CholeskyFactorSymbolic, MAT_CholeskyFactorNumeric, MAT_ILUFactor;
21 PetscLogEvent MAT_ILUFactorSymbolic, MAT_ICCFactorSymbolic, MAT_Copy, MAT_Convert, MAT_Scale, MAT_AssemblyBegin;
22 PetscLogEvent MAT_QRFactorNumeric, MAT_QRFactorSymbolic, MAT_QRFactor;
23 PetscLogEvent MAT_AssemblyEnd, MAT_SetValues, MAT_GetValues, MAT_GetRow, MAT_GetRowIJ, MAT_CreateSubMats, MAT_GetOrdering, MAT_RedundantMat, MAT_GetSeqNonzeroStructure;
24 PetscLogEvent MAT_IncreaseOverlap, MAT_Partitioning, MAT_PartitioningND, MAT_Coarsen, MAT_ZeroEntries, MAT_Load, MAT_View, MAT_AXPY, MAT_FDColoringCreate;
25 PetscLogEvent MAT_FDColoringSetUp, MAT_FDColoringApply, MAT_Transpose, MAT_FDColoringFunction, MAT_CreateSubMat;
26 PetscLogEvent MAT_TransposeColoringCreate;
27 PetscLogEvent MAT_MatMult, MAT_MatMultSymbolic, MAT_MatMultNumeric;
28 PetscLogEvent MAT_PtAP, MAT_PtAPSymbolic, MAT_PtAPNumeric, MAT_RARt, MAT_RARtSymbolic, MAT_RARtNumeric;
29 PetscLogEvent MAT_MatTransposeMult, MAT_MatTransposeMultSymbolic, MAT_MatTransposeMultNumeric;
30 PetscLogEvent MAT_TransposeMatMult, MAT_TransposeMatMultSymbolic, MAT_TransposeMatMultNumeric;
31 PetscLogEvent MAT_MatMatMult, MAT_MatMatMultSymbolic, MAT_MatMatMultNumeric;
32 PetscLogEvent MAT_MultHermitianTranspose, MAT_MultHermitianTransposeAdd;
33 PetscLogEvent MAT_Getsymtransreduced, MAT_GetBrowsOfAcols;
34 PetscLogEvent MAT_GetBrowsOfAocols, MAT_Getlocalmat, MAT_Getlocalmatcondensed, MAT_Seqstompi, MAT_Seqstompinum, MAT_Seqstompisym;
35 PetscLogEvent MAT_GetMultiProcBlock;
36 PetscLogEvent MAT_CUSPARSECopyToGPU, MAT_CUSPARSECopyFromGPU, MAT_CUSPARSEGenerateTranspose, MAT_CUSPARSESolveAnalysis;
37 PetscLogEvent MAT_HIPSPARSECopyToGPU, MAT_HIPSPARSECopyFromGPU, MAT_HIPSPARSEGenerateTranspose, MAT_HIPSPARSESolveAnalysis;
38 PetscLogEvent MAT_PreallCOO, MAT_SetVCOO;
39 PetscLogEvent MAT_SetValuesBatch;
40 PetscLogEvent MAT_ViennaCLCopyToGPU;
41 PetscLogEvent MAT_CUDACopyToGPU, MAT_HIPCopyToGPU;
42 PetscLogEvent MAT_DenseCopyToGPU, MAT_DenseCopyFromGPU;
43 PetscLogEvent MAT_Merge, MAT_Residual, MAT_SetRandom;
44 PetscLogEvent MAT_FactorFactS, MAT_FactorInvS;
45 PetscLogEvent MATCOLORING_Apply, MATCOLORING_Comm, MATCOLORING_Local, MATCOLORING_ISCreate, MATCOLORING_SetUp, MATCOLORING_Weights;
46 PetscLogEvent MAT_H2Opus_Build, MAT_H2Opus_Compress, MAT_H2Opus_Orthog, MAT_H2Opus_LR;
47 
48 const char *const MatFactorTypes[] = {"NONE", "LU", "CHOLESKY", "ILU", "ICC", "ILUDT", "QR", "MatFactorType", "MAT_FACTOR_", NULL};
49 
50 /*@
51   MatSetRandom - Sets all components of a matrix to random numbers.
52 
53   Logically Collective
54 
55   Input Parameters:
56 + x    - the matrix
57 - rctx - the `PetscRandom` object, formed by `PetscRandomCreate()`, or `NULL` and
58           it will create one internally.
59 
60   Example:
61 .vb
62      PetscRandomCreate(PETSC_COMM_WORLD,&rctx);
63      MatSetRandom(x,rctx);
64      PetscRandomDestroy(rctx);
65 .ve
66 
67   Level: intermediate
68 
69   Notes:
70   For sparse matrices that have been preallocated but not been assembled, it randomly selects appropriate locations,
71 
72   for sparse matrices that already have nonzero locations, it fills the locations with random numbers.
73 
74   It generates an error if used on unassembled sparse matrices that have not been preallocated.
75 
76 .seealso: [](ch_matrices), `Mat`, `PetscRandom`, `PetscRandomCreate()`, `MatZeroEntries()`, `MatSetValues()`, `PetscRandomDestroy()`
77 @*/
78 PetscErrorCode MatSetRandom(Mat x, PetscRandom rctx)
79 {
80   PetscRandom randObj = NULL;
81 
82   PetscFunctionBegin;
83   PetscValidHeaderSpecific(x, MAT_CLASSID, 1);
84   if (rctx) PetscValidHeaderSpecific(rctx, PETSC_RANDOM_CLASSID, 2);
85   PetscValidType(x, 1);
86   MatCheckPreallocated(x, 1);
87 
88   if (!rctx) {
89     MPI_Comm comm;
90     PetscCall(PetscObjectGetComm((PetscObject)x, &comm));
91     PetscCall(PetscRandomCreate(comm, &randObj));
92     PetscCall(PetscRandomSetType(randObj, x->defaultrandtype));
93     PetscCall(PetscRandomSetFromOptions(randObj));
94     rctx = randObj;
95   }
96   PetscCall(PetscLogEventBegin(MAT_SetRandom, x, rctx, 0, 0));
97   PetscUseTypeMethod(x, setrandom, rctx);
98   PetscCall(PetscLogEventEnd(MAT_SetRandom, x, rctx, 0, 0));
99 
100   PetscCall(MatAssemblyBegin(x, MAT_FINAL_ASSEMBLY));
101   PetscCall(MatAssemblyEnd(x, MAT_FINAL_ASSEMBLY));
102   PetscCall(PetscRandomDestroy(&randObj));
103   PetscFunctionReturn(PETSC_SUCCESS);
104 }
105 
106 /*@
107   MatFactorGetErrorZeroPivot - returns the pivot value that was determined to be zero and the row it occurred in
108 
109   Logically Collective
110 
111   Input Parameter:
112 . mat - the factored matrix
113 
114   Output Parameters:
115 + pivot - the pivot value computed
116 - row   - the row that the zero pivot occurred. This row value must be interpreted carefully due to row reorderings and which processes
117          the share the matrix
118 
119   Level: advanced
120 
121   Notes:
122   This routine does not work for factorizations done with external packages.
123 
124   This routine should only be called if `MatGetFactorError()` returns a value of `MAT_FACTOR_NUMERIC_ZEROPIVOT`
125 
126   This can also be called on non-factored matrices that come from, for example, matrices used in SOR.
127 
128 .seealso: [](ch_matrices), `Mat`, `MatZeroEntries()`, `MatFactor()`, `MatGetFactor()`,
129 `MatLUFactorSymbolic()`, `MatCholeskyFactorSymbolic()`, `MatFactorClearError()`,
130 `MAT_FACTOR_NUMERIC_ZEROPIVOT`
131 @*/
132 PetscErrorCode MatFactorGetErrorZeroPivot(Mat mat, PetscReal *pivot, PetscInt *row)
133 {
134   PetscFunctionBegin;
135   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
136   PetscAssertPointer(pivot, 2);
137   PetscAssertPointer(row, 3);
138   *pivot = mat->factorerror_zeropivot_value;
139   *row   = mat->factorerror_zeropivot_row;
140   PetscFunctionReturn(PETSC_SUCCESS);
141 }
142 
143 /*@
144   MatFactorGetError - gets the error code from a factorization
145 
146   Logically Collective
147 
148   Input Parameter:
149 . mat - the factored matrix
150 
151   Output Parameter:
152 . err - the error code
153 
154   Level: advanced
155 
156   Note:
157   This can also be called on non-factored matrices that come from, for example, matrices used in SOR.
158 
159 .seealso: [](ch_matrices), `Mat`, `MatZeroEntries()`, `MatFactor()`, `MatGetFactor()`, `MatLUFactorSymbolic()`, `MatCholeskyFactorSymbolic()`,
160           `MatFactorClearError()`, `MatFactorGetErrorZeroPivot()`, `MatFactorError`
161 @*/
162 PetscErrorCode MatFactorGetError(Mat mat, MatFactorError *err)
163 {
164   PetscFunctionBegin;
165   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
166   PetscAssertPointer(err, 2);
167   *err = mat->factorerrortype;
168   PetscFunctionReturn(PETSC_SUCCESS);
169 }
170 
171 /*@
172   MatFactorClearError - clears the error code in a factorization
173 
174   Logically Collective
175 
176   Input Parameter:
177 . mat - the factored matrix
178 
179   Level: developer
180 
181   Note:
182   This can also be called on non-factored matrices that come from, for example, matrices used in SOR.
183 
184 .seealso: [](ch_matrices), `Mat`, `MatZeroEntries()`, `MatFactor()`, `MatGetFactor()`, `MatLUFactorSymbolic()`, `MatCholeskyFactorSymbolic()`, `MatFactorGetError()`, `MatFactorGetErrorZeroPivot()`,
185           `MatGetErrorCode()`, `MatFactorError`
186 @*/
187 PetscErrorCode MatFactorClearError(Mat mat)
188 {
189   PetscFunctionBegin;
190   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
191   mat->factorerrortype             = MAT_FACTOR_NOERROR;
192   mat->factorerror_zeropivot_value = 0.0;
193   mat->factorerror_zeropivot_row   = 0;
194   PetscFunctionReturn(PETSC_SUCCESS);
195 }
196 
197 PetscErrorCode MatFindNonzeroRowsOrCols_Basic(Mat mat, PetscBool cols, PetscReal tol, IS *nonzero)
198 {
199   Vec                r, l;
200   const PetscScalar *al;
201   PetscInt           i, nz, gnz, N, n, st;
202 
203   PetscFunctionBegin;
204   PetscCall(MatCreateVecs(mat, &r, &l));
205   if (!cols) { /* nonzero rows */
206     PetscCall(MatGetOwnershipRange(mat, &st, NULL));
207     PetscCall(MatGetSize(mat, &N, NULL));
208     PetscCall(MatGetLocalSize(mat, &n, NULL));
209     PetscCall(VecSet(l, 0.0));
210     PetscCall(VecSetRandom(r, NULL));
211     PetscCall(MatMult(mat, r, l));
212     PetscCall(VecGetArrayRead(l, &al));
213   } else { /* nonzero columns */
214     PetscCall(MatGetOwnershipRangeColumn(mat, &st, NULL));
215     PetscCall(MatGetSize(mat, NULL, &N));
216     PetscCall(MatGetLocalSize(mat, NULL, &n));
217     PetscCall(VecSet(r, 0.0));
218     PetscCall(VecSetRandom(l, NULL));
219     PetscCall(MatMultTranspose(mat, l, r));
220     PetscCall(VecGetArrayRead(r, &al));
221   }
222   if (tol <= 0.0) {
223     for (i = 0, nz = 0; i < n; i++)
224       if (al[i] != 0.0) nz++;
225   } else {
226     for (i = 0, nz = 0; i < n; i++)
227       if (PetscAbsScalar(al[i]) > tol) nz++;
228   }
229   PetscCall(MPIU_Allreduce(&nz, &gnz, 1, MPIU_INT, MPI_SUM, PetscObjectComm((PetscObject)mat)));
230   if (gnz != N) {
231     PetscInt *nzr;
232     PetscCall(PetscMalloc1(nz, &nzr));
233     if (nz) {
234       if (tol < 0) {
235         for (i = 0, nz = 0; i < n; i++)
236           if (al[i] != 0.0) nzr[nz++] = i + st;
237       } else {
238         for (i = 0, nz = 0; i < n; i++)
239           if (PetscAbsScalar(al[i]) > tol) nzr[nz++] = i + st;
240       }
241     }
242     PetscCall(ISCreateGeneral(PetscObjectComm((PetscObject)mat), nz, nzr, PETSC_OWN_POINTER, nonzero));
243   } else *nonzero = NULL;
244   if (!cols) { /* nonzero rows */
245     PetscCall(VecRestoreArrayRead(l, &al));
246   } else {
247     PetscCall(VecRestoreArrayRead(r, &al));
248   }
249   PetscCall(VecDestroy(&l));
250   PetscCall(VecDestroy(&r));
251   PetscFunctionReturn(PETSC_SUCCESS);
252 }
253 
254 /*@
255   MatFindNonzeroRows - Locate all rows that are not completely zero in the matrix
256 
257   Input Parameter:
258 . mat - the matrix
259 
260   Output Parameter:
261 . keptrows - the rows that are not completely zero
262 
263   Level: intermediate
264 
265   Note:
266   `keptrows` is set to `NULL` if all rows are nonzero.
267 
268   Developer Note:
269   If `keptrows` is not `NULL`, it must be sorted.
270 
271 .seealso: [](ch_matrices), `Mat`, `MatFindZeroRows()`
272  @*/
273 PetscErrorCode MatFindNonzeroRows(Mat mat, IS *keptrows)
274 {
275   PetscFunctionBegin;
276   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
277   PetscValidType(mat, 1);
278   PetscAssertPointer(keptrows, 2);
279   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
280   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
281   if (mat->ops->findnonzerorows) PetscUseTypeMethod(mat, findnonzerorows, keptrows);
282   else PetscCall(MatFindNonzeroRowsOrCols_Basic(mat, PETSC_FALSE, 0.0, keptrows));
283   if (keptrows && *keptrows) PetscCall(ISSetInfo(*keptrows, IS_SORTED, IS_GLOBAL, PETSC_FALSE, PETSC_TRUE));
284   PetscFunctionReturn(PETSC_SUCCESS);
285 }
286 
287 /*@
288   MatFindZeroRows - Locate all rows that are completely zero in the matrix
289 
290   Input Parameter:
291 . mat - the matrix
292 
293   Output Parameter:
294 . zerorows - the rows that are completely zero
295 
296   Level: intermediate
297 
298   Note:
299   `zerorows` is set to `NULL` if no rows are zero.
300 
301 .seealso: [](ch_matrices), `Mat`, `MatFindNonzeroRows()`
302  @*/
303 PetscErrorCode MatFindZeroRows(Mat mat, IS *zerorows)
304 {
305   IS       keptrows;
306   PetscInt m, n;
307 
308   PetscFunctionBegin;
309   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
310   PetscValidType(mat, 1);
311   PetscAssertPointer(zerorows, 2);
312   PetscCall(MatFindNonzeroRows(mat, &keptrows));
313   /* MatFindNonzeroRows sets keptrows to NULL if there are no zero rows.
314      In keeping with this convention, we set zerorows to NULL if there are no zero
315      rows. */
316   if (keptrows == NULL) {
317     *zerorows = NULL;
318   } else {
319     PetscCall(MatGetOwnershipRange(mat, &m, &n));
320     PetscCall(ISComplement(keptrows, m, n, zerorows));
321     PetscCall(ISDestroy(&keptrows));
322   }
323   PetscFunctionReturn(PETSC_SUCCESS);
324 }
325 
326 /*@
327   MatGetDiagonalBlock - Returns the part of the matrix associated with the on-process coupling
328 
329   Not Collective
330 
331   Input Parameter:
332 . A - the matrix
333 
334   Output Parameter:
335 . a - the diagonal part (which is a SEQUENTIAL matrix)
336 
337   Level: advanced
338 
339   Notes:
340   See `MatCreateAIJ()` for more information on the "diagonal part" of the matrix.
341 
342   Use caution, as the reference count on the returned matrix is not incremented and it is used as part of `A`'s normal operation.
343 
344 .seealso: [](ch_matrices), `Mat`, `MatCreateAIJ()`, `MATAIJ`, `MATBAIJ`, `MATSBAIJ`
345 @*/
346 PetscErrorCode MatGetDiagonalBlock(Mat A, Mat *a)
347 {
348   PetscFunctionBegin;
349   PetscValidHeaderSpecific(A, MAT_CLASSID, 1);
350   PetscValidType(A, 1);
351   PetscAssertPointer(a, 2);
352   PetscCheck(!A->factortype, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
353   if (A->ops->getdiagonalblock) PetscUseTypeMethod(A, getdiagonalblock, a);
354   else {
355     PetscMPIInt size;
356 
357     PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)A), &size));
358     PetscCheck(size == 1, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "Not for parallel matrix type %s", ((PetscObject)A)->type_name);
359     *a = A;
360   }
361   PetscFunctionReturn(PETSC_SUCCESS);
362 }
363 
364 /*@
365   MatGetTrace - Gets the trace of a matrix. The sum of the diagonal entries.
366 
367   Collective
368 
369   Input Parameter:
370 . mat - the matrix
371 
372   Output Parameter:
373 . trace - the sum of the diagonal entries
374 
375   Level: advanced
376 
377 .seealso: [](ch_matrices), `Mat`
378 @*/
379 PetscErrorCode MatGetTrace(Mat mat, PetscScalar *trace)
380 {
381   Vec diag;
382 
383   PetscFunctionBegin;
384   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
385   PetscAssertPointer(trace, 2);
386   PetscCall(MatCreateVecs(mat, &diag, NULL));
387   PetscCall(MatGetDiagonal(mat, diag));
388   PetscCall(VecSum(diag, trace));
389   PetscCall(VecDestroy(&diag));
390   PetscFunctionReturn(PETSC_SUCCESS);
391 }
392 
393 /*@
394   MatRealPart - Zeros out the imaginary part of the matrix
395 
396   Logically Collective
397 
398   Input Parameter:
399 . mat - the matrix
400 
401   Level: advanced
402 
403 .seealso: [](ch_matrices), `Mat`, `MatImaginaryPart()`
404 @*/
405 PetscErrorCode MatRealPart(Mat mat)
406 {
407   PetscFunctionBegin;
408   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
409   PetscValidType(mat, 1);
410   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
411   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
412   MatCheckPreallocated(mat, 1);
413   PetscUseTypeMethod(mat, realpart);
414   PetscFunctionReturn(PETSC_SUCCESS);
415 }
416 
417 /*@C
418   MatGetGhosts - Get the global indices of all ghost nodes defined by the sparse matrix
419 
420   Collective
421 
422   Input Parameter:
423 . mat - the matrix
424 
425   Output Parameters:
426 + nghosts - number of ghosts (for `MATBAIJ` and `MATSBAIJ` matrices there is one ghost for each matrix block)
427 - ghosts  - the global indices of the ghost points
428 
429   Level: advanced
430 
431   Note:
432   `nghosts` and `ghosts` are suitable to pass into `VecCreateGhost()` or `VecCreateGhostBlock()`
433 
434 .seealso: [](ch_matrices), `Mat`, `VecCreateGhost()`, `VecCreateGhostBlock()`
435 @*/
436 PetscErrorCode MatGetGhosts(Mat mat, PetscInt *nghosts, const PetscInt *ghosts[])
437 {
438   PetscFunctionBegin;
439   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
440   PetscValidType(mat, 1);
441   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
442   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
443   if (mat->ops->getghosts) PetscUseTypeMethod(mat, getghosts, nghosts, ghosts);
444   else {
445     if (nghosts) *nghosts = 0;
446     if (ghosts) *ghosts = NULL;
447   }
448   PetscFunctionReturn(PETSC_SUCCESS);
449 }
450 
451 /*@
452   MatImaginaryPart - Moves the imaginary part of the matrix to the real part and zeros the imaginary part
453 
454   Logically Collective
455 
456   Input Parameter:
457 . mat - the matrix
458 
459   Level: advanced
460 
461 .seealso: [](ch_matrices), `Mat`, `MatRealPart()`
462 @*/
463 PetscErrorCode MatImaginaryPart(Mat mat)
464 {
465   PetscFunctionBegin;
466   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
467   PetscValidType(mat, 1);
468   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
469   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
470   MatCheckPreallocated(mat, 1);
471   PetscUseTypeMethod(mat, imaginarypart);
472   PetscFunctionReturn(PETSC_SUCCESS);
473 }
474 
475 /*@
476   MatMissingDiagonal - Determine if sparse matrix is missing a diagonal entry (or block entry for `MATBAIJ` and `MATSBAIJ` matrices) in the nonzero structure
477 
478   Not Collective
479 
480   Input Parameter:
481 . mat - the matrix
482 
483   Output Parameters:
484 + missing - is any diagonal entry missing
485 - dd      - first diagonal entry that is missing (optional) on this process
486 
487   Level: advanced
488 
489   Note:
490   This does not return diagonal entries that are in the nonzero structure but happen to have a zero numerical value
491 
492 .seealso: [](ch_matrices), `Mat`
493 @*/
494 PetscErrorCode MatMissingDiagonal(Mat mat, PetscBool *missing, PetscInt *dd)
495 {
496   PetscFunctionBegin;
497   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
498   PetscValidType(mat, 1);
499   PetscAssertPointer(missing, 2);
500   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix %s", ((PetscObject)mat)->type_name);
501   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
502   PetscUseTypeMethod(mat, missingdiagonal, missing, dd);
503   PetscFunctionReturn(PETSC_SUCCESS);
504 }
505 
506 // PetscClangLinter pragma disable: -fdoc-section-header-unknown
507 /*@C
508   MatGetRow - Gets a row of a matrix.  You MUST call `MatRestoreRow()`
509   for each row that you get to ensure that your application does
510   not bleed memory.
511 
512   Not Collective
513 
514   Input Parameters:
515 + mat - the matrix
516 - row - the row to get
517 
518   Output Parameters:
519 + ncols - if not `NULL`, the number of nonzeros in `row`
520 . cols  - if not `NULL`, the column numbers
521 - vals  - if not `NULL`, the numerical values
522 
523   Level: advanced
524 
525   Notes:
526   This routine is provided for people who need to have direct access
527   to the structure of a matrix.  We hope that we provide enough
528   high-level matrix routines that few users will need it.
529 
530   `MatGetRow()` always returns 0-based column indices, regardless of
531   whether the internal representation is 0-based (default) or 1-based.
532 
533   For better efficiency, set `cols` and/or `vals` to `NULL` if you do
534   not wish to extract these quantities.
535 
536   The user can only examine the values extracted with `MatGetRow()`;
537   the values CANNOT be altered.  To change the matrix entries, one
538   must use `MatSetValues()`.
539 
540   You can only have one call to `MatGetRow()` outstanding for a particular
541   matrix at a time, per processor. `MatGetRow()` can only obtain rows
542   associated with the given processor, it cannot get rows from the
543   other processors; for that we suggest using `MatCreateSubMatrices()`, then
544   `MatGetRow()` on the submatrix. The row index passed to `MatGetRow()`
545   is in the global number of rows.
546 
547   Use `MatGetRowIJ()` and `MatRestoreRowIJ()` to access all the local indices of the sparse matrix.
548 
549   Use `MatSeqAIJGetArray()` and similar functions to access the numerical values for certain matrix types directly.
550 
551   Fortran Note:
552   The calling sequence is
553 .vb
554    MatGetRow(matrix,row,ncols,cols,values,ierr)
555          Mat         matrix (input)
556          PetscInt    row    (input)
557          PetscInt    ncols  (output)
558          PetscInt    cols(maxcols) (output)
559          PetscScalar values(maxcols) output
560 .ve
561   where maxcols >= maximum nonzeros in any row of the matrix.
562 
563 .seealso: [](ch_matrices), `Mat`, `MatRestoreRow()`, `MatSetValues()`, `MatGetValues()`, `MatCreateSubMatrices()`, `MatGetDiagonal()`, `MatGetRowIJ()`, `MatRestoreRowIJ()`
564 @*/
565 PetscErrorCode MatGetRow(Mat mat, PetscInt row, PetscInt *ncols, const PetscInt *cols[], const PetscScalar *vals[])
566 {
567   PetscInt incols;
568 
569   PetscFunctionBegin;
570   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
571   PetscValidType(mat, 1);
572   PetscCheck(mat->assembled, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
573   PetscCheck(!mat->factortype, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
574   MatCheckPreallocated(mat, 1);
575   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);
576   PetscCall(PetscLogEventBegin(MAT_GetRow, mat, 0, 0, 0));
577   PetscUseTypeMethod(mat, getrow, row, &incols, (PetscInt **)cols, (PetscScalar **)vals);
578   if (ncols) *ncols = incols;
579   PetscCall(PetscLogEventEnd(MAT_GetRow, mat, 0, 0, 0));
580   PetscFunctionReturn(PETSC_SUCCESS);
581 }
582 
583 /*@
584   MatConjugate - replaces the matrix values with their complex conjugates
585 
586   Logically Collective
587 
588   Input Parameter:
589 . mat - the matrix
590 
591   Level: advanced
592 
593 .seealso: [](ch_matrices), `Mat`, `MatRealPart()`, `MatImaginaryPart()`, `VecConjugate()`, `MatTranspose()`
594 @*/
595 PetscErrorCode MatConjugate(Mat mat)
596 {
597   PetscFunctionBegin;
598   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
599   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
600   if (PetscDefined(USE_COMPLEX) && mat->hermitian != PETSC_BOOL3_TRUE) {
601     PetscUseTypeMethod(mat, conjugate);
602     PetscCall(PetscObjectStateIncrease((PetscObject)mat));
603   }
604   PetscFunctionReturn(PETSC_SUCCESS);
605 }
606 
607 /*@C
608   MatRestoreRow - Frees any temporary space allocated by `MatGetRow()`.
609 
610   Not Collective
611 
612   Input Parameters:
613 + mat   - the matrix
614 . row   - the row to get
615 . ncols - the number of nonzeros
616 . cols  - the columns of the nonzeros
617 - vals  - if nonzero the column values
618 
619   Level: advanced
620 
621   Notes:
622   This routine should be called after you have finished examining the entries.
623 
624   This routine zeros out `ncols`, `cols`, and `vals`. This is to prevent accidental
625   us of the array after it has been restored. If you pass `NULL`, it will
626   not zero the pointers.  Use of `cols` or `vals` after `MatRestoreRow()` is invalid.
627 
628   Fortran Note:
629   `MatRestoreRow()` MUST be called after `MatGetRow()`
630   before another call to `MatGetRow()` can be made.
631 
632 .seealso: [](ch_matrices), `Mat`, `MatGetRow()`
633 @*/
634 PetscErrorCode MatRestoreRow(Mat mat, PetscInt row, PetscInt *ncols, const PetscInt *cols[], const PetscScalar *vals[])
635 {
636   PetscFunctionBegin;
637   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
638   if (ncols) PetscAssertPointer(ncols, 3);
639   PetscCheck(mat->assembled, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
640   if (!mat->ops->restorerow) PetscFunctionReturn(PETSC_SUCCESS);
641   PetscUseTypeMethod(mat, restorerow, row, ncols, (PetscInt **)cols, (PetscScalar **)vals);
642   if (ncols) *ncols = 0;
643   if (cols) *cols = NULL;
644   if (vals) *vals = NULL;
645   PetscFunctionReturn(PETSC_SUCCESS);
646 }
647 
648 /*@
649   MatGetRowUpperTriangular - Sets a flag to enable calls to `MatGetRow()` for matrix in `MATSBAIJ` format.
650   You should call `MatRestoreRowUpperTriangular()` after calling` MatGetRow()` and `MatRestoreRow()` to disable the flag.
651 
652   Not Collective
653 
654   Input Parameter:
655 . mat - the matrix
656 
657   Level: advanced
658 
659   Note:
660   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.
661 
662 .seealso: [](ch_matrices), `Mat`, `MATSBAIJ`, `MatRestoreRowUpperTriangular()`
663 @*/
664 PetscErrorCode MatGetRowUpperTriangular(Mat mat)
665 {
666   PetscFunctionBegin;
667   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
668   PetscValidType(mat, 1);
669   PetscCheck(mat->assembled, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
670   PetscCheck(!mat->factortype, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
671   MatCheckPreallocated(mat, 1);
672   if (!mat->ops->getrowuppertriangular) PetscFunctionReturn(PETSC_SUCCESS);
673   PetscUseTypeMethod(mat, getrowuppertriangular);
674   PetscFunctionReturn(PETSC_SUCCESS);
675 }
676 
677 /*@
678   MatRestoreRowUpperTriangular - Disable calls to `MatGetRow()` for matrix in `MATSBAIJ` format.
679 
680   Not Collective
681 
682   Input Parameter:
683 . mat - the matrix
684 
685   Level: advanced
686 
687   Note:
688   This routine should be called after you have finished calls to `MatGetRow()` and `MatRestoreRow()`.
689 
690 .seealso: [](ch_matrices), `Mat`, `MATSBAIJ`, `MatGetRowUpperTriangular()`
691 @*/
692 PetscErrorCode MatRestoreRowUpperTriangular(Mat mat)
693 {
694   PetscFunctionBegin;
695   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
696   PetscValidType(mat, 1);
697   PetscCheck(mat->assembled, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
698   PetscCheck(!mat->factortype, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
699   MatCheckPreallocated(mat, 1);
700   if (!mat->ops->restorerowuppertriangular) PetscFunctionReturn(PETSC_SUCCESS);
701   PetscUseTypeMethod(mat, restorerowuppertriangular);
702   PetscFunctionReturn(PETSC_SUCCESS);
703 }
704 
705 /*@
706   MatSetOptionsPrefix - Sets the prefix used for searching for all
707   `Mat` options in the database.
708 
709   Logically Collective
710 
711   Input Parameters:
712 + A      - the matrix
713 - prefix - the prefix to prepend to all option names
714 
715   Level: advanced
716 
717   Notes:
718   A hyphen (-) must NOT be given at the beginning of the prefix name.
719   The first character of all runtime options is AUTOMATICALLY the hyphen.
720 
721   This is NOT used for options for the factorization of the matrix. Normally the
722   prefix is automatically passed in from the PC calling the factorization. To set
723   it directly use  `MatSetOptionsPrefixFactor()`
724 
725 .seealso: [](ch_matrices), `Mat`, `MatSetFromOptions()`, `MatSetOptionsPrefixFactor()`
726 @*/
727 PetscErrorCode MatSetOptionsPrefix(Mat A, const char prefix[])
728 {
729   PetscFunctionBegin;
730   PetscValidHeaderSpecific(A, MAT_CLASSID, 1);
731   PetscCall(PetscObjectSetOptionsPrefix((PetscObject)A, prefix));
732   PetscFunctionReturn(PETSC_SUCCESS);
733 }
734 
735 /*@
736   MatSetOptionsPrefixFactor - Sets the prefix used for searching for all matrix factor options in the database for
737   for matrices created with `MatGetFactor()`
738 
739   Logically Collective
740 
741   Input Parameters:
742 + A      - the matrix
743 - prefix - the prefix to prepend to all option names for the factored matrix
744 
745   Level: developer
746 
747   Notes:
748   A hyphen (-) must NOT be given at the beginning of the prefix name.
749   The first character of all runtime options is AUTOMATICALLY the hyphen.
750 
751   Normally the prefix is automatically passed in from the `PC` calling the factorization. To set
752   it directly when not using `KSP`/`PC` use  `MatSetOptionsPrefixFactor()`
753 
754 .seealso: [](ch_matrices), `Mat`,   [Matrix Factorization](sec_matfactor), `MatGetFactor()`, `MatSetFromOptions()`, `MatSetOptionsPrefix()`, `MatAppendOptionsPrefixFactor()`
755 @*/
756 PetscErrorCode MatSetOptionsPrefixFactor(Mat A, const char prefix[])
757 {
758   PetscFunctionBegin;
759   PetscValidHeaderSpecific(A, MAT_CLASSID, 1);
760   if (prefix) {
761     PetscAssertPointer(prefix, 2);
762     PetscCheck(prefix[0] != '-', PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_WRONG, "Options prefix should not begin with a hyphen");
763     if (prefix != A->factorprefix) {
764       PetscCall(PetscFree(A->factorprefix));
765       PetscCall(PetscStrallocpy(prefix, &A->factorprefix));
766     }
767   } else PetscCall(PetscFree(A->factorprefix));
768   PetscFunctionReturn(PETSC_SUCCESS);
769 }
770 
771 /*@
772   MatAppendOptionsPrefixFactor - Appends to the prefix used for searching for all matrix factor options in the database for
773   for matrices created with `MatGetFactor()`
774 
775   Logically Collective
776 
777   Input Parameters:
778 + A      - the matrix
779 - prefix - the prefix to prepend to all option names for the factored matrix
780 
781   Level: developer
782 
783   Notes:
784   A hyphen (-) must NOT be given at the beginning of the prefix name.
785   The first character of all runtime options is AUTOMATICALLY the hyphen.
786 
787   Normally the prefix is automatically passed in from the `PC` calling the factorization. To set
788   it directly when not using `KSP`/`PC` use  `MatAppendOptionsPrefixFactor()`
789 
790 .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatGetFactor()`, `PetscOptionsCreate()`, `PetscOptionsDestroy()`, `PetscObjectSetOptionsPrefix()`, `PetscObjectPrependOptionsPrefix()`,
791           `PetscObjectGetOptionsPrefix()`, `TSAppendOptionsPrefix()`, `SNESAppendOptionsPrefix()`, `KSPAppendOptionsPrefix()`, `MatSetOptionsPrefixFactor()`,
792           `MatSetOptionsPrefix()`
793 @*/
794 PetscErrorCode MatAppendOptionsPrefixFactor(Mat A, const char prefix[])
795 {
796   size_t len1, len2, new_len;
797 
798   PetscFunctionBegin;
799   PetscValidHeader(A, 1);
800   if (!prefix) PetscFunctionReturn(PETSC_SUCCESS);
801   if (!A->factorprefix) {
802     PetscCall(MatSetOptionsPrefixFactor(A, prefix));
803     PetscFunctionReturn(PETSC_SUCCESS);
804   }
805   PetscCheck(prefix[0] != '-', PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_WRONG, "Options prefix should not begin with a hyphen");
806 
807   PetscCall(PetscStrlen(A->factorprefix, &len1));
808   PetscCall(PetscStrlen(prefix, &len2));
809   new_len = len1 + len2 + 1;
810   PetscCall(PetscRealloc(new_len * sizeof(*A->factorprefix), &A->factorprefix));
811   PetscCall(PetscStrncpy(A->factorprefix + len1, prefix, len2 + 1));
812   PetscFunctionReturn(PETSC_SUCCESS);
813 }
814 
815 /*@
816   MatAppendOptionsPrefix - Appends to the prefix used for searching for all
817   matrix options in the database.
818 
819   Logically Collective
820 
821   Input Parameters:
822 + A      - the matrix
823 - prefix - the prefix to prepend to all option names
824 
825   Level: advanced
826 
827   Note:
828   A hyphen (-) must NOT be given at the beginning of the prefix name.
829   The first character of all runtime options is AUTOMATICALLY the hyphen.
830 
831 .seealso: [](ch_matrices), `Mat`, `MatGetOptionsPrefix()`, `MatAppendOptionsPrefixFactor()`, `MatSetOptionsPrefix()`
832 @*/
833 PetscErrorCode MatAppendOptionsPrefix(Mat A, const char prefix[])
834 {
835   PetscFunctionBegin;
836   PetscValidHeaderSpecific(A, MAT_CLASSID, 1);
837   PetscCall(PetscObjectAppendOptionsPrefix((PetscObject)A, prefix));
838   PetscFunctionReturn(PETSC_SUCCESS);
839 }
840 
841 /*@
842   MatGetOptionsPrefix - Gets the prefix used for searching for all
843   matrix options in the database.
844 
845   Not Collective
846 
847   Input Parameter:
848 . A - the matrix
849 
850   Output Parameter:
851 . prefix - pointer to the prefix string used
852 
853   Level: advanced
854 
855   Fortran Note:
856   The user should pass in a string `prefix` of
857   sufficient length to hold the prefix.
858 
859 .seealso: [](ch_matrices), `Mat`, `MatAppendOptionsPrefix()`, `MatSetOptionsPrefix()`, `MatAppendOptionsPrefixFactor()`, `MatSetOptionsPrefixFactor()`
860 @*/
861 PetscErrorCode MatGetOptionsPrefix(Mat A, const char *prefix[])
862 {
863   PetscFunctionBegin;
864   PetscValidHeaderSpecific(A, MAT_CLASSID, 1);
865   PetscAssertPointer(prefix, 2);
866   PetscCall(PetscObjectGetOptionsPrefix((PetscObject)A, prefix));
867   PetscFunctionReturn(PETSC_SUCCESS);
868 }
869 
870 /*@
871   MatGetState - Gets the state of a `Mat`. Same value as returned by `PetscObjectStateGet()`
872 
873   Not Collective
874 
875   Input Parameter:
876 . A - the matrix
877 
878   Output Parameter:
879 . state - the object state
880 
881   Level: advanced
882 
883   Note:
884   Object state is an integer which gets increased every time
885   the object is changed. By saving and later querying the object state
886   one can determine whether information about the object is still current.
887 
888   See `MatGetNonzeroState()` to determine if the nonzero structure of the matrix has changed.
889 
890 .seealso: [](ch_matrices), `Mat`, `MatCreate()`, `PetscObjectStateGet()`, `MatGetNonzeroState()`
891 @*/
892 PetscErrorCode MatGetState(Mat A, PetscObjectState *state)
893 {
894   PetscFunctionBegin;
895   PetscValidHeaderSpecific(A, MAT_CLASSID, 1);
896   PetscAssertPointer(state, 2);
897   PetscCall(PetscObjectStateGet((PetscObject)A, state));
898   PetscFunctionReturn(PETSC_SUCCESS);
899 }
900 
901 /*@
902   MatResetPreallocation - Reset matrix to use the original nonzero pattern provided by the user.
903 
904   Collective
905 
906   Input Parameter:
907 . A - the matrix
908 
909   Level: beginner
910 
911   Notes:
912   The allocated memory will be shrunk after calling `MatAssemblyBegin()` and `MatAssemblyEnd()` with `MAT_FINAL_ASSEMBLY`.
913 
914   Users can reset the preallocation to access the original memory.
915 
916   Currently only supported for  `MATAIJ` matrices.
917 
918 .seealso: [](ch_matrices), `Mat`, `MatSeqAIJSetPreallocation()`, `MatMPIAIJSetPreallocation()`, `MatXAIJSetPreallocation()`
919 @*/
920 PetscErrorCode MatResetPreallocation(Mat A)
921 {
922   PetscFunctionBegin;
923   PetscValidHeaderSpecific(A, MAT_CLASSID, 1);
924   PetscValidType(A, 1);
925   PetscCheck(A->insertmode == NOT_SET_VALUES, PETSC_COMM_SELF, PETSC_ERR_SUP, "Cannot reset preallocation after setting some values but not yet calling MatAssemblyBegin()/MatAssemblyEnd()");
926   if (A->num_ass == 0) PetscFunctionReturn(PETSC_SUCCESS);
927   PetscUseMethod(A, "MatResetPreallocation_C", (Mat), (A));
928   PetscFunctionReturn(PETSC_SUCCESS);
929 }
930 
931 /*@
932   MatSetUp - Sets up the internal matrix data structures for later use.
933 
934   Collective
935 
936   Input Parameter:
937 . A - the matrix
938 
939   Level: intermediate
940 
941   Notes:
942   If the user has not set preallocation for this matrix then an efficient algorithm will be used for the first round of
943   setting values in the matrix.
944 
945   This routine is called internally by other matrix functions when needed so rarely needs to be called by users
946 
947 .seealso: [](ch_matrices), `Mat`, `MatMult()`, `MatCreate()`, `MatDestroy()`, `MatXAIJSetPreallocation()`
948 @*/
949 PetscErrorCode MatSetUp(Mat A)
950 {
951   PetscFunctionBegin;
952   PetscValidHeaderSpecific(A, MAT_CLASSID, 1);
953   if (!((PetscObject)A)->type_name) {
954     PetscMPIInt size;
955 
956     PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)A), &size));
957     PetscCall(MatSetType(A, size == 1 ? MATSEQAIJ : MATMPIAIJ));
958   }
959   if (!A->preallocated) PetscTryTypeMethod(A, setup);
960   PetscCall(PetscLayoutSetUp(A->rmap));
961   PetscCall(PetscLayoutSetUp(A->cmap));
962   A->preallocated = PETSC_TRUE;
963   PetscFunctionReturn(PETSC_SUCCESS);
964 }
965 
966 #if defined(PETSC_HAVE_SAWS)
967   #include <petscviewersaws.h>
968 #endif
969 
970 /*
971    If threadsafety is on extraneous matrices may be printed
972 
973    This flag cannot be stored in the matrix because the original matrix in MatView() may assemble a new matrix which is passed into MatViewFromOptions()
974 */
975 #if !defined(PETSC_HAVE_THREADSAFETY)
976 static PetscInt insidematview = 0;
977 #endif
978 
979 /*@
980   MatViewFromOptions - View properties of the matrix based on options set in the options database
981 
982   Collective
983 
984   Input Parameters:
985 + A    - the matrix
986 . obj  - optional additional object that provides the options prefix to use
987 - name - command line option
988 
989   Options Database Key:
990 . -mat_view [viewertype]:... - the viewer and its options
991 
992   Level: intermediate
993 
994   Note:
995 .vb
996     If no value is provided ascii:stdout is used
997        ascii[:[filename][:[format][:append]]]    defaults to stdout - format can be one of ascii_info, ascii_info_detail, or ascii_matlab,
998                                                   for example ascii::ascii_info prints just the information about the object not all details
999                                                   unless :append is given filename opens in write mode, overwriting what was already there
1000        binary[:[filename][:[format][:append]]]   defaults to the file binaryoutput
1001        draw[:drawtype[:filename]]                for example, draw:tikz, draw:tikz:figure.tex  or draw:x
1002        socket[:port]                             defaults to the standard output port
1003        saws[:communicatorname]                    publishes object to the Scientific Application Webserver (SAWs)
1004 .ve
1005 
1006 .seealso: [](ch_matrices), `Mat`, `MatView()`, `PetscObjectViewFromOptions()`, `MatCreate()`
1007 @*/
1008 PetscErrorCode MatViewFromOptions(Mat A, PetscObject obj, const char name[])
1009 {
1010   PetscFunctionBegin;
1011   PetscValidHeaderSpecific(A, MAT_CLASSID, 1);
1012 #if !defined(PETSC_HAVE_THREADSAFETY)
1013   if (insidematview) PetscFunctionReturn(PETSC_SUCCESS);
1014 #endif
1015   PetscCall(PetscObjectViewFromOptions((PetscObject)A, obj, name));
1016   PetscFunctionReturn(PETSC_SUCCESS);
1017 }
1018 
1019 /*@
1020   MatView - display information about a matrix in a variety ways
1021 
1022   Collective on viewer
1023 
1024   Input Parameters:
1025 + mat    - the matrix
1026 - viewer - visualization context
1027 
1028   Options Database Keys:
1029 + -mat_view ::ascii_info           - Prints info on matrix at conclusion of `MatAssemblyEnd()`
1030 . -mat_view ::ascii_info_detail    - Prints more detailed info
1031 . -mat_view                        - Prints matrix in ASCII format
1032 . -mat_view ::ascii_matlab         - Prints matrix in MATLAB format
1033 . -mat_view draw                   - PetscDraws nonzero structure of matrix, using `MatView()` and `PetscDrawOpenX()`.
1034 . -display <name>                  - Sets display name (default is host)
1035 . -draw_pause <sec>                - Sets number of seconds to pause after display
1036 . -mat_view socket                 - Sends matrix to socket, can be accessed from MATLAB (see Users-Manual: ch_matlab for details)
1037 . -viewer_socket_machine <machine> - -
1038 . -viewer_socket_port <port>       - -
1039 . -mat_view binary                 - save matrix to file in binary format
1040 - -viewer_binary_filename <name>   - -
1041 
1042   Level: beginner
1043 
1044   Notes:
1045   The available visualization contexts include
1046 +    `PETSC_VIEWER_STDOUT_SELF` - for sequential matrices
1047 .    `PETSC_VIEWER_STDOUT_WORLD` - for parallel matrices created on `PETSC_COMM_WORLD`
1048 .    `PETSC_VIEWER_STDOUT_`(comm) - for matrices created on MPI communicator comm
1049 -     `PETSC_VIEWER_DRAW_WORLD` - graphical display of nonzero structure
1050 
1051   The user can open alternative visualization contexts with
1052 +    `PetscViewerASCIIOpen()` - Outputs matrix to a specified file
1053 .    `PetscViewerBinaryOpen()` - Outputs matrix in binary to a
1054   specified file; corresponding input uses `MatLoad()`
1055 .    `PetscViewerDrawOpen()` - Outputs nonzero matrix structure to
1056   an X window display
1057 -    `PetscViewerSocketOpen()` - Outputs matrix to Socket viewer.
1058   Currently only the `MATSEQDENSE` and `MATAIJ`
1059   matrix types support the Socket viewer.
1060 
1061   The user can call `PetscViewerPushFormat()` to specify the output
1062   format of ASCII printed objects (when using `PETSC_VIEWER_STDOUT_SELF`,
1063   `PETSC_VIEWER_STDOUT_WORLD` and `PetscViewerASCIIOpen()`).  Available formats include
1064 +    `PETSC_VIEWER_DEFAULT` - default, prints matrix contents
1065 .    `PETSC_VIEWER_ASCII_MATLAB` - prints matrix contents in MATLAB format
1066 .    `PETSC_VIEWER_ASCII_DENSE` - prints entire matrix including zeros
1067 .    `PETSC_VIEWER_ASCII_COMMON` - prints matrix contents, using a sparse
1068   format common among all matrix types
1069 .    `PETSC_VIEWER_ASCII_IMPL` - prints matrix contents, using an implementation-specific
1070   format (which is in many cases the same as the default)
1071 .    `PETSC_VIEWER_ASCII_INFO` - prints basic information about the matrix
1072   size and structure (not the matrix entries)
1073 -    `PETSC_VIEWER_ASCII_INFO_DETAIL` - prints more detailed information about
1074   the matrix structure
1075 
1076   The ASCII viewers are only recommended for small matrices on at most a moderate number of processes,
1077   the program will seemingly hang and take hours for larger matrices, for larger matrices one should use the binary format.
1078 
1079   In the debugger you can do "call MatView(mat,0)" to display the matrix. (The same holds for any PETSc object viewer).
1080 
1081   See the manual page for `MatLoad()` for the exact format of the binary file when the binary
1082   viewer is used.
1083 
1084   See share/petsc/matlab/PetscBinaryRead.m for a MATLAB code that can read in the binary file when the binary
1085   viewer is used and lib/petsc/bin/PetscBinaryIO.py for loading them into Python.
1086 
1087   One can use '-mat_view draw -draw_pause -1' to pause the graphical display of matrix nonzero structure,
1088   and then use the following mouse functions.
1089 .vb
1090   left mouse: zoom in
1091   middle mouse: zoom out
1092   right mouse: continue with the simulation
1093 .ve
1094 
1095 .seealso: [](ch_matrices), `Mat`, `PetscViewerPushFormat()`, `PetscViewerASCIIOpen()`, `PetscViewerDrawOpen()`, `PetscViewer`,
1096           `PetscViewerSocketOpen()`, `PetscViewerBinaryOpen()`, `MatLoad()`, `MatViewFromOptions()`
1097 @*/
1098 PetscErrorCode MatView(Mat mat, PetscViewer viewer)
1099 {
1100   PetscInt          rows, cols, rbs, cbs;
1101   PetscBool         isascii, isstring, issaws;
1102   PetscViewerFormat format;
1103   PetscMPIInt       size;
1104 
1105   PetscFunctionBegin;
1106   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
1107   PetscValidType(mat, 1);
1108   if (!viewer) PetscCall(PetscViewerASCIIGetStdout(PetscObjectComm((PetscObject)mat), &viewer));
1109   PetscValidHeaderSpecific(viewer, PETSC_VIEWER_CLASSID, 2);
1110 
1111   PetscCall(PetscViewerGetFormat(viewer, &format));
1112   PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)viewer), &size));
1113   if (size == 1 && format == PETSC_VIEWER_LOAD_BALANCE) PetscFunctionReturn(PETSC_SUCCESS);
1114 
1115 #if !defined(PETSC_HAVE_THREADSAFETY)
1116   insidematview++;
1117 #endif
1118   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERSTRING, &isstring));
1119   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERASCII, &isascii));
1120   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERSAWS, &issaws));
1121   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");
1122 
1123   PetscCall(PetscLogEventBegin(MAT_View, mat, viewer, 0, 0));
1124   if (isascii) {
1125     if (!mat->preallocated) {
1126       PetscCall(PetscViewerASCIIPrintf(viewer, "Matrix has not been preallocated yet\n"));
1127 #if !defined(PETSC_HAVE_THREADSAFETY)
1128       insidematview--;
1129 #endif
1130       PetscCall(PetscLogEventEnd(MAT_View, mat, viewer, 0, 0));
1131       PetscFunctionReturn(PETSC_SUCCESS);
1132     }
1133     if (!mat->assembled) {
1134       PetscCall(PetscViewerASCIIPrintf(viewer, "Matrix has not been assembled yet\n"));
1135 #if !defined(PETSC_HAVE_THREADSAFETY)
1136       insidematview--;
1137 #endif
1138       PetscCall(PetscLogEventEnd(MAT_View, mat, viewer, 0, 0));
1139       PetscFunctionReturn(PETSC_SUCCESS);
1140     }
1141     PetscCall(PetscObjectPrintClassNamePrefixType((PetscObject)mat, viewer));
1142     if (format == PETSC_VIEWER_ASCII_INFO || format == PETSC_VIEWER_ASCII_INFO_DETAIL) {
1143       MatNullSpace nullsp, transnullsp;
1144 
1145       PetscCall(PetscViewerASCIIPushTab(viewer));
1146       PetscCall(MatGetSize(mat, &rows, &cols));
1147       PetscCall(MatGetBlockSizes(mat, &rbs, &cbs));
1148       if (rbs != 1 || cbs != 1) {
1149         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" : ""));
1150         else PetscCall(PetscViewerASCIIPrintf(viewer, "rows=%" PetscInt_FMT ", cols=%" PetscInt_FMT ", bs=%" PetscInt_FMT "%s\n", rows, cols, rbs, mat->bsizes ? " variable blocks set" : ""));
1151       } else PetscCall(PetscViewerASCIIPrintf(viewer, "rows=%" PetscInt_FMT ", cols=%" PetscInt_FMT "\n", rows, cols));
1152       if (mat->factortype) {
1153         MatSolverType solver;
1154         PetscCall(MatFactorGetSolverType(mat, &solver));
1155         PetscCall(PetscViewerASCIIPrintf(viewer, "package used to perform factorization: %s\n", solver));
1156       }
1157       if (mat->ops->getinfo) {
1158         MatInfo info;
1159         PetscCall(MatGetInfo(mat, MAT_GLOBAL_SUM, &info));
1160         PetscCall(PetscViewerASCIIPrintf(viewer, "total: nonzeros=%.f, allocated nonzeros=%.f\n", info.nz_used, info.nz_allocated));
1161         if (!mat->factortype) PetscCall(PetscViewerASCIIPrintf(viewer, "total number of mallocs used during MatSetValues calls=%" PetscInt_FMT "\n", (PetscInt)info.mallocs));
1162       }
1163       PetscCall(MatGetNullSpace(mat, &nullsp));
1164       PetscCall(MatGetTransposeNullSpace(mat, &transnullsp));
1165       if (nullsp) PetscCall(PetscViewerASCIIPrintf(viewer, "  has attached null space\n"));
1166       if (transnullsp && transnullsp != nullsp) PetscCall(PetscViewerASCIIPrintf(viewer, "  has attached transposed null space\n"));
1167       PetscCall(MatGetNearNullSpace(mat, &nullsp));
1168       if (nullsp) PetscCall(PetscViewerASCIIPrintf(viewer, "  has attached near null space\n"));
1169       PetscCall(PetscViewerASCIIPushTab(viewer));
1170       PetscCall(MatProductView(mat, viewer));
1171       PetscCall(PetscViewerASCIIPopTab(viewer));
1172       if (mat->bsizes && format == PETSC_VIEWER_ASCII_INFO_DETAIL) {
1173         IS tmp;
1174 
1175         PetscCall(ISCreateGeneral(PetscObjectComm((PetscObject)viewer), mat->nblocks, mat->bsizes, PETSC_USE_POINTER, &tmp));
1176         PetscCall(PetscObjectSetName((PetscObject)tmp, "Block Sizes"));
1177         PetscCall(PetscViewerASCIIPushTab(viewer));
1178         PetscCall(ISView(tmp, viewer));
1179         PetscCall(PetscViewerASCIIPopTab(viewer));
1180         PetscCall(ISDestroy(&tmp));
1181       }
1182     }
1183   } else if (issaws) {
1184 #if defined(PETSC_HAVE_SAWS)
1185     PetscMPIInt rank;
1186 
1187     PetscCall(PetscObjectName((PetscObject)mat));
1188     PetscCallMPI(MPI_Comm_rank(PETSC_COMM_WORLD, &rank));
1189     if (!((PetscObject)mat)->amsmem && rank == 0) PetscCall(PetscObjectViewSAWs((PetscObject)mat, viewer));
1190 #endif
1191   } else if (isstring) {
1192     const char *type;
1193     PetscCall(MatGetType(mat, &type));
1194     PetscCall(PetscViewerStringSPrintf(viewer, " MatType: %-7.7s", type));
1195     PetscTryTypeMethod(mat, view, viewer);
1196   }
1197   if ((format == PETSC_VIEWER_NATIVE || format == PETSC_VIEWER_LOAD_BALANCE) && mat->ops->viewnative) {
1198     PetscCall(PetscViewerASCIIPushTab(viewer));
1199     PetscUseTypeMethod(mat, viewnative, viewer);
1200     PetscCall(PetscViewerASCIIPopTab(viewer));
1201   } else if (mat->ops->view) {
1202     PetscCall(PetscViewerASCIIPushTab(viewer));
1203     PetscUseTypeMethod(mat, view, viewer);
1204     PetscCall(PetscViewerASCIIPopTab(viewer));
1205   }
1206   if (isascii) {
1207     PetscCall(PetscViewerGetFormat(viewer, &format));
1208     if (format == PETSC_VIEWER_ASCII_INFO || format == PETSC_VIEWER_ASCII_INFO_DETAIL) PetscCall(PetscViewerASCIIPopTab(viewer));
1209   }
1210   PetscCall(PetscLogEventEnd(MAT_View, mat, viewer, 0, 0));
1211 #if !defined(PETSC_HAVE_THREADSAFETY)
1212   insidematview--;
1213 #endif
1214   PetscFunctionReturn(PETSC_SUCCESS);
1215 }
1216 
1217 #if defined(PETSC_USE_DEBUG)
1218   #include <../src/sys/totalview/tv_data_display.h>
1219 PETSC_UNUSED static int TV_display_type(const struct _p_Mat *mat)
1220 {
1221   TV_add_row("Local rows", "int", &mat->rmap->n);
1222   TV_add_row("Local columns", "int", &mat->cmap->n);
1223   TV_add_row("Global rows", "int", &mat->rmap->N);
1224   TV_add_row("Global columns", "int", &mat->cmap->N);
1225   TV_add_row("Typename", TV_ascii_string_type, ((PetscObject)mat)->type_name);
1226   return TV_format_OK;
1227 }
1228 #endif
1229 
1230 /*@
1231   MatLoad - Loads a matrix that has been stored in binary/HDF5 format
1232   with `MatView()`.  The matrix format is determined from the options database.
1233   Generates a parallel MPI matrix if the communicator has more than one
1234   processor.  The default matrix type is `MATAIJ`.
1235 
1236   Collective
1237 
1238   Input Parameters:
1239 + mat    - the newly loaded matrix, this needs to have been created with `MatCreate()`
1240             or some related function before a call to `MatLoad()`
1241 - viewer - `PETSCVIEWERBINARY`/`PETSCVIEWERHDF5` file viewer
1242 
1243   Options Database Key:
1244 . -matload_block_size <bs> - set block size
1245 
1246   Level: beginner
1247 
1248   Notes:
1249   If the `Mat` type has not yet been given then `MATAIJ` is used, call `MatSetFromOptions()` on the
1250   `Mat` before calling this routine if you wish to set it from the options database.
1251 
1252   `MatLoad()` automatically loads into the options database any options
1253   given in the file filename.info where filename is the name of the file
1254   that was passed to the `PetscViewerBinaryOpen()`. The options in the info
1255   file will be ignored if you use the -viewer_binary_skip_info option.
1256 
1257   If the type or size of mat is not set before a call to `MatLoad()`, PETSc
1258   sets the default matrix type AIJ and sets the local and global sizes.
1259   If type and/or size is already set, then the same are used.
1260 
1261   In parallel, each processor can load a subset of rows (or the
1262   entire matrix).  This routine is especially useful when a large
1263   matrix is stored on disk and only part of it is desired on each
1264   processor.  For example, a parallel solver may access only some of
1265   the rows from each processor.  The algorithm used here reads
1266   relatively small blocks of data rather than reading the entire
1267   matrix and then subsetting it.
1268 
1269   Viewer's `PetscViewerType` must be either `PETSCVIEWERBINARY` or `PETSCVIEWERHDF5`.
1270   Such viewer can be created using `PetscViewerBinaryOpen()` or `PetscViewerHDF5Open()`,
1271   or the sequence like
1272 .vb
1273     `PetscViewer` v;
1274     `PetscViewerCreate`(`PETSC_COMM_WORLD`,&v);
1275     `PetscViewerSetType`(v,`PETSCVIEWERBINARY`);
1276     `PetscViewerSetFromOptions`(v);
1277     `PetscViewerFileSetMode`(v,`FILE_MODE_READ`);
1278     `PetscViewerFileSetName`(v,"datafile");
1279 .ve
1280   The optional `PetscViewerSetFromOptions()` call allows overriding `PetscViewerSetType()` using the option
1281 $ -viewer_type {binary, hdf5}
1282 
1283   See the example src/ksp/ksp/tutorials/ex27.c with the first approach,
1284   and src/mat/tutorials/ex10.c with the second approach.
1285 
1286   In case of `PETSCVIEWERBINARY`, a native PETSc binary format is used. Each of the blocks
1287   is read onto MPI rank 0 and then shipped to its destination MPI rank, one after another.
1288   Multiple objects, both matrices and vectors, can be stored within the same file.
1289   Their `PetscObject` name is ignored; they are loaded in the order of their storage.
1290 
1291   Most users should not need to know the details of the binary storage
1292   format, since `MatLoad()` and `MatView()` completely hide these details.
1293   But for anyone who is interested, the standard binary matrix storage
1294   format is
1295 
1296 .vb
1297     PetscInt    MAT_FILE_CLASSID
1298     PetscInt    number of rows
1299     PetscInt    number of columns
1300     PetscInt    total number of nonzeros
1301     PetscInt    *number nonzeros in each row
1302     PetscInt    *column indices of all nonzeros (starting index is zero)
1303     PetscScalar *values of all nonzeros
1304 .ve
1305   If PETSc was not configured with `--with-64-bit-indices` then only `MATMPIAIJ` matrices with more than `PETSC_INT_MAX` non-zeros can be
1306   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
1307   case will not fit in a (32-bit) `PetscInt` the value `PETSC_INT_MAX` is used for the header entry `total number of nonzeros`.
1308 
1309   PETSc automatically does the byte swapping for
1310   machines that store the bytes reversed. Thus if you write your own binary
1311   read/write routines you have to swap the bytes; see `PetscBinaryRead()`
1312   and `PetscBinaryWrite()` to see how this may be done.
1313 
1314   In case of `PETSCVIEWERHDF5`, a parallel HDF5 reader is used.
1315   Each processor's chunk is loaded independently by its owning MPI process.
1316   Multiple objects, both matrices and vectors, can be stored within the same file.
1317   They are looked up by their PetscObject name.
1318 
1319   As the MATLAB MAT-File Version 7.3 format is also a HDF5 flavor, we decided to use
1320   by default the same structure and naming of the AIJ arrays and column count
1321   within the HDF5 file. This means that a MAT file saved with -v7.3 flag, e.g.
1322 $    save example.mat A b -v7.3
1323   can be directly read by this routine (see Reference 1 for details).
1324 
1325   Depending on your MATLAB version, this format might be a default,
1326   otherwise you can set it as default in Preferences.
1327 
1328   Unless -nocompression flag is used to save the file in MATLAB,
1329   PETSc must be configured with ZLIB package.
1330 
1331   See also examples src/mat/tutorials/ex10.c and src/ksp/ksp/tutorials/ex27.c
1332 
1333   This reader currently supports only real `MATSEQAIJ`, `MATMPIAIJ`, `MATSEQDENSE` and `MATMPIDENSE` matrices for `PETSCVIEWERHDF5`
1334 
1335   Corresponding `MatView()` is not yet implemented.
1336 
1337   The loaded matrix is actually a transpose of the original one in MATLAB,
1338   unless you push `PETSC_VIEWER_HDF5_MAT` format (see examples above).
1339   With this format, matrix is automatically transposed by PETSc,
1340   unless the matrix is marked as SPD or symmetric
1341   (see `MatSetOption()`, `MAT_SPD`, `MAT_SYMMETRIC`).
1342 
1343   See MATLAB Documentation on `save()`, <https://www.mathworks.com/help/matlab/ref/save.html#btox10b-1-version>
1344 
1345 .seealso: [](ch_matrices), `Mat`, `PetscViewerBinaryOpen()`, `PetscViewerSetType()`, `MatView()`, `VecLoad()`
1346  @*/
1347 PetscErrorCode MatLoad(Mat mat, PetscViewer viewer)
1348 {
1349   PetscBool flg;
1350 
1351   PetscFunctionBegin;
1352   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
1353   PetscValidHeaderSpecific(viewer, PETSC_VIEWER_CLASSID, 2);
1354 
1355   if (!((PetscObject)mat)->type_name) PetscCall(MatSetType(mat, MATAIJ));
1356 
1357   flg = PETSC_FALSE;
1358   PetscCall(PetscOptionsGetBool(((PetscObject)mat)->options, ((PetscObject)mat)->prefix, "-matload_symmetric", &flg, NULL));
1359   if (flg) {
1360     PetscCall(MatSetOption(mat, MAT_SYMMETRIC, PETSC_TRUE));
1361     PetscCall(MatSetOption(mat, MAT_SYMMETRY_ETERNAL, PETSC_TRUE));
1362   }
1363   flg = PETSC_FALSE;
1364   PetscCall(PetscOptionsGetBool(((PetscObject)mat)->options, ((PetscObject)mat)->prefix, "-matload_spd", &flg, NULL));
1365   if (flg) PetscCall(MatSetOption(mat, MAT_SPD, PETSC_TRUE));
1366 
1367   PetscCall(PetscLogEventBegin(MAT_Load, mat, viewer, 0, 0));
1368   PetscUseTypeMethod(mat, load, viewer);
1369   PetscCall(PetscLogEventEnd(MAT_Load, mat, viewer, 0, 0));
1370   PetscFunctionReturn(PETSC_SUCCESS);
1371 }
1372 
1373 static PetscErrorCode MatDestroy_Redundant(Mat_Redundant **redundant)
1374 {
1375   Mat_Redundant *redund = *redundant;
1376 
1377   PetscFunctionBegin;
1378   if (redund) {
1379     if (redund->matseq) { /* via MatCreateSubMatrices()  */
1380       PetscCall(ISDestroy(&redund->isrow));
1381       PetscCall(ISDestroy(&redund->iscol));
1382       PetscCall(MatDestroySubMatrices(1, &redund->matseq));
1383     } else {
1384       PetscCall(PetscFree2(redund->send_rank, redund->recv_rank));
1385       PetscCall(PetscFree(redund->sbuf_j));
1386       PetscCall(PetscFree(redund->sbuf_a));
1387       for (PetscInt i = 0; i < redund->nrecvs; i++) {
1388         PetscCall(PetscFree(redund->rbuf_j[i]));
1389         PetscCall(PetscFree(redund->rbuf_a[i]));
1390       }
1391       PetscCall(PetscFree4(redund->sbuf_nz, redund->rbuf_nz, redund->rbuf_j, redund->rbuf_a));
1392     }
1393 
1394     if (redund->subcomm) PetscCall(PetscCommDestroy(&redund->subcomm));
1395     PetscCall(PetscFree(redund));
1396   }
1397   PetscFunctionReturn(PETSC_SUCCESS);
1398 }
1399 
1400 /*@
1401   MatDestroy - Frees space taken by a matrix.
1402 
1403   Collective
1404 
1405   Input Parameter:
1406 . A - the matrix
1407 
1408   Level: beginner
1409 
1410   Developer Note:
1411   Some special arrays of matrices are not destroyed in this routine but instead by the routines called by
1412   `MatDestroySubMatrices()`. Thus one must be sure that any changes here must also be made in those routines.
1413   `MatHeaderMerge()` and `MatHeaderReplace()` also manipulate the data in the `Mat` object and likely need changes
1414   if changes are needed here.
1415 
1416 .seealso: [](ch_matrices), `Mat`, `MatCreate()`
1417 @*/
1418 PetscErrorCode MatDestroy(Mat *A)
1419 {
1420   PetscFunctionBegin;
1421   if (!*A) PetscFunctionReturn(PETSC_SUCCESS);
1422   PetscValidHeaderSpecific(*A, MAT_CLASSID, 1);
1423   if (--((PetscObject)*A)->refct > 0) {
1424     *A = NULL;
1425     PetscFunctionReturn(PETSC_SUCCESS);
1426   }
1427 
1428   /* if memory was published with SAWs then destroy it */
1429   PetscCall(PetscObjectSAWsViewOff((PetscObject)*A));
1430   PetscTryTypeMethod(*A, destroy);
1431 
1432   PetscCall(PetscFree((*A)->factorprefix));
1433   PetscCall(PetscFree((*A)->defaultvectype));
1434   PetscCall(PetscFree((*A)->defaultrandtype));
1435   PetscCall(PetscFree((*A)->bsizes));
1436   PetscCall(PetscFree((*A)->solvertype));
1437   for (PetscInt i = 0; i < MAT_FACTOR_NUM_TYPES; i++) PetscCall(PetscFree((*A)->preferredordering[i]));
1438   if ((*A)->redundant && (*A)->redundant->matseq[0] == *A) (*A)->redundant->matseq[0] = NULL;
1439   PetscCall(MatDestroy_Redundant(&(*A)->redundant));
1440   PetscCall(MatProductClear(*A));
1441   PetscCall(MatNullSpaceDestroy(&(*A)->nullsp));
1442   PetscCall(MatNullSpaceDestroy(&(*A)->transnullsp));
1443   PetscCall(MatNullSpaceDestroy(&(*A)->nearnullsp));
1444   PetscCall(MatDestroy(&(*A)->schur));
1445   PetscCall(PetscLayoutDestroy(&(*A)->rmap));
1446   PetscCall(PetscLayoutDestroy(&(*A)->cmap));
1447   PetscCall(PetscHeaderDestroy(A));
1448   PetscFunctionReturn(PETSC_SUCCESS);
1449 }
1450 
1451 // PetscClangLinter pragma disable: -fdoc-section-header-unknown
1452 /*@
1453   MatSetValues - Inserts or adds a block of values into a matrix.
1454   These values may be cached, so `MatAssemblyBegin()` and `MatAssemblyEnd()`
1455   MUST be called after all calls to `MatSetValues()` have been completed.
1456 
1457   Not Collective
1458 
1459   Input Parameters:
1460 + mat  - the matrix
1461 . v    - a logically two-dimensional array of values
1462 . m    - the number of rows
1463 . idxm - the global indices of the rows
1464 . n    - the number of columns
1465 . idxn - the global indices of the columns
1466 - addv - either `ADD_VALUES` to add values to any existing entries, or `INSERT_VALUES` to replace existing entries with new values
1467 
1468   Level: beginner
1469 
1470   Notes:
1471   By default the values, `v`, are stored row-oriented. See `MatSetOption()` for other options.
1472 
1473   Calls to `MatSetValues()` with the `INSERT_VALUES` and `ADD_VALUES`
1474   options cannot be mixed without intervening calls to the assembly
1475   routines.
1476 
1477   `MatSetValues()` uses 0-based row and column numbers in Fortran
1478   as well as in C.
1479 
1480   Negative indices may be passed in `idxm` and `idxn`, these rows and columns are
1481   simply ignored. This allows easily inserting element stiffness matrices
1482   with homogeneous Dirichlet boundary conditions that you don't want represented
1483   in the matrix.
1484 
1485   Efficiency Alert:
1486   The routine `MatSetValuesBlocked()` may offer much better efficiency
1487   for users of block sparse formats (`MATSEQBAIJ` and `MATMPIBAIJ`).
1488 
1489   Fortran Notes:
1490   If any of `idxm`, `idxn`, and `v` are scalars pass them using, for example,
1491 .vb
1492   MatSetValues(mat, one, [idxm], one, [idxn], [v], INSERT_VALUES)
1493 .ve
1494 
1495   If `v` is a two-dimensional array use `reshape()` to pass it as a one dimensional array
1496 
1497   Developer Note:
1498   This is labeled with C so does not automatically generate Fortran stubs and interfaces
1499   because it requires multiple Fortran interfaces depending on which arguments are scalar or arrays.
1500 
1501 .seealso: [](ch_matrices), `Mat`, `MatSetOption()`, `MatAssemblyBegin()`, `MatAssemblyEnd()`, `MatSetValuesBlocked()`, `MatSetValuesLocal()`,
1502           `InsertMode`, `INSERT_VALUES`, `ADD_VALUES`
1503 @*/
1504 PetscErrorCode MatSetValues(Mat mat, PetscInt m, const PetscInt idxm[], PetscInt n, const PetscInt idxn[], const PetscScalar v[], InsertMode addv)
1505 {
1506   PetscFunctionBeginHot;
1507   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
1508   PetscValidType(mat, 1);
1509   if (!m || !n) PetscFunctionReturn(PETSC_SUCCESS); /* no values to insert */
1510   PetscAssertPointer(idxm, 3);
1511   PetscAssertPointer(idxn, 5);
1512   MatCheckPreallocated(mat, 1);
1513 
1514   if (mat->insertmode == NOT_SET_VALUES) mat->insertmode = addv;
1515   else PetscCheck(mat->insertmode == addv, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Cannot mix add values and insert values");
1516 
1517   if (PetscDefined(USE_DEBUG)) {
1518     PetscInt i, j;
1519 
1520     PetscCheck(!mat->factortype, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
1521     if (v) {
1522       for (i = 0; i < m; i++) {
1523         for (j = 0; j < n; j++) {
1524           if (mat->erroriffailure && PetscIsInfOrNanScalar(v[i * n + j]))
1525 #if defined(PETSC_USE_COMPLEX)
1526             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]);
1527 #else
1528             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]);
1529 #endif
1530         }
1531       }
1532     }
1533     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);
1534     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);
1535   }
1536 
1537   if (mat->assembled) {
1538     mat->was_assembled = PETSC_TRUE;
1539     mat->assembled     = PETSC_FALSE;
1540   }
1541   PetscCall(PetscLogEventBegin(MAT_SetValues, mat, 0, 0, 0));
1542   PetscUseTypeMethod(mat, setvalues, m, idxm, n, idxn, v, addv);
1543   PetscCall(PetscLogEventEnd(MAT_SetValues, mat, 0, 0, 0));
1544   PetscFunctionReturn(PETSC_SUCCESS);
1545 }
1546 
1547 // PetscClangLinter pragma disable: -fdoc-section-header-unknown
1548 /*@
1549   MatSetValuesIS - Inserts or adds a block of values into a matrix using an `IS` to indicate the rows and columns
1550   These values may be cached, so `MatAssemblyBegin()` and `MatAssemblyEnd()`
1551   MUST be called after all calls to `MatSetValues()` have been completed.
1552 
1553   Not Collective
1554 
1555   Input Parameters:
1556 + mat  - the matrix
1557 . v    - a logically two-dimensional array of values
1558 . ism  - the rows to provide
1559 . isn  - the columns to provide
1560 - addv - either `ADD_VALUES` to add values to any existing entries, or `INSERT_VALUES` to replace existing entries with new values
1561 
1562   Level: beginner
1563 
1564   Notes:
1565   By default the values, `v`, are stored row-oriented. See `MatSetOption()` for other options.
1566 
1567   Calls to `MatSetValues()` with the `INSERT_VALUES` and `ADD_VALUES`
1568   options cannot be mixed without intervening calls to the assembly
1569   routines.
1570 
1571   `MatSetValues()` uses 0-based row and column numbers in Fortran
1572   as well as in C.
1573 
1574   Negative indices may be passed in `ism` and `isn`, these rows and columns are
1575   simply ignored. This allows easily inserting element stiffness matrices
1576   with homogeneous Dirichlet boundary conditions that you don't want represented
1577   in the matrix.
1578 
1579   Efficiency Alert:
1580   The routine `MatSetValuesBlocked()` may offer much better efficiency
1581   for users of block sparse formats (`MATSEQBAIJ` and `MATMPIBAIJ`).
1582 
1583   This is currently not optimized for any particular `ISType`
1584 
1585   Developer Note:
1586   This is labeled with C so does not automatically generate Fortran stubs and interfaces
1587   because it requires multiple Fortran interfaces depending on which arguments are scalar or arrays.
1588 
1589 .seealso: [](ch_matrices), `Mat`, `MatSetOption()`, `MatSetValues()`, `MatAssemblyBegin()`, `MatAssemblyEnd()`, `MatSetValuesBlocked()`, `MatSetValuesLocal()`,
1590           `InsertMode`, `INSERT_VALUES`, `ADD_VALUES`
1591 @*/
1592 PetscErrorCode MatSetValuesIS(Mat mat, IS ism, IS isn, const PetscScalar v[], InsertMode addv)
1593 {
1594   PetscInt        m, n;
1595   const PetscInt *rows, *cols;
1596 
1597   PetscFunctionBeginHot;
1598   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
1599   PetscCall(ISGetIndices(ism, &rows));
1600   PetscCall(ISGetIndices(isn, &cols));
1601   PetscCall(ISGetLocalSize(ism, &m));
1602   PetscCall(ISGetLocalSize(isn, &n));
1603   PetscCall(MatSetValues(mat, m, rows, n, cols, v, addv));
1604   PetscCall(ISRestoreIndices(ism, &rows));
1605   PetscCall(ISRestoreIndices(isn, &cols));
1606   PetscFunctionReturn(PETSC_SUCCESS);
1607 }
1608 
1609 /*@
1610   MatSetValuesRowLocal - Inserts a row (block row for `MATBAIJ` matrices) of nonzero
1611   values into a matrix
1612 
1613   Not Collective
1614 
1615   Input Parameters:
1616 + mat - the matrix
1617 . row - the (block) row to set
1618 - v   - a logically two-dimensional array of values
1619 
1620   Level: intermediate
1621 
1622   Notes:
1623   The values, `v`, are column-oriented (for the block version) and sorted
1624 
1625   All the nonzero values in `row` must be provided
1626 
1627   The matrix must have previously had its column indices set, likely by having been assembled.
1628 
1629   `row` must belong to this MPI process
1630 
1631 .seealso: [](ch_matrices), `Mat`, `MatSetOption()`, `MatAssemblyBegin()`, `MatAssemblyEnd()`, `MatSetValuesBlocked()`, `MatSetValuesLocal()`,
1632           `InsertMode`, `INSERT_VALUES`, `ADD_VALUES`, `MatSetValues()`, `MatSetValuesRow()`, `MatSetLocalToGlobalMapping()`
1633 @*/
1634 PetscErrorCode MatSetValuesRowLocal(Mat mat, PetscInt row, const PetscScalar v[])
1635 {
1636   PetscInt globalrow;
1637 
1638   PetscFunctionBegin;
1639   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
1640   PetscValidType(mat, 1);
1641   PetscAssertPointer(v, 3);
1642   PetscCall(ISLocalToGlobalMappingApply(mat->rmap->mapping, 1, &row, &globalrow));
1643   PetscCall(MatSetValuesRow(mat, globalrow, v));
1644   PetscFunctionReturn(PETSC_SUCCESS);
1645 }
1646 
1647 /*@
1648   MatSetValuesRow - Inserts a row (block row for `MATBAIJ` matrices) of nonzero
1649   values into a matrix
1650 
1651   Not Collective
1652 
1653   Input Parameters:
1654 + mat - the matrix
1655 . row - the (block) row to set
1656 - 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
1657 
1658   Level: advanced
1659 
1660   Notes:
1661   The values, `v`, are column-oriented for the block version.
1662 
1663   All the nonzeros in `row` must be provided
1664 
1665   THE MATRIX MUST HAVE PREVIOUSLY HAD ITS COLUMN INDICES SET. IT IS RARE THAT THIS ROUTINE IS USED, usually `MatSetValues()` is used.
1666 
1667   `row` must belong to this process
1668 
1669 .seealso: [](ch_matrices), `Mat`, `MatSetValues()`, `MatSetOption()`, `MatAssemblyBegin()`, `MatAssemblyEnd()`, `MatSetValuesBlocked()`, `MatSetValuesLocal()`,
1670           `InsertMode`, `INSERT_VALUES`, `ADD_VALUES`
1671 @*/
1672 PetscErrorCode MatSetValuesRow(Mat mat, PetscInt row, const PetscScalar v[])
1673 {
1674   PetscFunctionBeginHot;
1675   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
1676   PetscValidType(mat, 1);
1677   MatCheckPreallocated(mat, 1);
1678   PetscAssertPointer(v, 3);
1679   PetscCheck(mat->insertmode != ADD_VALUES, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Cannot mix add and insert values");
1680   PetscCheck(!mat->factortype, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
1681   mat->insertmode = INSERT_VALUES;
1682 
1683   if (mat->assembled) {
1684     mat->was_assembled = PETSC_TRUE;
1685     mat->assembled     = PETSC_FALSE;
1686   }
1687   PetscCall(PetscLogEventBegin(MAT_SetValues, mat, 0, 0, 0));
1688   PetscUseTypeMethod(mat, setvaluesrow, row, v);
1689   PetscCall(PetscLogEventEnd(MAT_SetValues, mat, 0, 0, 0));
1690   PetscFunctionReturn(PETSC_SUCCESS);
1691 }
1692 
1693 // PetscClangLinter pragma disable: -fdoc-section-header-unknown
1694 /*@
1695   MatSetValuesStencil - Inserts or adds a block of values into a matrix.
1696   Using structured grid indexing
1697 
1698   Not Collective
1699 
1700   Input Parameters:
1701 + mat  - the matrix
1702 . m    - number of rows being entered
1703 . idxm - grid coordinates (and component number when dof > 1) for matrix rows being entered
1704 . n    - number of columns being entered
1705 . idxn - grid coordinates (and component number when dof > 1) for matrix columns being entered
1706 . v    - a logically two-dimensional array of values
1707 - addv - either `ADD_VALUES` to add to existing entries at that location or `INSERT_VALUES` to replace existing entries with new values
1708 
1709   Level: beginner
1710 
1711   Notes:
1712   By default the values, `v`, are row-oriented.  See `MatSetOption()` for other options.
1713 
1714   Calls to `MatSetValuesStencil()` with the `INSERT_VALUES` and `ADD_VALUES`
1715   options cannot be mixed without intervening calls to the assembly
1716   routines.
1717 
1718   The grid coordinates are across the entire grid, not just the local portion
1719 
1720   `MatSetValuesStencil()` uses 0-based row and column numbers in Fortran
1721   as well as in C.
1722 
1723   For setting/accessing vector values via array coordinates you can use the `DMDAVecGetArray()` routine
1724 
1725   In order to use this routine you must either obtain the matrix with `DMCreateMatrix()`
1726   or call `MatSetLocalToGlobalMapping()` and `MatSetStencil()` first.
1727 
1728   The columns and rows in the stencil passed in MUST be contained within the
1729   ghost region of the given process as set with DMDACreateXXX() or `MatSetStencil()`. For example,
1730   if you create a `DMDA` with an overlap of one grid level and on a particular process its first
1731   local nonghost x logical coordinate is 6 (so its first ghost x logical coordinate is 5) the
1732   first i index you can use in your column and row indices in `MatSetStencil()` is 5.
1733 
1734   For periodic boundary conditions use negative indices for values to the left (below 0; that are to be
1735   obtained by wrapping values from right edge). For values to the right of the last entry using that index plus one
1736   etc to obtain values that obtained by wrapping the values from the left edge. This does not work for anything but the
1737   `DM_BOUNDARY_PERIODIC` boundary type.
1738 
1739   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
1740   a single value per point) you can skip filling those indices.
1741 
1742   Inspired by the structured grid interface to the HYPRE package
1743   (https://computation.llnl.gov/projects/hypre-scalable-linear-solvers-multigrid-methods)
1744 
1745   Efficiency Alert:
1746   The routine `MatSetValuesBlockedStencil()` may offer much better efficiency
1747   for users of block sparse formats (`MATSEQBAIJ` and `MATMPIBAIJ`).
1748 
1749   Fortran Note:
1750   `idxm` and `idxn` should be declared as
1751 $     MatStencil idxm(4,m),idxn(4,n)
1752   and the values inserted using
1753 .vb
1754     idxm(MatStencil_i,1) = i
1755     idxm(MatStencil_j,1) = j
1756     idxm(MatStencil_k,1) = k
1757     idxm(MatStencil_c,1) = c
1758     etc
1759 .ve
1760 
1761 .seealso: [](ch_matrices), `Mat`, `DMDA`, `MatSetOption()`, `MatAssemblyBegin()`, `MatAssemblyEnd()`, `MatSetValuesBlocked()`, `MatSetValuesLocal()`
1762           `MatSetValues()`, `MatSetValuesBlockedStencil()`, `MatSetStencil()`, `DMCreateMatrix()`, `DMDAVecGetArray()`, `MatStencil`
1763 @*/
1764 PetscErrorCode MatSetValuesStencil(Mat mat, PetscInt m, const MatStencil idxm[], PetscInt n, const MatStencil idxn[], const PetscScalar v[], InsertMode addv)
1765 {
1766   PetscInt  buf[8192], *bufm = NULL, *bufn = NULL, *jdxm, *jdxn;
1767   PetscInt  j, i, dim = mat->stencil.dim, *dims = mat->stencil.dims + 1, tmp;
1768   PetscInt *starts = mat->stencil.starts, *dxm = (PetscInt *)idxm, *dxn = (PetscInt *)idxn, sdim = dim - (1 - (PetscInt)mat->stencil.noc);
1769 
1770   PetscFunctionBegin;
1771   if (!m || !n) PetscFunctionReturn(PETSC_SUCCESS); /* no values to insert */
1772   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
1773   PetscValidType(mat, 1);
1774   PetscAssertPointer(idxm, 3);
1775   PetscAssertPointer(idxn, 5);
1776 
1777   if ((m + n) <= (PetscInt)PETSC_STATIC_ARRAY_LENGTH(buf)) {
1778     jdxm = buf;
1779     jdxn = buf + m;
1780   } else {
1781     PetscCall(PetscMalloc2(m, &bufm, n, &bufn));
1782     jdxm = bufm;
1783     jdxn = bufn;
1784   }
1785   for (i = 0; i < m; i++) {
1786     for (j = 0; j < 3 - sdim; j++) dxm++;
1787     tmp = *dxm++ - starts[0];
1788     for (j = 0; j < dim - 1; j++) {
1789       if ((*dxm++ - starts[j + 1]) < 0 || tmp < 0) tmp = -1;
1790       else tmp = tmp * dims[j] + *(dxm - 1) - starts[j + 1];
1791     }
1792     if (mat->stencil.noc) dxm++;
1793     jdxm[i] = tmp;
1794   }
1795   for (i = 0; i < n; i++) {
1796     for (j = 0; j < 3 - sdim; j++) dxn++;
1797     tmp = *dxn++ - starts[0];
1798     for (j = 0; j < dim - 1; j++) {
1799       if ((*dxn++ - starts[j + 1]) < 0 || tmp < 0) tmp = -1;
1800       else tmp = tmp * dims[j] + *(dxn - 1) - starts[j + 1];
1801     }
1802     if (mat->stencil.noc) dxn++;
1803     jdxn[i] = tmp;
1804   }
1805   PetscCall(MatSetValuesLocal(mat, m, jdxm, n, jdxn, v, addv));
1806   PetscCall(PetscFree2(bufm, bufn));
1807   PetscFunctionReturn(PETSC_SUCCESS);
1808 }
1809 
1810 /*@
1811   MatSetValuesBlockedStencil - Inserts or adds a block of values into a matrix.
1812   Using structured grid indexing
1813 
1814   Not Collective
1815 
1816   Input Parameters:
1817 + mat  - the matrix
1818 . m    - number of rows being entered
1819 . idxm - grid coordinates for matrix rows being entered
1820 . n    - number of columns being entered
1821 . idxn - grid coordinates for matrix columns being entered
1822 . v    - a logically two-dimensional array of values
1823 - addv - either `ADD_VALUES` to add to existing entries or `INSERT_VALUES` to replace existing entries with new values
1824 
1825   Level: beginner
1826 
1827   Notes:
1828   By default the values, `v`, are row-oriented and unsorted.
1829   See `MatSetOption()` for other options.
1830 
1831   Calls to `MatSetValuesBlockedStencil()` with the `INSERT_VALUES` and `ADD_VALUES`
1832   options cannot be mixed without intervening calls to the assembly
1833   routines.
1834 
1835   The grid coordinates are across the entire grid, not just the local portion
1836 
1837   `MatSetValuesBlockedStencil()` uses 0-based row and column numbers in Fortran
1838   as well as in C.
1839 
1840   For setting/accessing vector values via array coordinates you can use the `DMDAVecGetArray()` routine
1841 
1842   In order to use this routine you must either obtain the matrix with `DMCreateMatrix()`
1843   or call `MatSetBlockSize()`, `MatSetLocalToGlobalMapping()` and `MatSetStencil()` first.
1844 
1845   The columns and rows in the stencil passed in MUST be contained within the
1846   ghost region of the given process as set with DMDACreateXXX() or `MatSetStencil()`. For example,
1847   if you create a `DMDA` with an overlap of one grid level and on a particular process its first
1848   local nonghost x logical coordinate is 6 (so its first ghost x logical coordinate is 5) the
1849   first i index you can use in your column and row indices in `MatSetStencil()` is 5.
1850 
1851   Negative indices may be passed in idxm and idxn, these rows and columns are
1852   simply ignored. This allows easily inserting element stiffness matrices
1853   with homogeneous Dirichlet boundary conditions that you don't want represented
1854   in the matrix.
1855 
1856   Inspired by the structured grid interface to the HYPRE package
1857   (https://computation.llnl.gov/projects/hypre-scalable-linear-solvers-multigrid-methods)
1858 
1859   Fortran Note:
1860   `idxm` and `idxn` should be declared as
1861 $     MatStencil idxm(4,m),idxn(4,n)
1862   and the values inserted using
1863 .vb
1864     idxm(MatStencil_i,1) = i
1865     idxm(MatStencil_j,1) = j
1866     idxm(MatStencil_k,1) = k
1867    etc
1868 .ve
1869 
1870 .seealso: [](ch_matrices), `Mat`, `DMDA`, `MatSetOption()`, `MatAssemblyBegin()`, `MatAssemblyEnd()`, `MatSetValuesBlocked()`, `MatSetValuesLocal()`
1871           `MatSetValues()`, `MatSetValuesStencil()`, `MatSetStencil()`, `DMCreateMatrix()`, `DMDAVecGetArray()`, `MatStencil`,
1872           `MatSetBlockSize()`, `MatSetLocalToGlobalMapping()`
1873 @*/
1874 PetscErrorCode MatSetValuesBlockedStencil(Mat mat, PetscInt m, const MatStencil idxm[], PetscInt n, const MatStencil idxn[], const PetscScalar v[], InsertMode addv)
1875 {
1876   PetscInt  buf[8192], *bufm = NULL, *bufn = NULL, *jdxm, *jdxn;
1877   PetscInt  j, i, dim = mat->stencil.dim, *dims = mat->stencil.dims + 1, tmp;
1878   PetscInt *starts = mat->stencil.starts, *dxm = (PetscInt *)idxm, *dxn = (PetscInt *)idxn, sdim = dim - (1 - (PetscInt)mat->stencil.noc);
1879 
1880   PetscFunctionBegin;
1881   if (!m || !n) PetscFunctionReturn(PETSC_SUCCESS); /* no values to insert */
1882   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
1883   PetscValidType(mat, 1);
1884   PetscAssertPointer(idxm, 3);
1885   PetscAssertPointer(idxn, 5);
1886   PetscAssertPointer(v, 6);
1887 
1888   if ((m + n) <= (PetscInt)PETSC_STATIC_ARRAY_LENGTH(buf)) {
1889     jdxm = buf;
1890     jdxn = buf + m;
1891   } else {
1892     PetscCall(PetscMalloc2(m, &bufm, n, &bufn));
1893     jdxm = bufm;
1894     jdxn = bufn;
1895   }
1896   for (i = 0; i < m; i++) {
1897     for (j = 0; j < 3 - sdim; j++) dxm++;
1898     tmp = *dxm++ - starts[0];
1899     for (j = 0; j < sdim - 1; j++) {
1900       if ((*dxm++ - starts[j + 1]) < 0 || tmp < 0) tmp = -1;
1901       else tmp = tmp * dims[j] + *(dxm - 1) - starts[j + 1];
1902     }
1903     dxm++;
1904     jdxm[i] = tmp;
1905   }
1906   for (i = 0; i < n; i++) {
1907     for (j = 0; j < 3 - sdim; j++) dxn++;
1908     tmp = *dxn++ - starts[0];
1909     for (j = 0; j < sdim - 1; j++) {
1910       if ((*dxn++ - starts[j + 1]) < 0 || tmp < 0) tmp = -1;
1911       else tmp = tmp * dims[j] + *(dxn - 1) - starts[j + 1];
1912     }
1913     dxn++;
1914     jdxn[i] = tmp;
1915   }
1916   PetscCall(MatSetValuesBlockedLocal(mat, m, jdxm, n, jdxn, v, addv));
1917   PetscCall(PetscFree2(bufm, bufn));
1918   PetscFunctionReturn(PETSC_SUCCESS);
1919 }
1920 
1921 /*@
1922   MatSetStencil - Sets the grid information for setting values into a matrix via
1923   `MatSetValuesStencil()`
1924 
1925   Not Collective
1926 
1927   Input Parameters:
1928 + mat    - the matrix
1929 . dim    - dimension of the grid 1, 2, or 3
1930 . dims   - number of grid points in x, y, and z direction, including ghost points on your processor
1931 . starts - starting point of ghost nodes on your processor in x, y, and z direction
1932 - dof    - number of degrees of freedom per node
1933 
1934   Level: beginner
1935 
1936   Notes:
1937   Inspired by the structured grid interface to the HYPRE package
1938   (www.llnl.gov/CASC/hyper)
1939 
1940   For matrices generated with `DMCreateMatrix()` this routine is automatically called and so not needed by the
1941   user.
1942 
1943 .seealso: [](ch_matrices), `Mat`, `MatStencil`, `MatSetOption()`, `MatAssemblyBegin()`, `MatAssemblyEnd()`, `MatSetValuesBlocked()`, `MatSetValuesLocal()`
1944           `MatSetValues()`, `MatSetValuesBlockedStencil()`, `MatSetValuesStencil()`
1945 @*/
1946 PetscErrorCode MatSetStencil(Mat mat, PetscInt dim, const PetscInt dims[], const PetscInt starts[], PetscInt dof)
1947 {
1948   PetscFunctionBegin;
1949   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
1950   PetscAssertPointer(dims, 3);
1951   PetscAssertPointer(starts, 4);
1952 
1953   mat->stencil.dim = dim + (dof > 1);
1954   for (PetscInt i = 0; i < dim; i++) {
1955     mat->stencil.dims[i]   = dims[dim - i - 1]; /* copy the values in backwards */
1956     mat->stencil.starts[i] = starts[dim - i - 1];
1957   }
1958   mat->stencil.dims[dim]   = dof;
1959   mat->stencil.starts[dim] = 0;
1960   mat->stencil.noc         = (PetscBool)(dof == 1);
1961   PetscFunctionReturn(PETSC_SUCCESS);
1962 }
1963 
1964 /*@
1965   MatSetValuesBlocked - Inserts or adds a block of values into a matrix.
1966 
1967   Not Collective
1968 
1969   Input Parameters:
1970 + mat  - the matrix
1971 . v    - a logically two-dimensional array of values
1972 . m    - the number of block rows
1973 . idxm - the global block indices
1974 . n    - the number of block columns
1975 . idxn - the global block indices
1976 - addv - either `ADD_VALUES` to add values to any existing entries, or `INSERT_VALUES` replaces existing entries with new values
1977 
1978   Level: intermediate
1979 
1980   Notes:
1981   If you create the matrix yourself (that is not with a call to `DMCreateMatrix()`) then you MUST call
1982   MatXXXXSetPreallocation() or `MatSetUp()` before using this routine.
1983 
1984   The `m` and `n` count the NUMBER of blocks in the row direction and column direction,
1985   NOT the total number of rows/columns; for example, if the block size is 2 and
1986   you are passing in values for rows 2,3,4,5  then `m` would be 2 (not 4).
1987   The values in `idxm` would be 1 2; that is the first index for each block divided by
1988   the block size.
1989 
1990   You must call `MatSetBlockSize()` when constructing this matrix (before
1991   preallocating it).
1992 
1993   By default the values, `v`, are row-oriented, so the layout of
1994   `v` is the same as for `MatSetValues()`. See `MatSetOption()` for other options.
1995 
1996   Calls to `MatSetValuesBlocked()` with the `INSERT_VALUES` and `ADD_VALUES`
1997   options cannot be mixed without intervening calls to the assembly
1998   routines.
1999 
2000   `MatSetValuesBlocked()` uses 0-based row and column numbers in Fortran
2001   as well as in C.
2002 
2003   Negative indices may be passed in `idxm` and `idxn`, these rows and columns are
2004   simply ignored. This allows easily inserting element stiffness matrices
2005   with homogeneous Dirichlet boundary conditions that you don't want represented
2006   in the matrix.
2007 
2008   Each time an entry is set within a sparse matrix via `MatSetValues()`,
2009   internal searching must be done to determine where to place the
2010   data in the matrix storage space.  By instead inserting blocks of
2011   entries via `MatSetValuesBlocked()`, the overhead of matrix assembly is
2012   reduced.
2013 
2014   Example:
2015 .vb
2016    Suppose m=n=2 and block size(bs) = 2 The array is
2017 
2018    1  2  | 3  4
2019    5  6  | 7  8
2020    - - - | - - -
2021    9  10 | 11 12
2022    13 14 | 15 16
2023 
2024    v[] should be passed in like
2025    v[] = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]
2026 
2027   If you are not using row-oriented storage of v (that is you called MatSetOption(mat,MAT_ROW_ORIENTED,PETSC_FALSE)) then
2028    v[] = [1,5,9,13,2,6,10,14,3,7,11,15,4,8,12,16]
2029 .ve
2030 
2031   Fortran Notes:
2032   If any of `idmx`, `idxn`, and `v` are scalars pass them using, for example,
2033 .vb
2034   MatSetValuesBlocked(mat, one, [idxm], one, [idxn], [v], INSERT_VALUES)
2035 .ve
2036 
2037   If `v` is a two-dimensional array use `reshape()` to pass it as a one dimensional array
2038 
2039 .seealso: [](ch_matrices), `Mat`, `MatSetBlockSize()`, `MatSetOption()`, `MatAssemblyBegin()`, `MatAssemblyEnd()`, `MatSetValues()`, `MatSetValuesBlockedLocal()`
2040 @*/
2041 PetscErrorCode MatSetValuesBlocked(Mat mat, PetscInt m, const PetscInt idxm[], PetscInt n, const PetscInt idxn[], const PetscScalar v[], InsertMode addv)
2042 {
2043   PetscFunctionBeginHot;
2044   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
2045   PetscValidType(mat, 1);
2046   if (!m || !n) PetscFunctionReturn(PETSC_SUCCESS); /* no values to insert */
2047   PetscAssertPointer(idxm, 3);
2048   PetscAssertPointer(idxn, 5);
2049   MatCheckPreallocated(mat, 1);
2050   if (mat->insertmode == NOT_SET_VALUES) mat->insertmode = addv;
2051   else PetscCheck(mat->insertmode == addv, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Cannot mix add values and insert values");
2052   if (PetscDefined(USE_DEBUG)) {
2053     PetscCheck(!mat->factortype, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
2054     PetscCheck(mat->ops->setvaluesblocked || mat->ops->setvalues, PETSC_COMM_SELF, PETSC_ERR_SUP, "Mat type %s", ((PetscObject)mat)->type_name);
2055   }
2056   if (PetscDefined(USE_DEBUG)) {
2057     PetscInt rbs, cbs, M, N, i;
2058     PetscCall(MatGetBlockSizes(mat, &rbs, &cbs));
2059     PetscCall(MatGetSize(mat, &M, &N));
2060     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);
2061     for (i = 0; i < n; i++)
2062       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);
2063   }
2064   if (mat->assembled) {
2065     mat->was_assembled = PETSC_TRUE;
2066     mat->assembled     = PETSC_FALSE;
2067   }
2068   PetscCall(PetscLogEventBegin(MAT_SetValues, mat, 0, 0, 0));
2069   if (mat->ops->setvaluesblocked) {
2070     PetscUseTypeMethod(mat, setvaluesblocked, m, idxm, n, idxn, v, addv);
2071   } else {
2072     PetscInt buf[8192], *bufr = NULL, *bufc = NULL, *iidxm, *iidxn;
2073     PetscInt i, j, bs, cbs;
2074 
2075     PetscCall(MatGetBlockSizes(mat, &bs, &cbs));
2076     if ((m * bs + n * cbs) <= (PetscInt)PETSC_STATIC_ARRAY_LENGTH(buf)) {
2077       iidxm = buf;
2078       iidxn = buf + m * bs;
2079     } else {
2080       PetscCall(PetscMalloc2(m * bs, &bufr, n * cbs, &bufc));
2081       iidxm = bufr;
2082       iidxn = bufc;
2083     }
2084     for (i = 0; i < m; i++) {
2085       for (j = 0; j < bs; j++) iidxm[i * bs + j] = bs * idxm[i] + j;
2086     }
2087     if (m != n || bs != cbs || idxm != idxn) {
2088       for (i = 0; i < n; i++) {
2089         for (j = 0; j < cbs; j++) iidxn[i * cbs + j] = cbs * idxn[i] + j;
2090       }
2091     } else iidxn = iidxm;
2092     PetscCall(MatSetValues(mat, m * bs, iidxm, n * cbs, iidxn, v, addv));
2093     PetscCall(PetscFree2(bufr, bufc));
2094   }
2095   PetscCall(PetscLogEventEnd(MAT_SetValues, mat, 0, 0, 0));
2096   PetscFunctionReturn(PETSC_SUCCESS);
2097 }
2098 
2099 /*@
2100   MatGetValues - Gets a block of local values from a matrix.
2101 
2102   Not Collective; can only return values that are owned by the give process
2103 
2104   Input Parameters:
2105 + mat  - the matrix
2106 . v    - a logically two-dimensional array for storing the values
2107 . m    - the number of rows
2108 . idxm - the  global indices of the rows
2109 . n    - the number of columns
2110 - idxn - the global indices of the columns
2111 
2112   Level: advanced
2113 
2114   Notes:
2115   The user must allocate space (m*n `PetscScalar`s) for the values, `v`.
2116   The values, `v`, are then returned in a row-oriented format,
2117   analogous to that used by default in `MatSetValues()`.
2118 
2119   `MatGetValues()` uses 0-based row and column numbers in
2120   Fortran as well as in C.
2121 
2122   `MatGetValues()` requires that the matrix has been assembled
2123   with `MatAssemblyBegin()`/`MatAssemblyEnd()`.  Thus, calls to
2124   `MatSetValues()` and `MatGetValues()` CANNOT be made in succession
2125   without intermediate matrix assembly.
2126 
2127   Negative row or column indices will be ignored and those locations in `v` will be
2128   left unchanged.
2129 
2130   For the standard row-based matrix formats, `idxm` can only contain rows owned by the requesting MPI process.
2131   That is, rows with global index greater than or equal to rstart and less than rend where rstart and rend are obtainable
2132   from `MatGetOwnershipRange`(mat,&rstart,&rend).
2133 
2134 .seealso: [](ch_matrices), `Mat`, `MatGetRow()`, `MatCreateSubMatrices()`, `MatSetValues()`, `MatGetOwnershipRange()`, `MatGetValuesLocal()`, `MatGetValue()`
2135 @*/
2136 PetscErrorCode MatGetValues(Mat mat, PetscInt m, const PetscInt idxm[], PetscInt n, const PetscInt idxn[], PetscScalar v[])
2137 {
2138   PetscFunctionBegin;
2139   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
2140   PetscValidType(mat, 1);
2141   if (!m || !n) PetscFunctionReturn(PETSC_SUCCESS);
2142   PetscAssertPointer(idxm, 3);
2143   PetscAssertPointer(idxn, 5);
2144   PetscAssertPointer(v, 6);
2145   PetscCheck(mat->assembled, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
2146   PetscCheck(!mat->factortype, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
2147   MatCheckPreallocated(mat, 1);
2148 
2149   PetscCall(PetscLogEventBegin(MAT_GetValues, mat, 0, 0, 0));
2150   PetscUseTypeMethod(mat, getvalues, m, idxm, n, idxn, v);
2151   PetscCall(PetscLogEventEnd(MAT_GetValues, mat, 0, 0, 0));
2152   PetscFunctionReturn(PETSC_SUCCESS);
2153 }
2154 
2155 /*@
2156   MatGetValuesLocal - retrieves values from certain locations in a matrix using the local numbering of the indices
2157   defined previously by `MatSetLocalToGlobalMapping()`
2158 
2159   Not Collective
2160 
2161   Input Parameters:
2162 + mat  - the matrix
2163 . nrow - number of rows
2164 . irow - the row local indices
2165 . ncol - number of columns
2166 - icol - the column local indices
2167 
2168   Output Parameter:
2169 . y - a logically two-dimensional array of values
2170 
2171   Level: advanced
2172 
2173   Notes:
2174   If you create the matrix yourself (that is not with a call to `DMCreateMatrix()`) then you MUST call `MatSetLocalToGlobalMapping()` before using this routine.
2175 
2176   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,
2177   are greater than or equal to rstart and less than rend where rstart and rend are obtainable from `MatGetOwnershipRange`(mat,&rstart,&rend). One can
2178   determine if the resulting global row associated with the local row r is owned by the requesting MPI process by applying the `ISLocalToGlobalMapping` set
2179   with `MatSetLocalToGlobalMapping()`.
2180 
2181   Developer Note:
2182   This is labelled with C so does not automatically generate Fortran stubs and interfaces
2183   because it requires multiple Fortran interfaces depending on which arguments are scalar or arrays.
2184 
2185 .seealso: [](ch_matrices), `Mat`, `MatAssemblyBegin()`, `MatAssemblyEnd()`, `MatSetValues()`, `MatSetLocalToGlobalMapping()`,
2186           `MatSetValuesLocal()`, `MatGetValues()`
2187 @*/
2188 PetscErrorCode MatGetValuesLocal(Mat mat, PetscInt nrow, const PetscInt irow[], PetscInt ncol, const PetscInt icol[], PetscScalar y[])
2189 {
2190   PetscFunctionBeginHot;
2191   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
2192   PetscValidType(mat, 1);
2193   MatCheckPreallocated(mat, 1);
2194   if (!nrow || !ncol) PetscFunctionReturn(PETSC_SUCCESS); /* no values to retrieve */
2195   PetscAssertPointer(irow, 3);
2196   PetscAssertPointer(icol, 5);
2197   if (PetscDefined(USE_DEBUG)) {
2198     PetscCheck(!mat->factortype, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
2199     PetscCheck(mat->ops->getvalueslocal || mat->ops->getvalues, PETSC_COMM_SELF, PETSC_ERR_SUP, "Mat type %s", ((PetscObject)mat)->type_name);
2200   }
2201   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
2202   PetscCall(PetscLogEventBegin(MAT_GetValues, mat, 0, 0, 0));
2203   if (mat->ops->getvalueslocal) PetscUseTypeMethod(mat, getvalueslocal, nrow, irow, ncol, icol, y);
2204   else {
2205     PetscInt buf[8192], *bufr = NULL, *bufc = NULL, *irowm, *icolm;
2206     if ((nrow + ncol) <= (PetscInt)PETSC_STATIC_ARRAY_LENGTH(buf)) {
2207       irowm = buf;
2208       icolm = buf + nrow;
2209     } else {
2210       PetscCall(PetscMalloc2(nrow, &bufr, ncol, &bufc));
2211       irowm = bufr;
2212       icolm = bufc;
2213     }
2214     PetscCheck(mat->rmap->mapping, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "MatGetValuesLocal() cannot proceed without local-to-global row mapping (See MatSetLocalToGlobalMapping()).");
2215     PetscCheck(mat->cmap->mapping, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "MatGetValuesLocal() cannot proceed without local-to-global column mapping (See MatSetLocalToGlobalMapping()).");
2216     PetscCall(ISLocalToGlobalMappingApply(mat->rmap->mapping, nrow, irow, irowm));
2217     PetscCall(ISLocalToGlobalMappingApply(mat->cmap->mapping, ncol, icol, icolm));
2218     PetscCall(MatGetValues(mat, nrow, irowm, ncol, icolm, y));
2219     PetscCall(PetscFree2(bufr, bufc));
2220   }
2221   PetscCall(PetscLogEventEnd(MAT_GetValues, mat, 0, 0, 0));
2222   PetscFunctionReturn(PETSC_SUCCESS);
2223 }
2224 
2225 /*@
2226   MatSetValuesBatch - Adds (`ADD_VALUES`) many blocks of values into a matrix at once. The blocks must all be square and
2227   the same size. Currently, this can only be called once and creates the given matrix.
2228 
2229   Not Collective
2230 
2231   Input Parameters:
2232 + mat  - the matrix
2233 . nb   - the number of blocks
2234 . bs   - the number of rows (and columns) in each block
2235 . rows - a concatenation of the rows for each block
2236 - v    - a concatenation of logically two-dimensional arrays of values
2237 
2238   Level: advanced
2239 
2240   Notes:
2241   `MatSetPreallocationCOO()` and `MatSetValuesCOO()` may be a better way to provide the values
2242 
2243   In the future, we will extend this routine to handle rectangular blocks, and to allow multiple calls for a given matrix.
2244 
2245 .seealso: [](ch_matrices), `Mat`, `MatSetOption()`, `MatAssemblyBegin()`, `MatAssemblyEnd()`, `MatSetValuesBlocked()`, `MatSetValuesLocal()`,
2246           `InsertMode`, `INSERT_VALUES`, `ADD_VALUES`, `MatSetValues()`, `MatSetPreallocationCOO()`, `MatSetValuesCOO()`
2247 @*/
2248 PetscErrorCode MatSetValuesBatch(Mat mat, PetscInt nb, PetscInt bs, PetscInt rows[], const PetscScalar v[])
2249 {
2250   PetscFunctionBegin;
2251   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
2252   PetscValidType(mat, 1);
2253   PetscAssertPointer(rows, 4);
2254   PetscAssertPointer(v, 5);
2255   PetscAssert(!mat->factortype, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
2256 
2257   PetscCall(PetscLogEventBegin(MAT_SetValuesBatch, mat, 0, 0, 0));
2258   if (mat->ops->setvaluesbatch) PetscUseTypeMethod(mat, setvaluesbatch, nb, bs, rows, v);
2259   else {
2260     for (PetscInt b = 0; b < nb; ++b) PetscCall(MatSetValues(mat, bs, &rows[b * bs], bs, &rows[b * bs], &v[b * bs * bs], ADD_VALUES));
2261   }
2262   PetscCall(PetscLogEventEnd(MAT_SetValuesBatch, mat, 0, 0, 0));
2263   PetscFunctionReturn(PETSC_SUCCESS);
2264 }
2265 
2266 /*@
2267   MatSetLocalToGlobalMapping - Sets a local-to-global numbering for use by
2268   the routine `MatSetValuesLocal()` to allow users to insert matrix entries
2269   using a local (per-processor) numbering.
2270 
2271   Not Collective
2272 
2273   Input Parameters:
2274 + x        - the matrix
2275 . rmapping - row mapping created with `ISLocalToGlobalMappingCreate()` or `ISLocalToGlobalMappingCreateIS()`
2276 - cmapping - column mapping
2277 
2278   Level: intermediate
2279 
2280   Note:
2281   If the matrix is obtained with `DMCreateMatrix()` then this may already have been called on the matrix
2282 
2283 .seealso: [](ch_matrices), `Mat`, `DM`, `DMCreateMatrix()`, `MatGetLocalToGlobalMapping()`, `MatAssemblyBegin()`, `MatAssemblyEnd()`, `MatSetValues()`, `MatSetValuesLocal()`, `MatGetValuesLocal()`
2284 @*/
2285 PetscErrorCode MatSetLocalToGlobalMapping(Mat x, ISLocalToGlobalMapping rmapping, ISLocalToGlobalMapping cmapping)
2286 {
2287   PetscFunctionBegin;
2288   PetscValidHeaderSpecific(x, MAT_CLASSID, 1);
2289   PetscValidType(x, 1);
2290   if (rmapping) PetscValidHeaderSpecific(rmapping, IS_LTOGM_CLASSID, 2);
2291   if (cmapping) PetscValidHeaderSpecific(cmapping, IS_LTOGM_CLASSID, 3);
2292   if (x->ops->setlocaltoglobalmapping) PetscUseTypeMethod(x, setlocaltoglobalmapping, rmapping, cmapping);
2293   else {
2294     PetscCall(PetscLayoutSetISLocalToGlobalMapping(x->rmap, rmapping));
2295     PetscCall(PetscLayoutSetISLocalToGlobalMapping(x->cmap, cmapping));
2296   }
2297   PetscFunctionReturn(PETSC_SUCCESS);
2298 }
2299 
2300 /*@
2301   MatGetLocalToGlobalMapping - Gets the local-to-global numbering set by `MatSetLocalToGlobalMapping()`
2302 
2303   Not Collective
2304 
2305   Input Parameter:
2306 . A - the matrix
2307 
2308   Output Parameters:
2309 + rmapping - row mapping
2310 - cmapping - column mapping
2311 
2312   Level: advanced
2313 
2314 .seealso: [](ch_matrices), `Mat`, `MatSetLocalToGlobalMapping()`, `MatSetValuesLocal()`
2315 @*/
2316 PetscErrorCode MatGetLocalToGlobalMapping(Mat A, ISLocalToGlobalMapping *rmapping, ISLocalToGlobalMapping *cmapping)
2317 {
2318   PetscFunctionBegin;
2319   PetscValidHeaderSpecific(A, MAT_CLASSID, 1);
2320   PetscValidType(A, 1);
2321   if (rmapping) {
2322     PetscAssertPointer(rmapping, 2);
2323     *rmapping = A->rmap->mapping;
2324   }
2325   if (cmapping) {
2326     PetscAssertPointer(cmapping, 3);
2327     *cmapping = A->cmap->mapping;
2328   }
2329   PetscFunctionReturn(PETSC_SUCCESS);
2330 }
2331 
2332 /*@
2333   MatSetLayouts - Sets the `PetscLayout` objects for rows and columns of a matrix
2334 
2335   Logically Collective
2336 
2337   Input Parameters:
2338 + A    - the matrix
2339 . rmap - row layout
2340 - cmap - column layout
2341 
2342   Level: advanced
2343 
2344   Note:
2345   The `PetscLayout` objects are usually created automatically for the matrix so this routine rarely needs to be called.
2346 
2347 .seealso: [](ch_matrices), `Mat`, `PetscLayout`, `MatCreateVecs()`, `MatGetLocalToGlobalMapping()`, `MatGetLayouts()`
2348 @*/
2349 PetscErrorCode MatSetLayouts(Mat A, PetscLayout rmap, PetscLayout cmap)
2350 {
2351   PetscFunctionBegin;
2352   PetscValidHeaderSpecific(A, MAT_CLASSID, 1);
2353   PetscCall(PetscLayoutReference(rmap, &A->rmap));
2354   PetscCall(PetscLayoutReference(cmap, &A->cmap));
2355   PetscFunctionReturn(PETSC_SUCCESS);
2356 }
2357 
2358 /*@
2359   MatGetLayouts - Gets the `PetscLayout` objects for rows and columns
2360 
2361   Not Collective
2362 
2363   Input Parameter:
2364 . A - the matrix
2365 
2366   Output Parameters:
2367 + rmap - row layout
2368 - cmap - column layout
2369 
2370   Level: advanced
2371 
2372 .seealso: [](ch_matrices), `Mat`, [Matrix Layouts](sec_matlayout), `PetscLayout`, `MatCreateVecs()`, `MatGetLocalToGlobalMapping()`, `MatSetLayouts()`
2373 @*/
2374 PetscErrorCode MatGetLayouts(Mat A, PetscLayout *rmap, PetscLayout *cmap)
2375 {
2376   PetscFunctionBegin;
2377   PetscValidHeaderSpecific(A, MAT_CLASSID, 1);
2378   PetscValidType(A, 1);
2379   if (rmap) {
2380     PetscAssertPointer(rmap, 2);
2381     *rmap = A->rmap;
2382   }
2383   if (cmap) {
2384     PetscAssertPointer(cmap, 3);
2385     *cmap = A->cmap;
2386   }
2387   PetscFunctionReturn(PETSC_SUCCESS);
2388 }
2389 
2390 /*@
2391   MatSetValuesLocal - Inserts or adds values into certain locations of a matrix,
2392   using a local numbering of the rows and columns.
2393 
2394   Not Collective
2395 
2396   Input Parameters:
2397 + mat  - the matrix
2398 . nrow - number of rows
2399 . irow - the row local indices
2400 . ncol - number of columns
2401 . icol - the column local indices
2402 . y    - a logically two-dimensional array of values
2403 - addv - either `INSERT_VALUES` to add values to any existing entries, or `INSERT_VALUES` to replace existing entries with new values
2404 
2405   Level: intermediate
2406 
2407   Notes:
2408   If you create the matrix yourself (that is not with a call to `DMCreateMatrix()`) then you MUST call `MatSetLocalToGlobalMapping()` before using this routine
2409 
2410   Calls to `MatSetValuesLocal()` with the `INSERT_VALUES` and `ADD_VALUES`
2411   options cannot be mixed without intervening calls to the assembly
2412   routines.
2413 
2414   These values may be cached, so `MatAssemblyBegin()` and `MatAssemblyEnd()`
2415   MUST be called after all calls to `MatSetValuesLocal()` have been completed.
2416 
2417   Fortran Notes:
2418   If any of `irow`, `icol`, and `y` are scalars pass them using, for example,
2419 .vb
2420   MatSetValuesLocal(mat, one, [irow], one, [icol], [y], INSERT_VALUES)
2421 .ve
2422 
2423   If `y` is a two-dimensional array use `reshape()` to pass it as a one dimensional array
2424 
2425   Developer Note:
2426   This is labeled with C so does not automatically generate Fortran stubs and interfaces
2427   because it requires multiple Fortran interfaces depending on which arguments are scalar or arrays.
2428 
2429 .seealso: [](ch_matrices), `Mat`, `MatAssemblyBegin()`, `MatAssemblyEnd()`, `MatSetValues()`, `MatSetLocalToGlobalMapping()`,
2430           `MatGetValuesLocal()`
2431 @*/
2432 PetscErrorCode MatSetValuesLocal(Mat mat, PetscInt nrow, const PetscInt irow[], PetscInt ncol, const PetscInt icol[], const PetscScalar y[], InsertMode addv)
2433 {
2434   PetscFunctionBeginHot;
2435   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
2436   PetscValidType(mat, 1);
2437   MatCheckPreallocated(mat, 1);
2438   if (!nrow || !ncol) PetscFunctionReturn(PETSC_SUCCESS); /* no values to insert */
2439   PetscAssertPointer(irow, 3);
2440   PetscAssertPointer(icol, 5);
2441   if (mat->insertmode == NOT_SET_VALUES) mat->insertmode = addv;
2442   else PetscCheck(mat->insertmode == addv, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Cannot mix add values and insert values");
2443   if (PetscDefined(USE_DEBUG)) {
2444     PetscCheck(!mat->factortype, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
2445     PetscCheck(mat->ops->setvalueslocal || mat->ops->setvalues, PETSC_COMM_SELF, PETSC_ERR_SUP, "Mat type %s", ((PetscObject)mat)->type_name);
2446   }
2447 
2448   if (mat->assembled) {
2449     mat->was_assembled = PETSC_TRUE;
2450     mat->assembled     = PETSC_FALSE;
2451   }
2452   PetscCall(PetscLogEventBegin(MAT_SetValues, mat, 0, 0, 0));
2453   if (mat->ops->setvalueslocal) PetscUseTypeMethod(mat, setvalueslocal, nrow, irow, ncol, icol, y, addv);
2454   else {
2455     PetscInt        buf[8192], *bufr = NULL, *bufc = NULL;
2456     const PetscInt *irowm, *icolm;
2457 
2458     if ((!mat->rmap->mapping && !mat->cmap->mapping) || (nrow + ncol) <= (PetscInt)PETSC_STATIC_ARRAY_LENGTH(buf)) {
2459       bufr  = buf;
2460       bufc  = buf + nrow;
2461       irowm = bufr;
2462       icolm = bufc;
2463     } else {
2464       PetscCall(PetscMalloc2(nrow, &bufr, ncol, &bufc));
2465       irowm = bufr;
2466       icolm = bufc;
2467     }
2468     if (mat->rmap->mapping) PetscCall(ISLocalToGlobalMappingApply(mat->rmap->mapping, nrow, irow, bufr));
2469     else irowm = irow;
2470     if (mat->cmap->mapping) {
2471       if (mat->cmap->mapping != mat->rmap->mapping || ncol != nrow || icol != irow) {
2472         PetscCall(ISLocalToGlobalMappingApply(mat->cmap->mapping, ncol, icol, bufc));
2473       } else icolm = irowm;
2474     } else icolm = icol;
2475     PetscCall(MatSetValues(mat, nrow, irowm, ncol, icolm, y, addv));
2476     if (bufr != buf) PetscCall(PetscFree2(bufr, bufc));
2477   }
2478   PetscCall(PetscLogEventEnd(MAT_SetValues, mat, 0, 0, 0));
2479   PetscFunctionReturn(PETSC_SUCCESS);
2480 }
2481 
2482 /*@
2483   MatSetValuesBlockedLocal - Inserts or adds values into certain locations of a matrix,
2484   using a local ordering of the nodes a block at a time.
2485 
2486   Not Collective
2487 
2488   Input Parameters:
2489 + mat  - the matrix
2490 . nrow - number of rows
2491 . irow - the row local indices
2492 . ncol - number of columns
2493 . icol - the column local indices
2494 . y    - a logically two-dimensional array of values
2495 - addv - either `ADD_VALUES` to add values to any existing entries, or `INSERT_VALUES` to replace existing entries with new values
2496 
2497   Level: intermediate
2498 
2499   Notes:
2500   If you create the matrix yourself (that is not with a call to `DMCreateMatrix()`) then you MUST call `MatSetBlockSize()` and `MatSetLocalToGlobalMapping()`
2501   before using this routineBefore calling `MatSetValuesLocal()`, the user must first set the
2502 
2503   Calls to `MatSetValuesBlockedLocal()` with the `INSERT_VALUES` and `ADD_VALUES`
2504   options cannot be mixed without intervening calls to the assembly
2505   routines.
2506 
2507   These values may be cached, so `MatAssemblyBegin()` and `MatAssemblyEnd()`
2508   MUST be called after all calls to `MatSetValuesBlockedLocal()` have been completed.
2509 
2510   Fortran Notes:
2511   If any of `irow`, `icol`, and `y` are scalars pass them using, for example,
2512 .vb
2513   MatSetValuesBlockedLocal(mat, one, [irow], one, [icol], [y], INSERT_VALUES)
2514 .ve
2515 
2516   If `y` is a two-dimensional array use `reshape()` to pass it as a one dimensional array
2517 
2518   Developer Note:
2519   This is labeled with C so does not automatically generate Fortran stubs and interfaces
2520   because it requires multiple Fortran interfaces depending on which arguments are scalar or arrays.
2521 
2522 .seealso: [](ch_matrices), `Mat`, `MatSetBlockSize()`, `MatSetLocalToGlobalMapping()`, `MatAssemblyBegin()`, `MatAssemblyEnd()`,
2523           `MatSetValuesLocal()`, `MatSetValuesBlocked()`
2524 @*/
2525 PetscErrorCode MatSetValuesBlockedLocal(Mat mat, PetscInt nrow, const PetscInt irow[], PetscInt ncol, const PetscInt icol[], const PetscScalar y[], InsertMode addv)
2526 {
2527   PetscFunctionBeginHot;
2528   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
2529   PetscValidType(mat, 1);
2530   MatCheckPreallocated(mat, 1);
2531   if (!nrow || !ncol) PetscFunctionReturn(PETSC_SUCCESS); /* no values to insert */
2532   PetscAssertPointer(irow, 3);
2533   PetscAssertPointer(icol, 5);
2534   if (mat->insertmode == NOT_SET_VALUES) mat->insertmode = addv;
2535   else PetscCheck(mat->insertmode == addv, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Cannot mix add values and insert values");
2536   if (PetscDefined(USE_DEBUG)) {
2537     PetscCheck(!mat->factortype, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
2538     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);
2539   }
2540 
2541   if (mat->assembled) {
2542     mat->was_assembled = PETSC_TRUE;
2543     mat->assembled     = PETSC_FALSE;
2544   }
2545   if (PetscUnlikelyDebug(mat->rmap->mapping)) { /* Condition on the mapping existing, because MatSetValuesBlockedLocal_IS does not require it to be set. */
2546     PetscInt irbs, rbs;
2547     PetscCall(MatGetBlockSizes(mat, &rbs, NULL));
2548     PetscCall(ISLocalToGlobalMappingGetBlockSize(mat->rmap->mapping, &irbs));
2549     PetscCheck(rbs == irbs, PetscObjectComm((PetscObject)mat), PETSC_ERR_SUP, "Different row block sizes! mat %" PetscInt_FMT ", row l2g map %" PetscInt_FMT, rbs, irbs);
2550   }
2551   if (PetscUnlikelyDebug(mat->cmap->mapping)) {
2552     PetscInt icbs, cbs;
2553     PetscCall(MatGetBlockSizes(mat, NULL, &cbs));
2554     PetscCall(ISLocalToGlobalMappingGetBlockSize(mat->cmap->mapping, &icbs));
2555     PetscCheck(cbs == icbs, PetscObjectComm((PetscObject)mat), PETSC_ERR_SUP, "Different col block sizes! mat %" PetscInt_FMT ", col l2g map %" PetscInt_FMT, cbs, icbs);
2556   }
2557   PetscCall(PetscLogEventBegin(MAT_SetValues, mat, 0, 0, 0));
2558   if (mat->ops->setvaluesblockedlocal) PetscUseTypeMethod(mat, setvaluesblockedlocal, nrow, irow, ncol, icol, y, addv);
2559   else {
2560     PetscInt        buf[8192], *bufr = NULL, *bufc = NULL;
2561     const PetscInt *irowm, *icolm;
2562 
2563     if ((!mat->rmap->mapping && !mat->cmap->mapping) || (nrow + ncol) <= ((PetscInt)PETSC_STATIC_ARRAY_LENGTH(buf))) {
2564       bufr  = buf;
2565       bufc  = buf + nrow;
2566       irowm = bufr;
2567       icolm = bufc;
2568     } else {
2569       PetscCall(PetscMalloc2(nrow, &bufr, ncol, &bufc));
2570       irowm = bufr;
2571       icolm = bufc;
2572     }
2573     if (mat->rmap->mapping) PetscCall(ISLocalToGlobalMappingApplyBlock(mat->rmap->mapping, nrow, irow, bufr));
2574     else irowm = irow;
2575     if (mat->cmap->mapping) {
2576       if (mat->cmap->mapping != mat->rmap->mapping || ncol != nrow || icol != irow) {
2577         PetscCall(ISLocalToGlobalMappingApplyBlock(mat->cmap->mapping, ncol, icol, bufc));
2578       } else icolm = irowm;
2579     } else icolm = icol;
2580     PetscCall(MatSetValuesBlocked(mat, nrow, irowm, ncol, icolm, y, addv));
2581     if (bufr != buf) PetscCall(PetscFree2(bufr, bufc));
2582   }
2583   PetscCall(PetscLogEventEnd(MAT_SetValues, mat, 0, 0, 0));
2584   PetscFunctionReturn(PETSC_SUCCESS);
2585 }
2586 
2587 /*@
2588   MatMultDiagonalBlock - Computes the matrix-vector product, $y = Dx$. Where `D` is defined by the inode or block structure of the diagonal
2589 
2590   Collective
2591 
2592   Input Parameters:
2593 + mat - the matrix
2594 - x   - the vector to be multiplied
2595 
2596   Output Parameter:
2597 . y - the result
2598 
2599   Level: developer
2600 
2601   Note:
2602   The vectors `x` and `y` cannot be the same.  I.e., one cannot
2603   call `MatMultDiagonalBlock`(A,y,y).
2604 
2605 .seealso: [](ch_matrices), `Mat`, `MatMult()`, `MatMultTranspose()`, `MatMultAdd()`, `MatMultTransposeAdd()`
2606 @*/
2607 PetscErrorCode MatMultDiagonalBlock(Mat mat, Vec x, Vec y)
2608 {
2609   PetscFunctionBegin;
2610   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
2611   PetscValidType(mat, 1);
2612   PetscValidHeaderSpecific(x, VEC_CLASSID, 2);
2613   PetscValidHeaderSpecific(y, VEC_CLASSID, 3);
2614 
2615   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
2616   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
2617   PetscCheck(x != y, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "x and y must be different vectors");
2618   MatCheckPreallocated(mat, 1);
2619 
2620   PetscUseTypeMethod(mat, multdiagonalblock, x, y);
2621   PetscCall(PetscObjectStateIncrease((PetscObject)y));
2622   PetscFunctionReturn(PETSC_SUCCESS);
2623 }
2624 
2625 /*@
2626   MatMult - Computes the matrix-vector product, $y = Ax$.
2627 
2628   Neighbor-wise Collective
2629 
2630   Input Parameters:
2631 + mat - the matrix
2632 - x   - the vector to be multiplied
2633 
2634   Output Parameter:
2635 . y - the result
2636 
2637   Level: beginner
2638 
2639   Note:
2640   The vectors `x` and `y` cannot be the same.  I.e., one cannot
2641   call `MatMult`(A,y,y).
2642 
2643 .seealso: [](ch_matrices), `Mat`, `MatMultTranspose()`, `MatMultAdd()`, `MatMultTransposeAdd()`
2644 @*/
2645 PetscErrorCode MatMult(Mat mat, Vec x, Vec y)
2646 {
2647   PetscFunctionBegin;
2648   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
2649   PetscValidType(mat, 1);
2650   PetscValidHeaderSpecific(x, VEC_CLASSID, 2);
2651   VecCheckAssembled(x);
2652   PetscValidHeaderSpecific(y, VEC_CLASSID, 3);
2653   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
2654   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
2655   PetscCheck(x != y, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "x and y must be different vectors");
2656   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);
2657   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);
2658   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);
2659   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);
2660   PetscCall(VecSetErrorIfLocked(y, 3));
2661   if (mat->erroriffailure) PetscCall(VecValidValues_Internal(x, 2, PETSC_TRUE));
2662   MatCheckPreallocated(mat, 1);
2663 
2664   PetscCall(VecLockReadPush(x));
2665   PetscCall(PetscLogEventBegin(MAT_Mult, mat, x, y, 0));
2666   PetscUseTypeMethod(mat, mult, x, y);
2667   PetscCall(PetscLogEventEnd(MAT_Mult, mat, x, y, 0));
2668   if (mat->erroriffailure) PetscCall(VecValidValues_Internal(y, 3, PETSC_FALSE));
2669   PetscCall(VecLockReadPop(x));
2670   PetscFunctionReturn(PETSC_SUCCESS);
2671 }
2672 
2673 /*@
2674   MatMultTranspose - Computes matrix transpose times a vector $y = A^T * x$.
2675 
2676   Neighbor-wise Collective
2677 
2678   Input Parameters:
2679 + mat - the matrix
2680 - x   - the vector to be multiplied
2681 
2682   Output Parameter:
2683 . y - the result
2684 
2685   Level: beginner
2686 
2687   Notes:
2688   The vectors `x` and `y` cannot be the same.  I.e., one cannot
2689   call `MatMultTranspose`(A,y,y).
2690 
2691   For complex numbers this does NOT compute the Hermitian (complex conjugate) transpose multiple,
2692   use `MatMultHermitianTranspose()`
2693 
2694 .seealso: [](ch_matrices), `Mat`, `MatMult()`, `MatMultAdd()`, `MatMultTransposeAdd()`, `MatMultHermitianTranspose()`, `MatTranspose()`
2695 @*/
2696 PetscErrorCode MatMultTranspose(Mat mat, Vec x, Vec y)
2697 {
2698   PetscErrorCode (*op)(Mat, Vec, Vec) = NULL;
2699 
2700   PetscFunctionBegin;
2701   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
2702   PetscValidType(mat, 1);
2703   PetscValidHeaderSpecific(x, VEC_CLASSID, 2);
2704   VecCheckAssembled(x);
2705   PetscValidHeaderSpecific(y, VEC_CLASSID, 3);
2706 
2707   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
2708   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
2709   PetscCheck(x != y, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "x and y must be different vectors");
2710   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);
2711   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);
2712   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);
2713   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);
2714   if (mat->erroriffailure) PetscCall(VecValidValues_Internal(x, 2, PETSC_TRUE));
2715   MatCheckPreallocated(mat, 1);
2716 
2717   if (!mat->ops->multtranspose) {
2718     if (mat->symmetric == PETSC_BOOL3_TRUE && mat->ops->mult) op = mat->ops->mult;
2719     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);
2720   } else op = mat->ops->multtranspose;
2721   PetscCall(PetscLogEventBegin(MAT_MultTranspose, mat, x, y, 0));
2722   PetscCall(VecLockReadPush(x));
2723   PetscCall((*op)(mat, x, y));
2724   PetscCall(VecLockReadPop(x));
2725   PetscCall(PetscLogEventEnd(MAT_MultTranspose, mat, x, y, 0));
2726   PetscCall(PetscObjectStateIncrease((PetscObject)y));
2727   if (mat->erroriffailure) PetscCall(VecValidValues_Internal(y, 3, PETSC_FALSE));
2728   PetscFunctionReturn(PETSC_SUCCESS);
2729 }
2730 
2731 /*@
2732   MatMultHermitianTranspose - Computes matrix Hermitian-transpose times a vector $y = A^H * x$.
2733 
2734   Neighbor-wise Collective
2735 
2736   Input Parameters:
2737 + mat - the matrix
2738 - x   - the vector to be multiplied
2739 
2740   Output Parameter:
2741 . y - the result
2742 
2743   Level: beginner
2744 
2745   Notes:
2746   The vectors `x` and `y` cannot be the same.  I.e., one cannot
2747   call `MatMultHermitianTranspose`(A,y,y).
2748 
2749   Also called the conjugate transpose, complex conjugate transpose, or adjoint.
2750 
2751   For real numbers `MatMultTranspose()` and `MatMultHermitianTranspose()` are identical.
2752 
2753 .seealso: [](ch_matrices), `Mat`, `MatMult()`, `MatMultAdd()`, `MatMultHermitianTransposeAdd()`, `MatMultTranspose()`
2754 @*/
2755 PetscErrorCode MatMultHermitianTranspose(Mat mat, Vec x, Vec y)
2756 {
2757   PetscFunctionBegin;
2758   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
2759   PetscValidType(mat, 1);
2760   PetscValidHeaderSpecific(x, VEC_CLASSID, 2);
2761   PetscValidHeaderSpecific(y, VEC_CLASSID, 3);
2762 
2763   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
2764   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
2765   PetscCheck(x != y, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "x and y must be different vectors");
2766   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);
2767   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);
2768   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);
2769   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);
2770   MatCheckPreallocated(mat, 1);
2771 
2772   PetscCall(PetscLogEventBegin(MAT_MultHermitianTranspose, mat, x, y, 0));
2773 #if defined(PETSC_USE_COMPLEX)
2774   if (mat->ops->multhermitiantranspose || (mat->hermitian == PETSC_BOOL3_TRUE && mat->ops->mult)) {
2775     PetscCall(VecLockReadPush(x));
2776     if (mat->ops->multhermitiantranspose) PetscUseTypeMethod(mat, multhermitiantranspose, x, y);
2777     else PetscUseTypeMethod(mat, mult, x, y);
2778     PetscCall(VecLockReadPop(x));
2779   } else {
2780     Vec w;
2781     PetscCall(VecDuplicate(x, &w));
2782     PetscCall(VecCopy(x, w));
2783     PetscCall(VecConjugate(w));
2784     PetscCall(MatMultTranspose(mat, w, y));
2785     PetscCall(VecDestroy(&w));
2786     PetscCall(VecConjugate(y));
2787   }
2788   PetscCall(PetscObjectStateIncrease((PetscObject)y));
2789 #else
2790   PetscCall(MatMultTranspose(mat, x, y));
2791 #endif
2792   PetscCall(PetscLogEventEnd(MAT_MultHermitianTranspose, mat, x, y, 0));
2793   PetscFunctionReturn(PETSC_SUCCESS);
2794 }
2795 
2796 /*@
2797   MatMultAdd -  Computes $v3 = v2 + A * v1$.
2798 
2799   Neighbor-wise Collective
2800 
2801   Input Parameters:
2802 + mat - the matrix
2803 . v1  - the vector to be multiplied by `mat`
2804 - v2  - the vector to be added to the result
2805 
2806   Output Parameter:
2807 . v3 - the result
2808 
2809   Level: beginner
2810 
2811   Note:
2812   The vectors `v1` and `v3` cannot be the same.  I.e., one cannot
2813   call `MatMultAdd`(A,v1,v2,v1).
2814 
2815 .seealso: [](ch_matrices), `Mat`, `MatMultTranspose()`, `MatMult()`, `MatMultTransposeAdd()`
2816 @*/
2817 PetscErrorCode MatMultAdd(Mat mat, Vec v1, Vec v2, Vec v3)
2818 {
2819   PetscFunctionBegin;
2820   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
2821   PetscValidType(mat, 1);
2822   PetscValidHeaderSpecific(v1, VEC_CLASSID, 2);
2823   PetscValidHeaderSpecific(v2, VEC_CLASSID, 3);
2824   PetscValidHeaderSpecific(v3, VEC_CLASSID, 4);
2825 
2826   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
2827   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
2828   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);
2829   /* 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);
2830      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); */
2831   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);
2832   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);
2833   PetscCheck(v1 != v3, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_IDN, "v1 and v3 must be different vectors");
2834   MatCheckPreallocated(mat, 1);
2835 
2836   PetscCall(PetscLogEventBegin(MAT_MultAdd, mat, v1, v2, v3));
2837   PetscCall(VecLockReadPush(v1));
2838   PetscUseTypeMethod(mat, multadd, v1, v2, v3);
2839   PetscCall(VecLockReadPop(v1));
2840   PetscCall(PetscLogEventEnd(MAT_MultAdd, mat, v1, v2, v3));
2841   PetscCall(PetscObjectStateIncrease((PetscObject)v3));
2842   PetscFunctionReturn(PETSC_SUCCESS);
2843 }
2844 
2845 /*@
2846   MatMultTransposeAdd - Computes $v3 = v2 + A^T * v1$.
2847 
2848   Neighbor-wise Collective
2849 
2850   Input Parameters:
2851 + mat - the matrix
2852 . v1  - the vector to be multiplied by the transpose of the matrix
2853 - v2  - the vector to be added to the result
2854 
2855   Output Parameter:
2856 . v3 - the result
2857 
2858   Level: beginner
2859 
2860   Note:
2861   The vectors `v1` and `v3` cannot be the same.  I.e., one cannot
2862   call `MatMultTransposeAdd`(A,v1,v2,v1).
2863 
2864 .seealso: [](ch_matrices), `Mat`, `MatMultTranspose()`, `MatMultAdd()`, `MatMult()`
2865 @*/
2866 PetscErrorCode MatMultTransposeAdd(Mat mat, Vec v1, Vec v2, Vec v3)
2867 {
2868   PetscErrorCode (*op)(Mat, Vec, Vec, Vec) = (!mat->ops->multtransposeadd && mat->symmetric) ? mat->ops->multadd : mat->ops->multtransposeadd;
2869 
2870   PetscFunctionBegin;
2871   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
2872   PetscValidType(mat, 1);
2873   PetscValidHeaderSpecific(v1, VEC_CLASSID, 2);
2874   PetscValidHeaderSpecific(v2, VEC_CLASSID, 3);
2875   PetscValidHeaderSpecific(v3, VEC_CLASSID, 4);
2876 
2877   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
2878   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
2879   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);
2880   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);
2881   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);
2882   PetscCheck(v1 != v3, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_IDN, "v1 and v3 must be different vectors");
2883   PetscCheck(op, PetscObjectComm((PetscObject)mat), PETSC_ERR_SUP, "Mat type %s", ((PetscObject)mat)->type_name);
2884   MatCheckPreallocated(mat, 1);
2885 
2886   PetscCall(PetscLogEventBegin(MAT_MultTransposeAdd, mat, v1, v2, v3));
2887   PetscCall(VecLockReadPush(v1));
2888   PetscCall((*op)(mat, v1, v2, v3));
2889   PetscCall(VecLockReadPop(v1));
2890   PetscCall(PetscLogEventEnd(MAT_MultTransposeAdd, mat, v1, v2, v3));
2891   PetscCall(PetscObjectStateIncrease((PetscObject)v3));
2892   PetscFunctionReturn(PETSC_SUCCESS);
2893 }
2894 
2895 /*@
2896   MatMultHermitianTransposeAdd - Computes $v3 = v2 + A^H * v1$.
2897 
2898   Neighbor-wise Collective
2899 
2900   Input Parameters:
2901 + mat - the matrix
2902 . v1  - the vector to be multiplied by the Hermitian transpose
2903 - v2  - the vector to be added to the result
2904 
2905   Output Parameter:
2906 . v3 - the result
2907 
2908   Level: beginner
2909 
2910   Note:
2911   The vectors `v1` and `v3` cannot be the same.  I.e., one cannot
2912   call `MatMultHermitianTransposeAdd`(A,v1,v2,v1).
2913 
2914 .seealso: [](ch_matrices), `Mat`, `MatMultHermitianTranspose()`, `MatMultTranspose()`, `MatMultAdd()`, `MatMult()`
2915 @*/
2916 PetscErrorCode MatMultHermitianTransposeAdd(Mat mat, Vec v1, Vec v2, Vec v3)
2917 {
2918   PetscFunctionBegin;
2919   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
2920   PetscValidType(mat, 1);
2921   PetscValidHeaderSpecific(v1, VEC_CLASSID, 2);
2922   PetscValidHeaderSpecific(v2, VEC_CLASSID, 3);
2923   PetscValidHeaderSpecific(v3, VEC_CLASSID, 4);
2924 
2925   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
2926   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
2927   PetscCheck(v1 != v3, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_IDN, "v1 and v3 must be different vectors");
2928   PetscCheck(mat->rmap->N == v1->map->N, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_SIZ, "Mat mat,Vec v1: global dim %" PetscInt_FMT " %" PetscInt_FMT, mat->rmap->N, v1->map->N);
2929   PetscCheck(mat->cmap->N == v2->map->N, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_SIZ, "Mat mat,Vec v2: global dim %" PetscInt_FMT " %" PetscInt_FMT, mat->cmap->N, v2->map->N);
2930   PetscCheck(mat->cmap->N == v3->map->N, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_SIZ, "Mat mat,Vec v3: global dim %" PetscInt_FMT " %" PetscInt_FMT, mat->cmap->N, v3->map->N);
2931   MatCheckPreallocated(mat, 1);
2932 
2933   PetscCall(PetscLogEventBegin(MAT_MultHermitianTransposeAdd, mat, v1, v2, v3));
2934   PetscCall(VecLockReadPush(v1));
2935   if (mat->ops->multhermitiantransposeadd) PetscUseTypeMethod(mat, multhermitiantransposeadd, v1, v2, v3);
2936   else {
2937     Vec w, z;
2938     PetscCall(VecDuplicate(v1, &w));
2939     PetscCall(VecCopy(v1, w));
2940     PetscCall(VecConjugate(w));
2941     PetscCall(VecDuplicate(v3, &z));
2942     PetscCall(MatMultTranspose(mat, w, z));
2943     PetscCall(VecDestroy(&w));
2944     PetscCall(VecConjugate(z));
2945     if (v2 != v3) {
2946       PetscCall(VecWAXPY(v3, 1.0, v2, z));
2947     } else {
2948       PetscCall(VecAXPY(v3, 1.0, z));
2949     }
2950     PetscCall(VecDestroy(&z));
2951   }
2952   PetscCall(VecLockReadPop(v1));
2953   PetscCall(PetscLogEventEnd(MAT_MultHermitianTransposeAdd, mat, v1, v2, v3));
2954   PetscCall(PetscObjectStateIncrease((PetscObject)v3));
2955   PetscFunctionReturn(PETSC_SUCCESS);
2956 }
2957 
2958 /*@
2959   MatGetFactorType - gets the type of factorization a matrix is
2960 
2961   Not Collective
2962 
2963   Input Parameter:
2964 . mat - the matrix
2965 
2966   Output Parameter:
2967 . 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`
2968 
2969   Level: intermediate
2970 
2971 .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatFactorType`, `MatGetFactor()`, `MatSetFactorType()`, `MAT_FACTOR_NONE`, `MAT_FACTOR_LU`, `MAT_FACTOR_CHOLESKY`, `MAT_FACTOR_ILU`,
2972           `MAT_FACTOR_ICC`,`MAT_FACTOR_ILUDT`, `MAT_FACTOR_QR`
2973 @*/
2974 PetscErrorCode MatGetFactorType(Mat mat, MatFactorType *t)
2975 {
2976   PetscFunctionBegin;
2977   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
2978   PetscValidType(mat, 1);
2979   PetscAssertPointer(t, 2);
2980   *t = mat->factortype;
2981   PetscFunctionReturn(PETSC_SUCCESS);
2982 }
2983 
2984 /*@
2985   MatSetFactorType - sets the type of factorization a matrix is
2986 
2987   Logically Collective
2988 
2989   Input Parameters:
2990 + mat - the matrix
2991 - 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`
2992 
2993   Level: intermediate
2994 
2995 .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatFactorType`, `MatGetFactor()`, `MatGetFactorType()`, `MAT_FACTOR_NONE`, `MAT_FACTOR_LU`, `MAT_FACTOR_CHOLESKY`, `MAT_FACTOR_ILU`,
2996           `MAT_FACTOR_ICC`,`MAT_FACTOR_ILUDT`, `MAT_FACTOR_QR`
2997 @*/
2998 PetscErrorCode MatSetFactorType(Mat mat, MatFactorType t)
2999 {
3000   PetscFunctionBegin;
3001   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
3002   PetscValidType(mat, 1);
3003   mat->factortype = t;
3004   PetscFunctionReturn(PETSC_SUCCESS);
3005 }
3006 
3007 /*@
3008   MatGetInfo - Returns information about matrix storage (number of
3009   nonzeros, memory, etc.).
3010 
3011   Collective if `MAT_GLOBAL_MAX` or `MAT_GLOBAL_SUM` is used as the flag
3012 
3013   Input Parameters:
3014 + mat  - the matrix
3015 - 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)
3016 
3017   Output Parameter:
3018 . info - matrix information context
3019 
3020   Options Database Key:
3021 . -mat_view ::ascii_info - print matrix info to `PETSC_STDOUT`
3022 
3023   Level: intermediate
3024 
3025   Notes:
3026   The `MatInfo` context contains a variety of matrix data, including
3027   number of nonzeros allocated and used, number of mallocs during
3028   matrix assembly, etc.  Additional information for factored matrices
3029   is provided (such as the fill ratio, number of mallocs during
3030   factorization, etc.).
3031 
3032   Example:
3033   See the file ${PETSC_DIR}/include/petscmat.h for a complete list of
3034   data within the `MatInfo` context.  For example,
3035 .vb
3036       MatInfo info;
3037       Mat     A;
3038       double  mal, nz_a, nz_u;
3039 
3040       MatGetInfo(A, MAT_LOCAL, &info);
3041       mal  = info.mallocs;
3042       nz_a = info.nz_allocated;
3043 .ve
3044 
3045   Fortran Note:
3046   Declare info as a `MatInfo` array of dimension `MAT_INFO_SIZE`, and then extract the parameters
3047   of interest.  See the file ${PETSC_DIR}/include/petsc/finclude/petscmat.h
3048   a complete list of parameter names.
3049 .vb
3050       MatInfo info(MAT_INFO_SIZE)
3051       double  precision mal, nz_a
3052       Mat     A
3053       integer ierr
3054 
3055       call MatGetInfo(A, MAT_LOCAL, info, ierr)
3056       mal = info(MAT_INFO_MALLOCS)
3057       nz_a = info(MAT_INFO_NZ_ALLOCATED)
3058 .ve
3059 
3060 .seealso: [](ch_matrices), `Mat`, `MatInfo`, `MatStashGetInfo()`
3061 @*/
3062 PetscErrorCode MatGetInfo(Mat mat, MatInfoType flag, MatInfo *info)
3063 {
3064   PetscFunctionBegin;
3065   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
3066   PetscValidType(mat, 1);
3067   PetscAssertPointer(info, 3);
3068   MatCheckPreallocated(mat, 1);
3069   PetscUseTypeMethod(mat, getinfo, flag, info);
3070   PetscFunctionReturn(PETSC_SUCCESS);
3071 }
3072 
3073 /*
3074    This is used by external packages where it is not easy to get the info from the actual
3075    matrix factorization.
3076 */
3077 PetscErrorCode MatGetInfo_External(Mat A, MatInfoType flag, MatInfo *info)
3078 {
3079   PetscFunctionBegin;
3080   PetscCall(PetscMemzero(info, sizeof(MatInfo)));
3081   PetscFunctionReturn(PETSC_SUCCESS);
3082 }
3083 
3084 /*@
3085   MatLUFactor - Performs in-place LU factorization of matrix.
3086 
3087   Collective
3088 
3089   Input Parameters:
3090 + mat  - the matrix
3091 . row  - row permutation
3092 . col  - column permutation
3093 - info - options for factorization, includes
3094 .vb
3095           fill - expected fill as ratio of original fill.
3096           dtcol - pivot tolerance (0 no pivot, 1 full column pivoting)
3097                    Run with the option -info to determine an optimal value to use
3098 .ve
3099 
3100   Level: developer
3101 
3102   Notes:
3103   Most users should employ the `KSP` interface for linear solvers
3104   instead of working directly with matrix algebra routines such as this.
3105   See, e.g., `KSPCreate()`.
3106 
3107   This changes the state of the matrix to a factored matrix; it cannot be used
3108   for example with `MatSetValues()` unless one first calls `MatSetUnfactored()`.
3109 
3110   This is really in-place only for dense matrices, the preferred approach is to use `MatGetFactor()`, `MatLUFactorSymbolic()`, and `MatLUFactorNumeric()`
3111   when not using `KSP`.
3112 
3113   Developer Note:
3114   The Fortran interface is not autogenerated as the
3115   interface definition cannot be generated correctly [due to `MatFactorInfo`]
3116 
3117 .seealso: [](ch_matrices), [Matrix Factorization](sec_matfactor), `Mat`, `MatFactorType`, `MatLUFactorSymbolic()`, `MatLUFactorNumeric()`, `MatCholeskyFactor()`,
3118           `MatGetOrdering()`, `MatSetUnfactored()`, `MatFactorInfo`, `MatGetFactor()`
3119 @*/
3120 PetscErrorCode MatLUFactor(Mat mat, IS row, IS col, const MatFactorInfo *info)
3121 {
3122   MatFactorInfo tinfo;
3123 
3124   PetscFunctionBegin;
3125   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
3126   if (row) PetscValidHeaderSpecific(row, IS_CLASSID, 2);
3127   if (col) PetscValidHeaderSpecific(col, IS_CLASSID, 3);
3128   if (info) PetscAssertPointer(info, 4);
3129   PetscValidType(mat, 1);
3130   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
3131   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
3132   MatCheckPreallocated(mat, 1);
3133   if (!info) {
3134     PetscCall(MatFactorInfoInitialize(&tinfo));
3135     info = &tinfo;
3136   }
3137 
3138   PetscCall(PetscLogEventBegin(MAT_LUFactor, mat, row, col, 0));
3139   PetscUseTypeMethod(mat, lufactor, row, col, info);
3140   PetscCall(PetscLogEventEnd(MAT_LUFactor, mat, row, col, 0));
3141   PetscCall(PetscObjectStateIncrease((PetscObject)mat));
3142   PetscFunctionReturn(PETSC_SUCCESS);
3143 }
3144 
3145 /*@
3146   MatILUFactor - Performs in-place ILU factorization of matrix.
3147 
3148   Collective
3149 
3150   Input Parameters:
3151 + mat  - the matrix
3152 . row  - row permutation
3153 . col  - column permutation
3154 - info - structure containing
3155 .vb
3156       levels - number of levels of fill.
3157       expected fill - as ratio of original fill.
3158       1 or 0 - indicating force fill on diagonal (improves robustness for matrices
3159                 missing diagonal entries)
3160 .ve
3161 
3162   Level: developer
3163 
3164   Notes:
3165   Most users should employ the `KSP` interface for linear solvers
3166   instead of working directly with matrix algebra routines such as this.
3167   See, e.g., `KSPCreate()`.
3168 
3169   Probably really in-place only when level of fill is zero, otherwise allocates
3170   new space to store factored matrix and deletes previous memory. The preferred approach is to use `MatGetFactor()`, `MatILUFactorSymbolic()`, and `MatILUFactorNumeric()`
3171   when not using `KSP`.
3172 
3173   Developer Note:
3174   The Fortran interface is not autogenerated as the
3175   interface definition cannot be generated correctly [due to MatFactorInfo]
3176 
3177 .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatILUFactorSymbolic()`, `MatLUFactorNumeric()`, `MatCholeskyFactor()`, `MatFactorInfo`
3178 @*/
3179 PetscErrorCode MatILUFactor(Mat mat, IS row, IS col, const MatFactorInfo *info)
3180 {
3181   PetscFunctionBegin;
3182   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
3183   if (row) PetscValidHeaderSpecific(row, IS_CLASSID, 2);
3184   if (col) PetscValidHeaderSpecific(col, IS_CLASSID, 3);
3185   PetscAssertPointer(info, 4);
3186   PetscValidType(mat, 1);
3187   PetscCheck(mat->rmap->N == mat->cmap->N, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONG, "matrix must be square");
3188   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
3189   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
3190   MatCheckPreallocated(mat, 1);
3191 
3192   PetscCall(PetscLogEventBegin(MAT_ILUFactor, mat, row, col, 0));
3193   PetscUseTypeMethod(mat, ilufactor, row, col, info);
3194   PetscCall(PetscLogEventEnd(MAT_ILUFactor, mat, row, col, 0));
3195   PetscCall(PetscObjectStateIncrease((PetscObject)mat));
3196   PetscFunctionReturn(PETSC_SUCCESS);
3197 }
3198 
3199 /*@
3200   MatLUFactorSymbolic - Performs symbolic LU factorization of matrix.
3201   Call this routine before calling `MatLUFactorNumeric()` and after `MatGetFactor()`.
3202 
3203   Collective
3204 
3205   Input Parameters:
3206 + fact - the factor matrix obtained with `MatGetFactor()`
3207 . mat  - the matrix
3208 . row  - the row permutation
3209 . col  - the column permutation
3210 - info - options for factorization, includes
3211 .vb
3212           fill - expected fill as ratio of original fill. Run with the option -info to determine an optimal value to use
3213           dtcol - pivot tolerance (0 no pivot, 1 full column pivoting)
3214 .ve
3215 
3216   Level: developer
3217 
3218   Notes:
3219   See [Matrix Factorization](sec_matfactor) for additional information about factorizations
3220 
3221   Most users should employ the simplified `KSP` interface for linear solvers
3222   instead of working directly with matrix algebra routines such as this.
3223   See, e.g., `KSPCreate()`.
3224 
3225   Developer Note:
3226   The Fortran interface is not autogenerated as the
3227   interface definition cannot be generated correctly [due to `MatFactorInfo`]
3228 
3229 .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatGetFactor()`, `MatLUFactor()`, `MatLUFactorNumeric()`, `MatCholeskyFactor()`, `MatFactorInfo`, `MatFactorInfoInitialize()`
3230 @*/
3231 PetscErrorCode MatLUFactorSymbolic(Mat fact, Mat mat, IS row, IS col, const MatFactorInfo *info)
3232 {
3233   MatFactorInfo tinfo;
3234 
3235   PetscFunctionBegin;
3236   PetscValidHeaderSpecific(fact, MAT_CLASSID, 1);
3237   PetscValidHeaderSpecific(mat, MAT_CLASSID, 2);
3238   if (row) PetscValidHeaderSpecific(row, IS_CLASSID, 3);
3239   if (col) PetscValidHeaderSpecific(col, IS_CLASSID, 4);
3240   if (info) PetscAssertPointer(info, 5);
3241   PetscValidType(fact, 1);
3242   PetscValidType(mat, 2);
3243   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
3244   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
3245   MatCheckPreallocated(mat, 2);
3246   if (!info) {
3247     PetscCall(MatFactorInfoInitialize(&tinfo));
3248     info = &tinfo;
3249   }
3250 
3251   if (!fact->trivialsymbolic) PetscCall(PetscLogEventBegin(MAT_LUFactorSymbolic, mat, row, col, 0));
3252   PetscUseTypeMethod(fact, lufactorsymbolic, mat, row, col, info);
3253   if (!fact->trivialsymbolic) PetscCall(PetscLogEventEnd(MAT_LUFactorSymbolic, mat, row, col, 0));
3254   PetscCall(PetscObjectStateIncrease((PetscObject)fact));
3255   PetscFunctionReturn(PETSC_SUCCESS);
3256 }
3257 
3258 /*@
3259   MatLUFactorNumeric - Performs numeric LU factorization of a matrix.
3260   Call this routine after first calling `MatLUFactorSymbolic()` and `MatGetFactor()`.
3261 
3262   Collective
3263 
3264   Input Parameters:
3265 + fact - the factor matrix obtained with `MatGetFactor()`
3266 . mat  - the matrix
3267 - info - options for factorization
3268 
3269   Level: developer
3270 
3271   Notes:
3272   See `MatLUFactor()` for in-place factorization.  See
3273   `MatCholeskyFactorNumeric()` for the symmetric, positive definite case.
3274 
3275   Most users should employ the `KSP` interface for linear solvers
3276   instead of working directly with matrix algebra routines such as this.
3277   See, e.g., `KSPCreate()`.
3278 
3279   Developer Note:
3280   The Fortran interface is not autogenerated as the
3281   interface definition cannot be generated correctly [due to `MatFactorInfo`]
3282 
3283 .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatGetFactor()`, `MatFactorInfo`, `MatLUFactorSymbolic()`, `MatLUFactor()`, `MatCholeskyFactor()`
3284 @*/
3285 PetscErrorCode MatLUFactorNumeric(Mat fact, Mat mat, const MatFactorInfo *info)
3286 {
3287   MatFactorInfo tinfo;
3288 
3289   PetscFunctionBegin;
3290   PetscValidHeaderSpecific(fact, MAT_CLASSID, 1);
3291   PetscValidHeaderSpecific(mat, MAT_CLASSID, 2);
3292   PetscValidType(fact, 1);
3293   PetscValidType(mat, 2);
3294   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
3295   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,
3296              mat->rmap->N, (fact)->rmap->N, mat->cmap->N, (fact)->cmap->N);
3297 
3298   MatCheckPreallocated(mat, 2);
3299   if (!info) {
3300     PetscCall(MatFactorInfoInitialize(&tinfo));
3301     info = &tinfo;
3302   }
3303 
3304   if (!fact->trivialsymbolic) PetscCall(PetscLogEventBegin(MAT_LUFactorNumeric, mat, fact, 0, 0));
3305   else PetscCall(PetscLogEventBegin(MAT_LUFactor, mat, fact, 0, 0));
3306   PetscUseTypeMethod(fact, lufactornumeric, mat, info);
3307   if (!fact->trivialsymbolic) PetscCall(PetscLogEventEnd(MAT_LUFactorNumeric, mat, fact, 0, 0));
3308   else PetscCall(PetscLogEventEnd(MAT_LUFactor, mat, fact, 0, 0));
3309   PetscCall(MatViewFromOptions(fact, NULL, "-mat_factor_view"));
3310   PetscCall(PetscObjectStateIncrease((PetscObject)fact));
3311   PetscFunctionReturn(PETSC_SUCCESS);
3312 }
3313 
3314 /*@
3315   MatCholeskyFactor - Performs in-place Cholesky factorization of a
3316   symmetric matrix.
3317 
3318   Collective
3319 
3320   Input Parameters:
3321 + mat  - the matrix
3322 . perm - row and column permutations
3323 - info - expected fill as ratio of original fill
3324 
3325   Level: developer
3326 
3327   Notes:
3328   See `MatLUFactor()` for the nonsymmetric case.  See also `MatGetFactor()`,
3329   `MatCholeskyFactorSymbolic()`, and `MatCholeskyFactorNumeric()`.
3330 
3331   Most users should employ the `KSP` interface for linear solvers
3332   instead of working directly with matrix algebra routines such as this.
3333   See, e.g., `KSPCreate()`.
3334 
3335   Developer Note:
3336   The Fortran interface is not autogenerated as the
3337   interface definition cannot be generated correctly [due to `MatFactorInfo`]
3338 
3339 .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatGetFactor()`, `MatFactorInfo`, `MatLUFactor()`, `MatCholeskyFactorSymbolic()`, `MatCholeskyFactorNumeric()`
3340           `MatGetOrdering()`
3341 @*/
3342 PetscErrorCode MatCholeskyFactor(Mat mat, IS perm, const MatFactorInfo *info)
3343 {
3344   MatFactorInfo tinfo;
3345 
3346   PetscFunctionBegin;
3347   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
3348   if (perm) PetscValidHeaderSpecific(perm, IS_CLASSID, 2);
3349   if (info) PetscAssertPointer(info, 3);
3350   PetscValidType(mat, 1);
3351   PetscCheck(mat->rmap->N == mat->cmap->N, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONG, "Matrix must be square");
3352   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
3353   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
3354   MatCheckPreallocated(mat, 1);
3355   if (!info) {
3356     PetscCall(MatFactorInfoInitialize(&tinfo));
3357     info = &tinfo;
3358   }
3359 
3360   PetscCall(PetscLogEventBegin(MAT_CholeskyFactor, mat, perm, 0, 0));
3361   PetscUseTypeMethod(mat, choleskyfactor, perm, info);
3362   PetscCall(PetscLogEventEnd(MAT_CholeskyFactor, mat, perm, 0, 0));
3363   PetscCall(PetscObjectStateIncrease((PetscObject)mat));
3364   PetscFunctionReturn(PETSC_SUCCESS);
3365 }
3366 
3367 /*@
3368   MatCholeskyFactorSymbolic - Performs symbolic Cholesky factorization
3369   of a symmetric matrix.
3370 
3371   Collective
3372 
3373   Input Parameters:
3374 + fact - the factor matrix obtained with `MatGetFactor()`
3375 . mat  - the matrix
3376 . perm - row and column permutations
3377 - info - options for factorization, includes
3378 .vb
3379           fill - expected fill as ratio of original fill.
3380           dtcol - pivot tolerance (0 no pivot, 1 full column pivoting)
3381                    Run with the option -info to determine an optimal value to use
3382 .ve
3383 
3384   Level: developer
3385 
3386   Notes:
3387   See `MatLUFactorSymbolic()` for the nonsymmetric case.  See also
3388   `MatCholeskyFactor()` and `MatCholeskyFactorNumeric()`.
3389 
3390   Most users should employ the `KSP` interface for linear solvers
3391   instead of working directly with matrix algebra routines such as this.
3392   See, e.g., `KSPCreate()`.
3393 
3394   Developer Note:
3395   The Fortran interface is not autogenerated as the
3396   interface definition cannot be generated correctly [due to `MatFactorInfo`]
3397 
3398 .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatFactorInfo`, `MatGetFactor()`, `MatLUFactorSymbolic()`, `MatCholeskyFactor()`, `MatCholeskyFactorNumeric()`
3399           `MatGetOrdering()`
3400 @*/
3401 PetscErrorCode MatCholeskyFactorSymbolic(Mat fact, Mat mat, IS perm, const MatFactorInfo *info)
3402 {
3403   MatFactorInfo tinfo;
3404 
3405   PetscFunctionBegin;
3406   PetscValidHeaderSpecific(fact, MAT_CLASSID, 1);
3407   PetscValidHeaderSpecific(mat, MAT_CLASSID, 2);
3408   if (perm) PetscValidHeaderSpecific(perm, IS_CLASSID, 3);
3409   if (info) PetscAssertPointer(info, 4);
3410   PetscValidType(fact, 1);
3411   PetscValidType(mat, 2);
3412   PetscCheck(mat->rmap->N == mat->cmap->N, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONG, "Matrix must be square");
3413   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
3414   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
3415   MatCheckPreallocated(mat, 2);
3416   if (!info) {
3417     PetscCall(MatFactorInfoInitialize(&tinfo));
3418     info = &tinfo;
3419   }
3420 
3421   if (!fact->trivialsymbolic) PetscCall(PetscLogEventBegin(MAT_CholeskyFactorSymbolic, mat, perm, 0, 0));
3422   PetscUseTypeMethod(fact, choleskyfactorsymbolic, mat, perm, info);
3423   if (!fact->trivialsymbolic) PetscCall(PetscLogEventEnd(MAT_CholeskyFactorSymbolic, mat, perm, 0, 0));
3424   PetscCall(PetscObjectStateIncrease((PetscObject)fact));
3425   PetscFunctionReturn(PETSC_SUCCESS);
3426 }
3427 
3428 /*@
3429   MatCholeskyFactorNumeric - Performs numeric Cholesky factorization
3430   of a symmetric matrix. Call this routine after first calling `MatGetFactor()` and
3431   `MatCholeskyFactorSymbolic()`.
3432 
3433   Collective
3434 
3435   Input Parameters:
3436 + fact - the factor matrix obtained with `MatGetFactor()`, where the factored values are stored
3437 . mat  - the initial matrix that is to be factored
3438 - info - options for factorization
3439 
3440   Level: developer
3441 
3442   Note:
3443   Most users should employ the `KSP` interface for linear solvers
3444   instead of working directly with matrix algebra routines such as this.
3445   See, e.g., `KSPCreate()`.
3446 
3447   Developer Note:
3448   The Fortran interface is not autogenerated as the
3449   interface definition cannot be generated correctly [due to `MatFactorInfo`]
3450 
3451 .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatFactorInfo`, `MatGetFactor()`, `MatCholeskyFactorSymbolic()`, `MatCholeskyFactor()`, `MatLUFactorNumeric()`
3452 @*/
3453 PetscErrorCode MatCholeskyFactorNumeric(Mat fact, Mat mat, const MatFactorInfo *info)
3454 {
3455   MatFactorInfo tinfo;
3456 
3457   PetscFunctionBegin;
3458   PetscValidHeaderSpecific(fact, MAT_CLASSID, 1);
3459   PetscValidHeaderSpecific(mat, MAT_CLASSID, 2);
3460   PetscValidType(fact, 1);
3461   PetscValidType(mat, 2);
3462   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
3463   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,
3464              mat->rmap->N, (fact)->rmap->N, mat->cmap->N, (fact)->cmap->N);
3465   MatCheckPreallocated(mat, 2);
3466   if (!info) {
3467     PetscCall(MatFactorInfoInitialize(&tinfo));
3468     info = &tinfo;
3469   }
3470 
3471   if (!fact->trivialsymbolic) PetscCall(PetscLogEventBegin(MAT_CholeskyFactorNumeric, mat, fact, 0, 0));
3472   else PetscCall(PetscLogEventBegin(MAT_CholeskyFactor, mat, fact, 0, 0));
3473   PetscUseTypeMethod(fact, choleskyfactornumeric, mat, info);
3474   if (!fact->trivialsymbolic) PetscCall(PetscLogEventEnd(MAT_CholeskyFactorNumeric, mat, fact, 0, 0));
3475   else PetscCall(PetscLogEventEnd(MAT_CholeskyFactor, mat, fact, 0, 0));
3476   PetscCall(MatViewFromOptions(fact, NULL, "-mat_factor_view"));
3477   PetscCall(PetscObjectStateIncrease((PetscObject)fact));
3478   PetscFunctionReturn(PETSC_SUCCESS);
3479 }
3480 
3481 /*@
3482   MatQRFactor - Performs in-place QR factorization of matrix.
3483 
3484   Collective
3485 
3486   Input Parameters:
3487 + mat  - the matrix
3488 . col  - column permutation
3489 - info - options for factorization, includes
3490 .vb
3491           fill - expected fill as ratio of original fill.
3492           dtcol - pivot tolerance (0 no pivot, 1 full column pivoting)
3493                    Run with the option -info to determine an optimal value to use
3494 .ve
3495 
3496   Level: developer
3497 
3498   Notes:
3499   Most users should employ the `KSP` interface for linear solvers
3500   instead of working directly with matrix algebra routines such as this.
3501   See, e.g., `KSPCreate()`.
3502 
3503   This changes the state of the matrix to a factored matrix; it cannot be used
3504   for example with `MatSetValues()` unless one first calls `MatSetUnfactored()`.
3505 
3506   Developer Note:
3507   The Fortran interface is not autogenerated as the
3508   interface definition cannot be generated correctly [due to MatFactorInfo]
3509 
3510 .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatFactorInfo`, `MatGetFactor()`, `MatQRFactorSymbolic()`, `MatQRFactorNumeric()`, `MatLUFactor()`,
3511           `MatSetUnfactored()`
3512 @*/
3513 PetscErrorCode MatQRFactor(Mat mat, IS col, const MatFactorInfo *info)
3514 {
3515   PetscFunctionBegin;
3516   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
3517   if (col) PetscValidHeaderSpecific(col, IS_CLASSID, 2);
3518   if (info) PetscAssertPointer(info, 3);
3519   PetscValidType(mat, 1);
3520   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
3521   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
3522   MatCheckPreallocated(mat, 1);
3523   PetscCall(PetscLogEventBegin(MAT_QRFactor, mat, col, 0, 0));
3524   PetscUseMethod(mat, "MatQRFactor_C", (Mat, IS, const MatFactorInfo *), (mat, col, info));
3525   PetscCall(PetscLogEventEnd(MAT_QRFactor, mat, col, 0, 0));
3526   PetscCall(PetscObjectStateIncrease((PetscObject)mat));
3527   PetscFunctionReturn(PETSC_SUCCESS);
3528 }
3529 
3530 /*@
3531   MatQRFactorSymbolic - Performs symbolic QR factorization of matrix.
3532   Call this routine after `MatGetFactor()` but before calling `MatQRFactorNumeric()`.
3533 
3534   Collective
3535 
3536   Input Parameters:
3537 + fact - the factor matrix obtained with `MatGetFactor()`
3538 . mat  - the matrix
3539 . col  - column permutation
3540 - info - options for factorization, includes
3541 .vb
3542           fill - expected fill as ratio of original fill.
3543           dtcol - pivot tolerance (0 no pivot, 1 full column pivoting)
3544                    Run with the option -info to determine an optimal value to use
3545 .ve
3546 
3547   Level: developer
3548 
3549   Note:
3550   Most users should employ the `KSP` interface for linear solvers
3551   instead of working directly with matrix algebra routines such as this.
3552   See, e.g., `KSPCreate()`.
3553 
3554   Developer Note:
3555   The Fortran interface is not autogenerated as the
3556   interface definition cannot be generated correctly [due to `MatFactorInfo`]
3557 
3558 .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatGetFactor()`, `MatFactorInfo`, `MatQRFactor()`, `MatQRFactorNumeric()`, `MatLUFactor()`, `MatFactorInfoInitialize()`
3559 @*/
3560 PetscErrorCode MatQRFactorSymbolic(Mat fact, Mat mat, IS col, const MatFactorInfo *info)
3561 {
3562   MatFactorInfo tinfo;
3563 
3564   PetscFunctionBegin;
3565   PetscValidHeaderSpecific(fact, MAT_CLASSID, 1);
3566   PetscValidHeaderSpecific(mat, MAT_CLASSID, 2);
3567   if (col) PetscValidHeaderSpecific(col, IS_CLASSID, 3);
3568   if (info) PetscAssertPointer(info, 4);
3569   PetscValidType(fact, 1);
3570   PetscValidType(mat, 2);
3571   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
3572   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
3573   MatCheckPreallocated(mat, 2);
3574   if (!info) {
3575     PetscCall(MatFactorInfoInitialize(&tinfo));
3576     info = &tinfo;
3577   }
3578 
3579   if (!fact->trivialsymbolic) PetscCall(PetscLogEventBegin(MAT_QRFactorSymbolic, fact, mat, col, 0));
3580   PetscUseMethod(fact, "MatQRFactorSymbolic_C", (Mat, Mat, IS, const MatFactorInfo *), (fact, mat, col, info));
3581   if (!fact->trivialsymbolic) PetscCall(PetscLogEventEnd(MAT_QRFactorSymbolic, fact, mat, col, 0));
3582   PetscCall(PetscObjectStateIncrease((PetscObject)fact));
3583   PetscFunctionReturn(PETSC_SUCCESS);
3584 }
3585 
3586 /*@
3587   MatQRFactorNumeric - Performs numeric QR factorization of a matrix.
3588   Call this routine after first calling `MatGetFactor()`, and `MatQRFactorSymbolic()`.
3589 
3590   Collective
3591 
3592   Input Parameters:
3593 + fact - the factor matrix obtained with `MatGetFactor()`
3594 . mat  - the matrix
3595 - info - options for factorization
3596 
3597   Level: developer
3598 
3599   Notes:
3600   See `MatQRFactor()` for in-place factorization.
3601 
3602   Most users should employ the `KSP` interface for linear solvers
3603   instead of working directly with matrix algebra routines such as this.
3604   See, e.g., `KSPCreate()`.
3605 
3606   Developer Note:
3607   The Fortran interface is not autogenerated as the
3608   interface definition cannot be generated correctly [due to `MatFactorInfo`]
3609 
3610 .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatFactorInfo`, `MatGetFactor()`, `MatQRFactor()`, `MatQRFactorSymbolic()`, `MatLUFactor()`
3611 @*/
3612 PetscErrorCode MatQRFactorNumeric(Mat fact, Mat mat, const MatFactorInfo *info)
3613 {
3614   MatFactorInfo tinfo;
3615 
3616   PetscFunctionBegin;
3617   PetscValidHeaderSpecific(fact, MAT_CLASSID, 1);
3618   PetscValidHeaderSpecific(mat, MAT_CLASSID, 2);
3619   PetscValidType(fact, 1);
3620   PetscValidType(mat, 2);
3621   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
3622   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,
3623              mat->rmap->N, (fact)->rmap->N, mat->cmap->N, (fact)->cmap->N);
3624 
3625   MatCheckPreallocated(mat, 2);
3626   if (!info) {
3627     PetscCall(MatFactorInfoInitialize(&tinfo));
3628     info = &tinfo;
3629   }
3630 
3631   if (!fact->trivialsymbolic) PetscCall(PetscLogEventBegin(MAT_QRFactorNumeric, mat, fact, 0, 0));
3632   else PetscCall(PetscLogEventBegin(MAT_QRFactor, mat, fact, 0, 0));
3633   PetscUseMethod(fact, "MatQRFactorNumeric_C", (Mat, Mat, const MatFactorInfo *), (fact, mat, info));
3634   if (!fact->trivialsymbolic) PetscCall(PetscLogEventEnd(MAT_QRFactorNumeric, mat, fact, 0, 0));
3635   else PetscCall(PetscLogEventEnd(MAT_QRFactor, mat, fact, 0, 0));
3636   PetscCall(MatViewFromOptions(fact, NULL, "-mat_factor_view"));
3637   PetscCall(PetscObjectStateIncrease((PetscObject)fact));
3638   PetscFunctionReturn(PETSC_SUCCESS);
3639 }
3640 
3641 /*@
3642   MatSolve - Solves $A x = b$, given a factored matrix.
3643 
3644   Neighbor-wise Collective
3645 
3646   Input Parameters:
3647 + mat - the factored matrix
3648 - b   - the right-hand-side vector
3649 
3650   Output Parameter:
3651 . x - the result vector
3652 
3653   Level: developer
3654 
3655   Notes:
3656   The vectors `b` and `x` cannot be the same.  I.e., one cannot
3657   call `MatSolve`(A,x,x).
3658 
3659   Most users should employ the `KSP` interface for linear solvers
3660   instead of working directly with matrix algebra routines such as this.
3661   See, e.g., `KSPCreate()`.
3662 
3663 .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatGetFactor()`, `MatLUFactor()`, `MatSolveAdd()`, `MatSolveTranspose()`, `MatSolveTransposeAdd()`
3664 @*/
3665 PetscErrorCode MatSolve(Mat mat, Vec b, Vec x)
3666 {
3667   PetscFunctionBegin;
3668   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
3669   PetscValidType(mat, 1);
3670   PetscValidHeaderSpecific(b, VEC_CLASSID, 2);
3671   PetscValidHeaderSpecific(x, VEC_CLASSID, 3);
3672   PetscCheckSameComm(mat, 1, b, 2);
3673   PetscCheckSameComm(mat, 1, x, 3);
3674   PetscCheck(x != b, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_IDN, "x and b must be different vectors");
3675   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);
3676   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);
3677   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);
3678   if (!mat->rmap->N && !mat->cmap->N) PetscFunctionReturn(PETSC_SUCCESS);
3679   MatCheckPreallocated(mat, 1);
3680 
3681   PetscCall(PetscLogEventBegin(MAT_Solve, mat, b, x, 0));
3682   if (mat->factorerrortype) {
3683     PetscCall(PetscInfo(mat, "MatFactorError %d\n", mat->factorerrortype));
3684     PetscCall(VecSetInf(x));
3685   } else PetscUseTypeMethod(mat, solve, b, x);
3686   PetscCall(PetscLogEventEnd(MAT_Solve, mat, b, x, 0));
3687   PetscCall(PetscObjectStateIncrease((PetscObject)x));
3688   PetscFunctionReturn(PETSC_SUCCESS);
3689 }
3690 
3691 static PetscErrorCode MatMatSolve_Basic(Mat A, Mat B, Mat X, PetscBool trans)
3692 {
3693   Vec      b, x;
3694   PetscInt N, i;
3695   PetscErrorCode (*f)(Mat, Vec, Vec);
3696   PetscBool Abound, Bneedconv = PETSC_FALSE, Xneedconv = PETSC_FALSE;
3697 
3698   PetscFunctionBegin;
3699   if (A->factorerrortype) {
3700     PetscCall(PetscInfo(A, "MatFactorError %d\n", A->factorerrortype));
3701     PetscCall(MatSetInf(X));
3702     PetscFunctionReturn(PETSC_SUCCESS);
3703   }
3704   f = (!trans || (!A->ops->solvetranspose && A->symmetric)) ? A->ops->solve : A->ops->solvetranspose;
3705   PetscCheck(f, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "Mat type %s", ((PetscObject)A)->type_name);
3706   PetscCall(MatBoundToCPU(A, &Abound));
3707   if (!Abound) {
3708     PetscCall(PetscObjectTypeCompareAny((PetscObject)B, &Bneedconv, MATSEQDENSE, MATMPIDENSE, ""));
3709     PetscCall(PetscObjectTypeCompareAny((PetscObject)X, &Xneedconv, MATSEQDENSE, MATMPIDENSE, ""));
3710   }
3711 #if PetscDefined(HAVE_CUDA)
3712   if (Bneedconv) PetscCall(MatConvert(B, MATDENSECUDA, MAT_INPLACE_MATRIX, &B));
3713   if (Xneedconv) PetscCall(MatConvert(X, MATDENSECUDA, MAT_INPLACE_MATRIX, &X));
3714 #elif PetscDefined(HAVE_HIP)
3715   if (Bneedconv) PetscCall(MatConvert(B, MATDENSEHIP, MAT_INPLACE_MATRIX, &B));
3716   if (Xneedconv) PetscCall(MatConvert(X, MATDENSEHIP, MAT_INPLACE_MATRIX, &X));
3717 #endif
3718   PetscCall(MatGetSize(B, NULL, &N));
3719   for (i = 0; i < N; i++) {
3720     PetscCall(MatDenseGetColumnVecRead(B, i, &b));
3721     PetscCall(MatDenseGetColumnVecWrite(X, i, &x));
3722     PetscCall((*f)(A, b, x));
3723     PetscCall(MatDenseRestoreColumnVecWrite(X, i, &x));
3724     PetscCall(MatDenseRestoreColumnVecRead(B, i, &b));
3725   }
3726   if (Bneedconv) PetscCall(MatConvert(B, MATDENSE, MAT_INPLACE_MATRIX, &B));
3727   if (Xneedconv) PetscCall(MatConvert(X, MATDENSE, MAT_INPLACE_MATRIX, &X));
3728   PetscFunctionReturn(PETSC_SUCCESS);
3729 }
3730 
3731 /*@
3732   MatMatSolve - Solves $A X = B$, given a factored matrix.
3733 
3734   Neighbor-wise Collective
3735 
3736   Input Parameters:
3737 + A - the factored matrix
3738 - B - the right-hand-side matrix `MATDENSE` (or sparse `MATAIJ`-- when using MUMPS)
3739 
3740   Output Parameter:
3741 . X - the result matrix (dense matrix)
3742 
3743   Level: developer
3744 
3745   Note:
3746   If `B` is a `MATDENSE` matrix then one can call `MatMatSolve`(A,B,B) except with `MATSOLVERMKL_CPARDISO`;
3747   otherwise, `B` and `X` cannot be the same.
3748 
3749 .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatGetFactor()`, `MatSolve()`, `MatMatSolveTranspose()`, `MatLUFactor()`, `MatCholeskyFactor()`
3750 @*/
3751 PetscErrorCode MatMatSolve(Mat A, Mat B, Mat X)
3752 {
3753   PetscFunctionBegin;
3754   PetscValidHeaderSpecific(A, MAT_CLASSID, 1);
3755   PetscValidType(A, 1);
3756   PetscValidHeaderSpecific(B, MAT_CLASSID, 2);
3757   PetscValidHeaderSpecific(X, MAT_CLASSID, 3);
3758   PetscCheckSameComm(A, 1, B, 2);
3759   PetscCheckSameComm(A, 1, X, 3);
3760   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);
3761   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);
3762   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");
3763   if (!A->rmap->N && !A->cmap->N) PetscFunctionReturn(PETSC_SUCCESS);
3764   MatCheckPreallocated(A, 1);
3765 
3766   PetscCall(PetscLogEventBegin(MAT_MatSolve, A, B, X, 0));
3767   if (!A->ops->matsolve) {
3768     PetscCall(PetscInfo(A, "Mat type %s using basic MatMatSolve\n", ((PetscObject)A)->type_name));
3769     PetscCall(MatMatSolve_Basic(A, B, X, PETSC_FALSE));
3770   } else PetscUseTypeMethod(A, matsolve, B, X);
3771   PetscCall(PetscLogEventEnd(MAT_MatSolve, A, B, X, 0));
3772   PetscCall(PetscObjectStateIncrease((PetscObject)X));
3773   PetscFunctionReturn(PETSC_SUCCESS);
3774 }
3775 
3776 /*@
3777   MatMatSolveTranspose - Solves $A^T X = B $, given a factored matrix.
3778 
3779   Neighbor-wise Collective
3780 
3781   Input Parameters:
3782 + A - the factored matrix
3783 - B - the right-hand-side matrix  (`MATDENSE` matrix)
3784 
3785   Output Parameter:
3786 . X - the result matrix (dense matrix)
3787 
3788   Level: developer
3789 
3790   Note:
3791   The matrices `B` and `X` cannot be the same.  I.e., one cannot
3792   call `MatMatSolveTranspose`(A,X,X).
3793 
3794 .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatGetFactor()`, `MatSolveTranspose()`, `MatMatSolve()`, `MatLUFactor()`, `MatCholeskyFactor()`
3795 @*/
3796 PetscErrorCode MatMatSolveTranspose(Mat A, Mat B, Mat X)
3797 {
3798   PetscFunctionBegin;
3799   PetscValidHeaderSpecific(A, MAT_CLASSID, 1);
3800   PetscValidType(A, 1);
3801   PetscValidHeaderSpecific(B, MAT_CLASSID, 2);
3802   PetscValidHeaderSpecific(X, MAT_CLASSID, 3);
3803   PetscCheckSameComm(A, 1, B, 2);
3804   PetscCheckSameComm(A, 1, X, 3);
3805   PetscCheck(X != B, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_IDN, "X and B must be different matrices");
3806   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);
3807   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);
3808   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);
3809   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");
3810   if (!A->rmap->N && !A->cmap->N) PetscFunctionReturn(PETSC_SUCCESS);
3811   MatCheckPreallocated(A, 1);
3812 
3813   PetscCall(PetscLogEventBegin(MAT_MatSolve, A, B, X, 0));
3814   if (!A->ops->matsolvetranspose) {
3815     PetscCall(PetscInfo(A, "Mat type %s using basic MatMatSolveTranspose\n", ((PetscObject)A)->type_name));
3816     PetscCall(MatMatSolve_Basic(A, B, X, PETSC_TRUE));
3817   } else PetscUseTypeMethod(A, matsolvetranspose, B, X);
3818   PetscCall(PetscLogEventEnd(MAT_MatSolve, A, B, X, 0));
3819   PetscCall(PetscObjectStateIncrease((PetscObject)X));
3820   PetscFunctionReturn(PETSC_SUCCESS);
3821 }
3822 
3823 /*@
3824   MatMatTransposeSolve - Solves $A X = B^T$, given a factored matrix.
3825 
3826   Neighbor-wise Collective
3827 
3828   Input Parameters:
3829 + A  - the factored matrix
3830 - Bt - the transpose of right-hand-side matrix as a `MATDENSE`
3831 
3832   Output Parameter:
3833 . X - the result matrix (dense matrix)
3834 
3835   Level: developer
3836 
3837   Note:
3838   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
3839   format on the host processor and call `MatMatTransposeSolve()` to implement MUMPS' `MatMatSolve()`.
3840 
3841 .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatMatSolve()`, `MatMatSolveTranspose()`, `MatLUFactor()`, `MatCholeskyFactor()`
3842 @*/
3843 PetscErrorCode MatMatTransposeSolve(Mat A, Mat Bt, Mat X)
3844 {
3845   PetscFunctionBegin;
3846   PetscValidHeaderSpecific(A, MAT_CLASSID, 1);
3847   PetscValidType(A, 1);
3848   PetscValidHeaderSpecific(Bt, MAT_CLASSID, 2);
3849   PetscValidHeaderSpecific(X, MAT_CLASSID, 3);
3850   PetscCheckSameComm(A, 1, Bt, 2);
3851   PetscCheckSameComm(A, 1, X, 3);
3852 
3853   PetscCheck(X != Bt, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_IDN, "X and B must be different matrices");
3854   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);
3855   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);
3856   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");
3857   if (!A->rmap->N && !A->cmap->N) PetscFunctionReturn(PETSC_SUCCESS);
3858   PetscCheck(A->factortype, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_WRONGSTATE, "Unfactored matrix");
3859   MatCheckPreallocated(A, 1);
3860 
3861   PetscCall(PetscLogEventBegin(MAT_MatTrSolve, A, Bt, X, 0));
3862   PetscUseTypeMethod(A, mattransposesolve, Bt, X);
3863   PetscCall(PetscLogEventEnd(MAT_MatTrSolve, A, Bt, X, 0));
3864   PetscCall(PetscObjectStateIncrease((PetscObject)X));
3865   PetscFunctionReturn(PETSC_SUCCESS);
3866 }
3867 
3868 /*@
3869   MatForwardSolve - Solves $ L x = b $, given a factored matrix, $A = LU $, or
3870   $U^T*D^(1/2) x = b$, given a factored symmetric matrix, $A = U^T*D*U$,
3871 
3872   Neighbor-wise Collective
3873 
3874   Input Parameters:
3875 + mat - the factored matrix
3876 - b   - the right-hand-side vector
3877 
3878   Output Parameter:
3879 . x - the result vector
3880 
3881   Level: developer
3882 
3883   Notes:
3884   `MatSolve()` should be used for most applications, as it performs
3885   a forward solve followed by a backward solve.
3886 
3887   The vectors `b` and `x` cannot be the same,  i.e., one cannot
3888   call `MatForwardSolve`(A,x,x).
3889 
3890   For matrix in `MATSEQBAIJ` format with block size larger than 1,
3891   the diagonal blocks are not implemented as $D = D^(1/2) * D^(1/2)$ yet.
3892   `MatForwardSolve()` solves $U^T*D y = b$, and
3893   `MatBackwardSolve()` solves $U x = y$.
3894   Thus they do not provide a symmetric preconditioner.
3895 
3896 .seealso: [](ch_matrices), `Mat`, `MatBackwardSolve()`, `MatGetFactor()`, `MatSolve()`
3897 @*/
3898 PetscErrorCode MatForwardSolve(Mat mat, Vec b, Vec x)
3899 {
3900   PetscFunctionBegin;
3901   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
3902   PetscValidType(mat, 1);
3903   PetscValidHeaderSpecific(b, VEC_CLASSID, 2);
3904   PetscValidHeaderSpecific(x, VEC_CLASSID, 3);
3905   PetscCheckSameComm(mat, 1, b, 2);
3906   PetscCheckSameComm(mat, 1, x, 3);
3907   PetscCheck(x != b, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_IDN, "x and b must be different vectors");
3908   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);
3909   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);
3910   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);
3911   if (!mat->rmap->N && !mat->cmap->N) PetscFunctionReturn(PETSC_SUCCESS);
3912   MatCheckPreallocated(mat, 1);
3913 
3914   PetscCall(PetscLogEventBegin(MAT_ForwardSolve, mat, b, x, 0));
3915   PetscUseTypeMethod(mat, forwardsolve, b, x);
3916   PetscCall(PetscLogEventEnd(MAT_ForwardSolve, mat, b, x, 0));
3917   PetscCall(PetscObjectStateIncrease((PetscObject)x));
3918   PetscFunctionReturn(PETSC_SUCCESS);
3919 }
3920 
3921 /*@
3922   MatBackwardSolve - Solves $U x = b$, given a factored matrix, $A = LU$.
3923   $D^(1/2) U x = b$, given a factored symmetric matrix, $A = U^T*D*U$,
3924 
3925   Neighbor-wise Collective
3926 
3927   Input Parameters:
3928 + mat - the factored matrix
3929 - b   - the right-hand-side vector
3930 
3931   Output Parameter:
3932 . x - the result vector
3933 
3934   Level: developer
3935 
3936   Notes:
3937   `MatSolve()` should be used for most applications, as it performs
3938   a forward solve followed by a backward solve.
3939 
3940   The vectors `b` and `x` cannot be the same.  I.e., one cannot
3941   call `MatBackwardSolve`(A,x,x).
3942 
3943   For matrix in `MATSEQBAIJ` format with block size larger than 1,
3944   the diagonal blocks are not implemented as $D = D^(1/2) * D^(1/2)$ yet.
3945   `MatForwardSolve()` solves $U^T*D y = b$, and
3946   `MatBackwardSolve()` solves $U x = y$.
3947   Thus they do not provide a symmetric preconditioner.
3948 
3949 .seealso: [](ch_matrices), `Mat`, `MatForwardSolve()`, `MatGetFactor()`, `MatSolve()`
3950 @*/
3951 PetscErrorCode MatBackwardSolve(Mat mat, Vec b, Vec x)
3952 {
3953   PetscFunctionBegin;
3954   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
3955   PetscValidType(mat, 1);
3956   PetscValidHeaderSpecific(b, VEC_CLASSID, 2);
3957   PetscValidHeaderSpecific(x, VEC_CLASSID, 3);
3958   PetscCheckSameComm(mat, 1, b, 2);
3959   PetscCheckSameComm(mat, 1, x, 3);
3960   PetscCheck(x != b, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_IDN, "x and b must be different vectors");
3961   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);
3962   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);
3963   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);
3964   if (!mat->rmap->N && !mat->cmap->N) PetscFunctionReturn(PETSC_SUCCESS);
3965   MatCheckPreallocated(mat, 1);
3966 
3967   PetscCall(PetscLogEventBegin(MAT_BackwardSolve, mat, b, x, 0));
3968   PetscUseTypeMethod(mat, backwardsolve, b, x);
3969   PetscCall(PetscLogEventEnd(MAT_BackwardSolve, mat, b, x, 0));
3970   PetscCall(PetscObjectStateIncrease((PetscObject)x));
3971   PetscFunctionReturn(PETSC_SUCCESS);
3972 }
3973 
3974 /*@
3975   MatSolveAdd - Computes $x = y + A^{-1}*b$, given a factored matrix.
3976 
3977   Neighbor-wise Collective
3978 
3979   Input Parameters:
3980 + mat - the factored matrix
3981 . b   - the right-hand-side vector
3982 - y   - the vector to be added to
3983 
3984   Output Parameter:
3985 . x - the result vector
3986 
3987   Level: developer
3988 
3989   Note:
3990   The vectors `b` and `x` cannot be the same.  I.e., one cannot
3991   call `MatSolveAdd`(A,x,y,x).
3992 
3993 .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatSolve()`, `MatGetFactor()`, `MatSolveTranspose()`, `MatSolveTransposeAdd()`
3994 @*/
3995 PetscErrorCode MatSolveAdd(Mat mat, Vec b, Vec y, Vec x)
3996 {
3997   PetscScalar one = 1.0;
3998   Vec         tmp;
3999 
4000   PetscFunctionBegin;
4001   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
4002   PetscValidType(mat, 1);
4003   PetscValidHeaderSpecific(y, VEC_CLASSID, 3);
4004   PetscValidHeaderSpecific(b, VEC_CLASSID, 2);
4005   PetscValidHeaderSpecific(x, VEC_CLASSID, 4);
4006   PetscCheckSameComm(mat, 1, b, 2);
4007   PetscCheckSameComm(mat, 1, y, 3);
4008   PetscCheckSameComm(mat, 1, x, 4);
4009   PetscCheck(x != b, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_IDN, "x and b must be different vectors");
4010   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);
4011   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);
4012   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);
4013   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);
4014   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);
4015   if (!mat->rmap->N && !mat->cmap->N) PetscFunctionReturn(PETSC_SUCCESS);
4016   MatCheckPreallocated(mat, 1);
4017 
4018   PetscCall(PetscLogEventBegin(MAT_SolveAdd, mat, b, x, y));
4019   if (mat->factorerrortype) {
4020     PetscCall(PetscInfo(mat, "MatFactorError %d\n", mat->factorerrortype));
4021     PetscCall(VecSetInf(x));
4022   } else if (mat->ops->solveadd) {
4023     PetscUseTypeMethod(mat, solveadd, b, y, x);
4024   } else {
4025     /* do the solve then the add manually */
4026     if (x != y) {
4027       PetscCall(MatSolve(mat, b, x));
4028       PetscCall(VecAXPY(x, one, y));
4029     } else {
4030       PetscCall(VecDuplicate(x, &tmp));
4031       PetscCall(VecCopy(x, tmp));
4032       PetscCall(MatSolve(mat, b, x));
4033       PetscCall(VecAXPY(x, one, tmp));
4034       PetscCall(VecDestroy(&tmp));
4035     }
4036   }
4037   PetscCall(PetscLogEventEnd(MAT_SolveAdd, mat, b, x, y));
4038   PetscCall(PetscObjectStateIncrease((PetscObject)x));
4039   PetscFunctionReturn(PETSC_SUCCESS);
4040 }
4041 
4042 /*@
4043   MatSolveTranspose - Solves $A^T x = b$, given a factored matrix.
4044 
4045   Neighbor-wise Collective
4046 
4047   Input Parameters:
4048 + mat - the factored matrix
4049 - b   - the right-hand-side vector
4050 
4051   Output Parameter:
4052 . x - the result vector
4053 
4054   Level: developer
4055 
4056   Notes:
4057   The vectors `b` and `x` cannot be the same.  I.e., one cannot
4058   call `MatSolveTranspose`(A,x,x).
4059 
4060   Most users should employ the `KSP` interface for linear solvers
4061   instead of working directly with matrix algebra routines such as this.
4062   See, e.g., `KSPCreate()`.
4063 
4064 .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `KSP`, `MatSolve()`, `MatSolveAdd()`, `MatSolveTransposeAdd()`
4065 @*/
4066 PetscErrorCode MatSolveTranspose(Mat mat, Vec b, Vec x)
4067 {
4068   PetscErrorCode (*f)(Mat, Vec, Vec) = (!mat->ops->solvetranspose && mat->symmetric) ? mat->ops->solve : mat->ops->solvetranspose;
4069 
4070   PetscFunctionBegin;
4071   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
4072   PetscValidType(mat, 1);
4073   PetscValidHeaderSpecific(b, VEC_CLASSID, 2);
4074   PetscValidHeaderSpecific(x, VEC_CLASSID, 3);
4075   PetscCheckSameComm(mat, 1, b, 2);
4076   PetscCheckSameComm(mat, 1, x, 3);
4077   PetscCheck(x != b, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_IDN, "x and b must be different vectors");
4078   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);
4079   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);
4080   if (!mat->rmap->N && !mat->cmap->N) PetscFunctionReturn(PETSC_SUCCESS);
4081   MatCheckPreallocated(mat, 1);
4082   PetscCall(PetscLogEventBegin(MAT_SolveTranspose, mat, b, x, 0));
4083   if (mat->factorerrortype) {
4084     PetscCall(PetscInfo(mat, "MatFactorError %d\n", mat->factorerrortype));
4085     PetscCall(VecSetInf(x));
4086   } else {
4087     PetscCheck(f, PetscObjectComm((PetscObject)mat), PETSC_ERR_SUP, "Matrix type %s", ((PetscObject)mat)->type_name);
4088     PetscCall((*f)(mat, b, x));
4089   }
4090   PetscCall(PetscLogEventEnd(MAT_SolveTranspose, mat, b, x, 0));
4091   PetscCall(PetscObjectStateIncrease((PetscObject)x));
4092   PetscFunctionReturn(PETSC_SUCCESS);
4093 }
4094 
4095 /*@
4096   MatSolveTransposeAdd - Computes $x = y + A^{-T} b$
4097   factored matrix.
4098 
4099   Neighbor-wise Collective
4100 
4101   Input Parameters:
4102 + mat - the factored matrix
4103 . b   - the right-hand-side vector
4104 - y   - the vector to be added to
4105 
4106   Output Parameter:
4107 . x - the result vector
4108 
4109   Level: developer
4110 
4111   Note:
4112   The vectors `b` and `x` cannot be the same.  I.e., one cannot
4113   call `MatSolveTransposeAdd`(A,x,y,x).
4114 
4115 .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatSolve()`, `MatSolveAdd()`, `MatSolveTranspose()`
4116 @*/
4117 PetscErrorCode MatSolveTransposeAdd(Mat mat, Vec b, Vec y, Vec x)
4118 {
4119   PetscScalar one = 1.0;
4120   Vec         tmp;
4121   PetscErrorCode (*f)(Mat, Vec, Vec, Vec) = (!mat->ops->solvetransposeadd && mat->symmetric) ? mat->ops->solveadd : mat->ops->solvetransposeadd;
4122 
4123   PetscFunctionBegin;
4124   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
4125   PetscValidType(mat, 1);
4126   PetscValidHeaderSpecific(y, VEC_CLASSID, 3);
4127   PetscValidHeaderSpecific(b, VEC_CLASSID, 2);
4128   PetscValidHeaderSpecific(x, VEC_CLASSID, 4);
4129   PetscCheckSameComm(mat, 1, b, 2);
4130   PetscCheckSameComm(mat, 1, y, 3);
4131   PetscCheckSameComm(mat, 1, x, 4);
4132   PetscCheck(x != b, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_IDN, "x and b must be different vectors");
4133   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);
4134   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);
4135   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);
4136   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);
4137   if (!mat->rmap->N && !mat->cmap->N) PetscFunctionReturn(PETSC_SUCCESS);
4138   MatCheckPreallocated(mat, 1);
4139 
4140   PetscCall(PetscLogEventBegin(MAT_SolveTransposeAdd, mat, b, x, y));
4141   if (mat->factorerrortype) {
4142     PetscCall(PetscInfo(mat, "MatFactorError %d\n", mat->factorerrortype));
4143     PetscCall(VecSetInf(x));
4144   } else if (f) {
4145     PetscCall((*f)(mat, b, y, x));
4146   } else {
4147     /* do the solve then the add manually */
4148     if (x != y) {
4149       PetscCall(MatSolveTranspose(mat, b, x));
4150       PetscCall(VecAXPY(x, one, y));
4151     } else {
4152       PetscCall(VecDuplicate(x, &tmp));
4153       PetscCall(VecCopy(x, tmp));
4154       PetscCall(MatSolveTranspose(mat, b, x));
4155       PetscCall(VecAXPY(x, one, tmp));
4156       PetscCall(VecDestroy(&tmp));
4157     }
4158   }
4159   PetscCall(PetscLogEventEnd(MAT_SolveTransposeAdd, mat, b, x, y));
4160   PetscCall(PetscObjectStateIncrease((PetscObject)x));
4161   PetscFunctionReturn(PETSC_SUCCESS);
4162 }
4163 
4164 // PetscClangLinter pragma disable: -fdoc-section-header-unknown
4165 /*@
4166   MatSOR - Computes relaxation (SOR, Gauss-Seidel) sweeps.
4167 
4168   Neighbor-wise Collective
4169 
4170   Input Parameters:
4171 + mat   - the matrix
4172 . b     - the right-hand side
4173 . omega - the relaxation factor
4174 . flag  - flag indicating the type of SOR (see below)
4175 . shift - diagonal shift
4176 . its   - the number of iterations
4177 - lits  - the number of local iterations
4178 
4179   Output Parameter:
4180 . x - the solution (can contain an initial guess, use option `SOR_ZERO_INITIAL_GUESS` to indicate no guess)
4181 
4182   SOR Flags:
4183 +     `SOR_FORWARD_SWEEP` - forward SOR
4184 .     `SOR_BACKWARD_SWEEP` - backward SOR
4185 .     `SOR_SYMMETRIC_SWEEP` - SSOR (symmetric SOR)
4186 .     `SOR_LOCAL_FORWARD_SWEEP` - local forward SOR
4187 .     `SOR_LOCAL_BACKWARD_SWEEP` - local forward SOR
4188 .     `SOR_LOCAL_SYMMETRIC_SWEEP` - local SSOR
4189 .     `SOR_EISENSTAT` - SOR with Eisenstat trick
4190 .     `SOR_APPLY_UPPER`, `SOR_APPLY_LOWER` - applies
4191   upper/lower triangular part of matrix to
4192   vector (with omega)
4193 -     `SOR_ZERO_INITIAL_GUESS` - zero initial guess
4194 
4195   Level: developer
4196 
4197   Notes:
4198   `SOR_LOCAL_FORWARD_SWEEP`, `SOR_LOCAL_BACKWARD_SWEEP`, and
4199   `SOR_LOCAL_SYMMETRIC_SWEEP` perform separate independent smoothings
4200   on each processor.
4201 
4202   Application programmers will not generally use `MatSOR()` directly,
4203   but instead will employ the `KSP`/`PC` interface.
4204 
4205   For `MATBAIJ`, `MATSBAIJ`, and `MATAIJ` matrices with Inodes this does a block SOR smoothing, otherwise it does a pointwise smoothing
4206 
4207   Most users should employ the `KSP` interface for linear solvers
4208   instead of working directly with matrix algebra routines such as this.
4209   See, e.g., `KSPCreate()`.
4210 
4211   Vectors `x` and `b` CANNOT be the same
4212 
4213   The flags are implemented as bitwise inclusive or operations.
4214   For example, use (`SOR_ZERO_INITIAL_GUESS` | `SOR_SYMMETRIC_SWEEP`)
4215   to specify a zero initial guess for SSOR.
4216 
4217   Developer Note:
4218   We should add block SOR support for `MATAIJ` matrices with block size set to great than one and no inodes
4219 
4220 .seealso: [](ch_matrices), `Mat`, `MatMult()`, `KSP`, `PC`, `MatGetFactor()`
4221 @*/
4222 PetscErrorCode MatSOR(Mat mat, Vec b, PetscReal omega, MatSORType flag, PetscReal shift, PetscInt its, PetscInt lits, Vec x)
4223 {
4224   PetscFunctionBegin;
4225   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
4226   PetscValidType(mat, 1);
4227   PetscValidHeaderSpecific(b, VEC_CLASSID, 2);
4228   PetscValidHeaderSpecific(x, VEC_CLASSID, 8);
4229   PetscCheckSameComm(mat, 1, b, 2);
4230   PetscCheckSameComm(mat, 1, x, 8);
4231   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
4232   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
4233   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);
4234   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);
4235   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);
4236   PetscCheck(its > 0, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Relaxation requires global its %" PetscInt_FMT " positive", its);
4237   PetscCheck(lits > 0, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Relaxation requires local its %" PetscInt_FMT " positive", lits);
4238   PetscCheck(b != x, PETSC_COMM_SELF, PETSC_ERR_ARG_IDN, "b and x vector cannot be the same");
4239 
4240   MatCheckPreallocated(mat, 1);
4241   PetscCall(PetscLogEventBegin(MAT_SOR, mat, b, x, 0));
4242   PetscUseTypeMethod(mat, sor, b, omega, flag, shift, its, lits, x);
4243   PetscCall(PetscLogEventEnd(MAT_SOR, mat, b, x, 0));
4244   PetscCall(PetscObjectStateIncrease((PetscObject)x));
4245   PetscFunctionReturn(PETSC_SUCCESS);
4246 }
4247 
4248 /*
4249       Default matrix copy routine.
4250 */
4251 PetscErrorCode MatCopy_Basic(Mat A, Mat B, MatStructure str)
4252 {
4253   PetscInt           i, rstart = 0, rend = 0, nz;
4254   const PetscInt    *cwork;
4255   const PetscScalar *vwork;
4256 
4257   PetscFunctionBegin;
4258   if (B->assembled) PetscCall(MatZeroEntries(B));
4259   if (str == SAME_NONZERO_PATTERN) {
4260     PetscCall(MatGetOwnershipRange(A, &rstart, &rend));
4261     for (i = rstart; i < rend; i++) {
4262       PetscCall(MatGetRow(A, i, &nz, &cwork, &vwork));
4263       PetscCall(MatSetValues(B, 1, &i, nz, cwork, vwork, INSERT_VALUES));
4264       PetscCall(MatRestoreRow(A, i, &nz, &cwork, &vwork));
4265     }
4266   } else {
4267     PetscCall(MatAYPX(B, 0.0, A, str));
4268   }
4269   PetscCall(MatAssemblyBegin(B, MAT_FINAL_ASSEMBLY));
4270   PetscCall(MatAssemblyEnd(B, MAT_FINAL_ASSEMBLY));
4271   PetscFunctionReturn(PETSC_SUCCESS);
4272 }
4273 
4274 /*@
4275   MatCopy - Copies a matrix to another matrix.
4276 
4277   Collective
4278 
4279   Input Parameters:
4280 + A   - the matrix
4281 - str - `SAME_NONZERO_PATTERN` or `DIFFERENT_NONZERO_PATTERN`
4282 
4283   Output Parameter:
4284 . B - where the copy is put
4285 
4286   Level: intermediate
4287 
4288   Notes:
4289   If you use `SAME_NONZERO_PATTERN`, then the two matrices must have the same nonzero pattern or the routine will crash.
4290 
4291   `MatCopy()` copies the matrix entries of a matrix to another existing
4292   matrix (after first zeroing the second matrix).  A related routine is
4293   `MatConvert()`, which first creates a new matrix and then copies the data.
4294 
4295 .seealso: [](ch_matrices), `Mat`, `MatConvert()`, `MatDuplicate()`
4296 @*/
4297 PetscErrorCode MatCopy(Mat A, Mat B, MatStructure str)
4298 {
4299   PetscInt i;
4300 
4301   PetscFunctionBegin;
4302   PetscValidHeaderSpecific(A, MAT_CLASSID, 1);
4303   PetscValidHeaderSpecific(B, MAT_CLASSID, 2);
4304   PetscValidType(A, 1);
4305   PetscValidType(B, 2);
4306   PetscCheckSameComm(A, 1, B, 2);
4307   MatCheckPreallocated(B, 2);
4308   PetscCheck(A->assembled, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
4309   PetscCheck(!A->factortype, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
4310   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,
4311              A->cmap->N, B->cmap->N);
4312   MatCheckPreallocated(A, 1);
4313   if (A == B) PetscFunctionReturn(PETSC_SUCCESS);
4314 
4315   PetscCall(PetscLogEventBegin(MAT_Copy, A, B, 0, 0));
4316   if (A->ops->copy) PetscUseTypeMethod(A, copy, B, str);
4317   else PetscCall(MatCopy_Basic(A, B, str));
4318 
4319   B->stencil.dim = A->stencil.dim;
4320   B->stencil.noc = A->stencil.noc;
4321   for (i = 0; i <= A->stencil.dim + (A->stencil.noc ? 0 : -1); i++) {
4322     B->stencil.dims[i]   = A->stencil.dims[i];
4323     B->stencil.starts[i] = A->stencil.starts[i];
4324   }
4325 
4326   PetscCall(PetscLogEventEnd(MAT_Copy, A, B, 0, 0));
4327   PetscCall(PetscObjectStateIncrease((PetscObject)B));
4328   PetscFunctionReturn(PETSC_SUCCESS);
4329 }
4330 
4331 /*@
4332   MatConvert - Converts a matrix to another matrix, either of the same
4333   or different type.
4334 
4335   Collective
4336 
4337   Input Parameters:
4338 + mat     - the matrix
4339 . newtype - new matrix type.  Use `MATSAME` to create a new matrix of the
4340             same type as the original matrix.
4341 - reuse   - denotes if the destination matrix is to be created or reused.
4342             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
4343             `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).
4344 
4345   Output Parameter:
4346 . M - pointer to place new matrix
4347 
4348   Level: intermediate
4349 
4350   Notes:
4351   `MatConvert()` first creates a new matrix and then copies the data from
4352   the first matrix.  A related routine is `MatCopy()`, which copies the matrix
4353   entries of one matrix to another already existing matrix context.
4354 
4355   Cannot be used to convert a sequential matrix to parallel or parallel to sequential,
4356   the MPI communicator of the generated matrix is always the same as the communicator
4357   of the input matrix.
4358 
4359 .seealso: [](ch_matrices), `Mat`, `MatCopy()`, `MatDuplicate()`, `MAT_INITIAL_MATRIX`, `MAT_REUSE_MATRIX`, `MAT_INPLACE_MATRIX`
4360 @*/
4361 PetscErrorCode MatConvert(Mat mat, MatType newtype, MatReuse reuse, Mat *M)
4362 {
4363   PetscBool  sametype, issame, flg;
4364   PetscBool3 issymmetric, ishermitian;
4365   char       convname[256], mtype[256];
4366   Mat        B;
4367 
4368   PetscFunctionBegin;
4369   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
4370   PetscValidType(mat, 1);
4371   PetscAssertPointer(M, 4);
4372   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
4373   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
4374   MatCheckPreallocated(mat, 1);
4375 
4376   PetscCall(PetscOptionsGetString(((PetscObject)mat)->options, ((PetscObject)mat)->prefix, "-matconvert_type", mtype, sizeof(mtype), &flg));
4377   if (flg) newtype = mtype;
4378 
4379   PetscCall(PetscObjectTypeCompare((PetscObject)mat, newtype, &sametype));
4380   PetscCall(PetscStrcmp(newtype, "same", &issame));
4381   PetscCheck(!(reuse == MAT_INPLACE_MATRIX) || !(mat != *M), PetscObjectComm((PetscObject)mat), PETSC_ERR_SUP, "MAT_INPLACE_MATRIX requires same input and output matrix");
4382   if (reuse == MAT_REUSE_MATRIX) {
4383     PetscValidHeaderSpecific(*M, MAT_CLASSID, 4);
4384     PetscCheck(mat != *M, PetscObjectComm((PetscObject)mat), PETSC_ERR_SUP, "MAT_REUSE_MATRIX means reuse matrix in final argument, perhaps you mean MAT_INPLACE_MATRIX");
4385   }
4386 
4387   if ((reuse == MAT_INPLACE_MATRIX) && (issame || sametype)) {
4388     PetscCall(PetscInfo(mat, "Early return for inplace %s %d %d\n", ((PetscObject)mat)->type_name, sametype, issame));
4389     PetscFunctionReturn(PETSC_SUCCESS);
4390   }
4391 
4392   /* Cache Mat options because some converters use MatHeaderReplace  */
4393   issymmetric = mat->symmetric;
4394   ishermitian = mat->hermitian;
4395 
4396   if ((sametype || issame) && (reuse == MAT_INITIAL_MATRIX) && mat->ops->duplicate) {
4397     PetscCall(PetscInfo(mat, "Calling duplicate for initial matrix %s %d %d\n", ((PetscObject)mat)->type_name, sametype, issame));
4398     PetscUseTypeMethod(mat, duplicate, MAT_COPY_VALUES, M);
4399   } else {
4400     PetscErrorCode (*conv)(Mat, MatType, MatReuse, Mat *) = NULL;
4401     const char *prefix[3]                                 = {"seq", "mpi", ""};
4402     PetscInt    i;
4403     /*
4404        Order of precedence:
4405        0) See if newtype is a superclass of the current matrix.
4406        1) See if a specialized converter is known to the current matrix.
4407        2) See if a specialized converter is known to the desired matrix class.
4408        3) See if a good general converter is registered for the desired class
4409           (as of 6/27/03 only MATMPIADJ falls into this category).
4410        4) See if a good general converter is known for the current matrix.
4411        5) Use a really basic converter.
4412     */
4413 
4414     /* 0) See if newtype is a superclass of the current matrix.
4415           i.e mat is mpiaij and newtype is aij */
4416     for (i = 0; i < 2; i++) {
4417       PetscCall(PetscStrncpy(convname, prefix[i], sizeof(convname)));
4418       PetscCall(PetscStrlcat(convname, newtype, sizeof(convname)));
4419       PetscCall(PetscStrcmp(convname, ((PetscObject)mat)->type_name, &flg));
4420       PetscCall(PetscInfo(mat, "Check superclass %s %s -> %d\n", convname, ((PetscObject)mat)->type_name, flg));
4421       if (flg) {
4422         if (reuse == MAT_INPLACE_MATRIX) {
4423           PetscCall(PetscInfo(mat, "Early return\n"));
4424           PetscFunctionReturn(PETSC_SUCCESS);
4425         } else if (reuse == MAT_INITIAL_MATRIX && mat->ops->duplicate) {
4426           PetscCall(PetscInfo(mat, "Calling MatDuplicate\n"));
4427           PetscUseTypeMethod(mat, duplicate, MAT_COPY_VALUES, M);
4428           PetscFunctionReturn(PETSC_SUCCESS);
4429         } else if (reuse == MAT_REUSE_MATRIX && mat->ops->copy) {
4430           PetscCall(PetscInfo(mat, "Calling MatCopy\n"));
4431           PetscCall(MatCopy(mat, *M, SAME_NONZERO_PATTERN));
4432           PetscFunctionReturn(PETSC_SUCCESS);
4433         }
4434       }
4435     }
4436     /* 1) See if a specialized converter is known to the current matrix and the desired class */
4437     for (i = 0; i < 3; i++) {
4438       PetscCall(PetscStrncpy(convname, "MatConvert_", sizeof(convname)));
4439       PetscCall(PetscStrlcat(convname, ((PetscObject)mat)->type_name, sizeof(convname)));
4440       PetscCall(PetscStrlcat(convname, "_", sizeof(convname)));
4441       PetscCall(PetscStrlcat(convname, prefix[i], sizeof(convname)));
4442       PetscCall(PetscStrlcat(convname, issame ? ((PetscObject)mat)->type_name : newtype, sizeof(convname)));
4443       PetscCall(PetscStrlcat(convname, "_C", sizeof(convname)));
4444       PetscCall(PetscObjectQueryFunction((PetscObject)mat, convname, &conv));
4445       PetscCall(PetscInfo(mat, "Check specialized (1) %s (%s) -> %d\n", convname, ((PetscObject)mat)->type_name, !!conv));
4446       if (conv) goto foundconv;
4447     }
4448 
4449     /* 2)  See if a specialized converter is known to the desired matrix class. */
4450     PetscCall(MatCreate(PetscObjectComm((PetscObject)mat), &B));
4451     PetscCall(MatSetSizes(B, mat->rmap->n, mat->cmap->n, mat->rmap->N, mat->cmap->N));
4452     PetscCall(MatSetType(B, newtype));
4453     for (i = 0; i < 3; i++) {
4454       PetscCall(PetscStrncpy(convname, "MatConvert_", sizeof(convname)));
4455       PetscCall(PetscStrlcat(convname, ((PetscObject)mat)->type_name, sizeof(convname)));
4456       PetscCall(PetscStrlcat(convname, "_", sizeof(convname)));
4457       PetscCall(PetscStrlcat(convname, prefix[i], sizeof(convname)));
4458       PetscCall(PetscStrlcat(convname, newtype, sizeof(convname)));
4459       PetscCall(PetscStrlcat(convname, "_C", sizeof(convname)));
4460       PetscCall(PetscObjectQueryFunction((PetscObject)B, convname, &conv));
4461       PetscCall(PetscInfo(mat, "Check specialized (2) %s (%s) -> %d\n", convname, ((PetscObject)B)->type_name, !!conv));
4462       if (conv) {
4463         PetscCall(MatDestroy(&B));
4464         goto foundconv;
4465       }
4466     }
4467 
4468     /* 3) See if a good general converter is registered for the desired class */
4469     conv = B->ops->convertfrom;
4470     PetscCall(PetscInfo(mat, "Check convertfrom (%s) -> %d\n", ((PetscObject)B)->type_name, !!conv));
4471     PetscCall(MatDestroy(&B));
4472     if (conv) goto foundconv;
4473 
4474     /* 4) See if a good general converter is known for the current matrix */
4475     if (mat->ops->convert) conv = mat->ops->convert;
4476     PetscCall(PetscInfo(mat, "Check general convert (%s) -> %d\n", ((PetscObject)mat)->type_name, !!conv));
4477     if (conv) goto foundconv;
4478 
4479     /* 5) Use a really basic converter. */
4480     PetscCall(PetscInfo(mat, "Using MatConvert_Basic\n"));
4481     conv = MatConvert_Basic;
4482 
4483   foundconv:
4484     PetscCall(PetscLogEventBegin(MAT_Convert, mat, 0, 0, 0));
4485     PetscCall((*conv)(mat, newtype, reuse, M));
4486     if (mat->rmap->mapping && mat->cmap->mapping && !(*M)->rmap->mapping && !(*M)->cmap->mapping) {
4487       /* the block sizes must be same if the mappings are copied over */
4488       (*M)->rmap->bs = mat->rmap->bs;
4489       (*M)->cmap->bs = mat->cmap->bs;
4490       PetscCall(PetscObjectReference((PetscObject)mat->rmap->mapping));
4491       PetscCall(PetscObjectReference((PetscObject)mat->cmap->mapping));
4492       (*M)->rmap->mapping = mat->rmap->mapping;
4493       (*M)->cmap->mapping = mat->cmap->mapping;
4494     }
4495     (*M)->stencil.dim = mat->stencil.dim;
4496     (*M)->stencil.noc = mat->stencil.noc;
4497     for (i = 0; i <= mat->stencil.dim + (mat->stencil.noc ? 0 : -1); i++) {
4498       (*M)->stencil.dims[i]   = mat->stencil.dims[i];
4499       (*M)->stencil.starts[i] = mat->stencil.starts[i];
4500     }
4501     PetscCall(PetscLogEventEnd(MAT_Convert, mat, 0, 0, 0));
4502   }
4503   PetscCall(PetscObjectStateIncrease((PetscObject)*M));
4504 
4505   /* Copy Mat options */
4506   if (issymmetric == PETSC_BOOL3_TRUE) PetscCall(MatSetOption(*M, MAT_SYMMETRIC, PETSC_TRUE));
4507   else if (issymmetric == PETSC_BOOL3_FALSE) PetscCall(MatSetOption(*M, MAT_SYMMETRIC, PETSC_FALSE));
4508   if (ishermitian == PETSC_BOOL3_TRUE) PetscCall(MatSetOption(*M, MAT_HERMITIAN, PETSC_TRUE));
4509   else if (ishermitian == PETSC_BOOL3_FALSE) PetscCall(MatSetOption(*M, MAT_HERMITIAN, PETSC_FALSE));
4510   PetscFunctionReturn(PETSC_SUCCESS);
4511 }
4512 
4513 /*@
4514   MatFactorGetSolverType - Returns name of the package providing the factorization routines
4515 
4516   Not Collective
4517 
4518   Input Parameter:
4519 . mat - the matrix, must be a factored matrix
4520 
4521   Output Parameter:
4522 . type - the string name of the package (do not free this string)
4523 
4524   Level: intermediate
4525 
4526   Fortran Note:
4527   Pass in an empty string that is long enough and the package name will be copied into it.
4528 
4529 .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatGetFactor()`, `MatSolverType`, `MatCopy()`, `MatDuplicate()`, `MatGetFactorAvailable()`
4530 @*/
4531 PetscErrorCode MatFactorGetSolverType(Mat mat, MatSolverType *type)
4532 {
4533   PetscErrorCode (*conv)(Mat, MatSolverType *);
4534 
4535   PetscFunctionBegin;
4536   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
4537   PetscValidType(mat, 1);
4538   PetscAssertPointer(type, 2);
4539   PetscCheck(mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Only for factored matrix");
4540   PetscCall(PetscObjectQueryFunction((PetscObject)mat, "MatFactorGetSolverType_C", &conv));
4541   if (conv) PetscCall((*conv)(mat, type));
4542   else *type = MATSOLVERPETSC;
4543   PetscFunctionReturn(PETSC_SUCCESS);
4544 }
4545 
4546 typedef struct _MatSolverTypeForSpecifcType *MatSolverTypeForSpecifcType;
4547 struct _MatSolverTypeForSpecifcType {
4548   MatType mtype;
4549   /* no entry for MAT_FACTOR_NONE */
4550   PetscErrorCode (*createfactor[MAT_FACTOR_NUM_TYPES - 1])(Mat, MatFactorType, Mat *);
4551   MatSolverTypeForSpecifcType next;
4552 };
4553 
4554 typedef struct _MatSolverTypeHolder *MatSolverTypeHolder;
4555 struct _MatSolverTypeHolder {
4556   char                       *name;
4557   MatSolverTypeForSpecifcType handlers;
4558   MatSolverTypeHolder         next;
4559 };
4560 
4561 static MatSolverTypeHolder MatSolverTypeHolders = NULL;
4562 
4563 /*@C
4564   MatSolverTypeRegister - Registers a `MatSolverType` that works for a particular matrix type
4565 
4566   Logically Collective, No Fortran Support
4567 
4568   Input Parameters:
4569 + package      - name of the package, for example petsc or superlu
4570 . mtype        - the matrix type that works with this package
4571 . ftype        - the type of factorization supported by the package
4572 - createfactor - routine that will create the factored matrix ready to be used
4573 
4574   Level: developer
4575 
4576 .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatFactorGetSolverType()`, `MatCopy()`, `MatDuplicate()`, `MatGetFactorAvailable()`,
4577   `MatGetFactor()`
4578 @*/
4579 PetscErrorCode MatSolverTypeRegister(MatSolverType package, MatType mtype, MatFactorType ftype, PetscErrorCode (*createfactor)(Mat, MatFactorType, Mat *))
4580 {
4581   MatSolverTypeHolder         next = MatSolverTypeHolders, prev = NULL;
4582   PetscBool                   flg;
4583   MatSolverTypeForSpecifcType inext, iprev = NULL;
4584 
4585   PetscFunctionBegin;
4586   PetscCall(MatInitializePackage());
4587   if (!next) {
4588     PetscCall(PetscNew(&MatSolverTypeHolders));
4589     PetscCall(PetscStrallocpy(package, &MatSolverTypeHolders->name));
4590     PetscCall(PetscNew(&MatSolverTypeHolders->handlers));
4591     PetscCall(PetscStrallocpy(mtype, (char **)&MatSolverTypeHolders->handlers->mtype));
4592     MatSolverTypeHolders->handlers->createfactor[(int)ftype - 1] = createfactor;
4593     PetscFunctionReturn(PETSC_SUCCESS);
4594   }
4595   while (next) {
4596     PetscCall(PetscStrcasecmp(package, next->name, &flg));
4597     if (flg) {
4598       PetscCheck(next->handlers, PETSC_COMM_SELF, PETSC_ERR_PLIB, "MatSolverTypeHolder is missing handlers");
4599       inext = next->handlers;
4600       while (inext) {
4601         PetscCall(PetscStrcasecmp(mtype, inext->mtype, &flg));
4602         if (flg) {
4603           inext->createfactor[(int)ftype - 1] = createfactor;
4604           PetscFunctionReturn(PETSC_SUCCESS);
4605         }
4606         iprev = inext;
4607         inext = inext->next;
4608       }
4609       PetscCall(PetscNew(&iprev->next));
4610       PetscCall(PetscStrallocpy(mtype, (char **)&iprev->next->mtype));
4611       iprev->next->createfactor[(int)ftype - 1] = createfactor;
4612       PetscFunctionReturn(PETSC_SUCCESS);
4613     }
4614     prev = next;
4615     next = next->next;
4616   }
4617   PetscCall(PetscNew(&prev->next));
4618   PetscCall(PetscStrallocpy(package, &prev->next->name));
4619   PetscCall(PetscNew(&prev->next->handlers));
4620   PetscCall(PetscStrallocpy(mtype, (char **)&prev->next->handlers->mtype));
4621   prev->next->handlers->createfactor[(int)ftype - 1] = createfactor;
4622   PetscFunctionReturn(PETSC_SUCCESS);
4623 }
4624 
4625 /*@C
4626   MatSolverTypeGet - Gets the function that creates the factor matrix if it exist
4627 
4628   Input Parameters:
4629 + 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
4630 . ftype - the type of factorization supported by the type
4631 - mtype - the matrix type that works with this type
4632 
4633   Output Parameters:
4634 + foundtype    - `PETSC_TRUE` if the type was registered
4635 . foundmtype   - `PETSC_TRUE` if the type supports the requested mtype
4636 - createfactor - routine that will create the factored matrix ready to be used or `NULL` if not found
4637 
4638   Calling sequence of `createfactor`:
4639 + A     - the matrix providing the factor matrix
4640 . ftype - the `MatFactorType` of the factor requested
4641 - B     - the new factor matrix that responds to MatXXFactorSymbolic,Numeric() functions, such as `MatLUFactorSymbolic()`
4642 
4643   Level: developer
4644 
4645   Note:
4646   When `type` is `NULL` the available functions are searched for based on the order of the calls to `MatSolverTypeRegister()` in `MatInitializePackage()`.
4647   Since different PETSc configurations may have different external solvers, seemingly identical runs with different PETSc configurations may use a different solver.
4648   For example if one configuration had `--download-mumps` while a different one had `--download-superlu_dist`.
4649 
4650 .seealso: [](ch_matrices), `Mat`, `MatFactorType`, `MatType`, `MatCopy()`, `MatDuplicate()`, `MatGetFactorAvailable()`, `MatSolverTypeRegister()`, `MatGetFactor()`,
4651           `MatInitializePackage()`
4652 @*/
4653 PetscErrorCode MatSolverTypeGet(MatSolverType type, MatType mtype, MatFactorType ftype, PetscBool *foundtype, PetscBool *foundmtype, PetscErrorCode (**createfactor)(Mat A, MatFactorType ftype, Mat *B))
4654 {
4655   MatSolverTypeHolder         next = MatSolverTypeHolders;
4656   PetscBool                   flg;
4657   MatSolverTypeForSpecifcType inext;
4658 
4659   PetscFunctionBegin;
4660   if (foundtype) *foundtype = PETSC_FALSE;
4661   if (foundmtype) *foundmtype = PETSC_FALSE;
4662   if (createfactor) *createfactor = NULL;
4663 
4664   if (type) {
4665     while (next) {
4666       PetscCall(PetscStrcasecmp(type, next->name, &flg));
4667       if (flg) {
4668         if (foundtype) *foundtype = PETSC_TRUE;
4669         inext = next->handlers;
4670         while (inext) {
4671           PetscCall(PetscStrbeginswith(mtype, inext->mtype, &flg));
4672           if (flg) {
4673             if (foundmtype) *foundmtype = PETSC_TRUE;
4674             if (createfactor) *createfactor = inext->createfactor[(int)ftype - 1];
4675             PetscFunctionReturn(PETSC_SUCCESS);
4676           }
4677           inext = inext->next;
4678         }
4679       }
4680       next = next->next;
4681     }
4682   } else {
4683     while (next) {
4684       inext = next->handlers;
4685       while (inext) {
4686         PetscCall(PetscStrcmp(mtype, inext->mtype, &flg));
4687         if (flg && inext->createfactor[(int)ftype - 1]) {
4688           if (foundtype) *foundtype = PETSC_TRUE;
4689           if (foundmtype) *foundmtype = PETSC_TRUE;
4690           if (createfactor) *createfactor = inext->createfactor[(int)ftype - 1];
4691           PetscFunctionReturn(PETSC_SUCCESS);
4692         }
4693         inext = inext->next;
4694       }
4695       next = next->next;
4696     }
4697     /* try with base classes inext->mtype */
4698     next = MatSolverTypeHolders;
4699     while (next) {
4700       inext = next->handlers;
4701       while (inext) {
4702         PetscCall(PetscStrbeginswith(mtype, inext->mtype, &flg));
4703         if (flg && inext->createfactor[(int)ftype - 1]) {
4704           if (foundtype) *foundtype = PETSC_TRUE;
4705           if (foundmtype) *foundmtype = PETSC_TRUE;
4706           if (createfactor) *createfactor = inext->createfactor[(int)ftype - 1];
4707           PetscFunctionReturn(PETSC_SUCCESS);
4708         }
4709         inext = inext->next;
4710       }
4711       next = next->next;
4712     }
4713   }
4714   PetscFunctionReturn(PETSC_SUCCESS);
4715 }
4716 
4717 PetscErrorCode MatSolverTypeDestroy(void)
4718 {
4719   MatSolverTypeHolder         next = MatSolverTypeHolders, prev;
4720   MatSolverTypeForSpecifcType inext, iprev;
4721 
4722   PetscFunctionBegin;
4723   while (next) {
4724     PetscCall(PetscFree(next->name));
4725     inext = next->handlers;
4726     while (inext) {
4727       PetscCall(PetscFree(inext->mtype));
4728       iprev = inext;
4729       inext = inext->next;
4730       PetscCall(PetscFree(iprev));
4731     }
4732     prev = next;
4733     next = next->next;
4734     PetscCall(PetscFree(prev));
4735   }
4736   MatSolverTypeHolders = NULL;
4737   PetscFunctionReturn(PETSC_SUCCESS);
4738 }
4739 
4740 /*@
4741   MatFactorGetCanUseOrdering - Indicates if the factorization can use the ordering provided in `MatLUFactorSymbolic()`, `MatCholeskyFactorSymbolic()`
4742 
4743   Logically Collective
4744 
4745   Input Parameter:
4746 . mat - the matrix
4747 
4748   Output Parameter:
4749 . flg - `PETSC_TRUE` if uses the ordering
4750 
4751   Level: developer
4752 
4753   Note:
4754   Most internal PETSc factorizations use the ordering passed to the factorization routine but external
4755   packages do not, thus we want to skip generating the ordering when it is not needed or used.
4756 
4757 .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatCopy()`, `MatDuplicate()`, `MatGetFactorAvailable()`, `MatGetFactor()`, `MatLUFactorSymbolic()`, `MatCholeskyFactorSymbolic()`
4758 @*/
4759 PetscErrorCode MatFactorGetCanUseOrdering(Mat mat, PetscBool *flg)
4760 {
4761   PetscFunctionBegin;
4762   *flg = mat->canuseordering;
4763   PetscFunctionReturn(PETSC_SUCCESS);
4764 }
4765 
4766 /*@
4767   MatFactorGetPreferredOrdering - The preferred ordering for a particular matrix factor object
4768 
4769   Logically Collective
4770 
4771   Input Parameters:
4772 + mat   - the matrix obtained with `MatGetFactor()`
4773 - ftype - the factorization type to be used
4774 
4775   Output Parameter:
4776 . otype - the preferred ordering type
4777 
4778   Level: developer
4779 
4780 .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatFactorType`, `MatOrderingType`, `MatCopy()`, `MatDuplicate()`, `MatGetFactorAvailable()`, `MatGetFactor()`, `MatLUFactorSymbolic()`, `MatCholeskyFactorSymbolic()`
4781 @*/
4782 PetscErrorCode MatFactorGetPreferredOrdering(Mat mat, MatFactorType ftype, MatOrderingType *otype)
4783 {
4784   PetscFunctionBegin;
4785   *otype = mat->preferredordering[ftype];
4786   PetscCheck(*otype, PETSC_COMM_SELF, PETSC_ERR_PLIB, "MatFactor did not have a preferred ordering");
4787   PetscFunctionReturn(PETSC_SUCCESS);
4788 }
4789 
4790 /*@
4791   MatGetFactor - Returns a matrix suitable to calls to MatXXFactorSymbolic,Numeric()
4792 
4793   Collective
4794 
4795   Input Parameters:
4796 + mat   - the matrix
4797 . type  - name of solver type, for example, superlu, petsc (to use PETSc's solver if it is available), if this is 'NULL', then the first result that satisfies
4798           the other criteria is returned
4799 - ftype - factor type, `MAT_FACTOR_LU`, `MAT_FACTOR_CHOLESKY`, `MAT_FACTOR_ICC`, `MAT_FACTOR_ILU`, `MAT_FACTOR_QR`
4800 
4801   Output Parameter:
4802 . f - the factor matrix used with MatXXFactorSymbolic,Numeric() calls. Can be `NULL` in some cases, see notes below.
4803 
4804   Options Database Keys:
4805 + -pc_factor_mat_solver_type <type>             - choose the type at run time. When using `KSP` solvers
4806 - -mat_factor_bind_factorization <host, device> - Where to do matrix factorization? Default is device (might consume more device memory.
4807                                                   One can choose host to save device memory). Currently only supported with `MATSEQAIJCUSPARSE` matrices.
4808 
4809   Level: intermediate
4810 
4811   Notes:
4812   The return matrix can be `NULL` if the requested factorization is not available, since some combinations of matrix types and factorization
4813   types registered with `MatSolverTypeRegister()` cannot be fully tested if not at runtime.
4814 
4815   Users usually access the factorization solvers via `KSP`
4816 
4817   Some PETSc matrix formats have alternative solvers available that are contained in alternative packages
4818   such as pastix, superlu, mumps etc. PETSc must have been ./configure to use the external solver, using the option --download-package or --with-package-dir
4819 
4820   When `type` is `NULL` the available results are searched for based on the order of the calls to `MatSolverTypeRegister()` in `MatInitializePackage()`.
4821   Since different PETSc configurations may have different external solvers, seemingly identical runs with different PETSc configurations may use a different solver.
4822   For example if one configuration had --download-mumps while a different one had --download-superlu_dist.
4823 
4824   Some of the packages have options for controlling the factorization, these are in the form -prefix_mat_packagename_packageoption
4825   where prefix is normally obtained from the calling `KSP`/`PC`. If `MatGetFactor()` is called directly one can set
4826   call `MatSetOptionsPrefixFactor()` on the originating matrix or  `MatSetOptionsPrefix()` on the resulting factor matrix.
4827 
4828   Developer Note:
4829   This should actually be called `MatCreateFactor()` since it creates a new factor object
4830 
4831 .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `KSP`, `MatSolverType`, `MatFactorType`, `MatCopy()`, `MatDuplicate()`,
4832           `MatGetFactorAvailable()`, `MatFactorGetCanUseOrdering()`, `MatSolverTypeRegister()`, `MatSolverTypeGet()`
4833           `MAT_FACTOR_LU`, `MAT_FACTOR_CHOLESKY`, `MAT_FACTOR_ICC`, `MAT_FACTOR_ILU`, `MAT_FACTOR_QR`, `MatInitializePackage()`
4834 @*/
4835 PetscErrorCode MatGetFactor(Mat mat, MatSolverType type, MatFactorType ftype, Mat *f)
4836 {
4837   PetscBool foundtype, foundmtype;
4838   PetscErrorCode (*conv)(Mat, MatFactorType, Mat *);
4839 
4840   PetscFunctionBegin;
4841   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
4842   PetscValidType(mat, 1);
4843 
4844   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
4845   MatCheckPreallocated(mat, 1);
4846 
4847   PetscCall(MatSolverTypeGet(type, ((PetscObject)mat)->type_name, ftype, &foundtype, &foundmtype, &conv));
4848   if (!foundtype) {
4849     if (type) {
4850       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],
4851               ((PetscObject)mat)->type_name, type);
4852     } else {
4853       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);
4854     }
4855   }
4856   PetscCheck(foundmtype, PetscObjectComm((PetscObject)mat), PETSC_ERR_MISSING_FACTOR, "MatSolverType %s does not support matrix type %s", type, ((PetscObject)mat)->type_name);
4857   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);
4858 
4859   PetscCall((*conv)(mat, ftype, f));
4860   if (mat->factorprefix) PetscCall(MatSetOptionsPrefix(*f, mat->factorprefix));
4861   PetscFunctionReturn(PETSC_SUCCESS);
4862 }
4863 
4864 /*@
4865   MatGetFactorAvailable - Returns a flag if matrix supports particular type and factor type
4866 
4867   Not Collective
4868 
4869   Input Parameters:
4870 + mat   - the matrix
4871 . type  - name of solver type, for example, superlu, petsc (to use PETSc's default)
4872 - ftype - factor type, `MAT_FACTOR_LU`, `MAT_FACTOR_CHOLESKY`, `MAT_FACTOR_ICC`, `MAT_FACTOR_ILU`, `MAT_FACTOR_QR`
4873 
4874   Output Parameter:
4875 . flg - PETSC_TRUE if the factorization is available
4876 
4877   Level: intermediate
4878 
4879   Notes:
4880   Some PETSc matrix formats have alternative solvers available that are contained in alternative packages
4881   such as pastix, superlu, mumps etc.
4882 
4883   PETSc must have been ./configure to use the external solver, using the option --download-package
4884 
4885   Developer Note:
4886   This should actually be called `MatCreateFactorAvailable()` since `MatGetFactor()` creates a new factor object
4887 
4888 .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatSolverType`, `MatFactorType`, `MatGetFactor()`, `MatCopy()`, `MatDuplicate()`, `MatSolverTypeRegister()`,
4889           `MAT_FACTOR_LU`, `MAT_FACTOR_CHOLESKY`, `MAT_FACTOR_ICC`, `MAT_FACTOR_ILU`, `MAT_FACTOR_QR`, `MatSolverTypeGet()`
4890 @*/
4891 PetscErrorCode MatGetFactorAvailable(Mat mat, MatSolverType type, MatFactorType ftype, PetscBool *flg)
4892 {
4893   PetscErrorCode (*gconv)(Mat, MatFactorType, Mat *);
4894 
4895   PetscFunctionBegin;
4896   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
4897   PetscAssertPointer(flg, 4);
4898 
4899   *flg = PETSC_FALSE;
4900   if (!((PetscObject)mat)->type_name) PetscFunctionReturn(PETSC_SUCCESS);
4901 
4902   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
4903   MatCheckPreallocated(mat, 1);
4904 
4905   PetscCall(MatSolverTypeGet(type, ((PetscObject)mat)->type_name, ftype, NULL, NULL, &gconv));
4906   *flg = gconv ? PETSC_TRUE : PETSC_FALSE;
4907   PetscFunctionReturn(PETSC_SUCCESS);
4908 }
4909 
4910 /*@
4911   MatDuplicate - Duplicates a matrix including the non-zero structure.
4912 
4913   Collective
4914 
4915   Input Parameters:
4916 + mat - the matrix
4917 - op  - One of `MAT_DO_NOT_COPY_VALUES`, `MAT_COPY_VALUES`, or `MAT_SHARE_NONZERO_PATTERN`.
4918         See the manual page for `MatDuplicateOption()` for an explanation of these options.
4919 
4920   Output Parameter:
4921 . M - pointer to place new matrix
4922 
4923   Level: intermediate
4924 
4925   Notes:
4926   You cannot change the nonzero pattern for the parent or child matrix later if you use `MAT_SHARE_NONZERO_PATTERN`.
4927 
4928   If `op` is not `MAT_COPY_VALUES` the numerical values in the new matrix are zeroed.
4929 
4930   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.
4931 
4932   When original mat is a product of matrix operation, e.g., an output of `MatMatMult()` or `MatCreateSubMatrix()`, only the matrix data structure of `mat`
4933   is duplicated and the internal data structures created for the reuse of previous matrix operations are not duplicated.
4934   User should not use `MatDuplicate()` to create new matrix `M` if `M` is intended to be reused as the product of matrix operation.
4935 
4936 .seealso: [](ch_matrices), `Mat`, `MatCopy()`, `MatConvert()`, `MatDuplicateOption`
4937 @*/
4938 PetscErrorCode MatDuplicate(Mat mat, MatDuplicateOption op, Mat *M)
4939 {
4940   Mat         B;
4941   VecType     vtype;
4942   PetscInt    i;
4943   PetscObject dm, container_h, container_d;
4944   void (*viewf)(void);
4945 
4946   PetscFunctionBegin;
4947   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
4948   PetscValidType(mat, 1);
4949   PetscAssertPointer(M, 3);
4950   PetscCheck(op != MAT_COPY_VALUES || mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "MAT_COPY_VALUES not allowed for unassembled matrix");
4951   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
4952   MatCheckPreallocated(mat, 1);
4953 
4954   *M = NULL;
4955   PetscCall(PetscLogEventBegin(MAT_Convert, mat, 0, 0, 0));
4956   PetscUseTypeMethod(mat, duplicate, op, M);
4957   PetscCall(PetscLogEventEnd(MAT_Convert, mat, 0, 0, 0));
4958   B = *M;
4959 
4960   PetscCall(MatGetOperation(mat, MATOP_VIEW, &viewf));
4961   if (viewf) PetscCall(MatSetOperation(B, MATOP_VIEW, viewf));
4962   PetscCall(MatGetVecType(mat, &vtype));
4963   PetscCall(MatSetVecType(B, vtype));
4964 
4965   B->stencil.dim = mat->stencil.dim;
4966   B->stencil.noc = mat->stencil.noc;
4967   for (i = 0; i <= mat->stencil.dim + (mat->stencil.noc ? 0 : -1); i++) {
4968     B->stencil.dims[i]   = mat->stencil.dims[i];
4969     B->stencil.starts[i] = mat->stencil.starts[i];
4970   }
4971 
4972   B->nooffproczerorows = mat->nooffproczerorows;
4973   B->nooffprocentries  = mat->nooffprocentries;
4974 
4975   PetscCall(PetscObjectQuery((PetscObject)mat, "__PETSc_dm", &dm));
4976   if (dm) PetscCall(PetscObjectCompose((PetscObject)B, "__PETSc_dm", dm));
4977   PetscCall(PetscObjectQuery((PetscObject)mat, "__PETSc_MatCOOStruct_Host", &container_h));
4978   if (container_h) PetscCall(PetscObjectCompose((PetscObject)B, "__PETSc_MatCOOStruct_Host", container_h));
4979   PetscCall(PetscObjectQuery((PetscObject)mat, "__PETSc_MatCOOStruct_Device", &container_d));
4980   if (container_d) PetscCall(PetscObjectCompose((PetscObject)B, "__PETSc_MatCOOStruct_Device", container_d));
4981   PetscCall(PetscObjectStateIncrease((PetscObject)B));
4982   PetscFunctionReturn(PETSC_SUCCESS);
4983 }
4984 
4985 /*@
4986   MatGetDiagonal - Gets the diagonal of a matrix as a `Vec`
4987 
4988   Logically Collective
4989 
4990   Input Parameter:
4991 . mat - the matrix
4992 
4993   Output Parameter:
4994 . v - the diagonal of the matrix
4995 
4996   Level: intermediate
4997 
4998   Note:
4999   If `mat` has local sizes `n` x `m`, this routine fills the first `ndiag = min(n, m)` entries
5000   of `v` with the diagonal values. Thus `v` must have local size of at least `ndiag`. If `v`
5001   is larger than `ndiag`, the values of the remaining entries are unspecified.
5002 
5003   Currently only correct in parallel for square matrices.
5004 
5005 .seealso: [](ch_matrices), `Mat`, `Vec`, `MatGetRow()`, `MatCreateSubMatrices()`, `MatCreateSubMatrix()`, `MatGetRowMaxAbs()`
5006 @*/
5007 PetscErrorCode MatGetDiagonal(Mat mat, Vec v)
5008 {
5009   PetscFunctionBegin;
5010   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
5011   PetscValidType(mat, 1);
5012   PetscValidHeaderSpecific(v, VEC_CLASSID, 2);
5013   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
5014   MatCheckPreallocated(mat, 1);
5015   if (PetscDefined(USE_DEBUG)) {
5016     PetscInt nv, row, col, ndiag;
5017 
5018     PetscCall(VecGetLocalSize(v, &nv));
5019     PetscCall(MatGetLocalSize(mat, &row, &col));
5020     ndiag = PetscMin(row, col);
5021     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);
5022   }
5023 
5024   PetscUseTypeMethod(mat, getdiagonal, v);
5025   PetscCall(PetscObjectStateIncrease((PetscObject)v));
5026   PetscFunctionReturn(PETSC_SUCCESS);
5027 }
5028 
5029 /*@
5030   MatGetRowMin - Gets the minimum value (of the real part) of each
5031   row of the matrix
5032 
5033   Logically Collective
5034 
5035   Input Parameter:
5036 . mat - the matrix
5037 
5038   Output Parameters:
5039 + v   - the vector for storing the maximums
5040 - idx - the indices of the column found for each row (optional, pass `NULL` if not needed)
5041 
5042   Level: intermediate
5043 
5044   Note:
5045   The result of this call are the same as if one converted the matrix to dense format
5046   and found the minimum value in each row (i.e. the implicit zeros are counted as zeros).
5047 
5048   This code is only implemented for a couple of matrix formats.
5049 
5050 .seealso: [](ch_matrices), `Mat`, `MatGetDiagonal()`, `MatCreateSubMatrices()`, `MatCreateSubMatrix()`, `MatGetRowMaxAbs()`, `MatGetRowMinAbs()`,
5051           `MatGetRowMax()`
5052 @*/
5053 PetscErrorCode MatGetRowMin(Mat mat, Vec v, PetscInt idx[])
5054 {
5055   PetscFunctionBegin;
5056   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
5057   PetscValidType(mat, 1);
5058   PetscValidHeaderSpecific(v, VEC_CLASSID, 2);
5059   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
5060 
5061   if (!mat->cmap->N) {
5062     PetscCall(VecSet(v, PETSC_MAX_REAL));
5063     if (idx) {
5064       PetscInt i, m = mat->rmap->n;
5065       for (i = 0; i < m; i++) idx[i] = -1;
5066     }
5067   } else {
5068     MatCheckPreallocated(mat, 1);
5069   }
5070   PetscUseTypeMethod(mat, getrowmin, v, idx);
5071   PetscCall(PetscObjectStateIncrease((PetscObject)v));
5072   PetscFunctionReturn(PETSC_SUCCESS);
5073 }
5074 
5075 /*@
5076   MatGetRowMinAbs - Gets the minimum value (in absolute value) of each
5077   row of the matrix
5078 
5079   Logically Collective
5080 
5081   Input Parameter:
5082 . mat - the matrix
5083 
5084   Output Parameters:
5085 + v   - the vector for storing the minimums
5086 - idx - the indices of the column found for each row (or `NULL` if not needed)
5087 
5088   Level: intermediate
5089 
5090   Notes:
5091   if a row is completely empty or has only 0.0 values, then the `idx` value for that
5092   row is 0 (the first column).
5093 
5094   This code is only implemented for a couple of matrix formats.
5095 
5096 .seealso: [](ch_matrices), `Mat`, `MatGetDiagonal()`, `MatCreateSubMatrices()`, `MatCreateSubMatrix()`, `MatGetRowMax()`, `MatGetRowMaxAbs()`, `MatGetRowMin()`
5097 @*/
5098 PetscErrorCode MatGetRowMinAbs(Mat mat, Vec v, PetscInt idx[])
5099 {
5100   PetscFunctionBegin;
5101   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
5102   PetscValidType(mat, 1);
5103   PetscValidHeaderSpecific(v, VEC_CLASSID, 2);
5104   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
5105   PetscCheck(!mat->factortype, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
5106 
5107   if (!mat->cmap->N) {
5108     PetscCall(VecSet(v, 0.0));
5109     if (idx) {
5110       PetscInt i, m = mat->rmap->n;
5111       for (i = 0; i < m; i++) idx[i] = -1;
5112     }
5113   } else {
5114     MatCheckPreallocated(mat, 1);
5115     if (idx) PetscCall(PetscArrayzero(idx, mat->rmap->n));
5116     PetscUseTypeMethod(mat, getrowminabs, v, idx);
5117   }
5118   PetscCall(PetscObjectStateIncrease((PetscObject)v));
5119   PetscFunctionReturn(PETSC_SUCCESS);
5120 }
5121 
5122 /*@
5123   MatGetRowMax - Gets the maximum value (of the real part) of each
5124   row of the matrix
5125 
5126   Logically Collective
5127 
5128   Input Parameter:
5129 . mat - the matrix
5130 
5131   Output Parameters:
5132 + v   - the vector for storing the maximums
5133 - idx - the indices of the column found for each row (optional, otherwise pass `NULL`)
5134 
5135   Level: intermediate
5136 
5137   Notes:
5138   The result of this call are the same as if one converted the matrix to dense format
5139   and found the minimum value in each row (i.e. the implicit zeros are counted as zeros).
5140 
5141   This code is only implemented for a couple of matrix formats.
5142 
5143 .seealso: [](ch_matrices), `Mat`, `MatGetDiagonal()`, `MatCreateSubMatrices()`, `MatCreateSubMatrix()`, `MatGetRowMaxAbs()`, `MatGetRowMin()`, `MatGetRowMinAbs()`
5144 @*/
5145 PetscErrorCode MatGetRowMax(Mat mat, Vec v, PetscInt idx[])
5146 {
5147   PetscFunctionBegin;
5148   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
5149   PetscValidType(mat, 1);
5150   PetscValidHeaderSpecific(v, VEC_CLASSID, 2);
5151   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
5152 
5153   if (!mat->cmap->N) {
5154     PetscCall(VecSet(v, PETSC_MIN_REAL));
5155     if (idx) {
5156       PetscInt i, m = mat->rmap->n;
5157       for (i = 0; i < m; i++) idx[i] = -1;
5158     }
5159   } else {
5160     MatCheckPreallocated(mat, 1);
5161     PetscUseTypeMethod(mat, getrowmax, v, idx);
5162   }
5163   PetscCall(PetscObjectStateIncrease((PetscObject)v));
5164   PetscFunctionReturn(PETSC_SUCCESS);
5165 }
5166 
5167 /*@
5168   MatGetRowMaxAbs - Gets the maximum value (in absolute value) of each
5169   row of the matrix
5170 
5171   Logically Collective
5172 
5173   Input Parameter:
5174 . mat - the matrix
5175 
5176   Output Parameters:
5177 + v   - the vector for storing the maximums
5178 - idx - the indices of the column found for each row (or `NULL` if not needed)
5179 
5180   Level: intermediate
5181 
5182   Notes:
5183   if a row is completely empty or has only 0.0 values, then the `idx` value for that
5184   row is 0 (the first column).
5185 
5186   This code is only implemented for a couple of matrix formats.
5187 
5188 .seealso: [](ch_matrices), `Mat`, `MatGetDiagonal()`, `MatCreateSubMatrices()`, `MatCreateSubMatrix()`, `MatGetRowSum()`, `MatGetRowMin()`, `MatGetRowMinAbs()`
5189 @*/
5190 PetscErrorCode MatGetRowMaxAbs(Mat mat, Vec v, PetscInt idx[])
5191 {
5192   PetscFunctionBegin;
5193   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
5194   PetscValidType(mat, 1);
5195   PetscValidHeaderSpecific(v, VEC_CLASSID, 2);
5196   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
5197 
5198   if (!mat->cmap->N) {
5199     PetscCall(VecSet(v, 0.0));
5200     if (idx) {
5201       PetscInt i, m = mat->rmap->n;
5202       for (i = 0; i < m; i++) idx[i] = -1;
5203     }
5204   } else {
5205     MatCheckPreallocated(mat, 1);
5206     if (idx) PetscCall(PetscArrayzero(idx, mat->rmap->n));
5207     PetscUseTypeMethod(mat, getrowmaxabs, v, idx);
5208   }
5209   PetscCall(PetscObjectStateIncrease((PetscObject)v));
5210   PetscFunctionReturn(PETSC_SUCCESS);
5211 }
5212 
5213 /*@
5214   MatGetRowSumAbs - Gets the sum value (in absolute value) of each row of the matrix
5215 
5216   Logically Collective
5217 
5218   Input Parameter:
5219 . mat - the matrix
5220 
5221   Output Parameter:
5222 . v - the vector for storing the sum
5223 
5224   Level: intermediate
5225 
5226   This code is only implemented for a couple of matrix formats.
5227 
5228 .seealso: [](ch_matrices), `Mat`, `MatGetDiagonal()`, `MatCreateSubMatrices()`, `MatCreateSubMatrix()`, `MatGetRowMax()`, `MatGetRowMin()`, `MatGetRowMinAbs()`
5229 @*/
5230 PetscErrorCode MatGetRowSumAbs(Mat mat, Vec v)
5231 {
5232   PetscFunctionBegin;
5233   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
5234   PetscValidType(mat, 1);
5235   PetscValidHeaderSpecific(v, VEC_CLASSID, 2);
5236   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
5237 
5238   if (!mat->cmap->N) {
5239     PetscCall(VecSet(v, 0.0));
5240   } else {
5241     MatCheckPreallocated(mat, 1);
5242     PetscUseTypeMethod(mat, getrowsumabs, v);
5243   }
5244   PetscCall(PetscObjectStateIncrease((PetscObject)v));
5245   PetscFunctionReturn(PETSC_SUCCESS);
5246 }
5247 
5248 /*@
5249   MatGetRowSum - Gets the sum of each row of the matrix
5250 
5251   Logically or Neighborhood Collective
5252 
5253   Input Parameter:
5254 . mat - the matrix
5255 
5256   Output Parameter:
5257 . v - the vector for storing the sum of rows
5258 
5259   Level: intermediate
5260 
5261   Note:
5262   This code is slow since it is not currently specialized for different formats
5263 
5264 .seealso: [](ch_matrices), `Mat`, `MatGetDiagonal()`, `MatCreateSubMatrices()`, `MatCreateSubMatrix()`, `MatGetRowMax()`, `MatGetRowMin()`, `MatGetRowMaxAbs()`, `MatGetRowMinAbs()`, `MatGetRowSumAbs()`
5265 @*/
5266 PetscErrorCode MatGetRowSum(Mat mat, Vec v)
5267 {
5268   Vec ones;
5269 
5270   PetscFunctionBegin;
5271   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
5272   PetscValidType(mat, 1);
5273   PetscValidHeaderSpecific(v, VEC_CLASSID, 2);
5274   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
5275   MatCheckPreallocated(mat, 1);
5276   PetscCall(MatCreateVecs(mat, &ones, NULL));
5277   PetscCall(VecSet(ones, 1.));
5278   PetscCall(MatMult(mat, ones, v));
5279   PetscCall(VecDestroy(&ones));
5280   PetscFunctionReturn(PETSC_SUCCESS);
5281 }
5282 
5283 /*@
5284   MatTransposeSetPrecursor - Set the matrix from which the second matrix will receive numerical transpose data with a call to `MatTranspose`(A,`MAT_REUSE_MATRIX`,&B)
5285   when B was not obtained with `MatTranspose`(A,`MAT_INITIAL_MATRIX`,&B)
5286 
5287   Collective
5288 
5289   Input Parameter:
5290 . mat - the matrix to provide the transpose
5291 
5292   Output Parameter:
5293 . 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
5294 
5295   Level: advanced
5296 
5297   Note:
5298   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
5299   routine allows bypassing that call.
5300 
5301 .seealso: [](ch_matrices), `Mat`, `MatTransposeSymbolic()`, `MatTranspose()`, `MatMultTranspose()`, `MatMultTransposeAdd()`, `MatIsTranspose()`, `MatReuse`, `MAT_INITIAL_MATRIX`, `MAT_REUSE_MATRIX`, `MAT_INPLACE_MATRIX`
5302 @*/
5303 PetscErrorCode MatTransposeSetPrecursor(Mat mat, Mat B)
5304 {
5305   PetscContainer  rB = NULL;
5306   MatParentState *rb = NULL;
5307 
5308   PetscFunctionBegin;
5309   PetscCall(PetscNew(&rb));
5310   rb->id    = ((PetscObject)mat)->id;
5311   rb->state = 0;
5312   PetscCall(MatGetNonzeroState(mat, &rb->nonzerostate));
5313   PetscCall(PetscContainerCreate(PetscObjectComm((PetscObject)B), &rB));
5314   PetscCall(PetscContainerSetPointer(rB, rb));
5315   PetscCall(PetscContainerSetUserDestroy(rB, PetscContainerUserDestroyDefault));
5316   PetscCall(PetscObjectCompose((PetscObject)B, "MatTransposeParent", (PetscObject)rB));
5317   PetscCall(PetscObjectDereference((PetscObject)rB));
5318   PetscFunctionReturn(PETSC_SUCCESS);
5319 }
5320 
5321 /*@
5322   MatTranspose - Computes an in-place or out-of-place transpose of a matrix.
5323 
5324   Collective
5325 
5326   Input Parameters:
5327 + mat   - the matrix to transpose
5328 - reuse - either `MAT_INITIAL_MATRIX`, `MAT_REUSE_MATRIX`, or `MAT_INPLACE_MATRIX`
5329 
5330   Output Parameter:
5331 . B - the transpose
5332 
5333   Level: intermediate
5334 
5335   Notes:
5336   If you use `MAT_INPLACE_MATRIX` then you must pass in `&mat` for `B`
5337 
5338   `MAT_REUSE_MATRIX` uses the `B` matrix obtained from a previous call to this function with `MAT_INITIAL_MATRIX`. If you already have a matrix to contain the
5339   transpose, call `MatTransposeSetPrecursor(mat, B)` before calling this routine.
5340 
5341   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.
5342 
5343   Consider using `MatCreateTranspose()` instead if you only need a matrix that behaves like the transpose, but don't need the storage to be changed.
5344 
5345   If mat is unchanged from the last call this function returns immediately without recomputing the result
5346 
5347   If you only need the symbolic transpose, and not the numerical values, use `MatTransposeSymbolic()`
5348 
5349 .seealso: [](ch_matrices), `Mat`, `MatTransposeSetPrecursor()`, `MatMultTranspose()`, `MatMultTransposeAdd()`, `MatIsTranspose()`, `MatReuse`, `MAT_INITIAL_MATRIX`, `MAT_REUSE_MATRIX`, `MAT_INPLACE_MATRIX`,
5350           `MatTransposeSymbolic()`, `MatCreateTranspose()`
5351 @*/
5352 PetscErrorCode MatTranspose(Mat mat, MatReuse reuse, Mat *B)
5353 {
5354   PetscContainer  rB = NULL;
5355   MatParentState *rb = NULL;
5356 
5357   PetscFunctionBegin;
5358   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
5359   PetscValidType(mat, 1);
5360   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
5361   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
5362   PetscCheck(reuse != MAT_INPLACE_MATRIX || mat == *B, PetscObjectComm((PetscObject)mat), PETSC_ERR_SUP, "MAT_INPLACE_MATRIX requires last matrix to match first");
5363   PetscCheck(reuse != MAT_REUSE_MATRIX || mat != *B, PetscObjectComm((PetscObject)mat), PETSC_ERR_SUP, "Perhaps you mean MAT_INPLACE_MATRIX");
5364   MatCheckPreallocated(mat, 1);
5365   if (reuse == MAT_REUSE_MATRIX) {
5366     PetscCall(PetscObjectQuery((PetscObject)*B, "MatTransposeParent", (PetscObject *)&rB));
5367     PetscCheck(rB, PetscObjectComm((PetscObject)*B), PETSC_ERR_ARG_WRONG, "Reuse matrix used was not generated from call to MatTranspose(). Suggest MatTransposeSetPrecursor().");
5368     PetscCall(PetscContainerGetPointer(rB, (void **)&rb));
5369     PetscCheck(rb->id == ((PetscObject)mat)->id, PetscObjectComm((PetscObject)*B), PETSC_ERR_ARG_WRONG, "Reuse matrix used was not generated from input matrix");
5370     if (rb->state == ((PetscObject)mat)->state) PetscFunctionReturn(PETSC_SUCCESS);
5371   }
5372 
5373   PetscCall(PetscLogEventBegin(MAT_Transpose, mat, 0, 0, 0));
5374   if (reuse != MAT_INPLACE_MATRIX || mat->symmetric != PETSC_BOOL3_TRUE) {
5375     PetscUseTypeMethod(mat, transpose, reuse, B);
5376     PetscCall(PetscObjectStateIncrease((PetscObject)*B));
5377   }
5378   PetscCall(PetscLogEventEnd(MAT_Transpose, mat, 0, 0, 0));
5379 
5380   if (reuse == MAT_INITIAL_MATRIX) PetscCall(MatTransposeSetPrecursor(mat, *B));
5381   if (reuse != MAT_INPLACE_MATRIX) {
5382     PetscCall(PetscObjectQuery((PetscObject)*B, "MatTransposeParent", (PetscObject *)&rB));
5383     PetscCall(PetscContainerGetPointer(rB, (void **)&rb));
5384     rb->state        = ((PetscObject)mat)->state;
5385     rb->nonzerostate = mat->nonzerostate;
5386   }
5387   PetscFunctionReturn(PETSC_SUCCESS);
5388 }
5389 
5390 /*@
5391   MatTransposeSymbolic - Computes the symbolic part of the transpose of a matrix.
5392 
5393   Collective
5394 
5395   Input Parameter:
5396 . A - the matrix to transpose
5397 
5398   Output Parameter:
5399 . 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
5400       numerical portion.
5401 
5402   Level: intermediate
5403 
5404   Note:
5405   This is not supported for many matrix types, use `MatTranspose()` in those cases
5406 
5407 .seealso: [](ch_matrices), `Mat`, `MatTransposeSetPrecursor()`, `MatTranspose()`, `MatMultTranspose()`, `MatMultTransposeAdd()`, `MatIsTranspose()`, `MatReuse`, `MAT_INITIAL_MATRIX`, `MAT_REUSE_MATRIX`, `MAT_INPLACE_MATRIX`
5408 @*/
5409 PetscErrorCode MatTransposeSymbolic(Mat A, Mat *B)
5410 {
5411   PetscFunctionBegin;
5412   PetscValidHeaderSpecific(A, MAT_CLASSID, 1);
5413   PetscValidType(A, 1);
5414   PetscCheck(A->assembled, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
5415   PetscCheck(!A->factortype, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
5416   PetscCall(PetscLogEventBegin(MAT_Transpose, A, 0, 0, 0));
5417   PetscUseTypeMethod(A, transposesymbolic, B);
5418   PetscCall(PetscLogEventEnd(MAT_Transpose, A, 0, 0, 0));
5419 
5420   PetscCall(MatTransposeSetPrecursor(A, *B));
5421   PetscFunctionReturn(PETSC_SUCCESS);
5422 }
5423 
5424 PetscErrorCode MatTransposeCheckNonzeroState_Private(Mat A, Mat B)
5425 {
5426   PetscContainer  rB;
5427   MatParentState *rb;
5428 
5429   PetscFunctionBegin;
5430   PetscValidHeaderSpecific(A, MAT_CLASSID, 1);
5431   PetscValidType(A, 1);
5432   PetscCheck(A->assembled, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
5433   PetscCheck(!A->factortype, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
5434   PetscCall(PetscObjectQuery((PetscObject)B, "MatTransposeParent", (PetscObject *)&rB));
5435   PetscCheck(rB, PetscObjectComm((PetscObject)B), PETSC_ERR_ARG_WRONG, "Reuse matrix used was not generated from call to MatTranspose()");
5436   PetscCall(PetscContainerGetPointer(rB, (void **)&rb));
5437   PetscCheck(rb->id == ((PetscObject)A)->id, PetscObjectComm((PetscObject)B), PETSC_ERR_ARG_WRONG, "Reuse matrix used was not generated from input matrix");
5438   PetscCheck(rb->nonzerostate == A->nonzerostate, PetscObjectComm((PetscObject)B), PETSC_ERR_ARG_WRONGSTATE, "Reuse matrix has changed nonzero structure");
5439   PetscFunctionReturn(PETSC_SUCCESS);
5440 }
5441 
5442 /*@
5443   MatIsTranspose - Test whether a matrix is another one's transpose,
5444   or its own, in which case it tests symmetry.
5445 
5446   Collective
5447 
5448   Input Parameters:
5449 + A   - the matrix to test
5450 . B   - the matrix to test against, this can equal the first parameter
5451 - tol - tolerance, differences between entries smaller than this are counted as zero
5452 
5453   Output Parameter:
5454 . flg - the result
5455 
5456   Level: intermediate
5457 
5458   Notes:
5459   The sequential algorithm has a running time of the order of the number of nonzeros; the parallel
5460   test involves parallel copies of the block off-diagonal parts of the matrix.
5461 
5462 .seealso: [](ch_matrices), `Mat`, `MatTranspose()`, `MatIsSymmetric()`, `MatIsHermitian()`
5463 @*/
5464 PetscErrorCode MatIsTranspose(Mat A, Mat B, PetscReal tol, PetscBool *flg)
5465 {
5466   PetscErrorCode (*f)(Mat, Mat, PetscReal, PetscBool *), (*g)(Mat, Mat, PetscReal, PetscBool *);
5467 
5468   PetscFunctionBegin;
5469   PetscValidHeaderSpecific(A, MAT_CLASSID, 1);
5470   PetscValidHeaderSpecific(B, MAT_CLASSID, 2);
5471   PetscAssertPointer(flg, 4);
5472   PetscCall(PetscObjectQueryFunction((PetscObject)A, "MatIsTranspose_C", &f));
5473   PetscCall(PetscObjectQueryFunction((PetscObject)B, "MatIsTranspose_C", &g));
5474   *flg = PETSC_FALSE;
5475   if (f && g) {
5476     PetscCheck(f == g, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_NOTSAMETYPE, "Matrices do not have the same comparator for symmetry test");
5477     PetscCall((*f)(A, B, tol, flg));
5478   } else {
5479     MatType mattype;
5480 
5481     PetscCall(MatGetType(f ? B : A, &mattype));
5482     SETERRQ(PETSC_COMM_SELF, PETSC_ERR_SUP, "Matrix of type %s does not support checking for transpose", mattype);
5483   }
5484   PetscFunctionReturn(PETSC_SUCCESS);
5485 }
5486 
5487 /*@
5488   MatHermitianTranspose - Computes an in-place or out-of-place Hermitian transpose of a matrix in complex conjugate.
5489 
5490   Collective
5491 
5492   Input Parameters:
5493 + mat   - the matrix to transpose and complex conjugate
5494 - reuse - either `MAT_INITIAL_MATRIX`, `MAT_REUSE_MATRIX`, or `MAT_INPLACE_MATRIX`
5495 
5496   Output Parameter:
5497 . B - the Hermitian transpose
5498 
5499   Level: intermediate
5500 
5501 .seealso: [](ch_matrices), `Mat`, `MatTranspose()`, `MatMultTranspose()`, `MatMultTransposeAdd()`, `MatIsTranspose()`, `MatReuse`
5502 @*/
5503 PetscErrorCode MatHermitianTranspose(Mat mat, MatReuse reuse, Mat *B)
5504 {
5505   PetscFunctionBegin;
5506   PetscCall(MatTranspose(mat, reuse, B));
5507 #if defined(PETSC_USE_COMPLEX)
5508   PetscCall(MatConjugate(*B));
5509 #endif
5510   PetscFunctionReturn(PETSC_SUCCESS);
5511 }
5512 
5513 /*@
5514   MatIsHermitianTranspose - Test whether a matrix is another one's Hermitian transpose,
5515 
5516   Collective
5517 
5518   Input Parameters:
5519 + A   - the matrix to test
5520 . B   - the matrix to test against, this can equal the first parameter
5521 - tol - tolerance, differences between entries smaller than this are counted as zero
5522 
5523   Output Parameter:
5524 . flg - the result
5525 
5526   Level: intermediate
5527 
5528   Notes:
5529   Only available for `MATAIJ` matrices.
5530 
5531   The sequential algorithm
5532   has a running time of the order of the number of nonzeros; the parallel
5533   test involves parallel copies of the block off-diagonal parts of the matrix.
5534 
5535 .seealso: [](ch_matrices), `Mat`, `MatTranspose()`, `MatIsSymmetric()`, `MatIsHermitian()`, `MatIsTranspose()`
5536 @*/
5537 PetscErrorCode MatIsHermitianTranspose(Mat A, Mat B, PetscReal tol, PetscBool *flg)
5538 {
5539   PetscErrorCode (*f)(Mat, Mat, PetscReal, PetscBool *), (*g)(Mat, Mat, PetscReal, PetscBool *);
5540 
5541   PetscFunctionBegin;
5542   PetscValidHeaderSpecific(A, MAT_CLASSID, 1);
5543   PetscValidHeaderSpecific(B, MAT_CLASSID, 2);
5544   PetscAssertPointer(flg, 4);
5545   PetscCall(PetscObjectQueryFunction((PetscObject)A, "MatIsHermitianTranspose_C", &f));
5546   PetscCall(PetscObjectQueryFunction((PetscObject)B, "MatIsHermitianTranspose_C", &g));
5547   if (f && g) {
5548     PetscCheck(f != g, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_NOTSAMETYPE, "Matrices do not have the same comparator for Hermitian test");
5549     PetscCall((*f)(A, B, tol, flg));
5550   }
5551   PetscFunctionReturn(PETSC_SUCCESS);
5552 }
5553 
5554 /*@
5555   MatPermute - Creates a new matrix with rows and columns permuted from the
5556   original.
5557 
5558   Collective
5559 
5560   Input Parameters:
5561 + mat - the matrix to permute
5562 . row - row permutation, each processor supplies only the permutation for its rows
5563 - col - column permutation, each processor supplies only the permutation for its columns
5564 
5565   Output Parameter:
5566 . B - the permuted matrix
5567 
5568   Level: advanced
5569 
5570   Note:
5571   The index sets map from row/col of permuted matrix to row/col of original matrix.
5572   The index sets should be on the same communicator as mat and have the same local sizes.
5573 
5574   Developer Note:
5575   If you want to implement `MatPermute()` for a matrix type, and your approach doesn't
5576   exploit the fact that row and col are permutations, consider implementing the
5577   more general `MatCreateSubMatrix()` instead.
5578 
5579 .seealso: [](ch_matrices), `Mat`, `MatGetOrdering()`, `ISAllGather()`, `MatCreateSubMatrix()`
5580 @*/
5581 PetscErrorCode MatPermute(Mat mat, IS row, IS col, Mat *B)
5582 {
5583   PetscFunctionBegin;
5584   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
5585   PetscValidType(mat, 1);
5586   PetscValidHeaderSpecific(row, IS_CLASSID, 2);
5587   PetscValidHeaderSpecific(col, IS_CLASSID, 3);
5588   PetscAssertPointer(B, 4);
5589   PetscCheckSameComm(mat, 1, row, 2);
5590   if (row != col) PetscCheckSameComm(row, 2, col, 3);
5591   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
5592   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
5593   PetscCheck(mat->ops->permute || mat->ops->createsubmatrix, PETSC_COMM_SELF, PETSC_ERR_SUP, "MatPermute not available for Mat type %s", ((PetscObject)mat)->type_name);
5594   MatCheckPreallocated(mat, 1);
5595 
5596   if (mat->ops->permute) {
5597     PetscUseTypeMethod(mat, permute, row, col, B);
5598     PetscCall(PetscObjectStateIncrease((PetscObject)*B));
5599   } else {
5600     PetscCall(MatCreateSubMatrix(mat, row, col, MAT_INITIAL_MATRIX, B));
5601   }
5602   PetscFunctionReturn(PETSC_SUCCESS);
5603 }
5604 
5605 /*@
5606   MatEqual - Compares two matrices.
5607 
5608   Collective
5609 
5610   Input Parameters:
5611 + A - the first matrix
5612 - B - the second matrix
5613 
5614   Output Parameter:
5615 . flg - `PETSC_TRUE` if the matrices are equal; `PETSC_FALSE` otherwise.
5616 
5617   Level: intermediate
5618 
5619 .seealso: [](ch_matrices), `Mat`
5620 @*/
5621 PetscErrorCode MatEqual(Mat A, Mat B, PetscBool *flg)
5622 {
5623   PetscFunctionBegin;
5624   PetscValidHeaderSpecific(A, MAT_CLASSID, 1);
5625   PetscValidHeaderSpecific(B, MAT_CLASSID, 2);
5626   PetscValidType(A, 1);
5627   PetscValidType(B, 2);
5628   PetscAssertPointer(flg, 3);
5629   PetscCheckSameComm(A, 1, B, 2);
5630   MatCheckPreallocated(A, 1);
5631   MatCheckPreallocated(B, 2);
5632   PetscCheck(A->assembled, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
5633   PetscCheck(B->assembled, PetscObjectComm((PetscObject)B), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
5634   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,
5635              B->cmap->N);
5636   if (A->ops->equal && A->ops->equal == B->ops->equal) {
5637     PetscUseTypeMethod(A, equal, B, flg);
5638   } else {
5639     PetscCall(MatMultEqual(A, B, 10, flg));
5640   }
5641   PetscFunctionReturn(PETSC_SUCCESS);
5642 }
5643 
5644 /*@
5645   MatDiagonalScale - Scales a matrix on the left and right by diagonal
5646   matrices that are stored as vectors.  Either of the two scaling
5647   matrices can be `NULL`.
5648 
5649   Collective
5650 
5651   Input Parameters:
5652 + mat - the matrix to be scaled
5653 . l   - the left scaling vector (or `NULL`)
5654 - r   - the right scaling vector (or `NULL`)
5655 
5656   Level: intermediate
5657 
5658   Note:
5659   `MatDiagonalScale()` computes $A = LAR$, where
5660   L = a diagonal matrix (stored as a vector), R = a diagonal matrix (stored as a vector)
5661   The L scales the rows of the matrix, the R scales the columns of the matrix.
5662 
5663 .seealso: [](ch_matrices), `Mat`, `MatScale()`, `MatShift()`, `MatDiagonalSet()`
5664 @*/
5665 PetscErrorCode MatDiagonalScale(Mat mat, Vec l, Vec r)
5666 {
5667   PetscFunctionBegin;
5668   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
5669   PetscValidType(mat, 1);
5670   if (l) {
5671     PetscValidHeaderSpecific(l, VEC_CLASSID, 2);
5672     PetscCheckSameComm(mat, 1, l, 2);
5673   }
5674   if (r) {
5675     PetscValidHeaderSpecific(r, VEC_CLASSID, 3);
5676     PetscCheckSameComm(mat, 1, r, 3);
5677   }
5678   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
5679   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
5680   MatCheckPreallocated(mat, 1);
5681   if (!l && !r) PetscFunctionReturn(PETSC_SUCCESS);
5682 
5683   PetscCall(PetscLogEventBegin(MAT_Scale, mat, 0, 0, 0));
5684   PetscUseTypeMethod(mat, diagonalscale, l, r);
5685   PetscCall(PetscLogEventEnd(MAT_Scale, mat, 0, 0, 0));
5686   PetscCall(PetscObjectStateIncrease((PetscObject)mat));
5687   if (l != r) mat->symmetric = PETSC_BOOL3_FALSE;
5688   PetscFunctionReturn(PETSC_SUCCESS);
5689 }
5690 
5691 /*@
5692   MatScale - Scales all elements of a matrix by a given number.
5693 
5694   Logically Collective
5695 
5696   Input Parameters:
5697 + mat - the matrix to be scaled
5698 - a   - the scaling value
5699 
5700   Level: intermediate
5701 
5702 .seealso: [](ch_matrices), `Mat`, `MatDiagonalScale()`
5703 @*/
5704 PetscErrorCode MatScale(Mat mat, PetscScalar a)
5705 {
5706   PetscFunctionBegin;
5707   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
5708   PetscValidType(mat, 1);
5709   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
5710   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
5711   PetscValidLogicalCollectiveScalar(mat, a, 2);
5712   MatCheckPreallocated(mat, 1);
5713 
5714   PetscCall(PetscLogEventBegin(MAT_Scale, mat, 0, 0, 0));
5715   if (a != (PetscScalar)1.0) {
5716     PetscUseTypeMethod(mat, scale, a);
5717     PetscCall(PetscObjectStateIncrease((PetscObject)mat));
5718   }
5719   PetscCall(PetscLogEventEnd(MAT_Scale, mat, 0, 0, 0));
5720   PetscFunctionReturn(PETSC_SUCCESS);
5721 }
5722 
5723 /*@
5724   MatNorm - Calculates various norms of a matrix.
5725 
5726   Collective
5727 
5728   Input Parameters:
5729 + mat  - the matrix
5730 - type - the type of norm, `NORM_1`, `NORM_FROBENIUS`, `NORM_INFINITY`
5731 
5732   Output Parameter:
5733 . nrm - the resulting norm
5734 
5735   Level: intermediate
5736 
5737 .seealso: [](ch_matrices), `Mat`
5738 @*/
5739 PetscErrorCode MatNorm(Mat mat, NormType type, PetscReal *nrm)
5740 {
5741   PetscFunctionBegin;
5742   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
5743   PetscValidType(mat, 1);
5744   PetscAssertPointer(nrm, 3);
5745 
5746   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
5747   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
5748   MatCheckPreallocated(mat, 1);
5749 
5750   PetscUseTypeMethod(mat, norm, type, nrm);
5751   PetscFunctionReturn(PETSC_SUCCESS);
5752 }
5753 
5754 /*
5755      This variable is used to prevent counting of MatAssemblyBegin() that
5756    are called from within a MatAssemblyEnd().
5757 */
5758 static PetscInt MatAssemblyEnd_InUse = 0;
5759 /*@
5760   MatAssemblyBegin - Begins assembling the matrix.  This routine should
5761   be called after completing all calls to `MatSetValues()`.
5762 
5763   Collective
5764 
5765   Input Parameters:
5766 + mat  - the matrix
5767 - type - type of assembly, either `MAT_FLUSH_ASSEMBLY` or `MAT_FINAL_ASSEMBLY`
5768 
5769   Level: beginner
5770 
5771   Notes:
5772   `MatSetValues()` generally caches the values that belong to other MPI processes.  The matrix is ready to
5773   use only after `MatAssemblyBegin()` and `MatAssemblyEnd()` have been called.
5774 
5775   Use `MAT_FLUSH_ASSEMBLY` when switching between `ADD_VALUES` and `INSERT_VALUES`
5776   in `MatSetValues()`; use `MAT_FINAL_ASSEMBLY` for the final assembly before
5777   using the matrix.
5778 
5779   ALL processes that share a matrix MUST call `MatAssemblyBegin()` and `MatAssemblyEnd()` the SAME NUMBER of times, and each time with the
5780   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
5781   a global collective operation requiring all processes that share the matrix.
5782 
5783   Space for preallocated nonzeros that is not filled by a call to `MatSetValues()` or a related routine are compressed
5784   out by assembly. If you intend to use that extra space on a subsequent assembly, be sure to insert explicit zeros
5785   before `MAT_FINAL_ASSEMBLY` so the space is not compressed out.
5786 
5787 .seealso: [](ch_matrices), `Mat`, `MatAssemblyEnd()`, `MatSetValues()`, `MatAssembled()`
5788 @*/
5789 PetscErrorCode MatAssemblyBegin(Mat mat, MatAssemblyType type)
5790 {
5791   PetscFunctionBegin;
5792   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
5793   PetscValidType(mat, 1);
5794   MatCheckPreallocated(mat, 1);
5795   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix. Did you forget to call MatSetUnfactored()?");
5796   if (mat->assembled) {
5797     mat->was_assembled = PETSC_TRUE;
5798     mat->assembled     = PETSC_FALSE;
5799   }
5800 
5801   if (!MatAssemblyEnd_InUse) {
5802     PetscCall(PetscLogEventBegin(MAT_AssemblyBegin, mat, 0, 0, 0));
5803     PetscTryTypeMethod(mat, assemblybegin, type);
5804     PetscCall(PetscLogEventEnd(MAT_AssemblyBegin, mat, 0, 0, 0));
5805   } else PetscTryTypeMethod(mat, assemblybegin, type);
5806   PetscFunctionReturn(PETSC_SUCCESS);
5807 }
5808 
5809 /*@
5810   MatAssembled - Indicates if a matrix has been assembled and is ready for
5811   use; for example, in matrix-vector product.
5812 
5813   Not Collective
5814 
5815   Input Parameter:
5816 . mat - the matrix
5817 
5818   Output Parameter:
5819 . assembled - `PETSC_TRUE` or `PETSC_FALSE`
5820 
5821   Level: advanced
5822 
5823 .seealso: [](ch_matrices), `Mat`, `MatAssemblyEnd()`, `MatSetValues()`, `MatAssemblyBegin()`
5824 @*/
5825 PetscErrorCode MatAssembled(Mat mat, PetscBool *assembled)
5826 {
5827   PetscFunctionBegin;
5828   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
5829   PetscAssertPointer(assembled, 2);
5830   *assembled = mat->assembled;
5831   PetscFunctionReturn(PETSC_SUCCESS);
5832 }
5833 
5834 /*@
5835   MatAssemblyEnd - Completes assembling the matrix.  This routine should
5836   be called after `MatAssemblyBegin()`.
5837 
5838   Collective
5839 
5840   Input Parameters:
5841 + mat  - the matrix
5842 - type - type of assembly, either `MAT_FLUSH_ASSEMBLY` or `MAT_FINAL_ASSEMBLY`
5843 
5844   Options Database Keys:
5845 + -mat_view ::ascii_info             - Prints info on matrix at conclusion of `MatAssemblyEnd()`
5846 . -mat_view ::ascii_info_detail      - Prints more detailed info
5847 . -mat_view                          - Prints matrix in ASCII format
5848 . -mat_view ::ascii_matlab           - Prints matrix in MATLAB format
5849 . -mat_view draw                     - draws nonzero structure of matrix, using `MatView()` and `PetscDrawOpenX()`.
5850 . -display <name>                    - Sets display name (default is host)
5851 . -draw_pause <sec>                  - Sets number of seconds to pause after display
5852 . -mat_view socket                   - Sends matrix to socket, can be accessed from MATLAB (See [Using MATLAB with PETSc](ch_matlab))
5853 . -viewer_socket_machine <machine>   - Machine to use for socket
5854 . -viewer_socket_port <port>         - Port number to use for socket
5855 - -mat_view binary:filename[:append] - Save matrix to file in binary format
5856 
5857   Level: beginner
5858 
5859 .seealso: [](ch_matrices), `Mat`, `MatAssemblyBegin()`, `MatSetValues()`, `PetscDrawOpenX()`, `PetscDrawCreate()`, `MatView()`, `MatAssembled()`, `PetscViewerSocketOpen()`
5860 @*/
5861 PetscErrorCode MatAssemblyEnd(Mat mat, MatAssemblyType type)
5862 {
5863   static PetscInt inassm = 0;
5864   PetscBool       flg    = PETSC_FALSE;
5865 
5866   PetscFunctionBegin;
5867   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
5868   PetscValidType(mat, 1);
5869 
5870   inassm++;
5871   MatAssemblyEnd_InUse++;
5872   if (MatAssemblyEnd_InUse == 1) { /* Do the logging only the first time through */
5873     PetscCall(PetscLogEventBegin(MAT_AssemblyEnd, mat, 0, 0, 0));
5874     PetscTryTypeMethod(mat, assemblyend, type);
5875     PetscCall(PetscLogEventEnd(MAT_AssemblyEnd, mat, 0, 0, 0));
5876   } else PetscTryTypeMethod(mat, assemblyend, type);
5877 
5878   /* Flush assembly is not a true assembly */
5879   if (type != MAT_FLUSH_ASSEMBLY) {
5880     if (mat->num_ass) {
5881       if (!mat->symmetry_eternal) {
5882         mat->symmetric = PETSC_BOOL3_UNKNOWN;
5883         mat->hermitian = PETSC_BOOL3_UNKNOWN;
5884       }
5885       if (!mat->structural_symmetry_eternal && mat->ass_nonzerostate != mat->nonzerostate) mat->structurally_symmetric = PETSC_BOOL3_UNKNOWN;
5886       if (!mat->spd_eternal) mat->spd = PETSC_BOOL3_UNKNOWN;
5887     }
5888     mat->num_ass++;
5889     mat->assembled        = PETSC_TRUE;
5890     mat->ass_nonzerostate = mat->nonzerostate;
5891   }
5892 
5893   mat->insertmode = NOT_SET_VALUES;
5894   MatAssemblyEnd_InUse--;
5895   PetscCall(PetscObjectStateIncrease((PetscObject)mat));
5896   if (inassm == 1 && type != MAT_FLUSH_ASSEMBLY) {
5897     PetscCall(MatViewFromOptions(mat, NULL, "-mat_view"));
5898 
5899     if (mat->checksymmetryonassembly) {
5900       PetscCall(MatIsSymmetric(mat, mat->checksymmetrytol, &flg));
5901       if (flg) {
5902         PetscCall(PetscPrintf(PetscObjectComm((PetscObject)mat), "Matrix is symmetric (tolerance %g)\n", (double)mat->checksymmetrytol));
5903       } else {
5904         PetscCall(PetscPrintf(PetscObjectComm((PetscObject)mat), "Matrix is not symmetric (tolerance %g)\n", (double)mat->checksymmetrytol));
5905       }
5906     }
5907     if (mat->nullsp && mat->checknullspaceonassembly) PetscCall(MatNullSpaceTest(mat->nullsp, mat, NULL));
5908   }
5909   inassm--;
5910   PetscFunctionReturn(PETSC_SUCCESS);
5911 }
5912 
5913 // PetscClangLinter pragma disable: -fdoc-section-header-unknown
5914 /*@
5915   MatSetOption - Sets a parameter option for a matrix. Some options
5916   may be specific to certain storage formats.  Some options
5917   determine how values will be inserted (or added). Sorted,
5918   row-oriented input will generally assemble the fastest. The default
5919   is row-oriented.
5920 
5921   Logically Collective for certain operations, such as `MAT_SPD`, not collective for `MAT_ROW_ORIENTED`, see `MatOption`
5922 
5923   Input Parameters:
5924 + mat - the matrix
5925 . op  - the option, one of those listed below (and possibly others),
5926 - flg - turn the option on (`PETSC_TRUE`) or off (`PETSC_FALSE`)
5927 
5928   Options Describing Matrix Structure:
5929 + `MAT_SPD`                         - symmetric positive definite
5930 . `MAT_SYMMETRIC`                   - symmetric in terms of both structure and value
5931 . `MAT_HERMITIAN`                   - transpose is the complex conjugation
5932 . `MAT_STRUCTURALLY_SYMMETRIC`      - symmetric nonzero structure
5933 . `MAT_SYMMETRY_ETERNAL`            - indicates the symmetry (or Hermitian structure) or its absence will persist through any changes to the matrix
5934 . `MAT_STRUCTURAL_SYMMETRY_ETERNAL` - indicates the structural symmetry or its absence will persist through any changes to the matrix
5935 . `MAT_SPD_ETERNAL`                 - indicates the value of `MAT_SPD` (true or false) will persist through any changes to the matrix
5936 
5937    These are not really options of the matrix, they are knowledge about the structure of the matrix that users may provide so that they
5938    do not need to be computed (usually at a high cost)
5939 
5940    Options For Use with `MatSetValues()`:
5941    Insert a logically dense subblock, which can be
5942 . `MAT_ROW_ORIENTED`                - row-oriented (default)
5943 
5944    These options reflect the data you pass in with `MatSetValues()`; it has
5945    nothing to do with how the data is stored internally in the matrix
5946    data structure.
5947 
5948    When (re)assembling a matrix, we can restrict the input for
5949    efficiency/debugging purposes.  These options include
5950 . `MAT_NEW_NONZERO_LOCATIONS`       - additional insertions will be allowed if they generate a new nonzero (slow)
5951 . `MAT_FORCE_DIAGONAL_ENTRIES`      - forces diagonal entries to be allocated
5952 . `MAT_IGNORE_OFF_PROC_ENTRIES`     - drops off-processor entries
5953 . `MAT_NEW_NONZERO_LOCATION_ERR`    - generates an error for new matrix entry
5954 . `MAT_USE_HASH_TABLE`              - uses a hash table to speed up matrix assembly
5955 . `MAT_NO_OFF_PROC_ENTRIES`         - you know each process will only set values for its own rows, will generate an error if
5956         any process sets values for another process. This avoids all reductions in the MatAssembly routines and thus improves
5957         performance for very large process counts.
5958 - `MAT_SUBSET_OFF_PROC_ENTRIES`     - you know that the first assembly after setting this flag will set a superset
5959         of the off-process entries required for all subsequent assemblies. This avoids a rendezvous step in the MatAssembly
5960         functions, instead sending only neighbor messages.
5961 
5962   Level: intermediate
5963 
5964   Notes:
5965   Except for `MAT_UNUSED_NONZERO_LOCATION_ERR` and  `MAT_ROW_ORIENTED` all processes that share the matrix must pass the same value in flg!
5966 
5967   Some options are relevant only for particular matrix types and
5968   are thus ignored by others.  Other options are not supported by
5969   certain matrix types and will generate an error message if set.
5970 
5971   If using Fortran to compute a matrix, one may need to
5972   use the column-oriented option (or convert to the row-oriented
5973   format).
5974 
5975   `MAT_NEW_NONZERO_LOCATIONS` set to `PETSC_FALSE` indicates that any add or insertion
5976   that would generate a new entry in the nonzero structure is instead
5977   ignored.  Thus, if memory has not already been allocated for this particular
5978   data, then the insertion is ignored. For dense matrices, in which
5979   the entire array is allocated, no entries are ever ignored.
5980   Set after the first `MatAssemblyEnd()`. If this option is set, then the `MatAssemblyBegin()`/`MatAssemblyEnd()` processes has one less global reduction
5981 
5982   `MAT_NEW_NONZERO_LOCATION_ERR` set to PETSC_TRUE indicates that any add or insertion
5983   that would generate a new entry in the nonzero structure instead produces
5984   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
5985 
5986   `MAT_NEW_NONZERO_ALLOCATION_ERR` set to `PETSC_TRUE` indicates that any add or insertion
5987   that would generate a new entry that has not been preallocated will
5988   instead produce an error. (Currently supported for `MATAIJ` and `MATBAIJ` formats
5989   only.) This is a useful flag when debugging matrix memory preallocation.
5990   If this option is set, then the `MatAssemblyBegin()`/`MatAssemblyEnd()` processes has one less global reduction
5991 
5992   `MAT_IGNORE_OFF_PROC_ENTRIES` set to `PETSC_TRUE` indicates entries destined for
5993   other processors should be dropped, rather than stashed.
5994   This is useful if you know that the "owning" processor is also
5995   always generating the correct matrix entries, so that PETSc need
5996   not transfer duplicate entries generated on another processor.
5997 
5998   `MAT_USE_HASH_TABLE` indicates that a hash table be used to improve the
5999   searches during matrix assembly. When this flag is set, the hash table
6000   is created during the first matrix assembly. This hash table is
6001   used the next time through, during `MatSetValues()`/`MatSetValuesBlocked()`
6002   to improve the searching of indices. `MAT_NEW_NONZERO_LOCATIONS` flag
6003   should be used with `MAT_USE_HASH_TABLE` flag. This option is currently
6004   supported by `MATMPIBAIJ` format only.
6005 
6006   `MAT_KEEP_NONZERO_PATTERN` indicates when `MatZeroRows()` is called the zeroed entries
6007   are kept in the nonzero structure. This flag is not used for `MatZeroRowsColumns()`
6008 
6009   `MAT_IGNORE_ZERO_ENTRIES` - for `MATAIJ` and `MATIS` matrices this will stop zero values from creating
6010   a zero location in the matrix
6011 
6012   `MAT_USE_INODES` - indicates using inode version of the code - works with `MATAIJ` matrix types
6013 
6014   `MAT_NO_OFF_PROC_ZERO_ROWS` - you know each process will only zero its own rows. This avoids all reductions in the
6015   zero row routines and thus improves performance for very large process counts.
6016 
6017   `MAT_IGNORE_LOWER_TRIANGULAR` - For `MATSBAIJ` matrices will ignore any insertions you make in the lower triangular
6018   part of the matrix (since they should match the upper triangular part).
6019 
6020   `MAT_SORTED_FULL` - each process provides exactly its local rows; all column indices for a given row are passed in a
6021   single call to `MatSetValues()`, preallocation is perfect, row-oriented, `INSERT_VALUES` is used. Common
6022   with finite difference schemes with non-periodic boundary conditions.
6023 
6024   Developer Note:
6025   `MAT_SYMMETRY_ETERNAL`, `MAT_STRUCTURAL_SYMMETRY_ETERNAL`, and `MAT_SPD_ETERNAL` are used by `MatAssemblyEnd()` and in other
6026   places where otherwise the value of `MAT_SYMMETRIC`, `MAT_STRUCTURALLY_SYMMETRIC` or `MAT_SPD` would need to be changed back
6027   to `PETSC_BOOL3_UNKNOWN` because the matrix values had changed so the code cannot be certain that the related property had
6028   not changed.
6029 
6030 .seealso: [](ch_matrices), `MatOption`, `Mat`, `MatGetOption()`
6031 @*/
6032 PetscErrorCode MatSetOption(Mat mat, MatOption op, PetscBool flg)
6033 {
6034   PetscFunctionBegin;
6035   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
6036   if (op > 0) {
6037     PetscValidLogicalCollectiveEnum(mat, op, 2);
6038     PetscValidLogicalCollectiveBool(mat, flg, 3);
6039   }
6040 
6041   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);
6042 
6043   switch (op) {
6044   case MAT_FORCE_DIAGONAL_ENTRIES:
6045     mat->force_diagonals = flg;
6046     PetscFunctionReturn(PETSC_SUCCESS);
6047   case MAT_NO_OFF_PROC_ENTRIES:
6048     mat->nooffprocentries = flg;
6049     PetscFunctionReturn(PETSC_SUCCESS);
6050   case MAT_SUBSET_OFF_PROC_ENTRIES:
6051     mat->assembly_subset = flg;
6052     if (!mat->assembly_subset) { /* See the same logic in VecAssembly wrt VEC_SUBSET_OFF_PROC_ENTRIES */
6053 #if !defined(PETSC_HAVE_MPIUNI)
6054       PetscCall(MatStashScatterDestroy_BTS(&mat->stash));
6055 #endif
6056       mat->stash.first_assembly_done = PETSC_FALSE;
6057     }
6058     PetscFunctionReturn(PETSC_SUCCESS);
6059   case MAT_NO_OFF_PROC_ZERO_ROWS:
6060     mat->nooffproczerorows = flg;
6061     PetscFunctionReturn(PETSC_SUCCESS);
6062   case MAT_SPD:
6063     if (flg) {
6064       mat->spd                    = PETSC_BOOL3_TRUE;
6065       mat->symmetric              = PETSC_BOOL3_TRUE;
6066       mat->structurally_symmetric = PETSC_BOOL3_TRUE;
6067     } else {
6068       mat->spd = PETSC_BOOL3_FALSE;
6069     }
6070     break;
6071   case MAT_SYMMETRIC:
6072     mat->symmetric = flg ? PETSC_BOOL3_TRUE : PETSC_BOOL3_FALSE;
6073     if (flg) mat->structurally_symmetric = PETSC_BOOL3_TRUE;
6074 #if !defined(PETSC_USE_COMPLEX)
6075     mat->hermitian = flg ? PETSC_BOOL3_TRUE : PETSC_BOOL3_FALSE;
6076 #endif
6077     break;
6078   case MAT_HERMITIAN:
6079     mat->hermitian = flg ? PETSC_BOOL3_TRUE : PETSC_BOOL3_FALSE;
6080     if (flg) mat->structurally_symmetric = PETSC_BOOL3_TRUE;
6081 #if !defined(PETSC_USE_COMPLEX)
6082     mat->symmetric = flg ? PETSC_BOOL3_TRUE : PETSC_BOOL3_FALSE;
6083 #endif
6084     break;
6085   case MAT_STRUCTURALLY_SYMMETRIC:
6086     mat->structurally_symmetric = flg ? PETSC_BOOL3_TRUE : PETSC_BOOL3_FALSE;
6087     break;
6088   case MAT_SYMMETRY_ETERNAL:
6089     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");
6090     mat->symmetry_eternal = flg;
6091     if (flg) mat->structural_symmetry_eternal = PETSC_TRUE;
6092     break;
6093   case MAT_STRUCTURAL_SYMMETRY_ETERNAL:
6094     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");
6095     mat->structural_symmetry_eternal = flg;
6096     break;
6097   case MAT_SPD_ETERNAL:
6098     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");
6099     mat->spd_eternal = flg;
6100     if (flg) {
6101       mat->structural_symmetry_eternal = PETSC_TRUE;
6102       mat->symmetry_eternal            = PETSC_TRUE;
6103     }
6104     break;
6105   case MAT_STRUCTURE_ONLY:
6106     mat->structure_only = flg;
6107     break;
6108   case MAT_SORTED_FULL:
6109     mat->sortedfull = flg;
6110     break;
6111   default:
6112     break;
6113   }
6114   PetscTryTypeMethod(mat, setoption, op, flg);
6115   PetscFunctionReturn(PETSC_SUCCESS);
6116 }
6117 
6118 /*@
6119   MatGetOption - Gets a parameter option that has been set for a matrix.
6120 
6121   Logically Collective
6122 
6123   Input Parameters:
6124 + mat - the matrix
6125 - op  - the option, this only responds to certain options, check the code for which ones
6126 
6127   Output Parameter:
6128 . flg - turn the option on (`PETSC_TRUE`) or off (`PETSC_FALSE`)
6129 
6130   Level: intermediate
6131 
6132   Notes:
6133   Can only be called after `MatSetSizes()` and `MatSetType()` have been set.
6134 
6135   Certain option values may be unknown, for those use the routines `MatIsSymmetric()`, `MatIsHermitian()`, `MatIsStructurallySymmetric()`, or
6136   `MatIsSymmetricKnown()`, `MatIsHermitianKnown()`, `MatIsStructurallySymmetricKnown()`
6137 
6138 .seealso: [](ch_matrices), `Mat`, `MatOption`, `MatSetOption()`, `MatIsSymmetric()`, `MatIsHermitian()`, `MatIsStructurallySymmetric()`,
6139     `MatIsSymmetricKnown()`, `MatIsHermitianKnown()`, `MatIsStructurallySymmetricKnown()`
6140 @*/
6141 PetscErrorCode MatGetOption(Mat mat, MatOption op, PetscBool *flg)
6142 {
6143   PetscFunctionBegin;
6144   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
6145   PetscValidType(mat, 1);
6146 
6147   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);
6148   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()");
6149 
6150   switch (op) {
6151   case MAT_NO_OFF_PROC_ENTRIES:
6152     *flg = mat->nooffprocentries;
6153     break;
6154   case MAT_NO_OFF_PROC_ZERO_ROWS:
6155     *flg = mat->nooffproczerorows;
6156     break;
6157   case MAT_SYMMETRIC:
6158     SETERRQ(PetscObjectComm((PetscObject)mat), PETSC_ERR_SUP, "Use MatIsSymmetric() or MatIsSymmetricKnown()");
6159     break;
6160   case MAT_HERMITIAN:
6161     SETERRQ(PetscObjectComm((PetscObject)mat), PETSC_ERR_SUP, "Use MatIsHermitian() or MatIsHermitianKnown()");
6162     break;
6163   case MAT_STRUCTURALLY_SYMMETRIC:
6164     SETERRQ(PetscObjectComm((PetscObject)mat), PETSC_ERR_SUP, "Use MatIsStructurallySymmetric() or MatIsStructurallySymmetricKnown()");
6165     break;
6166   case MAT_SPD:
6167     SETERRQ(PetscObjectComm((PetscObject)mat), PETSC_ERR_SUP, "Use MatIsSPDKnown()");
6168     break;
6169   case MAT_SYMMETRY_ETERNAL:
6170     *flg = mat->symmetry_eternal;
6171     break;
6172   case MAT_STRUCTURAL_SYMMETRY_ETERNAL:
6173     *flg = mat->symmetry_eternal;
6174     break;
6175   default:
6176     break;
6177   }
6178   PetscFunctionReturn(PETSC_SUCCESS);
6179 }
6180 
6181 /*@
6182   MatZeroEntries - Zeros all entries of a matrix.  For sparse matrices
6183   this routine retains the old nonzero structure.
6184 
6185   Logically Collective
6186 
6187   Input Parameter:
6188 . mat - the matrix
6189 
6190   Level: intermediate
6191 
6192   Note:
6193   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.
6194   See the Performance chapter of the users manual for information on preallocating matrices.
6195 
6196 .seealso: [](ch_matrices), `Mat`, `MatZeroRows()`, `MatZeroRowsColumns()`
6197 @*/
6198 PetscErrorCode MatZeroEntries(Mat mat)
6199 {
6200   PetscFunctionBegin;
6201   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
6202   PetscValidType(mat, 1);
6203   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
6204   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");
6205   MatCheckPreallocated(mat, 1);
6206 
6207   PetscCall(PetscLogEventBegin(MAT_ZeroEntries, mat, 0, 0, 0));
6208   PetscUseTypeMethod(mat, zeroentries);
6209   PetscCall(PetscLogEventEnd(MAT_ZeroEntries, mat, 0, 0, 0));
6210   PetscCall(PetscObjectStateIncrease((PetscObject)mat));
6211   PetscFunctionReturn(PETSC_SUCCESS);
6212 }
6213 
6214 /*@
6215   MatZeroRowsColumns - Zeros all entries (except possibly the main diagonal)
6216   of a set of rows and columns of a matrix.
6217 
6218   Collective
6219 
6220   Input Parameters:
6221 + mat     - the matrix
6222 . numRows - the number of rows/columns to zero
6223 . rows    - the global row indices
6224 . diag    - value put in the diagonal of the eliminated rows
6225 . x       - optional vector of the solution for zeroed rows (other entries in vector are not used), these must be set before this call
6226 - b       - optional vector of the right-hand side, that will be adjusted by provided solution entries
6227 
6228   Level: intermediate
6229 
6230   Notes:
6231   This routine, along with `MatZeroRows()`, is typically used to eliminate known Dirichlet boundary conditions from a linear system.
6232 
6233   For each zeroed row, the value of the corresponding `b` is set to diag times the value of the corresponding `x`.
6234   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
6235 
6236   If the resulting linear system is to be solved with `KSP` then one can (but does not have to) call `KSPSetInitialGuessNonzero()` to allow the
6237   Krylov method to take advantage of the known solution on the zeroed rows.
6238 
6239   For the parallel case, all processes that share the matrix (i.e.,
6240   those in the communicator used for matrix creation) MUST call this
6241   routine, regardless of whether any rows being zeroed are owned by
6242   them.
6243 
6244   Unlike `MatZeroRows()`, this ignores the `MAT_KEEP_NONZERO_PATTERN` option value set with `MatSetOption()`, it merely zeros those entries in the matrix, but never
6245   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
6246   missing.
6247 
6248   Each processor can indicate any rows in the entire matrix to be zeroed (i.e. each process does NOT have to
6249   list only rows local to itself).
6250 
6251   The option `MAT_NO_OFF_PROC_ZERO_ROWS` does not apply to this routine.
6252 
6253 .seealso: [](ch_matrices), `Mat`, `MatZeroRowsIS()`, `MatZeroRows()`, `MatZeroRowsLocalIS()`, `MatZeroRowsStencil()`, `MatZeroEntries()`, `MatZeroRowsLocal()`, `MatSetOption()`,
6254           `MatZeroRowsColumnsLocal()`, `MatZeroRowsColumnsLocalIS()`, `MatZeroRowsColumnsIS()`, `MatZeroRowsColumnsStencil()`
6255 @*/
6256 PetscErrorCode MatZeroRowsColumns(Mat mat, PetscInt numRows, const PetscInt rows[], PetscScalar diag, Vec x, Vec b)
6257 {
6258   PetscFunctionBegin;
6259   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
6260   PetscValidType(mat, 1);
6261   if (numRows) PetscAssertPointer(rows, 3);
6262   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
6263   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
6264   MatCheckPreallocated(mat, 1);
6265 
6266   PetscUseTypeMethod(mat, zerorowscolumns, numRows, rows, diag, x, b);
6267   PetscCall(MatViewFromOptions(mat, NULL, "-mat_view"));
6268   PetscCall(PetscObjectStateIncrease((PetscObject)mat));
6269   PetscFunctionReturn(PETSC_SUCCESS);
6270 }
6271 
6272 /*@
6273   MatZeroRowsColumnsIS - Zeros all entries (except possibly the main diagonal)
6274   of a set of rows and columns of a matrix.
6275 
6276   Collective
6277 
6278   Input Parameters:
6279 + mat  - the matrix
6280 . is   - the rows to zero
6281 . diag - value put in all diagonals of eliminated rows (0.0 will even eliminate diagonal entry)
6282 . x    - optional vector of solutions for zeroed rows (other entries in vector are not used)
6283 - b    - optional vector of right-hand side, that will be adjusted by provided solution
6284 
6285   Level: intermediate
6286 
6287   Note:
6288   See `MatZeroRowsColumns()` for details on how this routine operates.
6289 
6290 .seealso: [](ch_matrices), `Mat`, `MatZeroRowsIS()`, `MatZeroRowsColumns()`, `MatZeroRowsLocalIS()`, `MatZeroRowsStencil()`, `MatZeroEntries()`, `MatZeroRowsLocal()`, `MatSetOption()`,
6291           `MatZeroRowsColumnsLocal()`, `MatZeroRowsColumnsLocalIS()`, `MatZeroRows()`, `MatZeroRowsColumnsStencil()`
6292 @*/
6293 PetscErrorCode MatZeroRowsColumnsIS(Mat mat, IS is, PetscScalar diag, Vec x, Vec b)
6294 {
6295   PetscInt        numRows;
6296   const PetscInt *rows;
6297 
6298   PetscFunctionBegin;
6299   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
6300   PetscValidHeaderSpecific(is, IS_CLASSID, 2);
6301   PetscValidType(mat, 1);
6302   PetscValidType(is, 2);
6303   PetscCall(ISGetLocalSize(is, &numRows));
6304   PetscCall(ISGetIndices(is, &rows));
6305   PetscCall(MatZeroRowsColumns(mat, numRows, rows, diag, x, b));
6306   PetscCall(ISRestoreIndices(is, &rows));
6307   PetscFunctionReturn(PETSC_SUCCESS);
6308 }
6309 
6310 /*@
6311   MatZeroRows - Zeros all entries (except possibly the main diagonal)
6312   of a set of rows of a matrix.
6313 
6314   Collective
6315 
6316   Input Parameters:
6317 + mat     - the matrix
6318 . numRows - the number of rows to zero
6319 . rows    - the global row indices
6320 . diag    - value put in the diagonal of the zeroed rows
6321 . x       - optional vector of solutions for zeroed rows (other entries in vector are not used), these must be set before this call
6322 - b       - optional vector of right-hand side, that will be adjusted by provided solution entries
6323 
6324   Level: intermediate
6325 
6326   Notes:
6327   This routine, along with `MatZeroRowsColumns()`, is typically used to eliminate known Dirichlet boundary conditions from a linear system.
6328 
6329   For each zeroed row, the value of the corresponding `b` is set to `diag` times the value of the corresponding `x`.
6330 
6331   If the resulting linear system is to be solved with `KSP` then one can (but does not have to) call `KSPSetInitialGuessNonzero()` to allow the
6332   Krylov method to take advantage of the known solution on the zeroed rows.
6333 
6334   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)
6335   from the matrix.
6336 
6337   Unlike `MatZeroRowsColumns()` for the `MATAIJ` and `MATBAIJ` matrix formats this removes the old nonzero structure, from the eliminated rows of the matrix
6338   but does not release memory.  Because of this removal matrix-vector products with the adjusted matrix will be a bit faster. For the dense and block diagonal
6339   formats this does not alter the nonzero structure.
6340 
6341   If the option `MatSetOption`(mat,`MAT_KEEP_NONZERO_PATTERN`,`PETSC_TRUE`) the nonzero structure
6342   of the matrix is not changed the values are
6343   merely zeroed.
6344 
6345   The user can set a value in the diagonal entry (or for the `MATAIJ` format
6346   formats can optionally remove the main diagonal entry from the
6347   nonzero structure as well, by passing 0.0 as the final argument).
6348 
6349   For the parallel case, all processes that share the matrix (i.e.,
6350   those in the communicator used for matrix creation) MUST call this
6351   routine, regardless of whether any rows being zeroed are owned by
6352   them.
6353 
6354   Each processor can indicate any rows in the entire matrix to be zeroed (i.e. each process does NOT have to
6355   list only rows local to itself).
6356 
6357   You can call `MatSetOption`(mat,`MAT_NO_OFF_PROC_ZERO_ROWS`,`PETSC_TRUE`) if each process indicates only rows it
6358   owns that are to be zeroed. This saves a global synchronization in the implementation.
6359 
6360 .seealso: [](ch_matrices), `Mat`, `MatZeroRowsIS()`, `MatZeroRowsColumns()`, `MatZeroRowsLocalIS()`, `MatZeroRowsStencil()`, `MatZeroEntries()`, `MatZeroRowsLocal()`, `MatSetOption()`,
6361           `MatZeroRowsColumnsLocal()`, `MatZeroRowsColumnsLocalIS()`, `MatZeroRowsColumnsIS()`, `MatZeroRowsColumnsStencil()`, `PCREDISTRIBUTE`, `MAT_KEEP_NONZERO_PATTERN`
6362 @*/
6363 PetscErrorCode MatZeroRows(Mat mat, PetscInt numRows, const PetscInt rows[], PetscScalar diag, Vec x, Vec b)
6364 {
6365   PetscFunctionBegin;
6366   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
6367   PetscValidType(mat, 1);
6368   if (numRows) PetscAssertPointer(rows, 3);
6369   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
6370   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
6371   MatCheckPreallocated(mat, 1);
6372 
6373   PetscUseTypeMethod(mat, zerorows, numRows, rows, diag, x, b);
6374   PetscCall(MatViewFromOptions(mat, NULL, "-mat_view"));
6375   PetscCall(PetscObjectStateIncrease((PetscObject)mat));
6376   PetscFunctionReturn(PETSC_SUCCESS);
6377 }
6378 
6379 /*@
6380   MatZeroRowsIS - Zeros all entries (except possibly the main diagonal)
6381   of a set of rows of a matrix.
6382 
6383   Collective
6384 
6385   Input Parameters:
6386 + mat  - the matrix
6387 . is   - index set of rows to remove (if `NULL` then no row is removed)
6388 . diag - value put in all diagonals of eliminated rows
6389 . x    - optional vector of solutions for zeroed rows (other entries in vector are not used)
6390 - b    - optional vector of right-hand side, that will be adjusted by provided solution
6391 
6392   Level: intermediate
6393 
6394   Note:
6395   See `MatZeroRows()` for details on how this routine operates.
6396 
6397 .seealso: [](ch_matrices), `Mat`, `MatZeroRows()`, `MatZeroRowsColumns()`, `MatZeroRowsLocalIS()`, `MatZeroRowsStencil()`, `MatZeroEntries()`, `MatZeroRowsLocal()`, `MatSetOption()`,
6398           `MatZeroRowsColumnsLocal()`, `MatZeroRowsColumnsLocalIS()`, `MatZeroRowsColumnsIS()`, `MatZeroRowsColumnsStencil()`
6399 @*/
6400 PetscErrorCode MatZeroRowsIS(Mat mat, IS is, PetscScalar diag, Vec x, Vec b)
6401 {
6402   PetscInt        numRows = 0;
6403   const PetscInt *rows    = NULL;
6404 
6405   PetscFunctionBegin;
6406   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
6407   PetscValidType(mat, 1);
6408   if (is) {
6409     PetscValidHeaderSpecific(is, IS_CLASSID, 2);
6410     PetscCall(ISGetLocalSize(is, &numRows));
6411     PetscCall(ISGetIndices(is, &rows));
6412   }
6413   PetscCall(MatZeroRows(mat, numRows, rows, diag, x, b));
6414   if (is) PetscCall(ISRestoreIndices(is, &rows));
6415   PetscFunctionReturn(PETSC_SUCCESS);
6416 }
6417 
6418 /*@
6419   MatZeroRowsStencil - Zeros all entries (except possibly the main diagonal)
6420   of a set of rows of a matrix. These rows must be local to the process.
6421 
6422   Collective
6423 
6424   Input Parameters:
6425 + mat     - the matrix
6426 . numRows - the number of rows to remove
6427 . rows    - the grid coordinates (and component number when dof > 1) for matrix rows
6428 . diag    - value put in all diagonals of eliminated rows (0.0 will even eliminate diagonal entry)
6429 . x       - optional vector of solutions for zeroed rows (other entries in vector are not used)
6430 - b       - optional vector of right-hand side, that will be adjusted by provided solution
6431 
6432   Level: intermediate
6433 
6434   Notes:
6435   See `MatZeroRows()` for details on how this routine operates.
6436 
6437   The grid coordinates are across the entire grid, not just the local portion
6438 
6439   For periodic boundary conditions use negative indices for values to the left (below 0; that are to be
6440   obtained by wrapping values from right edge). For values to the right of the last entry using that index plus one
6441   etc to obtain values that obtained by wrapping the values from the left edge. This does not work for anything but the
6442   `DM_BOUNDARY_PERIODIC` boundary type.
6443 
6444   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
6445   a single value per point) you can skip filling those indices.
6446 
6447   Fortran Note:
6448   `idxm` and `idxn` should be declared as
6449 $     MatStencil idxm(4, m)
6450   and the values inserted using
6451 .vb
6452     idxm(MatStencil_i, 1) = i
6453     idxm(MatStencil_j, 1) = j
6454     idxm(MatStencil_k, 1) = k
6455     idxm(MatStencil_c, 1) = c
6456    etc
6457 .ve
6458 
6459 .seealso: [](ch_matrices), `Mat`, `MatZeroRowsIS()`, `MatZeroRowsColumns()`, `MatZeroRowsLocalIS()`, `MatZeroRowsl()`, `MatZeroEntries()`, `MatZeroRowsLocal()`, `MatSetOption()`,
6460           `MatZeroRowsColumnsLocal()`, `MatZeroRowsColumnsLocalIS()`, `MatZeroRowsColumnsIS()`, `MatZeroRowsColumnsStencil()`
6461 @*/
6462 PetscErrorCode MatZeroRowsStencil(Mat mat, PetscInt numRows, const MatStencil rows[], PetscScalar diag, Vec x, Vec b)
6463 {
6464   PetscInt  dim    = mat->stencil.dim;
6465   PetscInt  sdim   = dim - (1 - (PetscInt)mat->stencil.noc);
6466   PetscInt *dims   = mat->stencil.dims + 1;
6467   PetscInt *starts = mat->stencil.starts;
6468   PetscInt *dxm    = (PetscInt *)rows;
6469   PetscInt *jdxm, i, j, tmp, numNewRows = 0;
6470 
6471   PetscFunctionBegin;
6472   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
6473   PetscValidType(mat, 1);
6474   if (numRows) PetscAssertPointer(rows, 3);
6475 
6476   PetscCall(PetscMalloc1(numRows, &jdxm));
6477   for (i = 0; i < numRows; ++i) {
6478     /* Skip unused dimensions (they are ordered k, j, i, c) */
6479     for (j = 0; j < 3 - sdim; ++j) dxm++;
6480     /* Local index in X dir */
6481     tmp = *dxm++ - starts[0];
6482     /* Loop over remaining dimensions */
6483     for (j = 0; j < dim - 1; ++j) {
6484       /* If nonlocal, set index to be negative */
6485       if ((*dxm++ - starts[j + 1]) < 0 || tmp < 0) tmp = PETSC_MIN_INT;
6486       /* Update local index */
6487       else tmp = tmp * dims[j] + *(dxm - 1) - starts[j + 1];
6488     }
6489     /* Skip component slot if necessary */
6490     if (mat->stencil.noc) dxm++;
6491     /* Local row number */
6492     if (tmp >= 0) jdxm[numNewRows++] = tmp;
6493   }
6494   PetscCall(MatZeroRowsLocal(mat, numNewRows, jdxm, diag, x, b));
6495   PetscCall(PetscFree(jdxm));
6496   PetscFunctionReturn(PETSC_SUCCESS);
6497 }
6498 
6499 /*@
6500   MatZeroRowsColumnsStencil - Zeros all row and column entries (except possibly the main diagonal)
6501   of a set of rows and columns of a matrix.
6502 
6503   Collective
6504 
6505   Input Parameters:
6506 + mat     - the matrix
6507 . numRows - the number of rows/columns to remove
6508 . rows    - the grid coordinates (and component number when dof > 1) for matrix rows
6509 . diag    - value put in all diagonals of eliminated rows (0.0 will even eliminate diagonal entry)
6510 . x       - optional vector of solutions for zeroed rows (other entries in vector are not used)
6511 - b       - optional vector of right-hand side, that will be adjusted by provided solution
6512 
6513   Level: intermediate
6514 
6515   Notes:
6516   See `MatZeroRowsColumns()` for details on how this routine operates.
6517 
6518   The grid coordinates are across the entire grid, not just the local portion
6519 
6520   For periodic boundary conditions use negative indices for values to the left (below 0; that are to be
6521   obtained by wrapping values from right edge). For values to the right of the last entry using that index plus one
6522   etc to obtain values that obtained by wrapping the values from the left edge. This does not work for anything but the
6523   `DM_BOUNDARY_PERIODIC` boundary type.
6524 
6525   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
6526   a single value per point) you can skip filling those indices.
6527 
6528   Fortran Note:
6529   `idxm` and `idxn` should be declared as
6530 $     MatStencil idxm(4, m)
6531   and the values inserted using
6532 .vb
6533     idxm(MatStencil_i, 1) = i
6534     idxm(MatStencil_j, 1) = j
6535     idxm(MatStencil_k, 1) = k
6536     idxm(MatStencil_c, 1) = c
6537     etc
6538 .ve
6539 
6540 .seealso: [](ch_matrices), `Mat`, `MatZeroRowsIS()`, `MatZeroRowsColumns()`, `MatZeroRowsLocalIS()`, `MatZeroRowsStencil()`, `MatZeroEntries()`, `MatZeroRowsLocal()`, `MatSetOption()`,
6541           `MatZeroRowsColumnsLocal()`, `MatZeroRowsColumnsLocalIS()`, `MatZeroRowsColumnsIS()`, `MatZeroRows()`
6542 @*/
6543 PetscErrorCode MatZeroRowsColumnsStencil(Mat mat, PetscInt numRows, const MatStencil rows[], PetscScalar diag, Vec x, Vec b)
6544 {
6545   PetscInt  dim    = mat->stencil.dim;
6546   PetscInt  sdim   = dim - (1 - (PetscInt)mat->stencil.noc);
6547   PetscInt *dims   = mat->stencil.dims + 1;
6548   PetscInt *starts = mat->stencil.starts;
6549   PetscInt *dxm    = (PetscInt *)rows;
6550   PetscInt *jdxm, i, j, tmp, numNewRows = 0;
6551 
6552   PetscFunctionBegin;
6553   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
6554   PetscValidType(mat, 1);
6555   if (numRows) PetscAssertPointer(rows, 3);
6556 
6557   PetscCall(PetscMalloc1(numRows, &jdxm));
6558   for (i = 0; i < numRows; ++i) {
6559     /* Skip unused dimensions (they are ordered k, j, i, c) */
6560     for (j = 0; j < 3 - sdim; ++j) dxm++;
6561     /* Local index in X dir */
6562     tmp = *dxm++ - starts[0];
6563     /* Loop over remaining dimensions */
6564     for (j = 0; j < dim - 1; ++j) {
6565       /* If nonlocal, set index to be negative */
6566       if ((*dxm++ - starts[j + 1]) < 0 || tmp < 0) tmp = PETSC_MIN_INT;
6567       /* Update local index */
6568       else tmp = tmp * dims[j] + *(dxm - 1) - starts[j + 1];
6569     }
6570     /* Skip component slot if necessary */
6571     if (mat->stencil.noc) dxm++;
6572     /* Local row number */
6573     if (tmp >= 0) jdxm[numNewRows++] = tmp;
6574   }
6575   PetscCall(MatZeroRowsColumnsLocal(mat, numNewRows, jdxm, diag, x, b));
6576   PetscCall(PetscFree(jdxm));
6577   PetscFunctionReturn(PETSC_SUCCESS);
6578 }
6579 
6580 /*@
6581   MatZeroRowsLocal - Zeros all entries (except possibly the main diagonal)
6582   of a set of rows of a matrix; using local numbering of rows.
6583 
6584   Collective
6585 
6586   Input Parameters:
6587 + mat     - the matrix
6588 . numRows - the number of rows to remove
6589 . rows    - the local row indices
6590 . diag    - value put in all diagonals of eliminated rows
6591 . x       - optional vector of solutions for zeroed rows (other entries in vector are not used)
6592 - b       - optional vector of right-hand side, that will be adjusted by provided solution
6593 
6594   Level: intermediate
6595 
6596   Notes:
6597   Before calling `MatZeroRowsLocal()`, the user must first set the
6598   local-to-global mapping by calling MatSetLocalToGlobalMapping(), this is often already set for matrices obtained with `DMCreateMatrix()`.
6599 
6600   See `MatZeroRows()` for details on how this routine operates.
6601 
6602 .seealso: [](ch_matrices), `Mat`, `MatZeroRowsIS()`, `MatZeroRowsColumns()`, `MatZeroRowsLocalIS()`, `MatZeroRowsStencil()`, `MatZeroEntries()`, `MatZeroRows()`, `MatSetOption()`,
6603           `MatZeroRowsColumnsLocal()`, `MatZeroRowsColumnsLocalIS()`, `MatZeroRowsColumnsIS()`, `MatZeroRowsColumnsStencil()`
6604 @*/
6605 PetscErrorCode MatZeroRowsLocal(Mat mat, PetscInt numRows, const PetscInt rows[], PetscScalar diag, Vec x, Vec b)
6606 {
6607   PetscFunctionBegin;
6608   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
6609   PetscValidType(mat, 1);
6610   if (numRows) PetscAssertPointer(rows, 3);
6611   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
6612   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
6613   MatCheckPreallocated(mat, 1);
6614 
6615   if (mat->ops->zerorowslocal) {
6616     PetscUseTypeMethod(mat, zerorowslocal, numRows, rows, diag, x, b);
6617   } else {
6618     IS              is, newis;
6619     const PetscInt *newRows;
6620 
6621     PetscCheck(mat->rmap->mapping, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Need to provide local to global mapping to matrix first");
6622     PetscCall(ISCreateGeneral(PETSC_COMM_SELF, numRows, rows, PETSC_COPY_VALUES, &is));
6623     PetscCall(ISLocalToGlobalMappingApplyIS(mat->rmap->mapping, is, &newis));
6624     PetscCall(ISGetIndices(newis, &newRows));
6625     PetscUseTypeMethod(mat, zerorows, numRows, newRows, diag, x, b);
6626     PetscCall(ISRestoreIndices(newis, &newRows));
6627     PetscCall(ISDestroy(&newis));
6628     PetscCall(ISDestroy(&is));
6629   }
6630   PetscCall(PetscObjectStateIncrease((PetscObject)mat));
6631   PetscFunctionReturn(PETSC_SUCCESS);
6632 }
6633 
6634 /*@
6635   MatZeroRowsLocalIS - Zeros all entries (except possibly the main diagonal)
6636   of a set of rows of a matrix; using local numbering of rows.
6637 
6638   Collective
6639 
6640   Input Parameters:
6641 + mat  - the matrix
6642 . is   - index set of rows to remove
6643 . diag - value put in all diagonals of eliminated rows
6644 . x    - optional vector of solutions for zeroed rows (other entries in vector are not used)
6645 - b    - optional vector of right-hand side, that will be adjusted by provided solution
6646 
6647   Level: intermediate
6648 
6649   Notes:
6650   Before calling `MatZeroRowsLocalIS()`, the user must first set the
6651   local-to-global mapping by calling `MatSetLocalToGlobalMapping()`, this is often already set for matrices obtained with `DMCreateMatrix()`.
6652 
6653   See `MatZeroRows()` for details on how this routine operates.
6654 
6655 .seealso: [](ch_matrices), `Mat`, `MatZeroRowsIS()`, `MatZeroRowsColumns()`, `MatZeroRows()`, `MatZeroRowsStencil()`, `MatZeroEntries()`, `MatZeroRowsLocal()`, `MatSetOption()`,
6656           `MatZeroRowsColumnsLocal()`, `MatZeroRowsColumnsLocalIS()`, `MatZeroRowsColumnsIS()`, `MatZeroRowsColumnsStencil()`
6657 @*/
6658 PetscErrorCode MatZeroRowsLocalIS(Mat mat, IS is, PetscScalar diag, Vec x, Vec b)
6659 {
6660   PetscInt        numRows;
6661   const PetscInt *rows;
6662 
6663   PetscFunctionBegin;
6664   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
6665   PetscValidType(mat, 1);
6666   PetscValidHeaderSpecific(is, IS_CLASSID, 2);
6667   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
6668   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
6669   MatCheckPreallocated(mat, 1);
6670 
6671   PetscCall(ISGetLocalSize(is, &numRows));
6672   PetscCall(ISGetIndices(is, &rows));
6673   PetscCall(MatZeroRowsLocal(mat, numRows, rows, diag, x, b));
6674   PetscCall(ISRestoreIndices(is, &rows));
6675   PetscFunctionReturn(PETSC_SUCCESS);
6676 }
6677 
6678 /*@
6679   MatZeroRowsColumnsLocal - Zeros all entries (except possibly the main diagonal)
6680   of a set of rows and columns of a matrix; using local numbering of rows.
6681 
6682   Collective
6683 
6684   Input Parameters:
6685 + mat     - the matrix
6686 . numRows - the number of rows to remove
6687 . rows    - the global row indices
6688 . diag    - value put in all diagonals of eliminated rows
6689 . x       - optional vector of solutions for zeroed rows (other entries in vector are not used)
6690 - b       - optional vector of right-hand side, that will be adjusted by provided solution
6691 
6692   Level: intermediate
6693 
6694   Notes:
6695   Before calling `MatZeroRowsColumnsLocal()`, the user must first set the
6696   local-to-global mapping by calling `MatSetLocalToGlobalMapping()`, this is often already set for matrices obtained with `DMCreateMatrix()`.
6697 
6698   See `MatZeroRowsColumns()` for details on how this routine operates.
6699 
6700 .seealso: [](ch_matrices), `Mat`, `MatZeroRowsIS()`, `MatZeroRowsColumns()`, `MatZeroRowsLocalIS()`, `MatZeroRowsStencil()`, `MatZeroEntries()`, `MatZeroRowsLocal()`, `MatSetOption()`,
6701           `MatZeroRows()`, `MatZeroRowsColumnsLocalIS()`, `MatZeroRowsColumnsIS()`, `MatZeroRowsColumnsStencil()`
6702 @*/
6703 PetscErrorCode MatZeroRowsColumnsLocal(Mat mat, PetscInt numRows, const PetscInt rows[], PetscScalar diag, Vec x, Vec b)
6704 {
6705   IS              is, newis;
6706   const PetscInt *newRows;
6707 
6708   PetscFunctionBegin;
6709   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
6710   PetscValidType(mat, 1);
6711   if (numRows) PetscAssertPointer(rows, 3);
6712   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
6713   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
6714   MatCheckPreallocated(mat, 1);
6715 
6716   PetscCheck(mat->cmap->mapping, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Need to provide local to global mapping to matrix first");
6717   PetscCall(ISCreateGeneral(PETSC_COMM_SELF, numRows, rows, PETSC_COPY_VALUES, &is));
6718   PetscCall(ISLocalToGlobalMappingApplyIS(mat->cmap->mapping, is, &newis));
6719   PetscCall(ISGetIndices(newis, &newRows));
6720   PetscUseTypeMethod(mat, zerorowscolumns, numRows, newRows, diag, x, b);
6721   PetscCall(ISRestoreIndices(newis, &newRows));
6722   PetscCall(ISDestroy(&newis));
6723   PetscCall(ISDestroy(&is));
6724   PetscCall(PetscObjectStateIncrease((PetscObject)mat));
6725   PetscFunctionReturn(PETSC_SUCCESS);
6726 }
6727 
6728 /*@
6729   MatZeroRowsColumnsLocalIS - Zeros all entries (except possibly the main diagonal)
6730   of a set of rows and columns of a matrix; using local numbering of rows.
6731 
6732   Collective
6733 
6734   Input Parameters:
6735 + mat  - the matrix
6736 . is   - index set of rows to remove
6737 . diag - value put in all diagonals of eliminated rows
6738 . x    - optional vector of solutions for zeroed rows (other entries in vector are not used)
6739 - b    - optional vector of right-hand side, that will be adjusted by provided solution
6740 
6741   Level: intermediate
6742 
6743   Notes:
6744   Before calling `MatZeroRowsColumnsLocalIS()`, the user must first set the
6745   local-to-global mapping by calling `MatSetLocalToGlobalMapping()`, this is often already set for matrices obtained with `DMCreateMatrix()`.
6746 
6747   See `MatZeroRowsColumns()` for details on how this routine operates.
6748 
6749 .seealso: [](ch_matrices), `Mat`, `MatZeroRowsIS()`, `MatZeroRowsColumns()`, `MatZeroRowsLocalIS()`, `MatZeroRowsStencil()`, `MatZeroEntries()`, `MatZeroRowsLocal()`, `MatSetOption()`,
6750           `MatZeroRowsColumnsLocal()`, `MatZeroRows()`, `MatZeroRowsColumnsIS()`, `MatZeroRowsColumnsStencil()`
6751 @*/
6752 PetscErrorCode MatZeroRowsColumnsLocalIS(Mat mat, IS is, PetscScalar diag, Vec x, Vec b)
6753 {
6754   PetscInt        numRows;
6755   const PetscInt *rows;
6756 
6757   PetscFunctionBegin;
6758   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
6759   PetscValidType(mat, 1);
6760   PetscValidHeaderSpecific(is, IS_CLASSID, 2);
6761   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
6762   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
6763   MatCheckPreallocated(mat, 1);
6764 
6765   PetscCall(ISGetLocalSize(is, &numRows));
6766   PetscCall(ISGetIndices(is, &rows));
6767   PetscCall(MatZeroRowsColumnsLocal(mat, numRows, rows, diag, x, b));
6768   PetscCall(ISRestoreIndices(is, &rows));
6769   PetscFunctionReturn(PETSC_SUCCESS);
6770 }
6771 
6772 /*@
6773   MatGetSize - Returns the numbers of rows and columns in a matrix.
6774 
6775   Not Collective
6776 
6777   Input Parameter:
6778 . mat - the matrix
6779 
6780   Output Parameters:
6781 + m - the number of global rows
6782 - n - the number of global columns
6783 
6784   Level: beginner
6785 
6786   Note:
6787   Both output parameters can be `NULL` on input.
6788 
6789 .seealso: [](ch_matrices), `Mat`, `MatSetSizes()`, `MatGetLocalSize()`
6790 @*/
6791 PetscErrorCode MatGetSize(Mat mat, PetscInt *m, PetscInt *n)
6792 {
6793   PetscFunctionBegin;
6794   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
6795   if (m) *m = mat->rmap->N;
6796   if (n) *n = mat->cmap->N;
6797   PetscFunctionReturn(PETSC_SUCCESS);
6798 }
6799 
6800 /*@
6801   MatGetLocalSize - For most matrix formats, excluding `MATELEMENTAL` and `MATSCALAPACK`, Returns the number of local rows and local columns
6802   of a matrix. For all matrices this is the local size of the left and right vectors as returned by `MatCreateVecs()`.
6803 
6804   Not Collective
6805 
6806   Input Parameter:
6807 . mat - the matrix
6808 
6809   Output Parameters:
6810 + m - the number of local rows, use `NULL` to not obtain this value
6811 - n - the number of local columns, use `NULL` to not obtain this value
6812 
6813   Level: beginner
6814 
6815 .seealso: [](ch_matrices), `Mat`, `MatSetSizes()`, `MatGetSize()`
6816 @*/
6817 PetscErrorCode MatGetLocalSize(Mat mat, PetscInt *m, PetscInt *n)
6818 {
6819   PetscFunctionBegin;
6820   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
6821   if (m) PetscAssertPointer(m, 2);
6822   if (n) PetscAssertPointer(n, 3);
6823   if (m) *m = mat->rmap->n;
6824   if (n) *n = mat->cmap->n;
6825   PetscFunctionReturn(PETSC_SUCCESS);
6826 }
6827 
6828 /*@
6829   MatGetOwnershipRangeColumn - Returns the range of matrix columns associated with rows of a
6830   vector one multiplies this matrix by that are owned by this processor.
6831 
6832   Not Collective, unless matrix has not been allocated, then collective
6833 
6834   Input Parameter:
6835 . mat - the matrix
6836 
6837   Output Parameters:
6838 + m - the global index of the first local column, use `NULL` to not obtain this value
6839 - n - one more than the global index of the last local column, use `NULL` to not obtain this value
6840 
6841   Level: developer
6842 
6843   Notes:
6844   If the `Mat` was obtained from a `DM` with `DMCreateMatrix()`, then the range values are determined by the specific `DM`.
6845 
6846   If the `Mat` was created directly the range values are determined by the local size passed to `MatSetSizes()` or `MatCreateAIJ()`.
6847   If `PETSC_DECIDE` was passed as the local size, then the vector uses default values for the range using `PetscSplitOwnership()`.
6848 
6849   For certain `DM`, such as `DMDA`, it is better to use `DM` specific routines, such as `DMDAGetGhostCorners()`, to determine
6850   the local values in the matrix.
6851 
6852   Returns the columns of the "diagonal block" for most sparse matrix formats. See [Matrix
6853   Layouts](sec_matlayout) for details on matrix layouts.
6854 
6855 .seealso: [](ch_matrices), `Mat`, `MatGetOwnershipRange()`, `MatGetOwnershipRanges()`, `MatGetOwnershipRangesColumn()`, `PetscLayout`,
6856           `MatSetSizes()`, `MatCreateAIJ()`, `DMDAGetGhostCorners()`, `DM`
6857 @*/
6858 PetscErrorCode MatGetOwnershipRangeColumn(Mat mat, PetscInt *m, PetscInt *n)
6859 {
6860   PetscFunctionBegin;
6861   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
6862   PetscValidType(mat, 1);
6863   if (m) PetscAssertPointer(m, 2);
6864   if (n) PetscAssertPointer(n, 3);
6865   MatCheckPreallocated(mat, 1);
6866   if (m) *m = mat->cmap->rstart;
6867   if (n) *n = mat->cmap->rend;
6868   PetscFunctionReturn(PETSC_SUCCESS);
6869 }
6870 
6871 /*@
6872   MatGetOwnershipRange - For matrices that own values by row, excludes `MATELEMENTAL` and `MATSCALAPACK`, returns the range of matrix rows owned by
6873   this MPI process.
6874 
6875   Not Collective
6876 
6877   Input Parameter:
6878 . mat - the matrix
6879 
6880   Output Parameters:
6881 + m - the global index of the first local row, use `NULL` to not obtain this value
6882 - n - one more than the global index of the last local row, use `NULL` to not obtain this value
6883 
6884   Level: beginner
6885 
6886   Notes:
6887   If the `Mat` was obtained from a `DM` with `DMCreateMatrix()`, then the range values are determined by the specific `DM`.
6888 
6889   If the `Mat` was created directly the range values are determined by the local size passed to `MatSetSizes()` or `MatCreateAIJ()`.
6890   If `PETSC_DECIDE` was passed as the local size, then the vector uses default values for the range using `PetscSplitOwnership()`.
6891 
6892   For certain `DM`, such as `DMDA`, it is better to use `DM` specific routines, such as `DMDAGetGhostCorners()`, to determine
6893   the local values in the matrix.
6894 
6895   The high argument is one more than the last element stored locally.
6896 
6897   For all matrices  it returns the range of matrix rows associated with rows of a vector that
6898   would contain the result of a matrix vector product with this matrix. See [Matrix
6899   Layouts](sec_matlayout) for details on matrix layouts.
6900 
6901 .seealso: [](ch_matrices), `Mat`, `MatGetOwnershipRanges()`, `MatGetOwnershipRangeColumn()`, `MatGetOwnershipRangesColumn()`, `PetscSplitOwnership()`,
6902           `PetscSplitOwnershipBlock()`, `PetscLayout`, `MatSetSizes()`, `MatCreateAIJ()`, `DMDAGetGhostCorners()`, `DM`
6903 @*/
6904 PetscErrorCode MatGetOwnershipRange(Mat mat, PetscInt *m, PetscInt *n)
6905 {
6906   PetscFunctionBegin;
6907   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
6908   PetscValidType(mat, 1);
6909   if (m) PetscAssertPointer(m, 2);
6910   if (n) PetscAssertPointer(n, 3);
6911   MatCheckPreallocated(mat, 1);
6912   if (m) *m = mat->rmap->rstart;
6913   if (n) *n = mat->rmap->rend;
6914   PetscFunctionReturn(PETSC_SUCCESS);
6915 }
6916 
6917 /*@C
6918   MatGetOwnershipRanges - For matrices that own values by row, excludes `MATELEMENTAL` and
6919   `MATSCALAPACK`, returns the range of matrix rows owned by each process.
6920 
6921   Not Collective, unless matrix has not been allocated
6922 
6923   Input Parameter:
6924 . mat - the matrix
6925 
6926   Output Parameter:
6927 . ranges - start of each processors portion plus one more than the total length at the end, of length `size` + 1
6928            where `size` is the number of MPI processes used by `mat`
6929 
6930   Level: beginner
6931 
6932   Notes:
6933   If the `Mat` was obtained from a `DM` with `DMCreateMatrix()`, then the range values are determined by the specific `DM`.
6934 
6935   If the `Mat` was created directly the range values are determined by the local size passed to `MatSetSizes()` or `MatCreateAIJ()`.
6936   If `PETSC_DECIDE` was passed as the local size, then the vector uses default values for the range using `PetscSplitOwnership()`.
6937 
6938   For certain `DM`, such as `DMDA`, it is better to use `DM` specific routines, such as `DMDAGetGhostCorners()`, to determine
6939   the local values in the matrix.
6940 
6941   For all matrices  it returns the ranges of matrix rows associated with rows of a vector that
6942   would contain the result of a matrix vector product with this matrix. See [Matrix
6943   Layouts](sec_matlayout) for details on matrix layouts.
6944 
6945 .seealso: [](ch_matrices), `Mat`, `MatGetOwnershipRange()`, `MatGetOwnershipRangeColumn()`, `MatGetOwnershipRangesColumn()`, `PetscLayout`,
6946           `PetscSplitOwnership()`, `PetscSplitOwnershipBlock()`, `MatSetSizes()`, `MatCreateAIJ()`,
6947           `DMDAGetGhostCorners()`, `DM`
6948 @*/
6949 PetscErrorCode MatGetOwnershipRanges(Mat mat, const PetscInt *ranges[])
6950 {
6951   PetscFunctionBegin;
6952   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
6953   PetscValidType(mat, 1);
6954   MatCheckPreallocated(mat, 1);
6955   PetscCall(PetscLayoutGetRanges(mat->rmap, ranges));
6956   PetscFunctionReturn(PETSC_SUCCESS);
6957 }
6958 
6959 /*@C
6960   MatGetOwnershipRangesColumn - Returns the ranges of matrix columns associated with rows of a
6961   vector one multiplies this vector by that are owned by each processor.
6962 
6963   Not Collective, unless matrix has not been allocated
6964 
6965   Input Parameter:
6966 . mat - the matrix
6967 
6968   Output Parameter:
6969 . ranges - start of each processors portion plus one more than the total length at the end
6970 
6971   Level: beginner
6972 
6973   Notes:
6974   If the `Mat` was obtained from a `DM` with `DMCreateMatrix()`, then the range values are determined by the specific `DM`.
6975 
6976   If the `Mat` was created directly the range values are determined by the local size passed to `MatSetSizes()` or `MatCreateAIJ()`.
6977   If `PETSC_DECIDE` was passed as the local size, then the vector uses default values for the range using `PetscSplitOwnership()`.
6978 
6979   For certain `DM`, such as `DMDA`, it is better to use `DM` specific routines, such as `DMDAGetGhostCorners()`, to determine
6980   the local values in the matrix.
6981 
6982   Returns the columns of the "diagonal blocks", for most sparse matrix formats. See [Matrix
6983   Layouts](sec_matlayout) for details on matrix layouts.
6984 
6985 .seealso: [](ch_matrices), `Mat`, `MatGetOwnershipRange()`, `MatGetOwnershipRangeColumn()`, `MatGetOwnershipRanges()`,
6986           `PetscSplitOwnership()`, `PetscSplitOwnershipBlock()`, `PetscLayout`, `MatSetSizes()`, `MatCreateAIJ()`,
6987           `DMDAGetGhostCorners()`, `DM`
6988 @*/
6989 PetscErrorCode MatGetOwnershipRangesColumn(Mat mat, const PetscInt *ranges[])
6990 {
6991   PetscFunctionBegin;
6992   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
6993   PetscValidType(mat, 1);
6994   MatCheckPreallocated(mat, 1);
6995   PetscCall(PetscLayoutGetRanges(mat->cmap, ranges));
6996   PetscFunctionReturn(PETSC_SUCCESS);
6997 }
6998 
6999 /*@
7000   MatGetOwnershipIS - Get row and column ownership of a matrices' values as index sets.
7001 
7002   Not Collective
7003 
7004   Input Parameter:
7005 . A - matrix
7006 
7007   Output Parameters:
7008 + rows - rows in which this process owns elements, , use `NULL` to not obtain this value
7009 - cols - columns in which this process owns elements, use `NULL` to not obtain this value
7010 
7011   Level: intermediate
7012 
7013   Note:
7014   You should call `ISDestroy()` on the returned `IS`
7015 
7016   For most matrices, excluding `MATELEMENTAL` and `MATSCALAPACK`, this corresponds to values
7017   returned by `MatGetOwnershipRange()`, `MatGetOwnershipRangeColumn()`. For `MATELEMENTAL` and
7018   `MATSCALAPACK` the ownership is more complicated. See [Matrix Layouts](sec_matlayout) for
7019   details on matrix layouts.
7020 
7021 .seealso: [](ch_matrices), `IS`, `Mat`, `MatGetOwnershipRanges()`, `MatSetValues()`, `MATELEMENTAL`, `MATSCALAPACK`
7022 @*/
7023 PetscErrorCode MatGetOwnershipIS(Mat A, IS *rows, IS *cols)
7024 {
7025   PetscErrorCode (*f)(Mat, IS *, IS *);
7026 
7027   PetscFunctionBegin;
7028   PetscValidHeaderSpecific(A, MAT_CLASSID, 1);
7029   PetscValidType(A, 1);
7030   MatCheckPreallocated(A, 1);
7031   PetscCall(PetscObjectQueryFunction((PetscObject)A, "MatGetOwnershipIS_C", &f));
7032   if (f) {
7033     PetscCall((*f)(A, rows, cols));
7034   } else { /* Create a standard row-based partition, each process is responsible for ALL columns in their row block */
7035     if (rows) PetscCall(ISCreateStride(PETSC_COMM_SELF, A->rmap->n, A->rmap->rstart, 1, rows));
7036     if (cols) PetscCall(ISCreateStride(PETSC_COMM_SELF, A->cmap->N, 0, 1, cols));
7037   }
7038   PetscFunctionReturn(PETSC_SUCCESS);
7039 }
7040 
7041 /*@
7042   MatILUFactorSymbolic - Performs symbolic ILU factorization of a matrix obtained with `MatGetFactor()`
7043   Uses levels of fill only, not drop tolerance. Use `MatLUFactorNumeric()`
7044   to complete the factorization.
7045 
7046   Collective
7047 
7048   Input Parameters:
7049 + fact - the factorized matrix obtained with `MatGetFactor()`
7050 . mat  - the matrix
7051 . row  - row permutation
7052 . col  - column permutation
7053 - info - structure containing
7054 .vb
7055       levels - number of levels of fill.
7056       expected fill - as ratio of original fill.
7057       1 or 0 - indicating force fill on diagonal (improves robustness for matrices
7058                 missing diagonal entries)
7059 .ve
7060 
7061   Level: developer
7062 
7063   Notes:
7064   See [Matrix Factorization](sec_matfactor) for additional information.
7065 
7066   Most users should employ the `KSP` interface for linear solvers
7067   instead of working directly with matrix algebra routines such as this.
7068   See, e.g., `KSPCreate()`.
7069 
7070   Uses the definition of level of fill as in Y. Saad, {cite}`saad2003`
7071 
7072   Developer Note:
7073   The Fortran interface is not autogenerated as the
7074   interface definition cannot be generated correctly [due to `MatFactorInfo`]
7075 
7076 .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatGetFactor()`, `MatLUFactorSymbolic()`, `MatLUFactorNumeric()`, `MatCholeskyFactor()`
7077           `MatGetOrdering()`, `MatFactorInfo`
7078 @*/
7079 PetscErrorCode MatILUFactorSymbolic(Mat fact, Mat mat, IS row, IS col, const MatFactorInfo *info)
7080 {
7081   PetscFunctionBegin;
7082   PetscValidHeaderSpecific(mat, MAT_CLASSID, 2);
7083   PetscValidType(mat, 2);
7084   if (row) PetscValidHeaderSpecific(row, IS_CLASSID, 3);
7085   if (col) PetscValidHeaderSpecific(col, IS_CLASSID, 4);
7086   PetscAssertPointer(info, 5);
7087   PetscAssertPointer(fact, 1);
7088   PetscCheck(info->levels >= 0, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_OUTOFRANGE, "Levels of fill negative %" PetscInt_FMT, (PetscInt)info->levels);
7089   PetscCheck(info->fill >= 1.0, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_OUTOFRANGE, "Expected fill less than 1.0 %g", (double)info->fill);
7090   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
7091   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
7092   MatCheckPreallocated(mat, 2);
7093 
7094   if (!fact->trivialsymbolic) PetscCall(PetscLogEventBegin(MAT_ILUFactorSymbolic, mat, row, col, 0));
7095   PetscUseTypeMethod(fact, ilufactorsymbolic, mat, row, col, info);
7096   if (!fact->trivialsymbolic) PetscCall(PetscLogEventEnd(MAT_ILUFactorSymbolic, mat, row, col, 0));
7097   PetscFunctionReturn(PETSC_SUCCESS);
7098 }
7099 
7100 /*@
7101   MatICCFactorSymbolic - Performs symbolic incomplete
7102   Cholesky factorization for a symmetric matrix.  Use
7103   `MatCholeskyFactorNumeric()` to complete the factorization.
7104 
7105   Collective
7106 
7107   Input Parameters:
7108 + fact - the factorized matrix obtained with `MatGetFactor()`
7109 . mat  - the matrix to be factored
7110 . perm - row and column permutation
7111 - info - structure containing
7112 .vb
7113       levels - number of levels of fill.
7114       expected fill - as ratio of original fill.
7115 .ve
7116 
7117   Level: developer
7118 
7119   Notes:
7120   Most users should employ the `KSP` interface for linear solvers
7121   instead of working directly with matrix algebra routines such as this.
7122   See, e.g., `KSPCreate()`.
7123 
7124   This uses the definition of level of fill as in Y. Saad {cite}`saad2003`
7125 
7126   Developer Note:
7127   The Fortran interface is not autogenerated as the
7128   interface definition cannot be generated correctly [due to `MatFactorInfo`]
7129 
7130 .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatCholeskyFactorNumeric()`, `MatCholeskyFactor()`, `MatFactorInfo`
7131 @*/
7132 PetscErrorCode MatICCFactorSymbolic(Mat fact, Mat mat, IS perm, const MatFactorInfo *info)
7133 {
7134   PetscFunctionBegin;
7135   PetscValidHeaderSpecific(mat, MAT_CLASSID, 2);
7136   PetscValidType(mat, 2);
7137   if (perm) PetscValidHeaderSpecific(perm, IS_CLASSID, 3);
7138   PetscAssertPointer(info, 4);
7139   PetscAssertPointer(fact, 1);
7140   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
7141   PetscCheck(info->levels >= 0, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_OUTOFRANGE, "Levels negative %" PetscInt_FMT, (PetscInt)info->levels);
7142   PetscCheck(info->fill >= 1.0, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_OUTOFRANGE, "Expected fill less than 1.0 %g", (double)info->fill);
7143   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
7144   MatCheckPreallocated(mat, 2);
7145 
7146   if (!fact->trivialsymbolic) PetscCall(PetscLogEventBegin(MAT_ICCFactorSymbolic, mat, perm, 0, 0));
7147   PetscUseTypeMethod(fact, iccfactorsymbolic, mat, perm, info);
7148   if (!fact->trivialsymbolic) PetscCall(PetscLogEventEnd(MAT_ICCFactorSymbolic, mat, perm, 0, 0));
7149   PetscFunctionReturn(PETSC_SUCCESS);
7150 }
7151 
7152 /*@C
7153   MatCreateSubMatrices - Extracts several submatrices from a matrix. If submat
7154   points to an array of valid matrices, they may be reused to store the new
7155   submatrices.
7156 
7157   Collective
7158 
7159   Input Parameters:
7160 + mat   - the matrix
7161 . n     - the number of submatrixes to be extracted (on this processor, may be zero)
7162 . irow  - index set of rows to extract
7163 . icol  - index set of columns to extract
7164 - scall - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`
7165 
7166   Output Parameter:
7167 . submat - the array of submatrices
7168 
7169   Level: advanced
7170 
7171   Notes:
7172   `MatCreateSubMatrices()` can extract ONLY sequential submatrices
7173   (from both sequential and parallel matrices). Use `MatCreateSubMatrix()`
7174   to extract a parallel submatrix.
7175 
7176   Some matrix types place restrictions on the row and column
7177   indices, such as that they be sorted or that they be equal to each other.
7178 
7179   The index sets may not have duplicate entries.
7180 
7181   When extracting submatrices from a parallel matrix, each processor can
7182   form a different submatrix by setting the rows and columns of its
7183   individual index sets according to the local submatrix desired.
7184 
7185   When finished using the submatrices, the user should destroy
7186   them with `MatDestroySubMatrices()`.
7187 
7188   `MAT_REUSE_MATRIX` can only be used when the nonzero structure of the
7189   original matrix has not changed from that last call to `MatCreateSubMatrices()`.
7190 
7191   This routine creates the matrices in submat; you should NOT create them before
7192   calling it. It also allocates the array of matrix pointers submat.
7193 
7194   For `MATBAIJ` matrices the index sets must respect the block structure, that is if they
7195   request one row/column in a block, they must request all rows/columns that are in
7196   that block. For example, if the block size is 2 you cannot request just row 0 and
7197   column 0.
7198 
7199   Fortran Note:
7200   One must pass in as `submat` a `Mat` array of size at least `n`+1.
7201 
7202 .seealso: [](ch_matrices), `Mat`, `MatDestroySubMatrices()`, `MatCreateSubMatrix()`, `MatGetRow()`, `MatGetDiagonal()`, `MatReuse`
7203 @*/
7204 PetscErrorCode MatCreateSubMatrices(Mat mat, PetscInt n, const IS irow[], const IS icol[], MatReuse scall, Mat *submat[])
7205 {
7206   PetscInt  i;
7207   PetscBool eq;
7208 
7209   PetscFunctionBegin;
7210   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
7211   PetscValidType(mat, 1);
7212   if (n) {
7213     PetscAssertPointer(irow, 3);
7214     for (i = 0; i < n; i++) PetscValidHeaderSpecific(irow[i], IS_CLASSID, 3);
7215     PetscAssertPointer(icol, 4);
7216     for (i = 0; i < n; i++) PetscValidHeaderSpecific(icol[i], IS_CLASSID, 4);
7217   }
7218   PetscAssertPointer(submat, 6);
7219   if (n && scall == MAT_REUSE_MATRIX) {
7220     PetscAssertPointer(*submat, 6);
7221     for (i = 0; i < n; i++) PetscValidHeaderSpecific((*submat)[i], MAT_CLASSID, 6);
7222   }
7223   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
7224   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
7225   MatCheckPreallocated(mat, 1);
7226   PetscCall(PetscLogEventBegin(MAT_CreateSubMats, mat, 0, 0, 0));
7227   PetscUseTypeMethod(mat, createsubmatrices, n, irow, icol, scall, submat);
7228   PetscCall(PetscLogEventEnd(MAT_CreateSubMats, mat, 0, 0, 0));
7229   for (i = 0; i < n; i++) {
7230     (*submat)[i]->factortype = MAT_FACTOR_NONE; /* in case in place factorization was previously done on submatrix */
7231     PetscCall(ISEqualUnsorted(irow[i], icol[i], &eq));
7232     if (eq) PetscCall(MatPropagateSymmetryOptions(mat, (*submat)[i]));
7233 #if defined(PETSC_HAVE_VIENNACL) || defined(PETSC_HAVE_CUDA) || defined(PETSC_HAVE_HIP)
7234     if (mat->boundtocpu && mat->bindingpropagates) {
7235       PetscCall(MatBindToCPU((*submat)[i], PETSC_TRUE));
7236       PetscCall(MatSetBindingPropagates((*submat)[i], PETSC_TRUE));
7237     }
7238 #endif
7239   }
7240   PetscFunctionReturn(PETSC_SUCCESS);
7241 }
7242 
7243 /*@C
7244   MatCreateSubMatricesMPI - Extracts MPI submatrices across a sub communicator of mat (by pairs of `IS` that may live on subcomms).
7245 
7246   Collective
7247 
7248   Input Parameters:
7249 + mat   - the matrix
7250 . n     - the number of submatrixes to be extracted
7251 . irow  - index set of rows to extract
7252 . icol  - index set of columns to extract
7253 - scall - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`
7254 
7255   Output Parameter:
7256 . submat - the array of submatrices
7257 
7258   Level: advanced
7259 
7260   Note:
7261   This is used by `PCGASM`
7262 
7263 .seealso: [](ch_matrices), `Mat`, `PCGASM`, `MatCreateSubMatrices()`, `MatCreateSubMatrix()`, `MatGetRow()`, `MatGetDiagonal()`, `MatReuse`
7264 @*/
7265 PetscErrorCode MatCreateSubMatricesMPI(Mat mat, PetscInt n, const IS irow[], const IS icol[], MatReuse scall, Mat *submat[])
7266 {
7267   PetscInt  i;
7268   PetscBool eq;
7269 
7270   PetscFunctionBegin;
7271   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
7272   PetscValidType(mat, 1);
7273   if (n) {
7274     PetscAssertPointer(irow, 3);
7275     PetscValidHeaderSpecific(*irow, IS_CLASSID, 3);
7276     PetscAssertPointer(icol, 4);
7277     PetscValidHeaderSpecific(*icol, IS_CLASSID, 4);
7278   }
7279   PetscAssertPointer(submat, 6);
7280   if (n && scall == MAT_REUSE_MATRIX) {
7281     PetscAssertPointer(*submat, 6);
7282     PetscValidHeaderSpecific(**submat, MAT_CLASSID, 6);
7283   }
7284   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
7285   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
7286   MatCheckPreallocated(mat, 1);
7287 
7288   PetscCall(PetscLogEventBegin(MAT_CreateSubMats, mat, 0, 0, 0));
7289   PetscUseTypeMethod(mat, createsubmatricesmpi, n, irow, icol, scall, submat);
7290   PetscCall(PetscLogEventEnd(MAT_CreateSubMats, mat, 0, 0, 0));
7291   for (i = 0; i < n; i++) {
7292     PetscCall(ISEqualUnsorted(irow[i], icol[i], &eq));
7293     if (eq) PetscCall(MatPropagateSymmetryOptions(mat, (*submat)[i]));
7294   }
7295   PetscFunctionReturn(PETSC_SUCCESS);
7296 }
7297 
7298 /*@C
7299   MatDestroyMatrices - Destroys an array of matrices.
7300 
7301   Collective
7302 
7303   Input Parameters:
7304 + n   - the number of local matrices
7305 - mat - the matrices (this is a pointer to the array of matrices)
7306 
7307   Level: advanced
7308 
7309   Notes:
7310   Frees not only the matrices, but also the array that contains the matrices
7311 
7312   For matrices obtained with  `MatCreateSubMatrices()` use `MatDestroySubMatrices()`
7313 
7314   Fortran Note:
7315   Does not free the `mat` array.
7316 
7317 .seealso: [](ch_matrices), `Mat`, `MatCreateSubMatrices()`, `MatDestroySubMatrices()`
7318 @*/
7319 PetscErrorCode MatDestroyMatrices(PetscInt n, Mat *mat[])
7320 {
7321   PetscInt i;
7322 
7323   PetscFunctionBegin;
7324   if (!*mat) PetscFunctionReturn(PETSC_SUCCESS);
7325   PetscCheck(n >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Trying to destroy negative number of matrices %" PetscInt_FMT, n);
7326   PetscAssertPointer(mat, 2);
7327 
7328   for (i = 0; i < n; i++) PetscCall(MatDestroy(&(*mat)[i]));
7329 
7330   /* memory is allocated even if n = 0 */
7331   PetscCall(PetscFree(*mat));
7332   PetscFunctionReturn(PETSC_SUCCESS);
7333 }
7334 
7335 /*@C
7336   MatDestroySubMatrices - Destroys a set of matrices obtained with `MatCreateSubMatrices()`.
7337 
7338   Collective
7339 
7340   Input Parameters:
7341 + n   - the number of local matrices
7342 - mat - the matrices (this is a pointer to the array of matrices, just to match the calling
7343                        sequence of `MatCreateSubMatrices()`)
7344 
7345   Level: advanced
7346 
7347   Note:
7348   Frees not only the matrices, but also the array that contains the matrices
7349 
7350   Fortran Note:
7351   Does not free the `mat` array.
7352 
7353 .seealso: [](ch_matrices), `Mat`, `MatCreateSubMatrices()`, `MatDestroyMatrices()`
7354 @*/
7355 PetscErrorCode MatDestroySubMatrices(PetscInt n, Mat *mat[])
7356 {
7357   Mat mat0;
7358 
7359   PetscFunctionBegin;
7360   if (!*mat) PetscFunctionReturn(PETSC_SUCCESS);
7361   /* mat[] is an array of length n+1, see MatCreateSubMatrices_xxx() */
7362   PetscCheck(n >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Trying to destroy negative number of matrices %" PetscInt_FMT, n);
7363   PetscAssertPointer(mat, 2);
7364 
7365   mat0 = (*mat)[0];
7366   if (mat0 && mat0->ops->destroysubmatrices) {
7367     PetscCall((*mat0->ops->destroysubmatrices)(n, mat));
7368   } else {
7369     PetscCall(MatDestroyMatrices(n, mat));
7370   }
7371   PetscFunctionReturn(PETSC_SUCCESS);
7372 }
7373 
7374 /*@
7375   MatGetSeqNonzeroStructure - Extracts the nonzero structure from a matrix and stores it, in its entirety, on each process
7376 
7377   Collective
7378 
7379   Input Parameter:
7380 . mat - the matrix
7381 
7382   Output Parameter:
7383 . matstruct - the sequential matrix with the nonzero structure of `mat`
7384 
7385   Level: developer
7386 
7387 .seealso: [](ch_matrices), `Mat`, `MatDestroySeqNonzeroStructure()`, `MatCreateSubMatrices()`, `MatDestroyMatrices()`
7388 @*/
7389 PetscErrorCode MatGetSeqNonzeroStructure(Mat mat, Mat *matstruct)
7390 {
7391   PetscFunctionBegin;
7392   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
7393   PetscAssertPointer(matstruct, 2);
7394 
7395   PetscValidType(mat, 1);
7396   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
7397   MatCheckPreallocated(mat, 1);
7398 
7399   PetscCall(PetscLogEventBegin(MAT_GetSeqNonzeroStructure, mat, 0, 0, 0));
7400   PetscUseTypeMethod(mat, getseqnonzerostructure, matstruct);
7401   PetscCall(PetscLogEventEnd(MAT_GetSeqNonzeroStructure, mat, 0, 0, 0));
7402   PetscFunctionReturn(PETSC_SUCCESS);
7403 }
7404 
7405 /*@C
7406   MatDestroySeqNonzeroStructure - Destroys matrix obtained with `MatGetSeqNonzeroStructure()`.
7407 
7408   Collective
7409 
7410   Input Parameter:
7411 . mat - the matrix
7412 
7413   Level: advanced
7414 
7415   Note:
7416   This is not needed, one can just call `MatDestroy()`
7417 
7418 .seealso: [](ch_matrices), `Mat`, `MatGetSeqNonzeroStructure()`
7419 @*/
7420 PetscErrorCode MatDestroySeqNonzeroStructure(Mat *mat)
7421 {
7422   PetscFunctionBegin;
7423   PetscAssertPointer(mat, 1);
7424   PetscCall(MatDestroy(mat));
7425   PetscFunctionReturn(PETSC_SUCCESS);
7426 }
7427 
7428 /*@
7429   MatIncreaseOverlap - Given a set of submatrices indicated by index sets,
7430   replaces the index sets by larger ones that represent submatrices with
7431   additional overlap.
7432 
7433   Collective
7434 
7435   Input Parameters:
7436 + mat - the matrix
7437 . n   - the number of index sets
7438 . is  - the array of index sets (these index sets will changed during the call)
7439 - ov  - the additional overlap requested
7440 
7441   Options Database Key:
7442 . -mat_increase_overlap_scalable - use a scalable algorithm to compute the overlap (supported by MPIAIJ matrix)
7443 
7444   Level: developer
7445 
7446   Note:
7447   The computed overlap preserves the matrix block sizes when the blocks are square.
7448   That is: if a matrix nonzero for a given block would increase the overlap all columns associated with
7449   that block are included in the overlap regardless of whether each specific column would increase the overlap.
7450 
7451 .seealso: [](ch_matrices), `Mat`, `PCASM`, `MatSetBlockSize()`, `MatIncreaseOverlapSplit()`, `MatCreateSubMatrices()`
7452 @*/
7453 PetscErrorCode MatIncreaseOverlap(Mat mat, PetscInt n, IS is[], PetscInt ov)
7454 {
7455   PetscInt i, bs, cbs;
7456 
7457   PetscFunctionBegin;
7458   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
7459   PetscValidType(mat, 1);
7460   PetscValidLogicalCollectiveInt(mat, n, 2);
7461   PetscCheck(n >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Must have one or more domains, you have %" PetscInt_FMT, n);
7462   if (n) {
7463     PetscAssertPointer(is, 3);
7464     for (i = 0; i < n; i++) PetscValidHeaderSpecific(is[i], IS_CLASSID, 3);
7465   }
7466   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
7467   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
7468   MatCheckPreallocated(mat, 1);
7469 
7470   if (!ov || !n) PetscFunctionReturn(PETSC_SUCCESS);
7471   PetscCall(PetscLogEventBegin(MAT_IncreaseOverlap, mat, 0, 0, 0));
7472   PetscUseTypeMethod(mat, increaseoverlap, n, is, ov);
7473   PetscCall(PetscLogEventEnd(MAT_IncreaseOverlap, mat, 0, 0, 0));
7474   PetscCall(MatGetBlockSizes(mat, &bs, &cbs));
7475   if (bs == cbs) {
7476     for (i = 0; i < n; i++) PetscCall(ISSetBlockSize(is[i], bs));
7477   }
7478   PetscFunctionReturn(PETSC_SUCCESS);
7479 }
7480 
7481 PetscErrorCode MatIncreaseOverlapSplit_Single(Mat, IS *, PetscInt);
7482 
7483 /*@
7484   MatIncreaseOverlapSplit - Given a set of submatrices indicated by index sets across
7485   a sub communicator, replaces the index sets by larger ones that represent submatrices with
7486   additional overlap.
7487 
7488   Collective
7489 
7490   Input Parameters:
7491 + mat - the matrix
7492 . n   - the number of index sets
7493 . is  - the array of index sets (these index sets will changed during the call)
7494 - ov  - the additional overlap requested
7495 
7496   `   Options Database Key:
7497 . -mat_increase_overlap_scalable - use a scalable algorithm to compute the overlap (supported by MPIAIJ matrix)
7498 
7499   Level: developer
7500 
7501 .seealso: [](ch_matrices), `Mat`, `MatCreateSubMatrices()`, `MatIncreaseOverlap()`
7502 @*/
7503 PetscErrorCode MatIncreaseOverlapSplit(Mat mat, PetscInt n, IS is[], PetscInt ov)
7504 {
7505   PetscInt i;
7506 
7507   PetscFunctionBegin;
7508   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
7509   PetscValidType(mat, 1);
7510   PetscCheck(n >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Must have one or more domains, you have %" PetscInt_FMT, n);
7511   if (n) {
7512     PetscAssertPointer(is, 3);
7513     PetscValidHeaderSpecific(*is, IS_CLASSID, 3);
7514   }
7515   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
7516   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
7517   MatCheckPreallocated(mat, 1);
7518   if (!ov) PetscFunctionReturn(PETSC_SUCCESS);
7519   PetscCall(PetscLogEventBegin(MAT_IncreaseOverlap, mat, 0, 0, 0));
7520   for (i = 0; i < n; i++) PetscCall(MatIncreaseOverlapSplit_Single(mat, &is[i], ov));
7521   PetscCall(PetscLogEventEnd(MAT_IncreaseOverlap, mat, 0, 0, 0));
7522   PetscFunctionReturn(PETSC_SUCCESS);
7523 }
7524 
7525 /*@
7526   MatGetBlockSize - Returns the matrix block size.
7527 
7528   Not Collective
7529 
7530   Input Parameter:
7531 . mat - the matrix
7532 
7533   Output Parameter:
7534 . bs - block size
7535 
7536   Level: intermediate
7537 
7538   Notes:
7539   Block row formats are `MATBAIJ` and `MATSBAIJ` ALWAYS have square block storage in the matrix.
7540 
7541   If the block size has not been set yet this routine returns 1.
7542 
7543 .seealso: [](ch_matrices), `Mat`, `MATBAIJ`, `MATSBAIJ`, `MatCreateSeqBAIJ()`, `MatCreateBAIJ()`, `MatGetBlockSizes()`
7544 @*/
7545 PetscErrorCode MatGetBlockSize(Mat mat, PetscInt *bs)
7546 {
7547   PetscFunctionBegin;
7548   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
7549   PetscAssertPointer(bs, 2);
7550   *bs = PetscAbs(mat->rmap->bs);
7551   PetscFunctionReturn(PETSC_SUCCESS);
7552 }
7553 
7554 /*@
7555   MatGetBlockSizes - Returns the matrix block row and column sizes.
7556 
7557   Not Collective
7558 
7559   Input Parameter:
7560 . mat - the matrix
7561 
7562   Output Parameters:
7563 + rbs - row block size
7564 - cbs - column block size
7565 
7566   Level: intermediate
7567 
7568   Notes:
7569   Block row formats are `MATBAIJ` and `MATSBAIJ` ALWAYS have square block storage in the matrix.
7570   If you pass a different block size for the columns than the rows, the row block size determines the square block storage.
7571 
7572   If a block size has not been set yet this routine returns 1.
7573 
7574 .seealso: [](ch_matrices), `Mat`, `MATBAIJ`, `MATSBAIJ`, `MatCreateSeqBAIJ()`, `MatCreateBAIJ()`, `MatGetBlockSize()`, `MatSetBlockSize()`, `MatSetBlockSizes()`
7575 @*/
7576 PetscErrorCode MatGetBlockSizes(Mat mat, PetscInt *rbs, PetscInt *cbs)
7577 {
7578   PetscFunctionBegin;
7579   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
7580   if (rbs) PetscAssertPointer(rbs, 2);
7581   if (cbs) PetscAssertPointer(cbs, 3);
7582   if (rbs) *rbs = PetscAbs(mat->rmap->bs);
7583   if (cbs) *cbs = PetscAbs(mat->cmap->bs);
7584   PetscFunctionReturn(PETSC_SUCCESS);
7585 }
7586 
7587 /*@
7588   MatSetBlockSize - Sets the matrix block size.
7589 
7590   Logically Collective
7591 
7592   Input Parameters:
7593 + mat - the matrix
7594 - bs  - block size
7595 
7596   Level: intermediate
7597 
7598   Notes:
7599   Block row formats are `MATBAIJ` and `MATSBAIJ` formats ALWAYS have square block storage in the matrix.
7600   This must be called before `MatSetUp()` or MatXXXSetPreallocation() (or will default to 1) and the block size cannot be changed later.
7601 
7602   For `MATAIJ` matrix format, this function can be called at a later stage, provided that the specified block size
7603   is compatible with the matrix local sizes.
7604 
7605 .seealso: [](ch_matrices), `Mat`, `MATBAIJ`, `MATSBAIJ`, `MATAIJ`, `MatCreateSeqBAIJ()`, `MatCreateBAIJ()`, `MatGetBlockSize()`, `MatSetBlockSizes()`, `MatGetBlockSizes()`
7606 @*/
7607 PetscErrorCode MatSetBlockSize(Mat mat, PetscInt bs)
7608 {
7609   PetscFunctionBegin;
7610   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
7611   PetscValidLogicalCollectiveInt(mat, bs, 2);
7612   PetscCall(MatSetBlockSizes(mat, bs, bs));
7613   PetscFunctionReturn(PETSC_SUCCESS);
7614 }
7615 
7616 typedef struct {
7617   PetscInt         n;
7618   IS              *is;
7619   Mat             *mat;
7620   PetscObjectState nonzerostate;
7621   Mat              C;
7622 } EnvelopeData;
7623 
7624 static PetscErrorCode EnvelopeDataDestroy(void *ptr)
7625 {
7626   EnvelopeData *edata = (EnvelopeData *)ptr;
7627 
7628   PetscFunctionBegin;
7629   for (PetscInt i = 0; i < edata->n; i++) PetscCall(ISDestroy(&edata->is[i]));
7630   PetscCall(PetscFree(edata->is));
7631   PetscCall(PetscFree(edata));
7632   PetscFunctionReturn(PETSC_SUCCESS);
7633 }
7634 
7635 /*@
7636   MatComputeVariableBlockEnvelope - Given a matrix whose nonzeros are in blocks along the diagonal this computes and stores
7637   the sizes of these blocks in the matrix. An individual block may lie over several processes.
7638 
7639   Collective
7640 
7641   Input Parameter:
7642 . mat - the matrix
7643 
7644   Level: intermediate
7645 
7646   Notes:
7647   There can be zeros within the blocks
7648 
7649   The blocks can overlap between processes, including laying on more than two processes
7650 
7651 .seealso: [](ch_matrices), `Mat`, `MatInvertVariableBlockEnvelope()`, `MatSetVariableBlockSizes()`
7652 @*/
7653 PetscErrorCode MatComputeVariableBlockEnvelope(Mat mat)
7654 {
7655   PetscInt           n, *sizes, *starts, i = 0, env = 0, tbs = 0, lblocks = 0, rstart, II, ln = 0, cnt = 0, cstart, cend;
7656   PetscInt          *diag, *odiag, sc;
7657   VecScatter         scatter;
7658   PetscScalar       *seqv;
7659   const PetscScalar *parv;
7660   const PetscInt    *ia, *ja;
7661   PetscBool          set, flag, done;
7662   Mat                AA = mat, A;
7663   MPI_Comm           comm;
7664   PetscMPIInt        rank, size, tag;
7665   MPI_Status         status;
7666   PetscContainer     container;
7667   EnvelopeData      *edata;
7668   Vec                seq, par;
7669   IS                 isglobal;
7670 
7671   PetscFunctionBegin;
7672   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
7673   PetscCall(MatIsSymmetricKnown(mat, &set, &flag));
7674   if (!set || !flag) {
7675     /* TODO: only needs nonzero structure of transpose */
7676     PetscCall(MatTranspose(mat, MAT_INITIAL_MATRIX, &AA));
7677     PetscCall(MatAXPY(AA, 1.0, mat, DIFFERENT_NONZERO_PATTERN));
7678   }
7679   PetscCall(MatAIJGetLocalMat(AA, &A));
7680   PetscCall(MatGetRowIJ(A, 0, PETSC_FALSE, PETSC_FALSE, &n, &ia, &ja, &done));
7681   PetscCheck(done, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "Unable to get IJ structure from matrix");
7682 
7683   PetscCall(MatGetLocalSize(mat, &n, NULL));
7684   PetscCall(PetscObjectGetNewTag((PetscObject)mat, &tag));
7685   PetscCall(PetscObjectGetComm((PetscObject)mat, &comm));
7686   PetscCallMPI(MPI_Comm_size(comm, &size));
7687   PetscCallMPI(MPI_Comm_rank(comm, &rank));
7688 
7689   PetscCall(PetscMalloc2(n, &sizes, n, &starts));
7690 
7691   if (rank > 0) {
7692     PetscCallMPI(MPI_Recv(&env, 1, MPIU_INT, rank - 1, tag, comm, &status));
7693     PetscCallMPI(MPI_Recv(&tbs, 1, MPIU_INT, rank - 1, tag, comm, &status));
7694   }
7695   PetscCall(MatGetOwnershipRange(mat, &rstart, NULL));
7696   for (i = 0; i < n; i++) {
7697     env = PetscMax(env, ja[ia[i + 1] - 1]);
7698     II  = rstart + i;
7699     if (env == II) {
7700       starts[lblocks]  = tbs;
7701       sizes[lblocks++] = 1 + II - tbs;
7702       tbs              = 1 + II;
7703     }
7704   }
7705   if (rank < size - 1) {
7706     PetscCallMPI(MPI_Send(&env, 1, MPIU_INT, rank + 1, tag, comm));
7707     PetscCallMPI(MPI_Send(&tbs, 1, MPIU_INT, rank + 1, tag, comm));
7708   }
7709 
7710   PetscCall(MatRestoreRowIJ(A, 0, PETSC_FALSE, PETSC_FALSE, &n, &ia, &ja, &done));
7711   if (!set || !flag) PetscCall(MatDestroy(&AA));
7712   PetscCall(MatDestroy(&A));
7713 
7714   PetscCall(PetscNew(&edata));
7715   PetscCall(MatGetNonzeroState(mat, &edata->nonzerostate));
7716   edata->n = lblocks;
7717   /* create IS needed for extracting blocks from the original matrix */
7718   PetscCall(PetscMalloc1(lblocks, &edata->is));
7719   for (PetscInt i = 0; i < lblocks; i++) PetscCall(ISCreateStride(PETSC_COMM_SELF, sizes[i], starts[i], 1, &edata->is[i]));
7720 
7721   /* Create the resulting inverse matrix structure with preallocation information */
7722   PetscCall(MatCreate(PetscObjectComm((PetscObject)mat), &edata->C));
7723   PetscCall(MatSetSizes(edata->C, mat->rmap->n, mat->cmap->n, mat->rmap->N, mat->cmap->N));
7724   PetscCall(MatSetBlockSizesFromMats(edata->C, mat, mat));
7725   PetscCall(MatSetType(edata->C, MATAIJ));
7726 
7727   /* Communicate the start and end of each row, from each block to the correct rank */
7728   /* TODO: Use PetscSF instead of VecScatter */
7729   for (PetscInt i = 0; i < lblocks; i++) ln += sizes[i];
7730   PetscCall(VecCreateSeq(PETSC_COMM_SELF, 2 * ln, &seq));
7731   PetscCall(VecGetArrayWrite(seq, &seqv));
7732   for (PetscInt i = 0; i < lblocks; i++) {
7733     for (PetscInt j = 0; j < sizes[i]; j++) {
7734       seqv[cnt]     = starts[i];
7735       seqv[cnt + 1] = starts[i] + sizes[i];
7736       cnt += 2;
7737     }
7738   }
7739   PetscCall(VecRestoreArrayWrite(seq, &seqv));
7740   PetscCallMPI(MPI_Scan(&cnt, &sc, 1, MPIU_INT, MPI_SUM, PetscObjectComm((PetscObject)mat)));
7741   sc -= cnt;
7742   PetscCall(VecCreateMPI(PetscObjectComm((PetscObject)mat), 2 * mat->rmap->n, 2 * mat->rmap->N, &par));
7743   PetscCall(ISCreateStride(PETSC_COMM_SELF, cnt, sc, 1, &isglobal));
7744   PetscCall(VecScatterCreate(seq, NULL, par, isglobal, &scatter));
7745   PetscCall(ISDestroy(&isglobal));
7746   PetscCall(VecScatterBegin(scatter, seq, par, INSERT_VALUES, SCATTER_FORWARD));
7747   PetscCall(VecScatterEnd(scatter, seq, par, INSERT_VALUES, SCATTER_FORWARD));
7748   PetscCall(VecScatterDestroy(&scatter));
7749   PetscCall(VecDestroy(&seq));
7750   PetscCall(MatGetOwnershipRangeColumn(mat, &cstart, &cend));
7751   PetscCall(PetscMalloc2(mat->rmap->n, &diag, mat->rmap->n, &odiag));
7752   PetscCall(VecGetArrayRead(par, &parv));
7753   cnt = 0;
7754   PetscCall(MatGetSize(mat, NULL, &n));
7755   for (PetscInt i = 0; i < mat->rmap->n; i++) {
7756     PetscInt start, end, d = 0, od = 0;
7757 
7758     start = (PetscInt)PetscRealPart(parv[cnt]);
7759     end   = (PetscInt)PetscRealPart(parv[cnt + 1]);
7760     cnt += 2;
7761 
7762     if (start < cstart) {
7763       od += cstart - start + n - cend;
7764       d += cend - cstart;
7765     } else if (start < cend) {
7766       od += n - cend;
7767       d += cend - start;
7768     } else od += n - start;
7769     if (end <= cstart) {
7770       od -= cstart - end + n - cend;
7771       d -= cend - cstart;
7772     } else if (end < cend) {
7773       od -= n - cend;
7774       d -= cend - end;
7775     } else od -= n - end;
7776 
7777     odiag[i] = od;
7778     diag[i]  = d;
7779   }
7780   PetscCall(VecRestoreArrayRead(par, &parv));
7781   PetscCall(VecDestroy(&par));
7782   PetscCall(MatXAIJSetPreallocation(edata->C, mat->rmap->bs, diag, odiag, NULL, NULL));
7783   PetscCall(PetscFree2(diag, odiag));
7784   PetscCall(PetscFree2(sizes, starts));
7785 
7786   PetscCall(PetscContainerCreate(PETSC_COMM_SELF, &container));
7787   PetscCall(PetscContainerSetPointer(container, edata));
7788   PetscCall(PetscContainerSetUserDestroy(container, (PetscErrorCode(*)(void *))EnvelopeDataDestroy));
7789   PetscCall(PetscObjectCompose((PetscObject)mat, "EnvelopeData", (PetscObject)container));
7790   PetscCall(PetscObjectDereference((PetscObject)container));
7791   PetscFunctionReturn(PETSC_SUCCESS);
7792 }
7793 
7794 /*@
7795   MatInvertVariableBlockEnvelope - set matrix C to be the inverted block diagonal of matrix A
7796 
7797   Collective
7798 
7799   Input Parameters:
7800 + A     - the matrix
7801 - reuse - indicates if the `C` matrix was obtained from a previous call to this routine
7802 
7803   Output Parameter:
7804 . C - matrix with inverted block diagonal of `A`
7805 
7806   Level: advanced
7807 
7808   Note:
7809   For efficiency the matrix `A` should have all the nonzero entries clustered in smallish blocks along the diagonal.
7810 
7811 .seealso: [](ch_matrices), `Mat`, `MatInvertBlockDiagonal()`, `MatComputeBlockDiagonal()`
7812 @*/
7813 PetscErrorCode MatInvertVariableBlockEnvelope(Mat A, MatReuse reuse, Mat *C)
7814 {
7815   PetscContainer   container;
7816   EnvelopeData    *edata;
7817   PetscObjectState nonzerostate;
7818 
7819   PetscFunctionBegin;
7820   PetscCall(PetscObjectQuery((PetscObject)A, "EnvelopeData", (PetscObject *)&container));
7821   if (!container) {
7822     PetscCall(MatComputeVariableBlockEnvelope(A));
7823     PetscCall(PetscObjectQuery((PetscObject)A, "EnvelopeData", (PetscObject *)&container));
7824   }
7825   PetscCall(PetscContainerGetPointer(container, (void **)&edata));
7826   PetscCall(MatGetNonzeroState(A, &nonzerostate));
7827   PetscCheck(nonzerostate <= edata->nonzerostate, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "Cannot handle changes to matrix nonzero structure");
7828   PetscCheck(reuse != MAT_REUSE_MATRIX || *C == edata->C, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "C matrix must be the same as previously output");
7829 
7830   PetscCall(MatCreateSubMatrices(A, edata->n, edata->is, edata->is, MAT_INITIAL_MATRIX, &edata->mat));
7831   *C = edata->C;
7832 
7833   for (PetscInt i = 0; i < edata->n; i++) {
7834     Mat          D;
7835     PetscScalar *dvalues;
7836 
7837     PetscCall(MatConvert(edata->mat[i], MATSEQDENSE, MAT_INITIAL_MATRIX, &D));
7838     PetscCall(MatSetOption(*C, MAT_ROW_ORIENTED, PETSC_FALSE));
7839     PetscCall(MatSeqDenseInvert(D));
7840     PetscCall(MatDenseGetArray(D, &dvalues));
7841     PetscCall(MatSetValuesIS(*C, edata->is[i], edata->is[i], dvalues, INSERT_VALUES));
7842     PetscCall(MatDestroy(&D));
7843   }
7844   PetscCall(MatDestroySubMatrices(edata->n, &edata->mat));
7845   PetscCall(MatAssemblyBegin(*C, MAT_FINAL_ASSEMBLY));
7846   PetscCall(MatAssemblyEnd(*C, MAT_FINAL_ASSEMBLY));
7847   PetscFunctionReturn(PETSC_SUCCESS);
7848 }
7849 
7850 /*@
7851   MatSetVariableBlockSizes - Sets diagonal point-blocks of the matrix that need not be of the same size
7852 
7853   Not Collective
7854 
7855   Input Parameters:
7856 + mat     - the matrix
7857 . nblocks - the number of blocks on this process, each block can only exist on a single process
7858 - bsizes  - the block sizes
7859 
7860   Level: intermediate
7861 
7862   Notes:
7863   Currently used by `PCVPBJACOBI` for `MATAIJ` matrices
7864 
7865   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.
7866 
7867 .seealso: [](ch_matrices), `Mat`, `MatCreateSeqBAIJ()`, `MatCreateBAIJ()`, `MatGetBlockSize()`, `MatSetBlockSizes()`, `MatGetBlockSizes()`, `MatGetVariableBlockSizes()`,
7868           `MatComputeVariableBlockEnvelope()`, `PCVPBJACOBI`
7869 @*/
7870 PetscErrorCode MatSetVariableBlockSizes(Mat mat, PetscInt nblocks, const PetscInt bsizes[])
7871 {
7872   PetscInt ncnt = 0, nlocal;
7873 
7874   PetscFunctionBegin;
7875   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
7876   PetscCall(MatGetLocalSize(mat, &nlocal, NULL));
7877   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);
7878   for (PetscInt i = 0; i < nblocks; i++) ncnt += bsizes[i];
7879   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);
7880   PetscCall(PetscFree(mat->bsizes));
7881   mat->nblocks = nblocks;
7882   PetscCall(PetscMalloc1(nblocks, &mat->bsizes));
7883   PetscCall(PetscArraycpy(mat->bsizes, bsizes, nblocks));
7884   PetscFunctionReturn(PETSC_SUCCESS);
7885 }
7886 
7887 /*@C
7888   MatGetVariableBlockSizes - Gets a diagonal blocks of the matrix that need not be of the same size
7889 
7890   Not Collective; No Fortran Support
7891 
7892   Input Parameter:
7893 . mat - the matrix
7894 
7895   Output Parameters:
7896 + nblocks - the number of blocks on this process
7897 - bsizes  - the block sizes
7898 
7899   Level: intermediate
7900 
7901 .seealso: [](ch_matrices), `Mat`, `MatCreateSeqBAIJ()`, `MatCreateBAIJ()`, `MatGetBlockSize()`, `MatSetBlockSizes()`, `MatGetBlockSizes()`, `MatSetVariableBlockSizes()`, `MatComputeVariableBlockEnvelope()`
7902 @*/
7903 PetscErrorCode MatGetVariableBlockSizes(Mat mat, PetscInt *nblocks, const PetscInt *bsizes[])
7904 {
7905   PetscFunctionBegin;
7906   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
7907   if (nblocks) *nblocks = mat->nblocks;
7908   if (bsizes) *bsizes = mat->bsizes;
7909   PetscFunctionReturn(PETSC_SUCCESS);
7910 }
7911 
7912 /*@
7913   MatSetBlockSizes - Sets the matrix block row and column sizes.
7914 
7915   Logically Collective
7916 
7917   Input Parameters:
7918 + mat - the matrix
7919 . rbs - row block size
7920 - cbs - column block size
7921 
7922   Level: intermediate
7923 
7924   Notes:
7925   Block row formats are `MATBAIJ` and  `MATSBAIJ`. These formats ALWAYS have square block storage in the matrix.
7926   If you pass a different block size for the columns than the rows, the row block size determines the square block storage.
7927   This must be called before `MatSetUp()` or MatXXXSetPreallocation() (or will default to 1) and the block size cannot be changed later.
7928 
7929   For `MATAIJ` matrix this function can be called at a later stage, provided that the specified block sizes
7930   are compatible with the matrix local sizes.
7931 
7932   The row and column block size determine the blocksize of the "row" and "column" vectors returned by `MatCreateVecs()`.
7933 
7934 .seealso: [](ch_matrices), `Mat`, `MatCreateSeqBAIJ()`, `MatCreateBAIJ()`, `MatGetBlockSize()`, `MatSetBlockSize()`, `MatGetBlockSizes()`
7935 @*/
7936 PetscErrorCode MatSetBlockSizes(Mat mat, PetscInt rbs, PetscInt cbs)
7937 {
7938   PetscFunctionBegin;
7939   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
7940   PetscValidLogicalCollectiveInt(mat, rbs, 2);
7941   PetscValidLogicalCollectiveInt(mat, cbs, 3);
7942   PetscTryTypeMethod(mat, setblocksizes, rbs, cbs);
7943   if (mat->rmap->refcnt) {
7944     ISLocalToGlobalMapping l2g  = NULL;
7945     PetscLayout            nmap = NULL;
7946 
7947     PetscCall(PetscLayoutDuplicate(mat->rmap, &nmap));
7948     if (mat->rmap->mapping) PetscCall(ISLocalToGlobalMappingDuplicate(mat->rmap->mapping, &l2g));
7949     PetscCall(PetscLayoutDestroy(&mat->rmap));
7950     mat->rmap          = nmap;
7951     mat->rmap->mapping = l2g;
7952   }
7953   if (mat->cmap->refcnt) {
7954     ISLocalToGlobalMapping l2g  = NULL;
7955     PetscLayout            nmap = NULL;
7956 
7957     PetscCall(PetscLayoutDuplicate(mat->cmap, &nmap));
7958     if (mat->cmap->mapping) PetscCall(ISLocalToGlobalMappingDuplicate(mat->cmap->mapping, &l2g));
7959     PetscCall(PetscLayoutDestroy(&mat->cmap));
7960     mat->cmap          = nmap;
7961     mat->cmap->mapping = l2g;
7962   }
7963   PetscCall(PetscLayoutSetBlockSize(mat->rmap, rbs));
7964   PetscCall(PetscLayoutSetBlockSize(mat->cmap, cbs));
7965   PetscFunctionReturn(PETSC_SUCCESS);
7966 }
7967 
7968 /*@
7969   MatSetBlockSizesFromMats - Sets the matrix block row and column sizes to match a pair of matrices
7970 
7971   Logically Collective
7972 
7973   Input Parameters:
7974 + mat     - the matrix
7975 . fromRow - matrix from which to copy row block size
7976 - fromCol - matrix from which to copy column block size (can be same as fromRow)
7977 
7978   Level: developer
7979 
7980 .seealso: [](ch_matrices), `Mat`, `MatCreateSeqBAIJ()`, `MatCreateBAIJ()`, `MatGetBlockSize()`, `MatSetBlockSizes()`
7981 @*/
7982 PetscErrorCode MatSetBlockSizesFromMats(Mat mat, Mat fromRow, Mat fromCol)
7983 {
7984   PetscFunctionBegin;
7985   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
7986   PetscValidHeaderSpecific(fromRow, MAT_CLASSID, 2);
7987   PetscValidHeaderSpecific(fromCol, MAT_CLASSID, 3);
7988   if (fromRow->rmap->bs > 0) PetscCall(PetscLayoutSetBlockSize(mat->rmap, fromRow->rmap->bs));
7989   if (fromCol->cmap->bs > 0) PetscCall(PetscLayoutSetBlockSize(mat->cmap, fromCol->cmap->bs));
7990   PetscFunctionReturn(PETSC_SUCCESS);
7991 }
7992 
7993 /*@
7994   MatResidual - Default routine to calculate the residual r = b - Ax
7995 
7996   Collective
7997 
7998   Input Parameters:
7999 + mat - the matrix
8000 . b   - the right-hand-side
8001 - x   - the approximate solution
8002 
8003   Output Parameter:
8004 . r - location to store the residual
8005 
8006   Level: developer
8007 
8008 .seealso: [](ch_matrices), `Mat`, `MatMult()`, `MatMultAdd()`, `PCMGSetResidual()`
8009 @*/
8010 PetscErrorCode MatResidual(Mat mat, Vec b, Vec x, Vec r)
8011 {
8012   PetscFunctionBegin;
8013   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
8014   PetscValidHeaderSpecific(b, VEC_CLASSID, 2);
8015   PetscValidHeaderSpecific(x, VEC_CLASSID, 3);
8016   PetscValidHeaderSpecific(r, VEC_CLASSID, 4);
8017   PetscValidType(mat, 1);
8018   MatCheckPreallocated(mat, 1);
8019   PetscCall(PetscLogEventBegin(MAT_Residual, mat, 0, 0, 0));
8020   if (!mat->ops->residual) {
8021     PetscCall(MatMult(mat, x, r));
8022     PetscCall(VecAYPX(r, -1.0, b));
8023   } else {
8024     PetscUseTypeMethod(mat, residual, b, x, r);
8025   }
8026   PetscCall(PetscLogEventEnd(MAT_Residual, mat, 0, 0, 0));
8027   PetscFunctionReturn(PETSC_SUCCESS);
8028 }
8029 
8030 /*MC
8031     MatGetRowIJF90 - Obtains the compressed row storage i and j indices for the local rows of a sparse matrix
8032 
8033     Synopsis:
8034     MatGetRowIJF90(Mat A, PetscInt shift, PetscBool symmetric, PetscBool inodecompressed, PetscInt n, {PetscInt, pointer :: ia(:)}, {PetscInt, pointer :: ja(:)}, PetscBool done,integer ierr)
8035 
8036     Not Collective
8037 
8038     Input Parameters:
8039 +   A - the matrix
8040 .   shift -  0 or 1 indicating we want the indices starting at 0 or 1
8041 .   symmetric - `PETSC_TRUE` or `PETSC_FALSE` indicating the matrix data structure should be symmetrized
8042 -   inodecompressed - `PETSC_TRUE` or `PETSC_FALSE`  indicating if the nonzero structure of the
8043                  inodes or the nonzero elements is wanted. For `MATBAIJ` matrices the compressed version is
8044                  always used.
8045 
8046     Output Parameters:
8047 +   n - number of local rows in the (possibly compressed) matrix
8048 .   ia - the row pointers; that is ia[0] = 0, ia[row] = ia[row-1] + number of elements in that row of the matrix
8049 .   ja - the column indices
8050 -   done - indicates if the routine actually worked and returned appropriate ia[] and ja[] arrays; callers
8051            are responsible for handling the case when done == `PETSC_FALSE` and ia and ja are not set
8052 
8053     Level: developer
8054 
8055     Note:
8056     Use  `MatRestoreRowIJF90()` when you no longer need access to the data
8057 
8058 .seealso: [](ch_matrices), [](sec_fortranarrays), `Mat`, `MATMPIAIJ`, `MatGetRowIJ()`, `MatRestoreRowIJ()`, `MatRestoreRowIJF90()`
8059 M*/
8060 
8061 /*MC
8062     MatRestoreRowIJF90 - restores the compressed row storage i and j indices for the local rows of a sparse matrix obtained with `MatGetRowIJF90()`
8063 
8064     Synopsis:
8065     MatRestoreRowIJF90(Mat A, PetscInt shift, PetscBool symmetric, PetscBool inodecompressed, PetscInt n, {PetscInt, pointer :: ia(:)}, {PetscInt, pointer :: ja(:)}, PetscBool done,integer ierr)
8066 
8067     Not Collective
8068 
8069     Input Parameters:
8070 +   A - the  matrix
8071 .   shift -  0 or 1 indicating we want the indices starting at 0 or 1
8072 .   symmetric - `PETSC_TRUE` or `PETSC_FALSE` indicating the matrix data structure should be symmetrized
8073     inodecompressed - `PETSC_TRUE` or `PETSC_FALSE`  indicating if the nonzero structure of the
8074                  inodes or the nonzero elements is wanted. For `MATBAIJ` matrices the compressed version is
8075                  always used.
8076 .   n - number of local rows in the (possibly compressed) matrix
8077 .   ia - the row pointers; that is ia[0] = 0, ia[row] = ia[row-1] + number of elements in that row of the matrix
8078 .   ja - the column indices
8079 -   done - indicates if the routine actually worked and returned appropriate ia[] and ja[] arrays; callers
8080            are responsible for handling the case when done == `PETSC_FALSE` and ia and ja are not set
8081 
8082     Level: developer
8083 
8084 .seealso: [](ch_matrices), [](sec_fortranarrays), `Mat`, `MATMPIAIJ`, `MatGetRowIJ()`, `MatRestoreRowIJ()`, `MatGetRowIJF90()`
8085 M*/
8086 
8087 /*@C
8088   MatGetRowIJ - Returns the compressed row storage i and j indices for the local rows of a sparse matrix
8089 
8090   Collective
8091 
8092   Input Parameters:
8093 + mat             - the matrix
8094 . shift           - 0 or 1 indicating we want the indices starting at 0 or 1
8095 . symmetric       - `PETSC_TRUE` or `PETSC_FALSE` indicating the matrix data structure should be symmetrized
8096 - inodecompressed - `PETSC_TRUE` or `PETSC_FALSE`  indicating if the nonzero structure of the
8097                  inodes or the nonzero elements is wanted. For `MATBAIJ` matrices the compressed version is
8098                  always used.
8099 
8100   Output Parameters:
8101 + n    - number of local rows in the (possibly compressed) matrix, use `NULL` if not needed
8102 . 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
8103 . ja   - the column indices, use `NULL` if not needed
8104 - done - indicates if the routine actually worked and returned appropriate ia[] and ja[] arrays; callers
8105            are responsible for handling the case when done == `PETSC_FALSE` and ia and ja are not set
8106 
8107   Level: developer
8108 
8109   Notes:
8110   You CANNOT change any of the ia[] or ja[] values.
8111 
8112   Use `MatRestoreRowIJ()` when you are finished accessing the ia[] and ja[] values.
8113 
8114   Fortran Notes:
8115   Use
8116 .vb
8117     PetscInt, pointer :: ia(:),ja(:)
8118     call MatGetRowIJF90(mat,shift,symmetric,inodecompressed,n,ia,ja,done,ierr)
8119     ! Access the ith and jth entries via ia(i) and ja(j)
8120 .ve
8121 
8122   `MatGetRowIJ()` Fortran binding is deprecated (since PETSc 3.19), use `MatGetRowIJF90()`
8123 
8124 .seealso: [](ch_matrices), `Mat`, `MATAIJ`, `MatGetRowIJF90()`, `MatGetColumnIJ()`, `MatRestoreRowIJ()`, `MatSeqAIJGetArray()`
8125 @*/
8126 PetscErrorCode MatGetRowIJ(Mat mat, PetscInt shift, PetscBool symmetric, PetscBool inodecompressed, PetscInt *n, const PetscInt *ia[], const PetscInt *ja[], PetscBool *done)
8127 {
8128   PetscFunctionBegin;
8129   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
8130   PetscValidType(mat, 1);
8131   if (n) PetscAssertPointer(n, 5);
8132   if (ia) PetscAssertPointer(ia, 6);
8133   if (ja) PetscAssertPointer(ja, 7);
8134   if (done) PetscAssertPointer(done, 8);
8135   MatCheckPreallocated(mat, 1);
8136   if (!mat->ops->getrowij && done) *done = PETSC_FALSE;
8137   else {
8138     if (done) *done = PETSC_TRUE;
8139     PetscCall(PetscLogEventBegin(MAT_GetRowIJ, mat, 0, 0, 0));
8140     PetscUseTypeMethod(mat, getrowij, shift, symmetric, inodecompressed, n, ia, ja, done);
8141     PetscCall(PetscLogEventEnd(MAT_GetRowIJ, mat, 0, 0, 0));
8142   }
8143   PetscFunctionReturn(PETSC_SUCCESS);
8144 }
8145 
8146 /*@C
8147   MatGetColumnIJ - Returns the compressed column storage i and j indices for sequential matrices.
8148 
8149   Collective
8150 
8151   Input Parameters:
8152 + mat             - the matrix
8153 . shift           - 1 or zero indicating we want the indices starting at 0 or 1
8154 . symmetric       - `PETSC_TRUE` or `PETSC_FALSE` indicating the matrix data structure should be
8155                 symmetrized
8156 . inodecompressed - `PETSC_TRUE` or `PETSC_FALSE` indicating if the nonzero structure of the
8157                  inodes or the nonzero elements is wanted. For `MATBAIJ` matrices the compressed version is
8158                  always used.
8159 . n               - number of columns in the (possibly compressed) matrix
8160 . ia              - the column pointers; that is ia[0] = 0, ia[col] = i[col-1] + number of elements in that col of the matrix
8161 - ja              - the row indices
8162 
8163   Output Parameter:
8164 . done - `PETSC_TRUE` or `PETSC_FALSE`, indicating whether the values have been returned
8165 
8166   Level: developer
8167 
8168 .seealso: [](ch_matrices), `Mat`, `MatGetRowIJ()`, `MatRestoreColumnIJ()`
8169 @*/
8170 PetscErrorCode MatGetColumnIJ(Mat mat, PetscInt shift, PetscBool symmetric, PetscBool inodecompressed, PetscInt *n, const PetscInt *ia[], const PetscInt *ja[], PetscBool *done)
8171 {
8172   PetscFunctionBegin;
8173   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
8174   PetscValidType(mat, 1);
8175   PetscAssertPointer(n, 5);
8176   if (ia) PetscAssertPointer(ia, 6);
8177   if (ja) PetscAssertPointer(ja, 7);
8178   PetscAssertPointer(done, 8);
8179   MatCheckPreallocated(mat, 1);
8180   if (!mat->ops->getcolumnij) *done = PETSC_FALSE;
8181   else {
8182     *done = PETSC_TRUE;
8183     PetscUseTypeMethod(mat, getcolumnij, shift, symmetric, inodecompressed, n, ia, ja, done);
8184   }
8185   PetscFunctionReturn(PETSC_SUCCESS);
8186 }
8187 
8188 /*@C
8189   MatRestoreRowIJ - Call after you are completed with the ia,ja indices obtained with `MatGetRowIJ()`.
8190 
8191   Collective
8192 
8193   Input Parameters:
8194 + mat             - the matrix
8195 . shift           - 1 or zero indicating we want the indices starting at 0 or 1
8196 . symmetric       - `PETSC_TRUE` or `PETSC_FALSE` indicating the matrix data structure should be symmetrized
8197 . inodecompressed - `PETSC_TRUE` or `PETSC_FALSE` indicating if the nonzero structure of the
8198                     inodes or the nonzero elements is wanted. For `MATBAIJ` matrices the compressed version is
8199                     always used.
8200 . n               - size of (possibly compressed) matrix
8201 . ia              - the row pointers
8202 - ja              - the column indices
8203 
8204   Output Parameter:
8205 . done - `PETSC_TRUE` or `PETSC_FALSE` indicated that the values have been returned
8206 
8207   Level: developer
8208 
8209   Note:
8210   This routine zeros out `n`, `ia`, and `ja`. This is to prevent accidental
8211   us of the array after it has been restored. If you pass `NULL`, it will
8212   not zero the pointers.  Use of ia or ja after `MatRestoreRowIJ()` is invalid.
8213 
8214   Fortran Note:
8215   `MatRestoreRowIJ()` Fortran binding is deprecated (since PETSc 3.19), use `MatRestoreRowIJF90()`
8216 
8217 .seealso: [](ch_matrices), `Mat`, `MatGetRowIJ()`, `MatRestoreRowIJF90()`, `MatRestoreColumnIJ()`
8218 @*/
8219 PetscErrorCode MatRestoreRowIJ(Mat mat, PetscInt shift, PetscBool symmetric, PetscBool inodecompressed, PetscInt *n, const PetscInt *ia[], const PetscInt *ja[], PetscBool *done)
8220 {
8221   PetscFunctionBegin;
8222   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
8223   PetscValidType(mat, 1);
8224   if (ia) PetscAssertPointer(ia, 6);
8225   if (ja) PetscAssertPointer(ja, 7);
8226   if (done) PetscAssertPointer(done, 8);
8227   MatCheckPreallocated(mat, 1);
8228 
8229   if (!mat->ops->restorerowij && done) *done = PETSC_FALSE;
8230   else {
8231     if (done) *done = PETSC_TRUE;
8232     PetscUseTypeMethod(mat, restorerowij, shift, symmetric, inodecompressed, n, ia, ja, done);
8233     if (n) *n = 0;
8234     if (ia) *ia = NULL;
8235     if (ja) *ja = NULL;
8236   }
8237   PetscFunctionReturn(PETSC_SUCCESS);
8238 }
8239 
8240 /*@C
8241   MatRestoreColumnIJ - Call after you are completed with the ia,ja indices obtained with `MatGetColumnIJ()`.
8242 
8243   Collective
8244 
8245   Input Parameters:
8246 + mat             - the matrix
8247 . shift           - 1 or zero indicating we want the indices starting at 0 or 1
8248 . symmetric       - `PETSC_TRUE` or `PETSC_FALSE` indicating the matrix data structure should be symmetrized
8249 - inodecompressed - `PETSC_TRUE` or `PETSC_FALSE` indicating if the nonzero structure of the
8250                     inodes or the nonzero elements is wanted. For `MATBAIJ` matrices the compressed version is
8251                     always used.
8252 
8253   Output Parameters:
8254 + n    - size of (possibly compressed) matrix
8255 . ia   - the column pointers
8256 . ja   - the row indices
8257 - done - `PETSC_TRUE` or `PETSC_FALSE` indicated that the values have been returned
8258 
8259   Level: developer
8260 
8261 .seealso: [](ch_matrices), `Mat`, `MatGetColumnIJ()`, `MatRestoreRowIJ()`
8262 @*/
8263 PetscErrorCode MatRestoreColumnIJ(Mat mat, PetscInt shift, PetscBool symmetric, PetscBool inodecompressed, PetscInt *n, const PetscInt *ia[], const PetscInt *ja[], PetscBool *done)
8264 {
8265   PetscFunctionBegin;
8266   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
8267   PetscValidType(mat, 1);
8268   if (ia) PetscAssertPointer(ia, 6);
8269   if (ja) PetscAssertPointer(ja, 7);
8270   PetscAssertPointer(done, 8);
8271   MatCheckPreallocated(mat, 1);
8272 
8273   if (!mat->ops->restorecolumnij) *done = PETSC_FALSE;
8274   else {
8275     *done = PETSC_TRUE;
8276     PetscUseTypeMethod(mat, restorecolumnij, shift, symmetric, inodecompressed, n, ia, ja, done);
8277     if (n) *n = 0;
8278     if (ia) *ia = NULL;
8279     if (ja) *ja = NULL;
8280   }
8281   PetscFunctionReturn(PETSC_SUCCESS);
8282 }
8283 
8284 /*@
8285   MatColoringPatch - Used inside matrix coloring routines that use `MatGetRowIJ()` and/or
8286   `MatGetColumnIJ()`.
8287 
8288   Collective
8289 
8290   Input Parameters:
8291 + mat        - the matrix
8292 . ncolors    - maximum color value
8293 . n          - number of entries in colorarray
8294 - colorarray - array indicating color for each column
8295 
8296   Output Parameter:
8297 . iscoloring - coloring generated using colorarray information
8298 
8299   Level: developer
8300 
8301 .seealso: [](ch_matrices), `Mat`, `MatGetRowIJ()`, `MatGetColumnIJ()`
8302 @*/
8303 PetscErrorCode MatColoringPatch(Mat mat, PetscInt ncolors, PetscInt n, ISColoringValue colorarray[], ISColoring *iscoloring)
8304 {
8305   PetscFunctionBegin;
8306   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
8307   PetscValidType(mat, 1);
8308   PetscAssertPointer(colorarray, 4);
8309   PetscAssertPointer(iscoloring, 5);
8310   MatCheckPreallocated(mat, 1);
8311 
8312   if (!mat->ops->coloringpatch) {
8313     PetscCall(ISColoringCreate(PetscObjectComm((PetscObject)mat), ncolors, n, colorarray, PETSC_OWN_POINTER, iscoloring));
8314   } else {
8315     PetscUseTypeMethod(mat, coloringpatch, ncolors, n, colorarray, iscoloring);
8316   }
8317   PetscFunctionReturn(PETSC_SUCCESS);
8318 }
8319 
8320 /*@
8321   MatSetUnfactored - Resets a factored matrix to be treated as unfactored.
8322 
8323   Logically Collective
8324 
8325   Input Parameter:
8326 . mat - the factored matrix to be reset
8327 
8328   Level: developer
8329 
8330   Notes:
8331   This routine should be used only with factored matrices formed by in-place
8332   factorization via ILU(0) (or by in-place LU factorization for the `MATSEQDENSE`
8333   format).  This option can save memory, for example, when solving nonlinear
8334   systems with a matrix-free Newton-Krylov method and a matrix-based, in-place
8335   ILU(0) preconditioner.
8336 
8337   One can specify in-place ILU(0) factorization by calling
8338 .vb
8339      PCType(pc,PCILU);
8340      PCFactorSeUseInPlace(pc);
8341 .ve
8342   or by using the options -pc_type ilu -pc_factor_in_place
8343 
8344   In-place factorization ILU(0) can also be used as a local
8345   solver for the blocks within the block Jacobi or additive Schwarz
8346   methods (runtime option: -sub_pc_factor_in_place).  See Users-Manual: ch_pc
8347   for details on setting local solver options.
8348 
8349   Most users should employ the `KSP` interface for linear solvers
8350   instead of working directly with matrix algebra routines such as this.
8351   See, e.g., `KSPCreate()`.
8352 
8353 .seealso: [](ch_matrices), `Mat`, `PCFactorSetUseInPlace()`, `PCFactorGetUseInPlace()`
8354 @*/
8355 PetscErrorCode MatSetUnfactored(Mat mat)
8356 {
8357   PetscFunctionBegin;
8358   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
8359   PetscValidType(mat, 1);
8360   MatCheckPreallocated(mat, 1);
8361   mat->factortype = MAT_FACTOR_NONE;
8362   if (!mat->ops->setunfactored) PetscFunctionReturn(PETSC_SUCCESS);
8363   PetscUseTypeMethod(mat, setunfactored);
8364   PetscFunctionReturn(PETSC_SUCCESS);
8365 }
8366 
8367 /*MC
8368     MatDenseGetArrayF90 - Accesses a matrix array from Fortran
8369 
8370     Synopsis:
8371     MatDenseGetArrayF90(Mat x,{Scalar, pointer :: xx_v(:,:)},integer ierr)
8372 
8373     Not Collective
8374 
8375     Input Parameter:
8376 .   x - matrix
8377 
8378     Output Parameters:
8379 +   xx_v - the Fortran pointer to the array
8380 -   ierr - error code
8381 
8382     Example of Usage:
8383 .vb
8384       PetscScalar, pointer xx_v(:,:)
8385       ....
8386       call MatDenseGetArrayF90(x,xx_v,ierr)
8387       a = xx_v(3)
8388       call MatDenseRestoreArrayF90(x,xx_v,ierr)
8389 .ve
8390 
8391     Level: advanced
8392 
8393 .seealso: [](ch_matrices), `Mat`, `MatDenseRestoreArrayF90()`, `MatDenseGetArray()`, `MatDenseRestoreArray()`, `MatSeqAIJGetArrayF90()`
8394 M*/
8395 
8396 /*MC
8397     MatDenseRestoreArrayF90 - Restores a matrix array that has been
8398     accessed with `MatDenseGetArrayF90()`.
8399 
8400     Synopsis:
8401     MatDenseRestoreArrayF90(Mat x,{Scalar, pointer :: xx_v(:,:)},integer ierr)
8402 
8403     Not Collective
8404 
8405     Input Parameters:
8406 +   x - matrix
8407 -   xx_v - the Fortran90 pointer to the array
8408 
8409     Output Parameter:
8410 .   ierr - error code
8411 
8412     Example of Usage:
8413 .vb
8414        PetscScalar, pointer xx_v(:,:)
8415        ....
8416        call MatDenseGetArrayF90(x,xx_v,ierr)
8417        a = xx_v(3)
8418        call MatDenseRestoreArrayF90(x,xx_v,ierr)
8419 .ve
8420 
8421     Level: advanced
8422 
8423 .seealso: [](ch_matrices), `Mat`, `MatDenseGetArrayF90()`, `MatDenseGetArray()`, `MatDenseRestoreArray()`, `MatSeqAIJRestoreArrayF90()`
8424 M*/
8425 
8426 /*MC
8427     MatSeqAIJGetArrayF90 - Accesses a matrix array from Fortran.
8428 
8429     Synopsis:
8430     MatSeqAIJGetArrayF90(Mat x,{Scalar, pointer :: xx_v(:)},integer ierr)
8431 
8432     Not Collective
8433 
8434     Input Parameter:
8435 .   x - matrix
8436 
8437     Output Parameters:
8438 +   xx_v - the Fortran pointer to the array
8439 -   ierr - error code
8440 
8441     Example of Usage:
8442 .vb
8443       PetscScalar, pointer xx_v(:)
8444       ....
8445       call MatSeqAIJGetArrayF90(x,xx_v,ierr)
8446       a = xx_v(3)
8447       call MatSeqAIJRestoreArrayF90(x,xx_v,ierr)
8448 .ve
8449 
8450     Level: advanced
8451 
8452 .seealso: [](ch_matrices), `Mat`, `MatSeqAIJRestoreArrayF90()`, `MatSeqAIJGetArray()`, `MatSeqAIJRestoreArray()`, `MatDenseGetArrayF90()`
8453 M*/
8454 
8455 /*MC
8456     MatSeqAIJRestoreArrayF90 - Restores a matrix array that has been
8457     accessed with `MatSeqAIJGetArrayF90()`.
8458 
8459     Synopsis:
8460     MatSeqAIJRestoreArrayF90(Mat x,{Scalar, pointer :: xx_v(:)},integer ierr)
8461 
8462     Not Collective
8463 
8464     Input Parameters:
8465 +   x - matrix
8466 -   xx_v - the Fortran90 pointer to the array
8467 
8468     Output Parameter:
8469 .   ierr - error code
8470 
8471     Example of Usage:
8472 .vb
8473        PetscScalar, pointer xx_v(:)
8474        ....
8475        call MatSeqAIJGetArrayF90(x,xx_v,ierr)
8476        a = xx_v(3)
8477        call MatSeqAIJRestoreArrayF90(x,xx_v,ierr)
8478 .ve
8479 
8480     Level: advanced
8481 
8482 .seealso: [](ch_matrices), `Mat`, `MatSeqAIJGetArrayF90()`, `MatSeqAIJGetArray()`, `MatSeqAIJRestoreArray()`, `MatDenseRestoreArrayF90()`
8483 M*/
8484 
8485 /*@
8486   MatCreateSubMatrix - Gets a single submatrix on the same number of processors
8487   as the original matrix.
8488 
8489   Collective
8490 
8491   Input Parameters:
8492 + mat   - the original matrix
8493 . isrow - parallel `IS` containing the rows this processor should obtain
8494 . 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.
8495 - cll   - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`
8496 
8497   Output Parameter:
8498 . newmat - the new submatrix, of the same type as the original matrix
8499 
8500   Level: advanced
8501 
8502   Notes:
8503   The submatrix will be able to be multiplied with vectors using the same layout as `iscol`.
8504 
8505   Some matrix types place restrictions on the row and column indices, such
8506   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;
8507   for example, if the block size is 3 one cannot select the 0 and 2 rows without selecting the 1 row.
8508 
8509   The index sets may not have duplicate entries.
8510 
8511   The first time this is called you should use a cll of `MAT_INITIAL_MATRIX`,
8512   the `MatCreateSubMatrix()` routine will create the newmat for you. Any additional calls
8513   to this routine with a mat of the same nonzero structure and with a call of `MAT_REUSE_MATRIX`
8514   will reuse the matrix generated the first time.  You should call `MatDestroy()` on `newmat` when
8515   you are finished using it.
8516 
8517   The communicator of the newly obtained matrix is ALWAYS the same as the communicator of
8518   the input matrix.
8519 
8520   If `iscol` is `NULL` then all columns are obtained (not supported in Fortran).
8521 
8522   If `isrow` and `iscol` have a nontrivial block-size, then the resulting matrix has this block-size as well. This feature
8523   is used by `PCFIELDSPLIT` to allow easy nesting of its use.
8524 
8525   Example usage:
8526   Consider the following 8x8 matrix with 34 non-zero values, that is
8527   assembled across 3 processors. Let's assume that proc0 owns 3 rows,
8528   proc1 owns 3 rows, proc2 owns 2 rows. This division can be shown
8529   as follows
8530 .vb
8531             1  2  0  |  0  3  0  |  0  4
8532     Proc0   0  5  6  |  7  0  0  |  8  0
8533             9  0 10  | 11  0  0  | 12  0
8534     -------------------------------------
8535            13  0 14  | 15 16 17  |  0  0
8536     Proc1   0 18  0  | 19 20 21  |  0  0
8537             0  0  0  | 22 23  0  | 24  0
8538     -------------------------------------
8539     Proc2  25 26 27  |  0  0 28  | 29  0
8540            30  0  0  | 31 32 33  |  0 34
8541 .ve
8542 
8543   Suppose `isrow` = [0 1 | 4 | 6 7] and `iscol` = [1 2 | 3 4 5 | 6].  The resulting submatrix is
8544 
8545 .vb
8546             2  0  |  0  3  0  |  0
8547     Proc0   5  6  |  7  0  0  |  8
8548     -------------------------------
8549     Proc1  18  0  | 19 20 21  |  0
8550     -------------------------------
8551     Proc2  26 27  |  0  0 28  | 29
8552             0  0  | 31 32 33  |  0
8553 .ve
8554 
8555 .seealso: [](ch_matrices), `Mat`, `MatCreateSubMatrices()`, `MatCreateSubMatricesMPI()`, `MatCreateSubMatrixVirtual()`, `MatSubMatrixVirtualUpdate()`
8556 @*/
8557 PetscErrorCode MatCreateSubMatrix(Mat mat, IS isrow, IS iscol, MatReuse cll, Mat *newmat)
8558 {
8559   PetscMPIInt size;
8560   Mat        *local;
8561   IS          iscoltmp;
8562   PetscBool   flg;
8563 
8564   PetscFunctionBegin;
8565   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
8566   PetscValidHeaderSpecific(isrow, IS_CLASSID, 2);
8567   if (iscol) PetscValidHeaderSpecific(iscol, IS_CLASSID, 3);
8568   PetscAssertPointer(newmat, 5);
8569   if (cll == MAT_REUSE_MATRIX) PetscValidHeaderSpecific(*newmat, MAT_CLASSID, 5);
8570   PetscValidType(mat, 1);
8571   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
8572   PetscCheck(cll != MAT_IGNORE_MATRIX, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Cannot use MAT_IGNORE_MATRIX");
8573 
8574   MatCheckPreallocated(mat, 1);
8575   PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)mat), &size));
8576 
8577   if (!iscol || isrow == iscol) {
8578     PetscBool   stride;
8579     PetscMPIInt grabentirematrix = 0, grab;
8580     PetscCall(PetscObjectTypeCompare((PetscObject)isrow, ISSTRIDE, &stride));
8581     if (stride) {
8582       PetscInt first, step, n, rstart, rend;
8583       PetscCall(ISStrideGetInfo(isrow, &first, &step));
8584       if (step == 1) {
8585         PetscCall(MatGetOwnershipRange(mat, &rstart, &rend));
8586         if (rstart == first) {
8587           PetscCall(ISGetLocalSize(isrow, &n));
8588           if (n == rend - rstart) grabentirematrix = 1;
8589         }
8590       }
8591     }
8592     PetscCall(MPIU_Allreduce(&grabentirematrix, &grab, 1, MPI_INT, MPI_MIN, PetscObjectComm((PetscObject)mat)));
8593     if (grab) {
8594       PetscCall(PetscInfo(mat, "Getting entire matrix as submatrix\n"));
8595       if (cll == MAT_INITIAL_MATRIX) {
8596         *newmat = mat;
8597         PetscCall(PetscObjectReference((PetscObject)mat));
8598       }
8599       PetscFunctionReturn(PETSC_SUCCESS);
8600     }
8601   }
8602 
8603   if (!iscol) {
8604     PetscCall(ISCreateStride(PetscObjectComm((PetscObject)mat), mat->cmap->n, mat->cmap->rstart, 1, &iscoltmp));
8605   } else {
8606     iscoltmp = iscol;
8607   }
8608 
8609   /* if original matrix is on just one processor then use submatrix generated */
8610   if (mat->ops->createsubmatrices && !mat->ops->createsubmatrix && size == 1 && cll == MAT_REUSE_MATRIX) {
8611     PetscCall(MatCreateSubMatrices(mat, 1, &isrow, &iscoltmp, MAT_REUSE_MATRIX, &newmat));
8612     goto setproperties;
8613   } else if (mat->ops->createsubmatrices && !mat->ops->createsubmatrix && size == 1) {
8614     PetscCall(MatCreateSubMatrices(mat, 1, &isrow, &iscoltmp, MAT_INITIAL_MATRIX, &local));
8615     *newmat = *local;
8616     PetscCall(PetscFree(local));
8617     goto setproperties;
8618   } else if (!mat->ops->createsubmatrix) {
8619     /* Create a new matrix type that implements the operation using the full matrix */
8620     PetscCall(PetscLogEventBegin(MAT_CreateSubMat, mat, 0, 0, 0));
8621     switch (cll) {
8622     case MAT_INITIAL_MATRIX:
8623       PetscCall(MatCreateSubMatrixVirtual(mat, isrow, iscoltmp, newmat));
8624       break;
8625     case MAT_REUSE_MATRIX:
8626       PetscCall(MatSubMatrixVirtualUpdate(*newmat, mat, isrow, iscoltmp));
8627       break;
8628     default:
8629       SETERRQ(PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_OUTOFRANGE, "Invalid MatReuse, must be either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX");
8630     }
8631     PetscCall(PetscLogEventEnd(MAT_CreateSubMat, mat, 0, 0, 0));
8632     goto setproperties;
8633   }
8634 
8635   PetscCall(PetscLogEventBegin(MAT_CreateSubMat, mat, 0, 0, 0));
8636   PetscUseTypeMethod(mat, createsubmatrix, isrow, iscoltmp, cll, newmat);
8637   PetscCall(PetscLogEventEnd(MAT_CreateSubMat, mat, 0, 0, 0));
8638 
8639 setproperties:
8640   PetscCall(ISEqualUnsorted(isrow, iscoltmp, &flg));
8641   if (flg) PetscCall(MatPropagateSymmetryOptions(mat, *newmat));
8642   if (!iscol) PetscCall(ISDestroy(&iscoltmp));
8643   if (*newmat && cll == MAT_INITIAL_MATRIX) PetscCall(PetscObjectStateIncrease((PetscObject)*newmat));
8644   PetscFunctionReturn(PETSC_SUCCESS);
8645 }
8646 
8647 /*@
8648   MatPropagateSymmetryOptions - Propagates symmetry options set on a matrix to another matrix
8649 
8650   Not Collective
8651 
8652   Input Parameters:
8653 + A - the matrix we wish to propagate options from
8654 - B - the matrix we wish to propagate options to
8655 
8656   Level: beginner
8657 
8658   Note:
8659   Propagates the options associated to `MAT_SYMMETRY_ETERNAL`, `MAT_STRUCTURALLY_SYMMETRIC`, `MAT_HERMITIAN`, `MAT_SPD`, `MAT_SYMMETRIC`, and `MAT_STRUCTURAL_SYMMETRY_ETERNAL`
8660 
8661 .seealso: [](ch_matrices), `Mat`, `MatSetOption()`, `MatIsSymmetricKnown()`, `MatIsSPDKnown()`, `MatIsHermitianKnown()`, `MatIsStructurallySymmetricKnown()`
8662 @*/
8663 PetscErrorCode MatPropagateSymmetryOptions(Mat A, Mat B)
8664 {
8665   PetscFunctionBegin;
8666   PetscValidHeaderSpecific(A, MAT_CLASSID, 1);
8667   PetscValidHeaderSpecific(B, MAT_CLASSID, 2);
8668   B->symmetry_eternal            = A->symmetry_eternal;
8669   B->structural_symmetry_eternal = A->structural_symmetry_eternal;
8670   B->symmetric                   = A->symmetric;
8671   B->structurally_symmetric      = A->structurally_symmetric;
8672   B->spd                         = A->spd;
8673   B->hermitian                   = A->hermitian;
8674   PetscFunctionReturn(PETSC_SUCCESS);
8675 }
8676 
8677 /*@
8678   MatStashSetInitialSize - sets the sizes of the matrix stash, that is
8679   used during the assembly process to store values that belong to
8680   other processors.
8681 
8682   Not Collective
8683 
8684   Input Parameters:
8685 + mat   - the matrix
8686 . size  - the initial size of the stash.
8687 - bsize - the initial size of the block-stash(if used).
8688 
8689   Options Database Keys:
8690 + -matstash_initial_size <size> or <size0,size1,...sizep-1>            - set initial size
8691 - -matstash_block_initial_size <bsize>  or <bsize0,bsize1,...bsizep-1> - set initial block size
8692 
8693   Level: intermediate
8694 
8695   Notes:
8696   The block-stash is used for values set with `MatSetValuesBlocked()` while
8697   the stash is used for values set with `MatSetValues()`
8698 
8699   Run with the option -info and look for output of the form
8700   MatAssemblyBegin_MPIXXX:Stash has MM entries, uses nn mallocs.
8701   to determine the appropriate value, MM, to use for size and
8702   MatAssemblyBegin_MPIXXX:Block-Stash has BMM entries, uses nn mallocs.
8703   to determine the value, BMM to use for bsize
8704 
8705 .seealso: [](ch_matrices), `MatAssemblyBegin()`, `MatAssemblyEnd()`, `Mat`, `MatStashGetInfo()`
8706 @*/
8707 PetscErrorCode MatStashSetInitialSize(Mat mat, PetscInt size, PetscInt bsize)
8708 {
8709   PetscFunctionBegin;
8710   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
8711   PetscValidType(mat, 1);
8712   PetscCall(MatStashSetInitialSize_Private(&mat->stash, size));
8713   PetscCall(MatStashSetInitialSize_Private(&mat->bstash, bsize));
8714   PetscFunctionReturn(PETSC_SUCCESS);
8715 }
8716 
8717 /*@
8718   MatInterpolateAdd - $w = y + A*x$ or $A^T*x$ depending on the shape of
8719   the matrix
8720 
8721   Neighbor-wise Collective
8722 
8723   Input Parameters:
8724 + A - the matrix
8725 . x - the vector to be multiplied by the interpolation operator
8726 - y - the vector to be added to the result
8727 
8728   Output Parameter:
8729 . w - the resulting vector
8730 
8731   Level: intermediate
8732 
8733   Notes:
8734   `w` may be the same vector as `y`.
8735 
8736   This allows one to use either the restriction or interpolation (its transpose)
8737   matrix to do the interpolation
8738 
8739 .seealso: [](ch_matrices), `Mat`, `MatMultAdd()`, `MatMultTransposeAdd()`, `MatRestrict()`, `PCMG`
8740 @*/
8741 PetscErrorCode MatInterpolateAdd(Mat A, Vec x, Vec y, Vec w)
8742 {
8743   PetscInt M, N, Ny;
8744 
8745   PetscFunctionBegin;
8746   PetscValidHeaderSpecific(A, MAT_CLASSID, 1);
8747   PetscValidHeaderSpecific(x, VEC_CLASSID, 2);
8748   PetscValidHeaderSpecific(y, VEC_CLASSID, 3);
8749   PetscValidHeaderSpecific(w, VEC_CLASSID, 4);
8750   PetscCall(MatGetSize(A, &M, &N));
8751   PetscCall(VecGetSize(y, &Ny));
8752   if (M == Ny) {
8753     PetscCall(MatMultAdd(A, x, y, w));
8754   } else {
8755     PetscCall(MatMultTransposeAdd(A, x, y, w));
8756   }
8757   PetscFunctionReturn(PETSC_SUCCESS);
8758 }
8759 
8760 /*@
8761   MatInterpolate - $y = A*x$ or $A^T*x$ depending on the shape of
8762   the matrix
8763 
8764   Neighbor-wise Collective
8765 
8766   Input Parameters:
8767 + A - the matrix
8768 - x - the vector to be interpolated
8769 
8770   Output Parameter:
8771 . y - the resulting vector
8772 
8773   Level: intermediate
8774 
8775   Note:
8776   This allows one to use either the restriction or interpolation (its transpose)
8777   matrix to do the interpolation
8778 
8779 .seealso: [](ch_matrices), `Mat`, `MatMultAdd()`, `MatMultTransposeAdd()`, `MatRestrict()`, `PCMG`
8780 @*/
8781 PetscErrorCode MatInterpolate(Mat A, Vec x, Vec y)
8782 {
8783   PetscInt M, N, Ny;
8784 
8785   PetscFunctionBegin;
8786   PetscValidHeaderSpecific(A, MAT_CLASSID, 1);
8787   PetscValidHeaderSpecific(x, VEC_CLASSID, 2);
8788   PetscValidHeaderSpecific(y, VEC_CLASSID, 3);
8789   PetscCall(MatGetSize(A, &M, &N));
8790   PetscCall(VecGetSize(y, &Ny));
8791   if (M == Ny) {
8792     PetscCall(MatMult(A, x, y));
8793   } else {
8794     PetscCall(MatMultTranspose(A, x, y));
8795   }
8796   PetscFunctionReturn(PETSC_SUCCESS);
8797 }
8798 
8799 /*@
8800   MatRestrict - $y = A*x$ or $A^T*x$
8801 
8802   Neighbor-wise Collective
8803 
8804   Input Parameters:
8805 + A - the matrix
8806 - x - the vector to be restricted
8807 
8808   Output Parameter:
8809 . y - the resulting vector
8810 
8811   Level: intermediate
8812 
8813   Note:
8814   This allows one to use either the restriction or interpolation (its transpose)
8815   matrix to do the restriction
8816 
8817 .seealso: [](ch_matrices), `Mat`, `MatMultAdd()`, `MatMultTransposeAdd()`, `MatInterpolate()`, `PCMG`
8818 @*/
8819 PetscErrorCode MatRestrict(Mat A, Vec x, Vec y)
8820 {
8821   PetscInt M, N, Nx;
8822 
8823   PetscFunctionBegin;
8824   PetscValidHeaderSpecific(A, MAT_CLASSID, 1);
8825   PetscValidHeaderSpecific(x, VEC_CLASSID, 2);
8826   PetscValidHeaderSpecific(y, VEC_CLASSID, 3);
8827   PetscCall(MatGetSize(A, &M, &N));
8828   PetscCall(VecGetSize(x, &Nx));
8829   if (M == Nx) {
8830     PetscCall(MatMultTranspose(A, x, y));
8831   } else {
8832     PetscCall(MatMult(A, x, y));
8833   }
8834   PetscFunctionReturn(PETSC_SUCCESS);
8835 }
8836 
8837 /*@
8838   MatMatInterpolateAdd - $Y = W + A*X$ or $W + A^T*X$ depending on the shape of `A`
8839 
8840   Neighbor-wise Collective
8841 
8842   Input Parameters:
8843 + A - the matrix
8844 . x - the input dense matrix to be multiplied
8845 - w - the input dense matrix to be added to the result
8846 
8847   Output Parameter:
8848 . y - the output dense matrix
8849 
8850   Level: intermediate
8851 
8852   Note:
8853   This allows one to use either the restriction or interpolation (its transpose)
8854   matrix to do the interpolation. `y` matrix can be reused if already created with the proper sizes,
8855   otherwise it will be recreated. `y` must be initialized to `NULL` if not supplied.
8856 
8857 .seealso: [](ch_matrices), `Mat`, `MatInterpolateAdd()`, `MatMatInterpolate()`, `MatMatRestrict()`, `PCMG`
8858 @*/
8859 PetscErrorCode MatMatInterpolateAdd(Mat A, Mat x, Mat w, Mat *y)
8860 {
8861   PetscInt  M, N, Mx, Nx, Mo, My = 0, Ny = 0;
8862   PetscBool trans = PETSC_TRUE;
8863   MatReuse  reuse = MAT_INITIAL_MATRIX;
8864 
8865   PetscFunctionBegin;
8866   PetscValidHeaderSpecific(A, MAT_CLASSID, 1);
8867   PetscValidHeaderSpecific(x, MAT_CLASSID, 2);
8868   PetscValidType(x, 2);
8869   if (w) PetscValidHeaderSpecific(w, MAT_CLASSID, 3);
8870   if (*y) PetscValidHeaderSpecific(*y, MAT_CLASSID, 4);
8871   PetscCall(MatGetSize(A, &M, &N));
8872   PetscCall(MatGetSize(x, &Mx, &Nx));
8873   if (N == Mx) trans = PETSC_FALSE;
8874   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);
8875   Mo = trans ? N : M;
8876   if (*y) {
8877     PetscCall(MatGetSize(*y, &My, &Ny));
8878     if (Mo == My && Nx == Ny) {
8879       reuse = MAT_REUSE_MATRIX;
8880     } else {
8881       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);
8882       PetscCall(MatDestroy(y));
8883     }
8884   }
8885 
8886   if (w && *y == w) { /* this is to minimize changes in PCMG */
8887     PetscBool flg;
8888 
8889     PetscCall(PetscObjectQuery((PetscObject)*y, "__MatMatIntAdd_w", (PetscObject *)&w));
8890     if (w) {
8891       PetscInt My, Ny, Mw, Nw;
8892 
8893       PetscCall(PetscObjectTypeCompare((PetscObject)*y, ((PetscObject)w)->type_name, &flg));
8894       PetscCall(MatGetSize(*y, &My, &Ny));
8895       PetscCall(MatGetSize(w, &Mw, &Nw));
8896       if (!flg || My != Mw || Ny != Nw) w = NULL;
8897     }
8898     if (!w) {
8899       PetscCall(MatDuplicate(*y, MAT_COPY_VALUES, &w));
8900       PetscCall(PetscObjectCompose((PetscObject)*y, "__MatMatIntAdd_w", (PetscObject)w));
8901       PetscCall(PetscObjectDereference((PetscObject)w));
8902     } else {
8903       PetscCall(MatCopy(*y, w, UNKNOWN_NONZERO_PATTERN));
8904     }
8905   }
8906   if (!trans) {
8907     PetscCall(MatMatMult(A, x, reuse, PETSC_DEFAULT, y));
8908   } else {
8909     PetscCall(MatTransposeMatMult(A, x, reuse, PETSC_DEFAULT, y));
8910   }
8911   if (w) PetscCall(MatAXPY(*y, 1.0, w, UNKNOWN_NONZERO_PATTERN));
8912   PetscFunctionReturn(PETSC_SUCCESS);
8913 }
8914 
8915 /*@
8916   MatMatInterpolate - $Y = A*X$ or $A^T*X$ depending on the shape of `A`
8917 
8918   Neighbor-wise Collective
8919 
8920   Input Parameters:
8921 + A - the matrix
8922 - x - the input dense matrix
8923 
8924   Output Parameter:
8925 . y - the output dense matrix
8926 
8927   Level: intermediate
8928 
8929   Note:
8930   This allows one to use either the restriction or interpolation (its transpose)
8931   matrix to do the interpolation. `y` matrix can be reused if already created with the proper sizes,
8932   otherwise it will be recreated. `y` must be initialized to `NULL` if not supplied.
8933 
8934 .seealso: [](ch_matrices), `Mat`, `MatInterpolate()`, `MatRestrict()`, `MatMatRestrict()`, `PCMG`
8935 @*/
8936 PetscErrorCode MatMatInterpolate(Mat A, Mat x, Mat *y)
8937 {
8938   PetscFunctionBegin;
8939   PetscCall(MatMatInterpolateAdd(A, x, NULL, y));
8940   PetscFunctionReturn(PETSC_SUCCESS);
8941 }
8942 
8943 /*@
8944   MatMatRestrict - $Y = A*X$ or $A^T*X$ depending on the shape of `A`
8945 
8946   Neighbor-wise Collective
8947 
8948   Input Parameters:
8949 + A - the matrix
8950 - x - the input dense matrix
8951 
8952   Output Parameter:
8953 . y - the output dense matrix
8954 
8955   Level: intermediate
8956 
8957   Note:
8958   This allows one to use either the restriction or interpolation (its transpose)
8959   matrix to do the restriction. `y` matrix can be reused if already created with the proper sizes,
8960   otherwise it will be recreated. `y` must be initialized to `NULL` if not supplied.
8961 
8962 .seealso: [](ch_matrices), `Mat`, `MatRestrict()`, `MatInterpolate()`, `MatMatInterpolate()`, `PCMG`
8963 @*/
8964 PetscErrorCode MatMatRestrict(Mat A, Mat x, Mat *y)
8965 {
8966   PetscFunctionBegin;
8967   PetscCall(MatMatInterpolateAdd(A, x, NULL, y));
8968   PetscFunctionReturn(PETSC_SUCCESS);
8969 }
8970 
8971 /*@
8972   MatGetNullSpace - retrieves the null space of a matrix.
8973 
8974   Logically Collective
8975 
8976   Input Parameters:
8977 + mat    - the matrix
8978 - nullsp - the null space object
8979 
8980   Level: developer
8981 
8982 .seealso: [](ch_matrices), `Mat`, `MatCreate()`, `MatNullSpaceCreate()`, `MatSetNearNullSpace()`, `MatSetNullSpace()`, `MatNullSpace`
8983 @*/
8984 PetscErrorCode MatGetNullSpace(Mat mat, MatNullSpace *nullsp)
8985 {
8986   PetscFunctionBegin;
8987   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
8988   PetscAssertPointer(nullsp, 2);
8989   *nullsp = (mat->symmetric == PETSC_BOOL3_TRUE && !mat->nullsp) ? mat->transnullsp : mat->nullsp;
8990   PetscFunctionReturn(PETSC_SUCCESS);
8991 }
8992 
8993 /*@C
8994   MatGetNullSpaces - gets the null spaces, transpose null spaces, and near null spaces from an array of matrices
8995 
8996   Logically Collective
8997 
8998   Input Parameters:
8999 + n   - the number of matrices
9000 - mat - the array of matrices
9001 
9002   Output Parameters:
9003 . nullsp - an array of null spaces, `NULL` for each matrix that does not have a null space, length 3 * `n`
9004 
9005   Level: developer
9006 
9007   Note:
9008   Call `MatRestoreNullspaces()` to provide these to another array of matrices
9009 
9010 .seealso: [](ch_matrices), `Mat`, `MatCreate()`, `MatNullSpaceCreate()`, `MatSetNearNullSpace()`, `MatGetNullSpace()`, `MatSetTransposeNullSpace()`, `MatGetTransposeNullSpace()`,
9011           `MatNullSpaceRemove()`, `MatRestoreNullSpaces()`
9012 @*/
9013 PetscErrorCode MatGetNullSpaces(PetscInt n, Mat mat[], MatNullSpace *nullsp[])
9014 {
9015   PetscFunctionBegin;
9016   PetscCheck(n >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Number of matrices %" PetscInt_FMT " must be non-negative", n);
9017   PetscAssertPointer(mat, 2);
9018   PetscAssertPointer(nullsp, 3);
9019 
9020   PetscCall(PetscCalloc1(3 * n, nullsp));
9021   for (PetscInt i = 0; i < n; i++) {
9022     PetscValidHeaderSpecific(mat[i], MAT_CLASSID, 2);
9023     (*nullsp)[i] = mat[i]->nullsp;
9024     PetscCall(PetscObjectReference((PetscObject)(*nullsp)[i]));
9025     (*nullsp)[n + i] = mat[i]->nearnullsp;
9026     PetscCall(PetscObjectReference((PetscObject)(*nullsp)[n + i]));
9027     (*nullsp)[2 * n + i] = mat[i]->transnullsp;
9028     PetscCall(PetscObjectReference((PetscObject)(*nullsp)[2 * n + i]));
9029   }
9030   PetscFunctionReturn(PETSC_SUCCESS);
9031 }
9032 
9033 /*@C
9034   MatRestoreNullSpaces - sets the null spaces, transpose null spaces, and near null spaces obtained with `MatGetNullSpaces()` for an array of matrices
9035 
9036   Logically Collective
9037 
9038   Input Parameters:
9039 + n      - the number of matrices
9040 . mat    - the array of matrices
9041 - nullsp - an array of null spaces
9042 
9043   Level: developer
9044 
9045   Note:
9046   Call `MatGetNullSpaces()` to create `nullsp`
9047 
9048 .seealso: [](ch_matrices), `Mat`, `MatCreate()`, `MatNullSpaceCreate()`, `MatSetNearNullSpace()`, `MatGetNullSpace()`, `MatSetTransposeNullSpace()`, `MatGetTransposeNullSpace()`,
9049           `MatNullSpaceRemove()`, `MatGetNullSpaces()`
9050 @*/
9051 PetscErrorCode MatRestoreNullSpaces(PetscInt n, Mat mat[], MatNullSpace *nullsp[])
9052 {
9053   PetscFunctionBegin;
9054   PetscCheck(n >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Number of matrices %" PetscInt_FMT " must be non-negative", n);
9055   PetscAssertPointer(mat, 2);
9056   PetscAssertPointer(nullsp, 3);
9057   PetscAssertPointer(*nullsp, 3);
9058 
9059   for (PetscInt i = 0; i < n; i++) {
9060     PetscValidHeaderSpecific(mat[i], MAT_CLASSID, 2);
9061     PetscCall(MatSetNullSpace(mat[i], (*nullsp)[i]));
9062     PetscCall(PetscObjectDereference((PetscObject)(*nullsp)[i]));
9063     PetscCall(MatSetNearNullSpace(mat[i], (*nullsp)[n + i]));
9064     PetscCall(PetscObjectDereference((PetscObject)(*nullsp)[n + i]));
9065     PetscCall(MatSetTransposeNullSpace(mat[i], (*nullsp)[2 * n + i]));
9066     PetscCall(PetscObjectDereference((PetscObject)(*nullsp)[2 * n + i]));
9067   }
9068   PetscCall(PetscFree(*nullsp));
9069   PetscFunctionReturn(PETSC_SUCCESS);
9070 }
9071 
9072 /*@
9073   MatSetNullSpace - attaches a null space to a matrix.
9074 
9075   Logically Collective
9076 
9077   Input Parameters:
9078 + mat    - the matrix
9079 - nullsp - the null space object
9080 
9081   Level: advanced
9082 
9083   Notes:
9084   This null space is used by the `KSP` linear solvers to solve singular systems.
9085 
9086   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`
9087 
9088   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 to
9089   to zero but the linear system will still be solved in a least squares sense.
9090 
9091   The fundamental theorem of linear algebra (Gilbert Strang, Introduction to Applied Mathematics, page 72) states that
9092   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), + the range of $A^T$, $R(A^T)$.
9093   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
9094   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
9095   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$).
9096   This  \hat{b} can be obtained by calling `MatNullSpaceRemove()` with the null space of the transpose of the matrix.
9097 
9098   If the matrix is known to be symmetric because it is an `MATSBAIJ` matrix or one as called
9099   `MatSetOption`(mat,`MAT_SYMMETRIC` or possibly `MAT_SYMMETRY_ETERNAL`,`PETSC_TRUE`); this
9100   routine also automatically calls `MatSetTransposeNullSpace()`.
9101 
9102   The user should call `MatNullSpaceDestroy()`.
9103 
9104 .seealso: [](ch_matrices), `Mat`, `MatCreate()`, `MatNullSpaceCreate()`, `MatSetNearNullSpace()`, `MatGetNullSpace()`, `MatSetTransposeNullSpace()`, `MatGetTransposeNullSpace()`, `MatNullSpaceRemove()`,
9105           `KSPSetPCSide()`
9106 @*/
9107 PetscErrorCode MatSetNullSpace(Mat mat, MatNullSpace nullsp)
9108 {
9109   PetscFunctionBegin;
9110   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
9111   if (nullsp) PetscValidHeaderSpecific(nullsp, MAT_NULLSPACE_CLASSID, 2);
9112   if (nullsp) PetscCall(PetscObjectReference((PetscObject)nullsp));
9113   PetscCall(MatNullSpaceDestroy(&mat->nullsp));
9114   mat->nullsp = nullsp;
9115   if (mat->symmetric == PETSC_BOOL3_TRUE) PetscCall(MatSetTransposeNullSpace(mat, nullsp));
9116   PetscFunctionReturn(PETSC_SUCCESS);
9117 }
9118 
9119 /*@
9120   MatGetTransposeNullSpace - retrieves the null space of the transpose of a matrix.
9121 
9122   Logically Collective
9123 
9124   Input Parameters:
9125 + mat    - the matrix
9126 - nullsp - the null space object
9127 
9128   Level: developer
9129 
9130 .seealso: [](ch_matrices), `Mat`, `MatNullSpace`, `MatCreate()`, `MatNullSpaceCreate()`, `MatSetNearNullSpace()`, `MatSetTransposeNullSpace()`, `MatSetNullSpace()`, `MatGetNullSpace()`
9131 @*/
9132 PetscErrorCode MatGetTransposeNullSpace(Mat mat, MatNullSpace *nullsp)
9133 {
9134   PetscFunctionBegin;
9135   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
9136   PetscValidType(mat, 1);
9137   PetscAssertPointer(nullsp, 2);
9138   *nullsp = (mat->symmetric == PETSC_BOOL3_TRUE && !mat->transnullsp) ? mat->nullsp : mat->transnullsp;
9139   PetscFunctionReturn(PETSC_SUCCESS);
9140 }
9141 
9142 /*@
9143   MatSetTransposeNullSpace - attaches the null space of a transpose of a matrix to the matrix
9144 
9145   Logically Collective
9146 
9147   Input Parameters:
9148 + mat    - the matrix
9149 - nullsp - the null space object
9150 
9151   Level: advanced
9152 
9153   Notes:
9154   This allows solving singular linear systems defined by the transpose of the matrix using `KSP` solvers with left preconditioning.
9155 
9156   See `MatSetNullSpace()`
9157 
9158 .seealso: [](ch_matrices), `Mat`, `MatNullSpace`, `MatCreate()`, `MatNullSpaceCreate()`, `MatSetNearNullSpace()`, `MatGetNullSpace()`, `MatSetNullSpace()`, `MatGetTransposeNullSpace()`, `MatNullSpaceRemove()`, `KSPSetPCSide()`
9159 @*/
9160 PetscErrorCode MatSetTransposeNullSpace(Mat mat, MatNullSpace nullsp)
9161 {
9162   PetscFunctionBegin;
9163   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
9164   if (nullsp) PetscValidHeaderSpecific(nullsp, MAT_NULLSPACE_CLASSID, 2);
9165   if (nullsp) PetscCall(PetscObjectReference((PetscObject)nullsp));
9166   PetscCall(MatNullSpaceDestroy(&mat->transnullsp));
9167   mat->transnullsp = nullsp;
9168   PetscFunctionReturn(PETSC_SUCCESS);
9169 }
9170 
9171 /*@
9172   MatSetNearNullSpace - attaches a null space to a matrix, which is often the null space (rigid body modes) of the operator without boundary conditions
9173   This null space will be used to provide near null space vectors to a multigrid preconditioner built from this matrix.
9174 
9175   Logically Collective
9176 
9177   Input Parameters:
9178 + mat    - the matrix
9179 - nullsp - the null space object
9180 
9181   Level: advanced
9182 
9183   Notes:
9184   Overwrites any previous near null space that may have been attached
9185 
9186   You can remove the null space by calling this routine with an `nullsp` of `NULL`
9187 
9188 .seealso: [](ch_matrices), `Mat`, `MatNullSpace`, `MatCreate()`, `MatNullSpaceCreate()`, `MatSetNullSpace()`, `MatNullSpaceCreateRigidBody()`, `MatGetNearNullSpace()`
9189 @*/
9190 PetscErrorCode MatSetNearNullSpace(Mat mat, MatNullSpace nullsp)
9191 {
9192   PetscFunctionBegin;
9193   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
9194   PetscValidType(mat, 1);
9195   if (nullsp) PetscValidHeaderSpecific(nullsp, MAT_NULLSPACE_CLASSID, 2);
9196   MatCheckPreallocated(mat, 1);
9197   if (nullsp) PetscCall(PetscObjectReference((PetscObject)nullsp));
9198   PetscCall(MatNullSpaceDestroy(&mat->nearnullsp));
9199   mat->nearnullsp = nullsp;
9200   PetscFunctionReturn(PETSC_SUCCESS);
9201 }
9202 
9203 /*@
9204   MatGetNearNullSpace - Get null space attached with `MatSetNearNullSpace()`
9205 
9206   Not Collective
9207 
9208   Input Parameter:
9209 . mat - the matrix
9210 
9211   Output Parameter:
9212 . nullsp - the null space object, `NULL` if not set
9213 
9214   Level: advanced
9215 
9216 .seealso: [](ch_matrices), `Mat`, `MatNullSpace`, `MatSetNearNullSpace()`, `MatGetNullSpace()`, `MatNullSpaceCreate()`
9217 @*/
9218 PetscErrorCode MatGetNearNullSpace(Mat mat, MatNullSpace *nullsp)
9219 {
9220   PetscFunctionBegin;
9221   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
9222   PetscValidType(mat, 1);
9223   PetscAssertPointer(nullsp, 2);
9224   MatCheckPreallocated(mat, 1);
9225   *nullsp = mat->nearnullsp;
9226   PetscFunctionReturn(PETSC_SUCCESS);
9227 }
9228 
9229 /*@
9230   MatICCFactor - Performs in-place incomplete Cholesky factorization of matrix.
9231 
9232   Collective
9233 
9234   Input Parameters:
9235 + mat  - the matrix
9236 . row  - row/column permutation
9237 - info - information on desired factorization process
9238 
9239   Level: developer
9240 
9241   Notes:
9242   Probably really in-place only when level of fill is zero, otherwise allocates
9243   new space to store factored matrix and deletes previous memory.
9244 
9245   Most users should employ the `KSP` interface for linear solvers
9246   instead of working directly with matrix algebra routines such as this.
9247   See, e.g., `KSPCreate()`.
9248 
9249   Developer Note:
9250   The Fortran interface is not autogenerated as the
9251   interface definition cannot be generated correctly [due to `MatFactorInfo`]
9252 
9253 .seealso: [](ch_matrices), `Mat`, `MatFactorInfo`, `MatGetFactor()`, `MatICCFactorSymbolic()`, `MatLUFactorNumeric()`, `MatCholeskyFactor()`
9254 @*/
9255 PetscErrorCode MatICCFactor(Mat mat, IS row, const MatFactorInfo *info)
9256 {
9257   PetscFunctionBegin;
9258   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
9259   PetscValidType(mat, 1);
9260   if (row) PetscValidHeaderSpecific(row, IS_CLASSID, 2);
9261   PetscAssertPointer(info, 3);
9262   PetscCheck(mat->rmap->N == mat->cmap->N, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONG, "matrix must be square");
9263   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
9264   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
9265   MatCheckPreallocated(mat, 1);
9266   PetscUseTypeMethod(mat, iccfactor, row, info);
9267   PetscCall(PetscObjectStateIncrease((PetscObject)mat));
9268   PetscFunctionReturn(PETSC_SUCCESS);
9269 }
9270 
9271 /*@
9272   MatDiagonalScaleLocal - Scales columns of a matrix given the scaling values including the
9273   ghosted ones.
9274 
9275   Not Collective
9276 
9277   Input Parameters:
9278 + mat  - the matrix
9279 - diag - the diagonal values, including ghost ones
9280 
9281   Level: developer
9282 
9283   Notes:
9284   Works only for `MATMPIAIJ` and `MATMPIBAIJ` matrices
9285 
9286   This allows one to avoid during communication to perform the scaling that must be done with `MatDiagonalScale()`
9287 
9288 .seealso: [](ch_matrices), `Mat`, `MatDiagonalScale()`
9289 @*/
9290 PetscErrorCode MatDiagonalScaleLocal(Mat mat, Vec diag)
9291 {
9292   PetscMPIInt size;
9293 
9294   PetscFunctionBegin;
9295   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
9296   PetscValidHeaderSpecific(diag, VEC_CLASSID, 2);
9297   PetscValidType(mat, 1);
9298 
9299   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Matrix must be already assembled");
9300   PetscCall(PetscLogEventBegin(MAT_Scale, mat, 0, 0, 0));
9301   PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)mat), &size));
9302   if (size == 1) {
9303     PetscInt n, m;
9304     PetscCall(VecGetSize(diag, &n));
9305     PetscCall(MatGetSize(mat, NULL, &m));
9306     PetscCheck(m == n, PETSC_COMM_SELF, PETSC_ERR_SUP, "Only supported for sequential matrices when no ghost points/periodic conditions");
9307     PetscCall(MatDiagonalScale(mat, NULL, diag));
9308   } else {
9309     PetscUseMethod(mat, "MatDiagonalScaleLocal_C", (Mat, Vec), (mat, diag));
9310   }
9311   PetscCall(PetscLogEventEnd(MAT_Scale, mat, 0, 0, 0));
9312   PetscCall(PetscObjectStateIncrease((PetscObject)mat));
9313   PetscFunctionReturn(PETSC_SUCCESS);
9314 }
9315 
9316 /*@
9317   MatGetInertia - Gets the inertia from a factored matrix
9318 
9319   Collective
9320 
9321   Input Parameter:
9322 . mat - the matrix
9323 
9324   Output Parameters:
9325 + nneg  - number of negative eigenvalues
9326 . nzero - number of zero eigenvalues
9327 - npos  - number of positive eigenvalues
9328 
9329   Level: advanced
9330 
9331   Note:
9332   Matrix must have been factored by `MatCholeskyFactor()`
9333 
9334 .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatCholeskyFactor()`
9335 @*/
9336 PetscErrorCode MatGetInertia(Mat mat, PetscInt *nneg, PetscInt *nzero, PetscInt *npos)
9337 {
9338   PetscFunctionBegin;
9339   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
9340   PetscValidType(mat, 1);
9341   PetscCheck(mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Unfactored matrix");
9342   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Numeric factor mat is not assembled");
9343   PetscUseTypeMethod(mat, getinertia, nneg, nzero, npos);
9344   PetscFunctionReturn(PETSC_SUCCESS);
9345 }
9346 
9347 /*@C
9348   MatSolves - Solves $A x = b$, given a factored matrix, for a collection of vectors
9349 
9350   Neighbor-wise Collective
9351 
9352   Input Parameters:
9353 + mat - the factored matrix obtained with `MatGetFactor()`
9354 - b   - the right-hand-side vectors
9355 
9356   Output Parameter:
9357 . x - the result vectors
9358 
9359   Level: developer
9360 
9361   Note:
9362   The vectors `b` and `x` cannot be the same.  I.e., one cannot
9363   call `MatSolves`(A,x,x).
9364 
9365 .seealso: [](ch_matrices), `Mat`, `Vecs`, `MatSolveAdd()`, `MatSolveTranspose()`, `MatSolveTransposeAdd()`, `MatSolve()`
9366 @*/
9367 PetscErrorCode MatSolves(Mat mat, Vecs b, Vecs x)
9368 {
9369   PetscFunctionBegin;
9370   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
9371   PetscValidType(mat, 1);
9372   PetscCheck(x != b, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_IDN, "x and b must be different vectors");
9373   PetscCheck(mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Unfactored matrix");
9374   if (!mat->rmap->N && !mat->cmap->N) PetscFunctionReturn(PETSC_SUCCESS);
9375 
9376   MatCheckPreallocated(mat, 1);
9377   PetscCall(PetscLogEventBegin(MAT_Solves, mat, 0, 0, 0));
9378   PetscUseTypeMethod(mat, solves, b, x);
9379   PetscCall(PetscLogEventEnd(MAT_Solves, mat, 0, 0, 0));
9380   PetscFunctionReturn(PETSC_SUCCESS);
9381 }
9382 
9383 /*@
9384   MatIsSymmetric - Test whether a matrix is symmetric
9385 
9386   Collective
9387 
9388   Input Parameters:
9389 + A   - the matrix to test
9390 - tol - difference between value and its transpose less than this amount counts as equal (use 0.0 for exact transpose)
9391 
9392   Output Parameter:
9393 . flg - the result
9394 
9395   Level: intermediate
9396 
9397   Notes:
9398   For real numbers `MatIsSymmetric()` and `MatIsHermitian()` return identical results
9399 
9400   If the matrix does not yet know if it is symmetric or not this can be an expensive operation, also available `MatIsSymmetricKnown()`
9401 
9402   One can declare that a matrix is symmetric with `MatSetOption`(mat,`MAT_SYMMETRIC`,`PETSC_TRUE`) and if it is known to remain symmetric
9403   after changes to the matrices values one can call `MatSetOption`(mat,`MAT_SYMMETRY_ETERNAL`,`PETSC_TRUE`)
9404 
9405 .seealso: [](ch_matrices), `Mat`, `MatTranspose()`, `MatIsTranspose()`, `MatIsHermitian()`, `MatIsStructurallySymmetric()`, `MatSetOption()`, `MatIsSymmetricKnown()`,
9406           `MAT_SYMMETRIC`, `MAT_SYMMETRY_ETERNAL`
9407 @*/
9408 PetscErrorCode MatIsSymmetric(Mat A, PetscReal tol, PetscBool *flg)
9409 {
9410   PetscFunctionBegin;
9411   PetscValidHeaderSpecific(A, MAT_CLASSID, 1);
9412   PetscAssertPointer(flg, 3);
9413   if (A->symmetric != PETSC_BOOL3_UNKNOWN) *flg = PetscBool3ToBool(A->symmetric);
9414   else {
9415     if (A->ops->issymmetric) PetscUseTypeMethod(A, issymmetric, tol, flg);
9416     else PetscCall(MatIsTranspose(A, A, tol, flg));
9417     if (!tol) PetscCall(MatSetOption(A, MAT_SYMMETRIC, *flg));
9418   }
9419   PetscFunctionReturn(PETSC_SUCCESS);
9420 }
9421 
9422 /*@
9423   MatIsHermitian - Test whether a matrix is Hermitian
9424 
9425   Collective
9426 
9427   Input Parameters:
9428 + A   - the matrix to test
9429 - tol - difference between value and its transpose less than this amount counts as equal (use 0.0 for exact Hermitian)
9430 
9431   Output Parameter:
9432 . flg - the result
9433 
9434   Level: intermediate
9435 
9436   Notes:
9437   For real numbers `MatIsSymmetric()` and `MatIsHermitian()` return identical results
9438 
9439   If the matrix does not yet know if it is Hermitian or not this can be an expensive operation, also available `MatIsHermitianKnown()`
9440 
9441   One can declare that a matrix is Hermitian with `MatSetOption`(mat,`MAT_HERMITIAN`,`PETSC_TRUE`) and if it is known to remain Hermitian
9442   after changes to the matrices values one can call `MatSetOption`(mat,`MAT_SYMEMTRY_ETERNAL`,`PETSC_TRUE`)
9443 
9444 .seealso: [](ch_matrices), `Mat`, `MatTranspose()`, `MatIsTranspose()`, `MatIsHermitianKnown()`, `MatIsStructurallySymmetric()`, `MatSetOption()`,
9445           `MatIsSymmetricKnown()`, `MatIsSymmetric()`, `MAT_HERMITIAN`, `MAT_SYMMETRY_ETERNAL`
9446 @*/
9447 PetscErrorCode MatIsHermitian(Mat A, PetscReal tol, PetscBool *flg)
9448 {
9449   PetscFunctionBegin;
9450   PetscValidHeaderSpecific(A, MAT_CLASSID, 1);
9451   PetscAssertPointer(flg, 3);
9452   if (A->hermitian != PETSC_BOOL3_UNKNOWN) *flg = PetscBool3ToBool(A->hermitian);
9453   else {
9454     if (A->ops->ishermitian) PetscUseTypeMethod(A, ishermitian, tol, flg);
9455     else PetscCall(MatIsHermitianTranspose(A, A, tol, flg));
9456     if (!tol) PetscCall(MatSetOption(A, MAT_HERMITIAN, *flg));
9457   }
9458   PetscFunctionReturn(PETSC_SUCCESS);
9459 }
9460 
9461 /*@
9462   MatIsSymmetricKnown - Checks if a matrix knows if it is symmetric or not and its symmetric state
9463 
9464   Not Collective
9465 
9466   Input Parameter:
9467 . A - the matrix to check
9468 
9469   Output Parameters:
9470 + set - `PETSC_TRUE` if the matrix knows its symmetry state (this tells you if the next flag is valid)
9471 - flg - the result (only valid if set is `PETSC_TRUE`)
9472 
9473   Level: advanced
9474 
9475   Notes:
9476   Does not check the matrix values directly, so this may return unknown (set = `PETSC_FALSE`). Use `MatIsSymmetric()`
9477   if you want it explicitly checked
9478 
9479   One can declare that a matrix is symmetric with `MatSetOption`(mat,`MAT_SYMMETRIC`,`PETSC_TRUE`) and if it is known to remain symmetric
9480   after changes to the matrices values one can call `MatSetOption`(mat,`MAT_SYMMETRY_ETERNAL`,`PETSC_TRUE`)
9481 
9482 .seealso: [](ch_matrices), `Mat`, `MAT_SYMMETRY_ETERNAL`, `MatTranspose()`, `MatIsTranspose()`, `MatIsHermitian()`, `MatIsStructurallySymmetric()`, `MatSetOption()`, `MatIsSymmetric()`, `MatIsHermitianKnown()`
9483 @*/
9484 PetscErrorCode MatIsSymmetricKnown(Mat A, PetscBool *set, PetscBool *flg)
9485 {
9486   PetscFunctionBegin;
9487   PetscValidHeaderSpecific(A, MAT_CLASSID, 1);
9488   PetscAssertPointer(set, 2);
9489   PetscAssertPointer(flg, 3);
9490   if (A->symmetric != PETSC_BOOL3_UNKNOWN) {
9491     *set = PETSC_TRUE;
9492     *flg = PetscBool3ToBool(A->symmetric);
9493   } else {
9494     *set = PETSC_FALSE;
9495   }
9496   PetscFunctionReturn(PETSC_SUCCESS);
9497 }
9498 
9499 /*@
9500   MatIsSPDKnown - Checks if a matrix knows if it is symmetric positive definite or not and its symmetric positive definite state
9501 
9502   Not Collective
9503 
9504   Input Parameter:
9505 . A - the matrix to check
9506 
9507   Output Parameters:
9508 + set - `PETSC_TRUE` if the matrix knows its symmetric positive definite state (this tells you if the next flag is valid)
9509 - flg - the result (only valid if set is `PETSC_TRUE`)
9510 
9511   Level: advanced
9512 
9513   Notes:
9514   Does not check the matrix values directly, so this may return unknown (set = `PETSC_FALSE`).
9515 
9516   One can declare that a matrix is SPD with `MatSetOption`(mat,`MAT_SPD`,`PETSC_TRUE`) and if it is known to remain SPD
9517   after changes to the matrices values one can call `MatSetOption`(mat,`MAT_SPD_ETERNAL`,`PETSC_TRUE`)
9518 
9519 .seealso: [](ch_matrices), `Mat`, `MAT_SPD_ETERNAL`, `MAT_SPD`, `MatTranspose()`, `MatIsTranspose()`, `MatIsHermitian()`, `MatIsStructurallySymmetric()`, `MatSetOption()`, `MatIsSymmetric()`, `MatIsHermitianKnown()`
9520 @*/
9521 PetscErrorCode MatIsSPDKnown(Mat A, PetscBool *set, PetscBool *flg)
9522 {
9523   PetscFunctionBegin;
9524   PetscValidHeaderSpecific(A, MAT_CLASSID, 1);
9525   PetscAssertPointer(set, 2);
9526   PetscAssertPointer(flg, 3);
9527   if (A->spd != PETSC_BOOL3_UNKNOWN) {
9528     *set = PETSC_TRUE;
9529     *flg = PetscBool3ToBool(A->spd);
9530   } else {
9531     *set = PETSC_FALSE;
9532   }
9533   PetscFunctionReturn(PETSC_SUCCESS);
9534 }
9535 
9536 /*@
9537   MatIsHermitianKnown - Checks if a matrix knows if it is Hermitian or not and its Hermitian state
9538 
9539   Not Collective
9540 
9541   Input Parameter:
9542 . A - the matrix to check
9543 
9544   Output Parameters:
9545 + set - `PETSC_TRUE` if the matrix knows its Hermitian state (this tells you if the next flag is valid)
9546 - flg - the result (only valid if set is `PETSC_TRUE`)
9547 
9548   Level: advanced
9549 
9550   Notes:
9551   Does not check the matrix values directly, so this may return unknown (set = `PETSC_FALSE`). Use `MatIsHermitian()`
9552   if you want it explicitly checked
9553 
9554   One can declare that a matrix is Hermitian with `MatSetOption`(mat,`MAT_HERMITIAN`,`PETSC_TRUE`) and if it is known to remain Hermitian
9555   after changes to the matrices values one can call `MatSetOption`(mat,`MAT_SYMMETRY_ETERNAL`,`PETSC_TRUE`)
9556 
9557 .seealso: [](ch_matrices), `Mat`, `MAT_SYMMETRY_ETERNAL`, `MAT_HERMITIAN`, `MatTranspose()`, `MatIsTranspose()`, `MatIsHermitian()`, `MatIsStructurallySymmetric()`, `MatSetOption()`, `MatIsSymmetric()`
9558 @*/
9559 PetscErrorCode MatIsHermitianKnown(Mat A, PetscBool *set, PetscBool *flg)
9560 {
9561   PetscFunctionBegin;
9562   PetscValidHeaderSpecific(A, MAT_CLASSID, 1);
9563   PetscAssertPointer(set, 2);
9564   PetscAssertPointer(flg, 3);
9565   if (A->hermitian != PETSC_BOOL3_UNKNOWN) {
9566     *set = PETSC_TRUE;
9567     *flg = PetscBool3ToBool(A->hermitian);
9568   } else {
9569     *set = PETSC_FALSE;
9570   }
9571   PetscFunctionReturn(PETSC_SUCCESS);
9572 }
9573 
9574 /*@
9575   MatIsStructurallySymmetric - Test whether a matrix is structurally symmetric
9576 
9577   Collective
9578 
9579   Input Parameter:
9580 . A - the matrix to test
9581 
9582   Output Parameter:
9583 . flg - the result
9584 
9585   Level: intermediate
9586 
9587   Notes:
9588   If the matrix does yet know it is structurally symmetric this can be an expensive operation, also available `MatIsStructurallySymmetricKnown()`
9589 
9590   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
9591   symmetric after changes to the matrices values one can call `MatSetOption`(mat,`MAT_STRUCTURAL_SYMMETRY_ETERNAL`,`PETSC_TRUE`)
9592 
9593 .seealso: [](ch_matrices), `Mat`, `MAT_STRUCTURALLY_SYMMETRIC`, `MAT_STRUCTURAL_SYMMETRY_ETERNAL`, `MatTranspose()`, `MatIsTranspose()`, `MatIsHermitian()`, `MatIsSymmetric()`, `MatSetOption()`, `MatIsStructurallySymmetricKnown()`
9594 @*/
9595 PetscErrorCode MatIsStructurallySymmetric(Mat A, PetscBool *flg)
9596 {
9597   PetscFunctionBegin;
9598   PetscValidHeaderSpecific(A, MAT_CLASSID, 1);
9599   PetscAssertPointer(flg, 2);
9600   if (A->structurally_symmetric != PETSC_BOOL3_UNKNOWN) {
9601     *flg = PetscBool3ToBool(A->structurally_symmetric);
9602   } else {
9603     PetscUseTypeMethod(A, isstructurallysymmetric, flg);
9604     PetscCall(MatSetOption(A, MAT_STRUCTURALLY_SYMMETRIC, *flg));
9605   }
9606   PetscFunctionReturn(PETSC_SUCCESS);
9607 }
9608 
9609 /*@
9610   MatIsStructurallySymmetricKnown - Checks if a matrix knows if it is structurally symmetric or not and its structurally symmetric state
9611 
9612   Not Collective
9613 
9614   Input Parameter:
9615 . A - the matrix to check
9616 
9617   Output Parameters:
9618 + set - PETSC_TRUE if the matrix knows its structurally symmetric state (this tells you if the next flag is valid)
9619 - flg - the result (only valid if set is PETSC_TRUE)
9620 
9621   Level: advanced
9622 
9623   Notes:
9624   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
9625   symmetric after changes to the matrices values one can call `MatSetOption`(mat,`MAT_STRUCTURAL_SYMMETRY_ETERNAL`,`PETSC_TRUE`)
9626 
9627   Use `MatIsStructurallySymmetric()` to explicitly check if a matrix is structurally symmetric (this is an expensive operation)
9628 
9629 .seealso: [](ch_matrices), `Mat`, `MAT_STRUCTURALLY_SYMMETRIC`, `MatTranspose()`, `MatIsTranspose()`, `MatIsHermitian()`, `MatIsStructurallySymmetric()`, `MatSetOption()`, `MatIsSymmetric()`, `MatIsHermitianKnown()`
9630 @*/
9631 PetscErrorCode MatIsStructurallySymmetricKnown(Mat A, PetscBool *set, PetscBool *flg)
9632 {
9633   PetscFunctionBegin;
9634   PetscValidHeaderSpecific(A, MAT_CLASSID, 1);
9635   PetscAssertPointer(set, 2);
9636   PetscAssertPointer(flg, 3);
9637   if (A->structurally_symmetric != PETSC_BOOL3_UNKNOWN) {
9638     *set = PETSC_TRUE;
9639     *flg = PetscBool3ToBool(A->structurally_symmetric);
9640   } else {
9641     *set = PETSC_FALSE;
9642   }
9643   PetscFunctionReturn(PETSC_SUCCESS);
9644 }
9645 
9646 /*@
9647   MatStashGetInfo - Gets how many values are currently in the matrix stash, i.e. need
9648   to be communicated to other processors during the `MatAssemblyBegin()`/`MatAssemblyEnd()` process
9649 
9650   Not Collective
9651 
9652   Input Parameter:
9653 . mat - the matrix
9654 
9655   Output Parameters:
9656 + nstash    - the size of the stash
9657 . reallocs  - the number of additional mallocs incurred.
9658 . bnstash   - the size of the block stash
9659 - breallocs - the number of additional mallocs incurred.in the block stash
9660 
9661   Level: advanced
9662 
9663 .seealso: [](ch_matrices), `MatAssemblyBegin()`, `MatAssemblyEnd()`, `Mat`, `MatStashSetInitialSize()`
9664 @*/
9665 PetscErrorCode MatStashGetInfo(Mat mat, PetscInt *nstash, PetscInt *reallocs, PetscInt *bnstash, PetscInt *breallocs)
9666 {
9667   PetscFunctionBegin;
9668   PetscCall(MatStashGetInfo_Private(&mat->stash, nstash, reallocs));
9669   PetscCall(MatStashGetInfo_Private(&mat->bstash, bnstash, breallocs));
9670   PetscFunctionReturn(PETSC_SUCCESS);
9671 }
9672 
9673 /*@
9674   MatCreateVecs - Get vector(s) compatible with the matrix, i.e. with the same
9675   parallel layout, `PetscLayout` for rows and columns
9676 
9677   Collective
9678 
9679   Input Parameter:
9680 . mat - the matrix
9681 
9682   Output Parameters:
9683 + right - (optional) vector that the matrix can be multiplied against
9684 - left  - (optional) vector that the matrix vector product can be stored in
9685 
9686   Level: advanced
9687 
9688   Notes:
9689   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()`.
9690 
9691   These are new vectors which are not owned by the mat, they should be destroyed in `VecDestroy()` when no longer needed
9692 
9693 .seealso: [](ch_matrices), `Mat`, `Vec`, `VecCreate()`, `VecDestroy()`, `DMCreateGlobalVector()`
9694 @*/
9695 PetscErrorCode MatCreateVecs(Mat mat, Vec *right, Vec *left)
9696 {
9697   PetscFunctionBegin;
9698   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
9699   PetscValidType(mat, 1);
9700   if (mat->ops->getvecs) {
9701     PetscUseTypeMethod(mat, getvecs, right, left);
9702   } else {
9703     if (right) {
9704       PetscCheck(mat->cmap->n >= 0, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "PetscLayout for columns not yet setup");
9705       PetscCall(VecCreateWithLayout_Private(mat->cmap, right));
9706       PetscCall(VecSetType(*right, mat->defaultvectype));
9707 #if defined(PETSC_HAVE_VIENNACL) || defined(PETSC_HAVE_CUDA) || defined(PETSC_HAVE_HIP)
9708       if (mat->boundtocpu && mat->bindingpropagates) {
9709         PetscCall(VecSetBindingPropagates(*right, PETSC_TRUE));
9710         PetscCall(VecBindToCPU(*right, PETSC_TRUE));
9711       }
9712 #endif
9713     }
9714     if (left) {
9715       PetscCheck(mat->rmap->n >= 0, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "PetscLayout for rows not yet setup");
9716       PetscCall(VecCreateWithLayout_Private(mat->rmap, left));
9717       PetscCall(VecSetType(*left, mat->defaultvectype));
9718 #if defined(PETSC_HAVE_VIENNACL) || defined(PETSC_HAVE_CUDA) || defined(PETSC_HAVE_HIP)
9719       if (mat->boundtocpu && mat->bindingpropagates) {
9720         PetscCall(VecSetBindingPropagates(*left, PETSC_TRUE));
9721         PetscCall(VecBindToCPU(*left, PETSC_TRUE));
9722       }
9723 #endif
9724     }
9725   }
9726   PetscFunctionReturn(PETSC_SUCCESS);
9727 }
9728 
9729 /*@
9730   MatFactorInfoInitialize - Initializes a `MatFactorInfo` data structure
9731   with default values.
9732 
9733   Not Collective
9734 
9735   Input Parameter:
9736 . info - the `MatFactorInfo` data structure
9737 
9738   Level: developer
9739 
9740   Notes:
9741   The solvers are generally used through the `KSP` and `PC` objects, for example
9742   `PCLU`, `PCILU`, `PCCHOLESKY`, `PCICC`
9743 
9744   Once the data structure is initialized one may change certain entries as desired for the particular factorization to be performed
9745 
9746 .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatFactorInfo`
9747 @*/
9748 PetscErrorCode MatFactorInfoInitialize(MatFactorInfo *info)
9749 {
9750   PetscFunctionBegin;
9751   PetscCall(PetscMemzero(info, sizeof(MatFactorInfo)));
9752   PetscFunctionReturn(PETSC_SUCCESS);
9753 }
9754 
9755 /*@
9756   MatFactorSetSchurIS - Set indices corresponding to the Schur complement you wish to have computed
9757 
9758   Collective
9759 
9760   Input Parameters:
9761 + mat - the factored matrix
9762 - is  - the index set defining the Schur indices (0-based)
9763 
9764   Level: advanced
9765 
9766   Notes:
9767   Call `MatFactorSolveSchurComplement()` or `MatFactorSolveSchurComplementTranspose()` after this call to solve a Schur complement system.
9768 
9769   You can call `MatFactorGetSchurComplement()` or `MatFactorCreateSchurComplement()` after this call.
9770 
9771   This functionality is only supported for `MATSOLVERMUMPS` and `MATSOLVERMKL_PARDISO`
9772 
9773 .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatFactorGetSchurComplement()`, `MatFactorRestoreSchurComplement()`, `MatFactorCreateSchurComplement()`, `MatFactorSolveSchurComplement()`,
9774           `MatFactorSolveSchurComplementTranspose()`, `MATSOLVERMUMPS`, `MATSOLVERMKL_PARDISO`
9775 @*/
9776 PetscErrorCode MatFactorSetSchurIS(Mat mat, IS is)
9777 {
9778   PetscErrorCode (*f)(Mat, IS);
9779 
9780   PetscFunctionBegin;
9781   PetscValidType(mat, 1);
9782   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
9783   PetscValidType(is, 2);
9784   PetscValidHeaderSpecific(is, IS_CLASSID, 2);
9785   PetscCheckSameComm(mat, 1, is, 2);
9786   PetscCheck(mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Only for factored matrix");
9787   PetscCall(PetscObjectQueryFunction((PetscObject)mat, "MatFactorSetSchurIS_C", &f));
9788   PetscCheck(f, PetscObjectComm((PetscObject)mat), PETSC_ERR_SUP, "The selected MatSolverType does not support Schur complement computation. You should use MATSOLVERMUMPS or MATSOLVERMKL_PARDISO");
9789   PetscCall(MatDestroy(&mat->schur));
9790   PetscCall((*f)(mat, is));
9791   PetscCheck(mat->schur, PetscObjectComm((PetscObject)mat), PETSC_ERR_PLIB, "Schur complement has not been created");
9792   PetscFunctionReturn(PETSC_SUCCESS);
9793 }
9794 
9795 /*@
9796   MatFactorCreateSchurComplement - Create a Schur complement matrix object using Schur data computed during the factorization step
9797 
9798   Logically Collective
9799 
9800   Input Parameters:
9801 + F      - the factored matrix obtained by calling `MatGetFactor()`
9802 . S      - location where to return the Schur complement, can be `NULL`
9803 - status - the status of the Schur complement matrix, can be `NULL`
9804 
9805   Level: advanced
9806 
9807   Notes:
9808   You must call `MatFactorSetSchurIS()` before calling this routine.
9809 
9810   This functionality is only supported for `MATSOLVERMUMPS` and `MATSOLVERMKL_PARDISO`
9811 
9812   The routine provides a copy of the Schur matrix stored within the solver data structures.
9813   The caller must destroy the object when it is no longer needed.
9814   If `MatFactorInvertSchurComplement()` has been called, the routine gets back the inverse.
9815 
9816   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)
9817 
9818   See `MatCreateSchurComplement()` or `MatGetSchurComplement()` for ways to create virtual or approximate Schur complements.
9819 
9820   Developer Note:
9821   The reason this routine exists is because the representation of the Schur complement within the factor matrix may be different than a standard PETSc
9822   matrix representation and we normally do not want to use the time or memory to make a copy as a regular PETSc matrix.
9823 
9824 .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatFactorSetSchurIS()`, `MatFactorGetSchurComplement()`, `MatFactorSchurStatus`, `MATSOLVERMUMPS`, `MATSOLVERMKL_PARDISO`
9825 @*/
9826 PetscErrorCode MatFactorCreateSchurComplement(Mat F, Mat *S, MatFactorSchurStatus *status)
9827 {
9828   PetscFunctionBegin;
9829   PetscValidHeaderSpecific(F, MAT_CLASSID, 1);
9830   if (S) PetscAssertPointer(S, 2);
9831   if (status) PetscAssertPointer(status, 3);
9832   if (S) {
9833     PetscErrorCode (*f)(Mat, Mat *);
9834 
9835     PetscCall(PetscObjectQueryFunction((PetscObject)F, "MatFactorCreateSchurComplement_C", &f));
9836     if (f) {
9837       PetscCall((*f)(F, S));
9838     } else {
9839       PetscCall(MatDuplicate(F->schur, MAT_COPY_VALUES, S));
9840     }
9841   }
9842   if (status) *status = F->schur_status;
9843   PetscFunctionReturn(PETSC_SUCCESS);
9844 }
9845 
9846 /*@
9847   MatFactorGetSchurComplement - Gets access to a Schur complement matrix using the current Schur data within a factored matrix
9848 
9849   Logically Collective
9850 
9851   Input Parameters:
9852 + F      - the factored matrix obtained by calling `MatGetFactor()`
9853 . S      - location where to return the Schur complement, can be `NULL`
9854 - status - the status of the Schur complement matrix, can be `NULL`
9855 
9856   Level: advanced
9857 
9858   Notes:
9859   You must call `MatFactorSetSchurIS()` before calling this routine.
9860 
9861   Schur complement mode is currently implemented for sequential matrices with factor type of `MATSOLVERMUMPS`
9862 
9863   The routine returns a the Schur Complement stored within the data structures of the solver.
9864 
9865   If `MatFactorInvertSchurComplement()` has previously been called, the returned matrix is actually the inverse of the Schur complement.
9866 
9867   The returned matrix should not be destroyed; the caller should call `MatFactorRestoreSchurComplement()` when the object is no longer needed.
9868 
9869   Use `MatFactorCreateSchurComplement()` to create a copy of the Schur complement matrix that is within a factored matrix
9870 
9871   See `MatCreateSchurComplement()` or `MatGetSchurComplement()` for ways to create virtual or approximate Schur complements.
9872 
9873 .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatFactorSetSchurIS()`, `MatFactorRestoreSchurComplement()`, `MatFactorCreateSchurComplement()`, `MatFactorSchurStatus`
9874 @*/
9875 PetscErrorCode MatFactorGetSchurComplement(Mat F, Mat *S, MatFactorSchurStatus *status)
9876 {
9877   PetscFunctionBegin;
9878   PetscValidHeaderSpecific(F, MAT_CLASSID, 1);
9879   if (S) {
9880     PetscAssertPointer(S, 2);
9881     *S = F->schur;
9882   }
9883   if (status) {
9884     PetscAssertPointer(status, 3);
9885     *status = F->schur_status;
9886   }
9887   PetscFunctionReturn(PETSC_SUCCESS);
9888 }
9889 
9890 static PetscErrorCode MatFactorUpdateSchurStatus_Private(Mat F)
9891 {
9892   Mat S = F->schur;
9893 
9894   PetscFunctionBegin;
9895   switch (F->schur_status) {
9896   case MAT_FACTOR_SCHUR_UNFACTORED: // fall-through
9897   case MAT_FACTOR_SCHUR_INVERTED:
9898     if (S) {
9899       S->ops->solve             = NULL;
9900       S->ops->matsolve          = NULL;
9901       S->ops->solvetranspose    = NULL;
9902       S->ops->matsolvetranspose = NULL;
9903       S->ops->solveadd          = NULL;
9904       S->ops->solvetransposeadd = NULL;
9905       S->factortype             = MAT_FACTOR_NONE;
9906       PetscCall(PetscFree(S->solvertype));
9907     }
9908   case MAT_FACTOR_SCHUR_FACTORED: // fall-through
9909     break;
9910   default:
9911     SETERRQ(PetscObjectComm((PetscObject)F), PETSC_ERR_SUP, "Unhandled MatFactorSchurStatus %d", F->schur_status);
9912   }
9913   PetscFunctionReturn(PETSC_SUCCESS);
9914 }
9915 
9916 /*@
9917   MatFactorRestoreSchurComplement - Restore the Schur complement matrix object obtained from a call to `MatFactorGetSchurComplement()`
9918 
9919   Logically Collective
9920 
9921   Input Parameters:
9922 + F      - the factored matrix obtained by calling `MatGetFactor()`
9923 . S      - location where the Schur complement is stored
9924 - status - the status of the Schur complement matrix (see `MatFactorSchurStatus`)
9925 
9926   Level: advanced
9927 
9928 .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatFactorSetSchurIS()`, `MatFactorCreateSchurComplement()`, `MatFactorSchurStatus`
9929 @*/
9930 PetscErrorCode MatFactorRestoreSchurComplement(Mat F, Mat *S, MatFactorSchurStatus status)
9931 {
9932   PetscFunctionBegin;
9933   PetscValidHeaderSpecific(F, MAT_CLASSID, 1);
9934   if (S) {
9935     PetscValidHeaderSpecific(*S, MAT_CLASSID, 2);
9936     *S = NULL;
9937   }
9938   F->schur_status = status;
9939   PetscCall(MatFactorUpdateSchurStatus_Private(F));
9940   PetscFunctionReturn(PETSC_SUCCESS);
9941 }
9942 
9943 /*@
9944   MatFactorSolveSchurComplementTranspose - Solve the transpose of the Schur complement system computed during the factorization step
9945 
9946   Logically Collective
9947 
9948   Input Parameters:
9949 + F   - the factored matrix obtained by calling `MatGetFactor()`
9950 . rhs - location where the right-hand side of the Schur complement system is stored
9951 - sol - location where the solution of the Schur complement system has to be returned
9952 
9953   Level: advanced
9954 
9955   Notes:
9956   The sizes of the vectors should match the size of the Schur complement
9957 
9958   Must be called after `MatFactorSetSchurIS()`
9959 
9960 .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatFactorSetSchurIS()`, `MatFactorSolveSchurComplement()`
9961 @*/
9962 PetscErrorCode MatFactorSolveSchurComplementTranspose(Mat F, Vec rhs, Vec sol)
9963 {
9964   PetscFunctionBegin;
9965   PetscValidType(F, 1);
9966   PetscValidType(rhs, 2);
9967   PetscValidType(sol, 3);
9968   PetscValidHeaderSpecific(F, MAT_CLASSID, 1);
9969   PetscValidHeaderSpecific(rhs, VEC_CLASSID, 2);
9970   PetscValidHeaderSpecific(sol, VEC_CLASSID, 3);
9971   PetscCheckSameComm(F, 1, rhs, 2);
9972   PetscCheckSameComm(F, 1, sol, 3);
9973   PetscCall(MatFactorFactorizeSchurComplement(F));
9974   switch (F->schur_status) {
9975   case MAT_FACTOR_SCHUR_FACTORED:
9976     PetscCall(MatSolveTranspose(F->schur, rhs, sol));
9977     break;
9978   case MAT_FACTOR_SCHUR_INVERTED:
9979     PetscCall(MatMultTranspose(F->schur, rhs, sol));
9980     break;
9981   default:
9982     SETERRQ(PetscObjectComm((PetscObject)F), PETSC_ERR_SUP, "Unhandled MatFactorSchurStatus %d", F->schur_status);
9983   }
9984   PetscFunctionReturn(PETSC_SUCCESS);
9985 }
9986 
9987 /*@
9988   MatFactorSolveSchurComplement - Solve the Schur complement system computed during the factorization step
9989 
9990   Logically Collective
9991 
9992   Input Parameters:
9993 + F   - the factored matrix obtained by calling `MatGetFactor()`
9994 . rhs - location where the right-hand side of the Schur complement system is stored
9995 - sol - location where the solution of the Schur complement system has to be returned
9996 
9997   Level: advanced
9998 
9999   Notes:
10000   The sizes of the vectors should match the size of the Schur complement
10001 
10002   Must be called after `MatFactorSetSchurIS()`
10003 
10004 .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatFactorSetSchurIS()`, `MatFactorSolveSchurComplementTranspose()`
10005 @*/
10006 PetscErrorCode MatFactorSolveSchurComplement(Mat F, Vec rhs, Vec sol)
10007 {
10008   PetscFunctionBegin;
10009   PetscValidType(F, 1);
10010   PetscValidType(rhs, 2);
10011   PetscValidType(sol, 3);
10012   PetscValidHeaderSpecific(F, MAT_CLASSID, 1);
10013   PetscValidHeaderSpecific(rhs, VEC_CLASSID, 2);
10014   PetscValidHeaderSpecific(sol, VEC_CLASSID, 3);
10015   PetscCheckSameComm(F, 1, rhs, 2);
10016   PetscCheckSameComm(F, 1, sol, 3);
10017   PetscCall(MatFactorFactorizeSchurComplement(F));
10018   switch (F->schur_status) {
10019   case MAT_FACTOR_SCHUR_FACTORED:
10020     PetscCall(MatSolve(F->schur, rhs, sol));
10021     break;
10022   case MAT_FACTOR_SCHUR_INVERTED:
10023     PetscCall(MatMult(F->schur, rhs, sol));
10024     break;
10025   default:
10026     SETERRQ(PetscObjectComm((PetscObject)F), PETSC_ERR_SUP, "Unhandled MatFactorSchurStatus %d", F->schur_status);
10027   }
10028   PetscFunctionReturn(PETSC_SUCCESS);
10029 }
10030 
10031 PETSC_EXTERN PetscErrorCode MatSeqDenseInvertFactors_Private(Mat);
10032 #if PetscDefined(HAVE_CUDA)
10033 PETSC_SINGLE_LIBRARY_INTERN PetscErrorCode MatSeqDenseCUDAInvertFactors_Internal(Mat);
10034 #endif
10035 
10036 /* Schur status updated in the interface */
10037 static PetscErrorCode MatFactorInvertSchurComplement_Private(Mat F)
10038 {
10039   Mat S = F->schur;
10040 
10041   PetscFunctionBegin;
10042   if (S) {
10043     PetscMPIInt size;
10044     PetscBool   isdense, isdensecuda;
10045 
10046     PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)S), &size));
10047     PetscCheck(size <= 1, PetscObjectComm((PetscObject)S), PETSC_ERR_SUP, "Not yet implemented");
10048     PetscCall(PetscObjectTypeCompare((PetscObject)S, MATSEQDENSE, &isdense));
10049     PetscCall(PetscObjectTypeCompare((PetscObject)S, MATSEQDENSECUDA, &isdensecuda));
10050     PetscCheck(isdense || isdensecuda, PetscObjectComm((PetscObject)S), PETSC_ERR_SUP, "Not implemented for type %s", ((PetscObject)S)->type_name);
10051     PetscCall(PetscLogEventBegin(MAT_FactorInvS, F, 0, 0, 0));
10052     if (isdense) {
10053       PetscCall(MatSeqDenseInvertFactors_Private(S));
10054     } else if (isdensecuda) {
10055 #if defined(PETSC_HAVE_CUDA)
10056       PetscCall(MatSeqDenseCUDAInvertFactors_Internal(S));
10057 #endif
10058     }
10059     // HIP??????????????
10060     PetscCall(PetscLogEventEnd(MAT_FactorInvS, F, 0, 0, 0));
10061   }
10062   PetscFunctionReturn(PETSC_SUCCESS);
10063 }
10064 
10065 /*@
10066   MatFactorInvertSchurComplement - Invert the Schur complement matrix computed during the factorization step
10067 
10068   Logically Collective
10069 
10070   Input Parameter:
10071 . F - the factored matrix obtained by calling `MatGetFactor()`
10072 
10073   Level: advanced
10074 
10075   Notes:
10076   Must be called after `MatFactorSetSchurIS()`.
10077 
10078   Call `MatFactorGetSchurComplement()` or  `MatFactorCreateSchurComplement()` AFTER this call to actually compute the inverse and get access to it.
10079 
10080 .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatFactorSetSchurIS()`, `MatFactorGetSchurComplement()`, `MatFactorCreateSchurComplement()`
10081 @*/
10082 PetscErrorCode MatFactorInvertSchurComplement(Mat F)
10083 {
10084   PetscFunctionBegin;
10085   PetscValidType(F, 1);
10086   PetscValidHeaderSpecific(F, MAT_CLASSID, 1);
10087   if (F->schur_status == MAT_FACTOR_SCHUR_INVERTED) PetscFunctionReturn(PETSC_SUCCESS);
10088   PetscCall(MatFactorFactorizeSchurComplement(F));
10089   PetscCall(MatFactorInvertSchurComplement_Private(F));
10090   F->schur_status = MAT_FACTOR_SCHUR_INVERTED;
10091   PetscFunctionReturn(PETSC_SUCCESS);
10092 }
10093 
10094 /*@
10095   MatFactorFactorizeSchurComplement - Factorize the Schur complement matrix computed during the factorization step
10096 
10097   Logically Collective
10098 
10099   Input Parameter:
10100 . F - the factored matrix obtained by calling `MatGetFactor()`
10101 
10102   Level: advanced
10103 
10104   Note:
10105   Must be called after `MatFactorSetSchurIS()`
10106 
10107 .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatFactorSetSchurIS()`, `MatFactorInvertSchurComplement()`
10108 @*/
10109 PetscErrorCode MatFactorFactorizeSchurComplement(Mat F)
10110 {
10111   MatFactorInfo info;
10112 
10113   PetscFunctionBegin;
10114   PetscValidType(F, 1);
10115   PetscValidHeaderSpecific(F, MAT_CLASSID, 1);
10116   if (F->schur_status == MAT_FACTOR_SCHUR_INVERTED || F->schur_status == MAT_FACTOR_SCHUR_FACTORED) PetscFunctionReturn(PETSC_SUCCESS);
10117   PetscCall(PetscLogEventBegin(MAT_FactorFactS, F, 0, 0, 0));
10118   PetscCall(PetscMemzero(&info, sizeof(MatFactorInfo)));
10119   if (F->factortype == MAT_FACTOR_CHOLESKY) { /* LDL^t regarded as Cholesky */
10120     PetscCall(MatCholeskyFactor(F->schur, NULL, &info));
10121   } else {
10122     PetscCall(MatLUFactor(F->schur, NULL, NULL, &info));
10123   }
10124   PetscCall(PetscLogEventEnd(MAT_FactorFactS, F, 0, 0, 0));
10125   F->schur_status = MAT_FACTOR_SCHUR_FACTORED;
10126   PetscFunctionReturn(PETSC_SUCCESS);
10127 }
10128 
10129 /*@
10130   MatPtAP - Creates the matrix product $C = P^T * A * P$
10131 
10132   Neighbor-wise Collective
10133 
10134   Input Parameters:
10135 + A     - the matrix
10136 . P     - the projection matrix
10137 . scall - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`
10138 - fill  - expected fill as ratio of nnz(C)/(nnz(A) + nnz(P)), use `PETSC_DEFAULT` if you do not have a good estimate
10139           if the result is a dense matrix this is irrelevant
10140 
10141   Output Parameter:
10142 . C - the product matrix
10143 
10144   Level: intermediate
10145 
10146   Notes:
10147   C will be created and must be destroyed by the user with `MatDestroy()`.
10148 
10149   An alternative approach to this function is to use `MatProductCreate()` and set the desired options before the computation is done
10150 
10151   Developer Note:
10152   For matrix types without special implementation the function fallbacks to `MatMatMult()` followed by `MatTransposeMatMult()`.
10153 
10154 .seealso: [](ch_matrices), `Mat`, `MatProductCreate()`, `MatMatMult()`, `MatRARt()`
10155 @*/
10156 PetscErrorCode MatPtAP(Mat A, Mat P, MatReuse scall, PetscReal fill, Mat *C)
10157 {
10158   PetscFunctionBegin;
10159   if (scall == MAT_REUSE_MATRIX) MatCheckProduct(*C, 5);
10160   PetscCheck(scall != MAT_INPLACE_MATRIX, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "Inplace product not supported");
10161 
10162   if (scall == MAT_INITIAL_MATRIX) {
10163     PetscCall(MatProductCreate(A, P, NULL, C));
10164     PetscCall(MatProductSetType(*C, MATPRODUCT_PtAP));
10165     PetscCall(MatProductSetAlgorithm(*C, "default"));
10166     PetscCall(MatProductSetFill(*C, fill));
10167 
10168     (*C)->product->api_user = PETSC_TRUE;
10169     PetscCall(MatProductSetFromOptions(*C));
10170     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);
10171     PetscCall(MatProductSymbolic(*C));
10172   } else { /* scall == MAT_REUSE_MATRIX */
10173     PetscCall(MatProductReplaceMats(A, P, NULL, *C));
10174   }
10175 
10176   PetscCall(MatProductNumeric(*C));
10177   (*C)->symmetric = A->symmetric;
10178   (*C)->spd       = A->spd;
10179   PetscFunctionReturn(PETSC_SUCCESS);
10180 }
10181 
10182 /*@
10183   MatRARt - Creates the matrix product $C = R * A * R^T$
10184 
10185   Neighbor-wise Collective
10186 
10187   Input Parameters:
10188 + A     - the matrix
10189 . R     - the projection matrix
10190 . scall - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`
10191 - fill  - expected fill as ratio of nnz(C)/nnz(A), use `PETSC_DEFAULT` if you do not have a good estimate
10192           if the result is a dense matrix this is irrelevant
10193 
10194   Output Parameter:
10195 . C - the product matrix
10196 
10197   Level: intermediate
10198 
10199   Notes:
10200   C will be created and must be destroyed by the user with `MatDestroy()`.
10201 
10202   An alternative approach to this function is to use `MatProductCreate()` and set the desired options before the computation is done
10203 
10204   This routine is currently only implemented for pairs of `MATAIJ` matrices and classes
10205   which inherit from `MATAIJ`. Due to PETSc sparse matrix block row distribution among processes,
10206   parallel MatRARt is implemented via explicit transpose of R, which could be very expensive.
10207   We recommend using MatPtAP().
10208 
10209 .seealso: [](ch_matrices), `Mat`, `MatProductCreate()`, `MatMatMult()`, `MatPtAP()`
10210 @*/
10211 PetscErrorCode MatRARt(Mat A, Mat R, MatReuse scall, PetscReal fill, Mat *C)
10212 {
10213   PetscFunctionBegin;
10214   if (scall == MAT_REUSE_MATRIX) MatCheckProduct(*C, 5);
10215   PetscCheck(scall != MAT_INPLACE_MATRIX, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "Inplace product not supported");
10216 
10217   if (scall == MAT_INITIAL_MATRIX) {
10218     PetscCall(MatProductCreate(A, R, NULL, C));
10219     PetscCall(MatProductSetType(*C, MATPRODUCT_RARt));
10220     PetscCall(MatProductSetAlgorithm(*C, "default"));
10221     PetscCall(MatProductSetFill(*C, fill));
10222 
10223     (*C)->product->api_user = PETSC_TRUE;
10224     PetscCall(MatProductSetFromOptions(*C));
10225     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);
10226     PetscCall(MatProductSymbolic(*C));
10227   } else { /* scall == MAT_REUSE_MATRIX */
10228     PetscCall(MatProductReplaceMats(A, R, NULL, *C));
10229   }
10230 
10231   PetscCall(MatProductNumeric(*C));
10232   if (A->symmetric == PETSC_BOOL3_TRUE) PetscCall(MatSetOption(*C, MAT_SYMMETRIC, PETSC_TRUE));
10233   PetscFunctionReturn(PETSC_SUCCESS);
10234 }
10235 
10236 static PetscErrorCode MatProduct_Private(Mat A, Mat B, MatReuse scall, PetscReal fill, MatProductType ptype, Mat *C)
10237 {
10238   PetscBool flg = PETSC_TRUE;
10239 
10240   PetscFunctionBegin;
10241   PetscCheck(scall != MAT_INPLACE_MATRIX, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "MAT_INPLACE_MATRIX product not supported");
10242   if (scall == MAT_INITIAL_MATRIX) {
10243     PetscCall(PetscInfo(A, "Calling MatProduct API with MAT_INITIAL_MATRIX and product type %s\n", MatProductTypes[ptype]));
10244     PetscCall(MatProductCreate(A, B, NULL, C));
10245     PetscCall(MatProductSetAlgorithm(*C, MATPRODUCTALGORITHMDEFAULT));
10246     PetscCall(MatProductSetFill(*C, fill));
10247   } else { /* scall == MAT_REUSE_MATRIX */
10248     Mat_Product *product = (*C)->product;
10249 
10250     PetscCall(PetscObjectBaseTypeCompareAny((PetscObject)*C, &flg, MATSEQDENSE, MATMPIDENSE, ""));
10251     if (flg && product && product->type != ptype) {
10252       PetscCall(MatProductClear(*C));
10253       product = NULL;
10254     }
10255     PetscCall(PetscInfo(A, "Calling MatProduct API with MAT_REUSE_MATRIX %s product present and product type %s\n", product ? "with" : "without", MatProductTypes[ptype]));
10256     if (!product) { /* user provide the dense matrix *C without calling MatProductCreate() or reusing it from previous calls */
10257       PetscCheck(flg, PetscObjectComm((PetscObject)*C), PETSC_ERR_SUP, "Call MatProductCreate() first");
10258       PetscCall(MatProductCreate_Private(A, B, NULL, *C));
10259       product        = (*C)->product;
10260       product->fill  = fill;
10261       product->clear = PETSC_TRUE;
10262     } else { /* user may change input matrices A or B when MAT_REUSE_MATRIX */
10263       flg = PETSC_FALSE;
10264       PetscCall(MatProductReplaceMats(A, B, NULL, *C));
10265     }
10266   }
10267   if (flg) {
10268     (*C)->product->api_user = PETSC_TRUE;
10269     PetscCall(MatProductSetType(*C, ptype));
10270     PetscCall(MatProductSetFromOptions(*C));
10271     PetscCall(MatProductSymbolic(*C));
10272   }
10273   PetscCall(MatProductNumeric(*C));
10274   PetscFunctionReturn(PETSC_SUCCESS);
10275 }
10276 
10277 /*@
10278   MatMatMult - Performs matrix-matrix multiplication C=A*B.
10279 
10280   Neighbor-wise Collective
10281 
10282   Input Parameters:
10283 + A     - the left matrix
10284 . B     - the right matrix
10285 . scall - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`
10286 - fill  - expected fill as ratio of nnz(C)/(nnz(A) + nnz(B)), use `PETSC_DEFAULT` if you do not have a good estimate
10287           if the result is a dense matrix this is irrelevant
10288 
10289   Output Parameter:
10290 . C - the product matrix
10291 
10292   Notes:
10293   Unless scall is `MAT_REUSE_MATRIX` C will be created.
10294 
10295   `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
10296   call to this function with `MAT_INITIAL_MATRIX`.
10297 
10298   To determine the correct fill value, run with -info and search for the string "Fill ratio" to see the value actually needed.
10299 
10300   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`,
10301   rather than first having `MatMatMult()` create it for you. You can NEVER do this if the matrix C is sparse.
10302 
10303   Example of Usage:
10304 .vb
10305      MatProductCreate(A,B,NULL,&C);
10306      MatProductSetType(C,MATPRODUCT_AB);
10307      MatProductSymbolic(C);
10308      MatProductNumeric(C); // compute C=A * B
10309      MatProductReplaceMats(A1,B1,NULL,C); // compute C=A1 * B1
10310      MatProductNumeric(C);
10311      MatProductReplaceMats(A2,NULL,NULL,C); // compute C=A2 * B1
10312      MatProductNumeric(C);
10313 .ve
10314 
10315   Level: intermediate
10316 
10317 .seealso: [](ch_matrices), `Mat`, `MatProductType`, `MATPRODUCT_AB`, `MatTransposeMatMult()`, `MatMatTransposeMult()`, `MatPtAP()`, `MatProductCreate()`, `MatProductSymbolic()`, `MatProductReplaceMats()`, `MatProductNumeric()`
10318 @*/
10319 PetscErrorCode MatMatMult(Mat A, Mat B, MatReuse scall, PetscReal fill, Mat *C)
10320 {
10321   PetscFunctionBegin;
10322   PetscCall(MatProduct_Private(A, B, scall, fill, MATPRODUCT_AB, C));
10323   PetscFunctionReturn(PETSC_SUCCESS);
10324 }
10325 
10326 /*@
10327   MatMatTransposeMult - Performs matrix-matrix multiplication $C = A*B^T$.
10328 
10329   Neighbor-wise Collective
10330 
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_DEFAULT` if not known
10336 
10337   Output Parameter:
10338 . C - the product matrix
10339 
10340   Options Database Key:
10341 . -matmattransmult_mpidense_mpidense_via {allgatherv,cyclic} - Choose between algorithms for `MATMPIDENSE` matrices: the
10342               first redundantly copies the transposed `B` matrix on each process and requires O(log P) communication complexity;
10343               the second never stores more than one portion of the `B` matrix at a time but requires O(P) communication complexity.
10344 
10345   Level: intermediate
10346 
10347   Notes:
10348   C will be created if `MAT_INITIAL_MATRIX` and must be destroyed by the user with `MatDestroy()`.
10349 
10350   `MAT_REUSE_MATRIX` can only be used if the matrices A and B have the same nonzero pattern as in the previous call
10351 
10352   To determine the correct fill value, run with -info and search for the string "Fill ratio" to see the value
10353   actually needed.
10354 
10355   This routine is currently only implemented for pairs of `MATSEQAIJ` matrices, for the `MATSEQDENSE` class,
10356   and for pairs of `MATMPIDENSE` matrices.
10357 
10358   This routine is shorthand for using `MatProductCreate()` with the `MatProductType` of `MATPRODUCT_ABt`
10359 
10360 .seealso: [](ch_matrices), `Mat`, `MatProductCreate()`, `MATPRODUCT_ABt`, `MatMatMult()`, `MatTransposeMatMult()` `MatPtAP()`, `MatProductAlgorithm`, `MatProductType`
10361 @*/
10362 PetscErrorCode MatMatTransposeMult(Mat A, Mat B, MatReuse scall, PetscReal fill, Mat *C)
10363 {
10364   PetscFunctionBegin;
10365   PetscCall(MatProduct_Private(A, B, scall, fill, MATPRODUCT_ABt, C));
10366   if (A == B) PetscCall(MatSetOption(*C, MAT_SYMMETRIC, PETSC_TRUE));
10367   PetscFunctionReturn(PETSC_SUCCESS);
10368 }
10369 
10370 /*@
10371   MatTransposeMatMult - Performs matrix-matrix multiplication $C = A^T*B$.
10372 
10373   Neighbor-wise Collective
10374 
10375   Input Parameters:
10376 + A     - the left matrix
10377 . B     - the right matrix
10378 . scall - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`
10379 - fill  - expected fill as ratio of nnz(C)/(nnz(A) + nnz(B)), use `PETSC_DEFAULT` if not known
10380 
10381   Output Parameter:
10382 . C - the product matrix
10383 
10384   Level: intermediate
10385 
10386   Notes:
10387   `C` will be created if `MAT_INITIAL_MATRIX` and must be destroyed by the user with `MatDestroy()`.
10388 
10389   `MAT_REUSE_MATRIX` can only be used if the matrices A and B have the same nonzero pattern as in the previous call.
10390 
10391   This routine is shorthand for using `MatProductCreate()` with the `MatProductType` of `MATPRODUCT_AtB`
10392 
10393   To determine the correct fill value, run with -info and search for the string "Fill ratio" to see the value
10394   actually needed.
10395 
10396   This routine is currently implemented for pairs of `MATAIJ` matrices and pairs of `MATSEQDENSE` matrices and classes
10397   which inherit from `MATSEQAIJ`.  `C` will be of the same type as the input matrices.
10398 
10399 .seealso: [](ch_matrices), `Mat`, `MatProductCreate()`, `MATPRODUCT_AtB`, `MatMatMult()`, `MatMatTransposeMult()`, `MatPtAP()`
10400 @*/
10401 PetscErrorCode MatTransposeMatMult(Mat A, Mat B, MatReuse scall, PetscReal fill, Mat *C)
10402 {
10403   PetscFunctionBegin;
10404   PetscCall(MatProduct_Private(A, B, scall, fill, MATPRODUCT_AtB, C));
10405   PetscFunctionReturn(PETSC_SUCCESS);
10406 }
10407 
10408 /*@
10409   MatMatMatMult - Performs matrix-matrix-matrix multiplication D=A*B*C.
10410 
10411   Neighbor-wise Collective
10412 
10413   Input Parameters:
10414 + A     - the left matrix
10415 . B     - the middle matrix
10416 . C     - the right matrix
10417 . scall - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`
10418 - fill  - expected fill as ratio of nnz(D)/(nnz(A) + nnz(B)+nnz(C)), use `PETSC_DEFAULT` if you do not have a good estimate
10419           if the result is a dense matrix this is irrelevant
10420 
10421   Output Parameter:
10422 . D - the product matrix
10423 
10424   Level: intermediate
10425 
10426   Notes:
10427   Unless `scall` is `MAT_REUSE_MATRIX` D will be created.
10428 
10429   `MAT_REUSE_MATRIX` can only be used if the matrices `A`, `B`, and `C` have the same nonzero pattern as in the previous call
10430 
10431   This routine is shorthand for using `MatProductCreate()` with the `MatProductType` of `MATPRODUCT_ABC`
10432 
10433   To determine the correct fill value, run with -info and search for the string "Fill ratio" to see the value
10434   actually needed.
10435 
10436   If you have many matrices with the same non-zero structure to multiply, you
10437   should use `MAT_REUSE_MATRIX` in all calls but the first
10438 
10439 .seealso: [](ch_matrices), `Mat`, `MatProductCreate()`, `MATPRODUCT_ABC`, `MatMatMult`, `MatPtAP()`, `MatMatTransposeMult()`, `MatTransposeMatMult()`
10440 @*/
10441 PetscErrorCode MatMatMatMult(Mat A, Mat B, Mat C, MatReuse scall, PetscReal fill, Mat *D)
10442 {
10443   PetscFunctionBegin;
10444   if (scall == MAT_REUSE_MATRIX) MatCheckProduct(*D, 6);
10445   PetscCheck(scall != MAT_INPLACE_MATRIX, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "Inplace product not supported");
10446 
10447   if (scall == MAT_INITIAL_MATRIX) {
10448     PetscCall(MatProductCreate(A, B, C, D));
10449     PetscCall(MatProductSetType(*D, MATPRODUCT_ABC));
10450     PetscCall(MatProductSetAlgorithm(*D, "default"));
10451     PetscCall(MatProductSetFill(*D, fill));
10452 
10453     (*D)->product->api_user = PETSC_TRUE;
10454     PetscCall(MatProductSetFromOptions(*D));
10455     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,
10456                ((PetscObject)C)->type_name);
10457     PetscCall(MatProductSymbolic(*D));
10458   } else { /* user may change input matrices when REUSE */
10459     PetscCall(MatProductReplaceMats(A, B, C, *D));
10460   }
10461   PetscCall(MatProductNumeric(*D));
10462   PetscFunctionReturn(PETSC_SUCCESS);
10463 }
10464 
10465 /*@
10466   MatCreateRedundantMatrix - Create redundant matrices and put them into processors of subcommunicators.
10467 
10468   Collective
10469 
10470   Input Parameters:
10471 + mat      - the matrix
10472 . nsubcomm - the number of subcommunicators (= number of redundant parallel or sequential matrices)
10473 . subcomm  - MPI communicator split from the communicator where mat resides in (or `MPI_COMM_NULL` if nsubcomm is used)
10474 - reuse    - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`
10475 
10476   Output Parameter:
10477 . matredundant - redundant matrix
10478 
10479   Level: advanced
10480 
10481   Notes:
10482   `MAT_REUSE_MATRIX` can only be used when the nonzero structure of the
10483   original matrix has not changed from that last call to `MatCreateRedundantMatrix()`.
10484 
10485   This routine creates the duplicated matrices in the subcommunicators; you should NOT create them before
10486   calling it.
10487 
10488   `PetscSubcommCreate()` can be used to manage the creation of the subcomm but need not be.
10489 
10490 .seealso: [](ch_matrices), `Mat`, `MatDestroy()`, `PetscSubcommCreate()`, `PetscSubcomm`
10491 @*/
10492 PetscErrorCode MatCreateRedundantMatrix(Mat mat, PetscInt nsubcomm, MPI_Comm subcomm, MatReuse reuse, Mat *matredundant)
10493 {
10494   MPI_Comm       comm;
10495   PetscMPIInt    size;
10496   PetscInt       mloc_sub, nloc_sub, rstart, rend, M = mat->rmap->N, N = mat->cmap->N, bs = mat->rmap->bs;
10497   Mat_Redundant *redund     = NULL;
10498   PetscSubcomm   psubcomm   = NULL;
10499   MPI_Comm       subcomm_in = subcomm;
10500   Mat           *matseq;
10501   IS             isrow, iscol;
10502   PetscBool      newsubcomm = PETSC_FALSE;
10503 
10504   PetscFunctionBegin;
10505   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
10506   if (nsubcomm && reuse == MAT_REUSE_MATRIX) {
10507     PetscAssertPointer(*matredundant, 5);
10508     PetscValidHeaderSpecific(*matredundant, MAT_CLASSID, 5);
10509   }
10510 
10511   PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)mat), &size));
10512   if (size == 1 || nsubcomm == 1) {
10513     if (reuse == MAT_INITIAL_MATRIX) {
10514       PetscCall(MatDuplicate(mat, MAT_COPY_VALUES, matredundant));
10515     } else {
10516       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");
10517       PetscCall(MatCopy(mat, *matredundant, SAME_NONZERO_PATTERN));
10518     }
10519     PetscFunctionReturn(PETSC_SUCCESS);
10520   }
10521 
10522   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
10523   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
10524   MatCheckPreallocated(mat, 1);
10525 
10526   PetscCall(PetscLogEventBegin(MAT_RedundantMat, mat, 0, 0, 0));
10527   if (subcomm_in == MPI_COMM_NULL && reuse == MAT_INITIAL_MATRIX) { /* get subcomm if user does not provide subcomm */
10528     /* create psubcomm, then get subcomm */
10529     PetscCall(PetscObjectGetComm((PetscObject)mat, &comm));
10530     PetscCallMPI(MPI_Comm_size(comm, &size));
10531     PetscCheck(nsubcomm >= 1 && nsubcomm <= size, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "nsubcomm must between 1 and %d", size);
10532 
10533     PetscCall(PetscSubcommCreate(comm, &psubcomm));
10534     PetscCall(PetscSubcommSetNumber(psubcomm, nsubcomm));
10535     PetscCall(PetscSubcommSetType(psubcomm, PETSC_SUBCOMM_CONTIGUOUS));
10536     PetscCall(PetscSubcommSetFromOptions(psubcomm));
10537     PetscCall(PetscCommDuplicate(PetscSubcommChild(psubcomm), &subcomm, NULL));
10538     newsubcomm = PETSC_TRUE;
10539     PetscCall(PetscSubcommDestroy(&psubcomm));
10540   }
10541 
10542   /* get isrow, iscol and a local sequential matrix matseq[0] */
10543   if (reuse == MAT_INITIAL_MATRIX) {
10544     mloc_sub = PETSC_DECIDE;
10545     nloc_sub = PETSC_DECIDE;
10546     if (bs < 1) {
10547       PetscCall(PetscSplitOwnership(subcomm, &mloc_sub, &M));
10548       PetscCall(PetscSplitOwnership(subcomm, &nloc_sub, &N));
10549     } else {
10550       PetscCall(PetscSplitOwnershipBlock(subcomm, bs, &mloc_sub, &M));
10551       PetscCall(PetscSplitOwnershipBlock(subcomm, bs, &nloc_sub, &N));
10552     }
10553     PetscCallMPI(MPI_Scan(&mloc_sub, &rend, 1, MPIU_INT, MPI_SUM, subcomm));
10554     rstart = rend - mloc_sub;
10555     PetscCall(ISCreateStride(PETSC_COMM_SELF, mloc_sub, rstart, 1, &isrow));
10556     PetscCall(ISCreateStride(PETSC_COMM_SELF, N, 0, 1, &iscol));
10557     PetscCall(ISSetIdentity(iscol));
10558   } else { /* reuse == MAT_REUSE_MATRIX */
10559     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");
10560     /* retrieve subcomm */
10561     PetscCall(PetscObjectGetComm((PetscObject)*matredundant, &subcomm));
10562     redund = (*matredundant)->redundant;
10563     isrow  = redund->isrow;
10564     iscol  = redund->iscol;
10565     matseq = redund->matseq;
10566   }
10567   PetscCall(MatCreateSubMatrices(mat, 1, &isrow, &iscol, reuse, &matseq));
10568 
10569   /* get matredundant over subcomm */
10570   if (reuse == MAT_INITIAL_MATRIX) {
10571     PetscCall(MatCreateMPIMatConcatenateSeqMat(subcomm, matseq[0], nloc_sub, reuse, matredundant));
10572 
10573     /* create a supporting struct and attach it to C for reuse */
10574     PetscCall(PetscNew(&redund));
10575     (*matredundant)->redundant = redund;
10576     redund->isrow              = isrow;
10577     redund->iscol              = iscol;
10578     redund->matseq             = matseq;
10579     if (newsubcomm) {
10580       redund->subcomm = subcomm;
10581     } else {
10582       redund->subcomm = MPI_COMM_NULL;
10583     }
10584   } else {
10585     PetscCall(MatCreateMPIMatConcatenateSeqMat(subcomm, matseq[0], PETSC_DECIDE, reuse, matredundant));
10586   }
10587 #if defined(PETSC_HAVE_VIENNACL) || defined(PETSC_HAVE_CUDA) || defined(PETSC_HAVE_HIP)
10588   if (matseq[0]->boundtocpu && matseq[0]->bindingpropagates) {
10589     PetscCall(MatBindToCPU(*matredundant, PETSC_TRUE));
10590     PetscCall(MatSetBindingPropagates(*matredundant, PETSC_TRUE));
10591   }
10592 #endif
10593   PetscCall(PetscLogEventEnd(MAT_RedundantMat, mat, 0, 0, 0));
10594   PetscFunctionReturn(PETSC_SUCCESS);
10595 }
10596 
10597 /*@C
10598   MatGetMultiProcBlock - Create multiple 'parallel submatrices' from
10599   a given `Mat`. Each submatrix can span multiple procs.
10600 
10601   Collective
10602 
10603   Input Parameters:
10604 + mat     - the matrix
10605 . subComm - the sub communicator obtained as if by `MPI_Comm_split(PetscObjectComm((PetscObject)mat))`
10606 - scall   - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`
10607 
10608   Output Parameter:
10609 . subMat - parallel sub-matrices each spanning a given `subcomm`
10610 
10611   Level: advanced
10612 
10613   Notes:
10614   The submatrix partition across processors is dictated by `subComm` a
10615   communicator obtained by `MPI_comm_split()` or via `PetscSubcommCreate()`. The `subComm`
10616   is not restricted to be grouped with consecutive original MPI processes.
10617 
10618   Due the `MPI_Comm_split()` usage, the parallel layout of the submatrices
10619   map directly to the layout of the original matrix [wrt the local
10620   row,col partitioning]. So the original 'DiagonalMat' naturally maps
10621   into the 'DiagonalMat' of the `subMat`, hence it is used directly from
10622   the `subMat`. However the offDiagMat looses some columns - and this is
10623   reconstructed with `MatSetValues()`
10624 
10625   This is used by `PCBJACOBI` when a single block spans multiple MPI processes.
10626 
10627 .seealso: [](ch_matrices), `Mat`, `MatCreateRedundantMatrix()`, `MatCreateSubMatrices()`, `PCBJACOBI`
10628 @*/
10629 PetscErrorCode MatGetMultiProcBlock(Mat mat, MPI_Comm subComm, MatReuse scall, Mat *subMat)
10630 {
10631   PetscMPIInt commsize, subCommSize;
10632 
10633   PetscFunctionBegin;
10634   PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)mat), &commsize));
10635   PetscCallMPI(MPI_Comm_size(subComm, &subCommSize));
10636   PetscCheck(subCommSize <= commsize, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_OUTOFRANGE, "CommSize %d < SubCommZize %d", commsize, subCommSize);
10637 
10638   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");
10639   PetscCall(PetscLogEventBegin(MAT_GetMultiProcBlock, mat, 0, 0, 0));
10640   PetscUseTypeMethod(mat, getmultiprocblock, subComm, scall, subMat);
10641   PetscCall(PetscLogEventEnd(MAT_GetMultiProcBlock, mat, 0, 0, 0));
10642   PetscFunctionReturn(PETSC_SUCCESS);
10643 }
10644 
10645 /*@
10646   MatGetLocalSubMatrix - Gets a reference to a submatrix specified in local numbering
10647 
10648   Not Collective
10649 
10650   Input Parameters:
10651 + mat   - matrix to extract local submatrix from
10652 . isrow - local row indices for submatrix
10653 - iscol - local column indices for submatrix
10654 
10655   Output Parameter:
10656 . submat - the submatrix
10657 
10658   Level: intermediate
10659 
10660   Notes:
10661   `submat` should be disposed of with `MatRestoreLocalSubMatrix()`.
10662 
10663   Depending on the format of `mat`, the returned `submat` may not implement `MatMult()`.  Its communicator may be
10664   the same as `mat`, it may be `PETSC_COMM_SELF`, or some other sub-communictor of `mat`'s.
10665 
10666   `submat` always implements `MatSetValuesLocal()`.  If `isrow` and `iscol` have the same block size, then
10667   `MatSetValuesBlockedLocal()` will also be implemented.
10668 
10669   `mat` must have had a `ISLocalToGlobalMapping` provided to it with `MatSetLocalToGlobalMapping()`.
10670   Matrices obtained with `DMCreateMatrix()` generally already have the local to global mapping provided.
10671 
10672 .seealso: [](ch_matrices), `Mat`, `MatRestoreLocalSubMatrix()`, `MatCreateLocalRef()`, `MatSetLocalToGlobalMapping()`
10673 @*/
10674 PetscErrorCode MatGetLocalSubMatrix(Mat mat, IS isrow, IS iscol, Mat *submat)
10675 {
10676   PetscFunctionBegin;
10677   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
10678   PetscValidHeaderSpecific(isrow, IS_CLASSID, 2);
10679   PetscValidHeaderSpecific(iscol, IS_CLASSID, 3);
10680   PetscCheckSameComm(isrow, 2, iscol, 3);
10681   PetscAssertPointer(submat, 4);
10682   PetscCheck(mat->rmap->mapping, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Matrix must have local to global mapping provided before this call");
10683 
10684   if (mat->ops->getlocalsubmatrix) {
10685     PetscUseTypeMethod(mat, getlocalsubmatrix, isrow, iscol, submat);
10686   } else {
10687     PetscCall(MatCreateLocalRef(mat, isrow, iscol, submat));
10688   }
10689   PetscFunctionReturn(PETSC_SUCCESS);
10690 }
10691 
10692 /*@
10693   MatRestoreLocalSubMatrix - Restores a reference to a submatrix specified in local numbering obtained with `MatGetLocalSubMatrix()`
10694 
10695   Not Collective
10696 
10697   Input Parameters:
10698 + mat    - matrix to extract local submatrix from
10699 . isrow  - local row indices for submatrix
10700 . iscol  - local column indices for submatrix
10701 - submat - the submatrix
10702 
10703   Level: intermediate
10704 
10705 .seealso: [](ch_matrices), `Mat`, `MatGetLocalSubMatrix()`
10706 @*/
10707 PetscErrorCode MatRestoreLocalSubMatrix(Mat mat, IS isrow, IS iscol, Mat *submat)
10708 {
10709   PetscFunctionBegin;
10710   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
10711   PetscValidHeaderSpecific(isrow, IS_CLASSID, 2);
10712   PetscValidHeaderSpecific(iscol, IS_CLASSID, 3);
10713   PetscCheckSameComm(isrow, 2, iscol, 3);
10714   PetscAssertPointer(submat, 4);
10715   if (*submat) PetscValidHeaderSpecific(*submat, MAT_CLASSID, 4);
10716 
10717   if (mat->ops->restorelocalsubmatrix) {
10718     PetscUseTypeMethod(mat, restorelocalsubmatrix, isrow, iscol, submat);
10719   } else {
10720     PetscCall(MatDestroy(submat));
10721   }
10722   *submat = NULL;
10723   PetscFunctionReturn(PETSC_SUCCESS);
10724 }
10725 
10726 /*@
10727   MatFindZeroDiagonals - Finds all the rows of a matrix that have zero or no diagonal entry in the matrix
10728 
10729   Collective
10730 
10731   Input Parameter:
10732 . mat - the matrix
10733 
10734   Output Parameter:
10735 . is - if any rows have zero diagonals this contains the list of them
10736 
10737   Level: developer
10738 
10739 .seealso: [](ch_matrices), `Mat`, `MatMultTranspose()`, `MatMultAdd()`, `MatMultTransposeAdd()`
10740 @*/
10741 PetscErrorCode MatFindZeroDiagonals(Mat mat, IS *is)
10742 {
10743   PetscFunctionBegin;
10744   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
10745   PetscValidType(mat, 1);
10746   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
10747   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
10748 
10749   if (!mat->ops->findzerodiagonals) {
10750     Vec                diag;
10751     const PetscScalar *a;
10752     PetscInt          *rows;
10753     PetscInt           rStart, rEnd, r, nrow = 0;
10754 
10755     PetscCall(MatCreateVecs(mat, &diag, NULL));
10756     PetscCall(MatGetDiagonal(mat, diag));
10757     PetscCall(MatGetOwnershipRange(mat, &rStart, &rEnd));
10758     PetscCall(VecGetArrayRead(diag, &a));
10759     for (r = 0; r < rEnd - rStart; ++r)
10760       if (a[r] == 0.0) ++nrow;
10761     PetscCall(PetscMalloc1(nrow, &rows));
10762     nrow = 0;
10763     for (r = 0; r < rEnd - rStart; ++r)
10764       if (a[r] == 0.0) rows[nrow++] = r + rStart;
10765     PetscCall(VecRestoreArrayRead(diag, &a));
10766     PetscCall(VecDestroy(&diag));
10767     PetscCall(ISCreateGeneral(PetscObjectComm((PetscObject)mat), nrow, rows, PETSC_OWN_POINTER, is));
10768   } else {
10769     PetscUseTypeMethod(mat, findzerodiagonals, is);
10770   }
10771   PetscFunctionReturn(PETSC_SUCCESS);
10772 }
10773 
10774 /*@
10775   MatFindOffBlockDiagonalEntries - Finds all the rows of a matrix that have entries outside of the main diagonal block (defined by the matrix block size)
10776 
10777   Collective
10778 
10779   Input Parameter:
10780 . mat - the matrix
10781 
10782   Output Parameter:
10783 . is - contains the list of rows with off block diagonal entries
10784 
10785   Level: developer
10786 
10787 .seealso: [](ch_matrices), `Mat`, `MatMultTranspose()`, `MatMultAdd()`, `MatMultTransposeAdd()`
10788 @*/
10789 PetscErrorCode MatFindOffBlockDiagonalEntries(Mat mat, IS *is)
10790 {
10791   PetscFunctionBegin;
10792   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
10793   PetscValidType(mat, 1);
10794   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
10795   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
10796 
10797   PetscUseTypeMethod(mat, findoffblockdiagonalentries, is);
10798   PetscFunctionReturn(PETSC_SUCCESS);
10799 }
10800 
10801 /*@C
10802   MatInvertBlockDiagonal - Inverts the block diagonal entries.
10803 
10804   Collective; No Fortran Support
10805 
10806   Input Parameter:
10807 . mat - the matrix
10808 
10809   Output Parameter:
10810 . values - the block inverses in column major order (FORTRAN-like)
10811 
10812   Level: advanced
10813 
10814   Notes:
10815   The size of the blocks is determined by the block size of the matrix.
10816 
10817   The blocks never overlap between two MPI processes, use `MatInvertVariableBlockEnvelope()` for that case
10818 
10819   The blocks all have the same size, use `MatInvertVariableBlockDiagonal()` for variable block size
10820 
10821 .seealso: [](ch_matrices), `Mat`, `MatInvertVariableBlockEnvelope()`, `MatInvertBlockDiagonalMat()`
10822 @*/
10823 PetscErrorCode MatInvertBlockDiagonal(Mat mat, const PetscScalar *values[])
10824 {
10825   PetscFunctionBegin;
10826   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
10827   PetscCheck(mat->assembled, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
10828   PetscCheck(!mat->factortype, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
10829   PetscUseTypeMethod(mat, invertblockdiagonal, values);
10830   PetscFunctionReturn(PETSC_SUCCESS);
10831 }
10832 
10833 /*@
10834   MatInvertVariableBlockDiagonal - Inverts the point block diagonal entries.
10835 
10836   Collective; No Fortran Support
10837 
10838   Input Parameters:
10839 + mat     - the matrix
10840 . nblocks - the number of blocks on the process, set with `MatSetVariableBlockSizes()`
10841 - bsizes  - the size of each block on the process, set with `MatSetVariableBlockSizes()`
10842 
10843   Output Parameter:
10844 . values - the block inverses in column major order (FORTRAN-like)
10845 
10846   Level: advanced
10847 
10848   Notes:
10849   Use `MatInvertBlockDiagonal()` if all blocks have the same size
10850 
10851   The blocks never overlap between two MPI processes, use `MatInvertVariableBlockEnvelope()` for that case
10852 
10853 .seealso: [](ch_matrices), `Mat`, `MatInvertBlockDiagonal()`, `MatSetVariableBlockSizes()`, `MatInvertVariableBlockEnvelope()`
10854 @*/
10855 PetscErrorCode MatInvertVariableBlockDiagonal(Mat mat, PetscInt nblocks, const PetscInt bsizes[], PetscScalar values[])
10856 {
10857   PetscFunctionBegin;
10858   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
10859   PetscCheck(mat->assembled, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
10860   PetscCheck(!mat->factortype, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
10861   PetscUseTypeMethod(mat, invertvariableblockdiagonal, nblocks, bsizes, values);
10862   PetscFunctionReturn(PETSC_SUCCESS);
10863 }
10864 
10865 /*@
10866   MatInvertBlockDiagonalMat - set the values of matrix C to be the inverted block diagonal of matrix A
10867 
10868   Collective
10869 
10870   Input Parameters:
10871 + A - the matrix
10872 - C - matrix with inverted block diagonal of `A`.  This matrix should be created and may have its type set.
10873 
10874   Level: advanced
10875 
10876   Note:
10877   The blocksize of the matrix is used to determine the blocks on the diagonal of `C`
10878 
10879 .seealso: [](ch_matrices), `Mat`, `MatInvertBlockDiagonal()`
10880 @*/
10881 PetscErrorCode MatInvertBlockDiagonalMat(Mat A, Mat C)
10882 {
10883   const PetscScalar *vals;
10884   PetscInt          *dnnz;
10885   PetscInt           m, rstart, rend, bs, i, j;
10886 
10887   PetscFunctionBegin;
10888   PetscCall(MatInvertBlockDiagonal(A, &vals));
10889   PetscCall(MatGetBlockSize(A, &bs));
10890   PetscCall(MatGetLocalSize(A, &m, NULL));
10891   PetscCall(MatSetLayouts(C, A->rmap, A->cmap));
10892   PetscCall(PetscMalloc1(m / bs, &dnnz));
10893   for (j = 0; j < m / bs; j++) dnnz[j] = 1;
10894   PetscCall(MatXAIJSetPreallocation(C, bs, dnnz, NULL, NULL, NULL));
10895   PetscCall(PetscFree(dnnz));
10896   PetscCall(MatGetOwnershipRange(C, &rstart, &rend));
10897   PetscCall(MatSetOption(C, MAT_ROW_ORIENTED, PETSC_FALSE));
10898   for (i = rstart / bs; i < rend / bs; i++) PetscCall(MatSetValuesBlocked(C, 1, &i, 1, &i, &vals[(i - rstart / bs) * bs * bs], INSERT_VALUES));
10899   PetscCall(MatAssemblyBegin(C, MAT_FINAL_ASSEMBLY));
10900   PetscCall(MatAssemblyEnd(C, MAT_FINAL_ASSEMBLY));
10901   PetscCall(MatSetOption(C, MAT_ROW_ORIENTED, PETSC_TRUE));
10902   PetscFunctionReturn(PETSC_SUCCESS);
10903 }
10904 
10905 /*@
10906   MatTransposeColoringDestroy - Destroys a coloring context for matrix product $C = A*B^T$ that was created
10907   via `MatTransposeColoringCreate()`.
10908 
10909   Collective
10910 
10911   Input Parameter:
10912 . c - coloring context
10913 
10914   Level: intermediate
10915 
10916 .seealso: [](ch_matrices), `Mat`, `MatTransposeColoringCreate()`
10917 @*/
10918 PetscErrorCode MatTransposeColoringDestroy(MatTransposeColoring *c)
10919 {
10920   MatTransposeColoring matcolor = *c;
10921 
10922   PetscFunctionBegin;
10923   if (!matcolor) PetscFunctionReturn(PETSC_SUCCESS);
10924   if (--((PetscObject)matcolor)->refct > 0) {
10925     matcolor = NULL;
10926     PetscFunctionReturn(PETSC_SUCCESS);
10927   }
10928 
10929   PetscCall(PetscFree3(matcolor->ncolumns, matcolor->nrows, matcolor->colorforrow));
10930   PetscCall(PetscFree(matcolor->rows));
10931   PetscCall(PetscFree(matcolor->den2sp));
10932   PetscCall(PetscFree(matcolor->colorforcol));
10933   PetscCall(PetscFree(matcolor->columns));
10934   if (matcolor->brows > 0) PetscCall(PetscFree(matcolor->lstart));
10935   PetscCall(PetscHeaderDestroy(c));
10936   PetscFunctionReturn(PETSC_SUCCESS);
10937 }
10938 
10939 /*@
10940   MatTransColoringApplySpToDen - Given a symbolic matrix product $C = A*B^T$ for which
10941   a `MatTransposeColoring` context has been created, computes a dense $B^T$ by applying
10942   `MatTransposeColoring` to sparse `B`.
10943 
10944   Collective
10945 
10946   Input Parameters:
10947 + coloring - coloring context created with `MatTransposeColoringCreate()`
10948 - B        - sparse matrix
10949 
10950   Output Parameter:
10951 . Btdense - dense matrix $B^T$
10952 
10953   Level: developer
10954 
10955   Note:
10956   These are used internally for some implementations of `MatRARt()`
10957 
10958 .seealso: [](ch_matrices), `Mat`, `MatTransposeColoringCreate()`, `MatTransposeColoringDestroy()`, `MatTransColoringApplyDenToSp()`
10959 @*/
10960 PetscErrorCode MatTransColoringApplySpToDen(MatTransposeColoring coloring, Mat B, Mat Btdense)
10961 {
10962   PetscFunctionBegin;
10963   PetscValidHeaderSpecific(coloring, MAT_TRANSPOSECOLORING_CLASSID, 1);
10964   PetscValidHeaderSpecific(B, MAT_CLASSID, 2);
10965   PetscValidHeaderSpecific(Btdense, MAT_CLASSID, 3);
10966 
10967   PetscCall((*B->ops->transcoloringapplysptoden)(coloring, B, Btdense));
10968   PetscFunctionReturn(PETSC_SUCCESS);
10969 }
10970 
10971 /*@
10972   MatTransColoringApplyDenToSp - Given a symbolic matrix product $C_{sp} = A*B^T$ for which
10973   a `MatTransposeColoring` context has been created and a dense matrix $C_{den} = A*B^T_{dense}$
10974   in which `B^T_{dens}` is obtained from `MatTransColoringApplySpToDen()`, recover sparse matrix
10975   $C_{sp}$ from $C_{den}$.
10976 
10977   Collective
10978 
10979   Input Parameters:
10980 + matcoloring - coloring context created with `MatTransposeColoringCreate()`
10981 - Cden        - matrix product of a sparse matrix and a dense matrix Btdense
10982 
10983   Output Parameter:
10984 . Csp - sparse matrix
10985 
10986   Level: developer
10987 
10988   Note:
10989   These are used internally for some implementations of `MatRARt()`
10990 
10991 .seealso: [](ch_matrices), `Mat`, `MatTransposeColoringCreate()`, `MatTransposeColoringDestroy()`, `MatTransColoringApplySpToDen()`
10992 @*/
10993 PetscErrorCode MatTransColoringApplyDenToSp(MatTransposeColoring matcoloring, Mat Cden, Mat Csp)
10994 {
10995   PetscFunctionBegin;
10996   PetscValidHeaderSpecific(matcoloring, MAT_TRANSPOSECOLORING_CLASSID, 1);
10997   PetscValidHeaderSpecific(Cden, MAT_CLASSID, 2);
10998   PetscValidHeaderSpecific(Csp, MAT_CLASSID, 3);
10999 
11000   PetscCall((*Csp->ops->transcoloringapplydentosp)(matcoloring, Cden, Csp));
11001   PetscCall(MatAssemblyBegin(Csp, MAT_FINAL_ASSEMBLY));
11002   PetscCall(MatAssemblyEnd(Csp, MAT_FINAL_ASSEMBLY));
11003   PetscFunctionReturn(PETSC_SUCCESS);
11004 }
11005 
11006 /*@
11007   MatTransposeColoringCreate - Creates a matrix coloring context for the matrix product $C = A*B^T$.
11008 
11009   Collective
11010 
11011   Input Parameters:
11012 + mat        - the matrix product C
11013 - iscoloring - the coloring of the matrix; usually obtained with `MatColoringCreate()` or `DMCreateColoring()`
11014 
11015   Output Parameter:
11016 . color - the new coloring context
11017 
11018   Level: intermediate
11019 
11020 .seealso: [](ch_matrices), `Mat`, `MatTransposeColoringDestroy()`, `MatTransColoringApplySpToDen()`,
11021           `MatTransColoringApplyDenToSp()`
11022 @*/
11023 PetscErrorCode MatTransposeColoringCreate(Mat mat, ISColoring iscoloring, MatTransposeColoring *color)
11024 {
11025   MatTransposeColoring c;
11026   MPI_Comm             comm;
11027 
11028   PetscFunctionBegin;
11029   PetscAssertPointer(color, 3);
11030 
11031   PetscCall(PetscLogEventBegin(MAT_TransposeColoringCreate, mat, 0, 0, 0));
11032   PetscCall(PetscObjectGetComm((PetscObject)mat, &comm));
11033   PetscCall(PetscHeaderCreate(c, MAT_TRANSPOSECOLORING_CLASSID, "MatTransposeColoring", "Matrix product C=A*B^T via coloring", "Mat", comm, MatTransposeColoringDestroy, NULL));
11034   c->ctype = iscoloring->ctype;
11035   PetscUseTypeMethod(mat, transposecoloringcreate, iscoloring, c);
11036   *color = c;
11037   PetscCall(PetscLogEventEnd(MAT_TransposeColoringCreate, mat, 0, 0, 0));
11038   PetscFunctionReturn(PETSC_SUCCESS);
11039 }
11040 
11041 /*@
11042   MatGetNonzeroState - Returns a 64-bit integer representing the current state of nonzeros in the matrix. If the
11043   matrix has had new nonzero locations added to (or removed from) the matrix since the previous call, the value will be larger.
11044 
11045   Not Collective
11046 
11047   Input Parameter:
11048 . mat - the matrix
11049 
11050   Output Parameter:
11051 . state - the current state
11052 
11053   Level: intermediate
11054 
11055   Notes:
11056   You can only compare states from two different calls to the SAME matrix, you cannot compare calls between
11057   different matrices
11058 
11059   Use `PetscObjectStateGet()` to check for changes to the numerical values in a matrix
11060 
11061   Use the result of `PetscObjectGetId()` to compare if a previously checked matrix is the same as the current matrix, do not compare object pointers.
11062 
11063 .seealso: [](ch_matrices), `Mat`, `PetscObjectStateGet()`, `PetscObjectGetId()`
11064 @*/
11065 PetscErrorCode MatGetNonzeroState(Mat mat, PetscObjectState *state)
11066 {
11067   PetscFunctionBegin;
11068   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
11069   *state = mat->nonzerostate;
11070   PetscFunctionReturn(PETSC_SUCCESS);
11071 }
11072 
11073 /*@
11074   MatCreateMPIMatConcatenateSeqMat - Creates a single large PETSc matrix by concatenating sequential
11075   matrices from each processor
11076 
11077   Collective
11078 
11079   Input Parameters:
11080 + comm   - the communicators the parallel matrix will live on
11081 . seqmat - the input sequential matrices
11082 . n      - number of local columns (or `PETSC_DECIDE`)
11083 - reuse  - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`
11084 
11085   Output Parameter:
11086 . mpimat - the parallel matrix generated
11087 
11088   Level: developer
11089 
11090   Note:
11091   The number of columns of the matrix in EACH processor MUST be the same.
11092 
11093 .seealso: [](ch_matrices), `Mat`
11094 @*/
11095 PetscErrorCode MatCreateMPIMatConcatenateSeqMat(MPI_Comm comm, Mat seqmat, PetscInt n, MatReuse reuse, Mat *mpimat)
11096 {
11097   PetscMPIInt size;
11098 
11099   PetscFunctionBegin;
11100   PetscCallMPI(MPI_Comm_size(comm, &size));
11101   if (size == 1) {
11102     if (reuse == MAT_INITIAL_MATRIX) {
11103       PetscCall(MatDuplicate(seqmat, MAT_COPY_VALUES, mpimat));
11104     } else {
11105       PetscCall(MatCopy(seqmat, *mpimat, SAME_NONZERO_PATTERN));
11106     }
11107     PetscFunctionReturn(PETSC_SUCCESS);
11108   }
11109 
11110   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");
11111 
11112   PetscCall(PetscLogEventBegin(MAT_Merge, seqmat, 0, 0, 0));
11113   PetscCall((*seqmat->ops->creatempimatconcatenateseqmat)(comm, seqmat, n, reuse, mpimat));
11114   PetscCall(PetscLogEventEnd(MAT_Merge, seqmat, 0, 0, 0));
11115   PetscFunctionReturn(PETSC_SUCCESS);
11116 }
11117 
11118 /*@
11119   MatSubdomainsCreateCoalesce - Creates index subdomains by coalescing adjacent MPI processes' ownership ranges.
11120 
11121   Collective
11122 
11123   Input Parameters:
11124 + A - the matrix to create subdomains from
11125 - N - requested number of subdomains
11126 
11127   Output Parameters:
11128 + n   - number of subdomains resulting on this MPI process
11129 - iss - `IS` list with indices of subdomains on this MPI process
11130 
11131   Level: advanced
11132 
11133   Note:
11134   The number of subdomains must be smaller than the communicator size
11135 
11136 .seealso: [](ch_matrices), `Mat`, `IS`
11137 @*/
11138 PetscErrorCode MatSubdomainsCreateCoalesce(Mat A, PetscInt N, PetscInt *n, IS *iss[])
11139 {
11140   MPI_Comm    comm, subcomm;
11141   PetscMPIInt size, rank, color;
11142   PetscInt    rstart, rend, k;
11143 
11144   PetscFunctionBegin;
11145   PetscCall(PetscObjectGetComm((PetscObject)A, &comm));
11146   PetscCallMPI(MPI_Comm_size(comm, &size));
11147   PetscCallMPI(MPI_Comm_rank(comm, &rank));
11148   PetscCheck(N >= 1 && N < (PetscInt)size, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "number of subdomains must be > 0 and < %d, got N = %" PetscInt_FMT, size, N);
11149   *n    = 1;
11150   k     = ((PetscInt)size) / N + ((PetscInt)size % N > 0); /* There are up to k ranks to a color */
11151   color = rank / k;
11152   PetscCallMPI(MPI_Comm_split(comm, color, rank, &subcomm));
11153   PetscCall(PetscMalloc1(1, iss));
11154   PetscCall(MatGetOwnershipRange(A, &rstart, &rend));
11155   PetscCall(ISCreateStride(subcomm, rend - rstart, rstart, 1, iss[0]));
11156   PetscCallMPI(MPI_Comm_free(&subcomm));
11157   PetscFunctionReturn(PETSC_SUCCESS);
11158 }
11159 
11160 /*@
11161   MatGalerkin - Constructs the coarse grid problem matrix via Galerkin projection.
11162 
11163   If the interpolation and restriction operators are the same, uses `MatPtAP()`.
11164   If they are not the same, uses `MatMatMatMult()`.
11165 
11166   Once the coarse grid problem is constructed, correct for interpolation operators
11167   that are not of full rank, which can legitimately happen in the case of non-nested
11168   geometric multigrid.
11169 
11170   Input Parameters:
11171 + restrct     - restriction operator
11172 . dA          - fine grid matrix
11173 . interpolate - interpolation operator
11174 . reuse       - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`
11175 - fill        - expected fill, use `PETSC_DEFAULT` if you do not have a good estimate
11176 
11177   Output Parameter:
11178 . A - the Galerkin coarse matrix
11179 
11180   Options Database Key:
11181 . -pc_mg_galerkin <both,pmat,mat,none> - for what matrices the Galerkin process should be used
11182 
11183   Level: developer
11184 
11185 .seealso: [](ch_matrices), `Mat`, `MatPtAP()`, `MatMatMatMult()`
11186 @*/
11187 PetscErrorCode MatGalerkin(Mat restrct, Mat dA, Mat interpolate, MatReuse reuse, PetscReal fill, Mat *A)
11188 {
11189   IS  zerorows;
11190   Vec diag;
11191 
11192   PetscFunctionBegin;
11193   PetscCheck(reuse != MAT_INPLACE_MATRIX, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "Inplace product not supported");
11194   /* Construct the coarse grid matrix */
11195   if (interpolate == restrct) {
11196     PetscCall(MatPtAP(dA, interpolate, reuse, fill, A));
11197   } else {
11198     PetscCall(MatMatMatMult(restrct, dA, interpolate, reuse, fill, A));
11199   }
11200 
11201   /* If the interpolation matrix is not of full rank, A will have zero rows.
11202      This can legitimately happen in the case of non-nested geometric multigrid.
11203      In that event, we set the rows of the matrix to the rows of the identity,
11204      ignoring the equations (as the RHS will also be zero). */
11205 
11206   PetscCall(MatFindZeroRows(*A, &zerorows));
11207 
11208   if (zerorows != NULL) { /* if there are any zero rows */
11209     PetscCall(MatCreateVecs(*A, &diag, NULL));
11210     PetscCall(MatGetDiagonal(*A, diag));
11211     PetscCall(VecISSet(diag, zerorows, 1.0));
11212     PetscCall(MatDiagonalSet(*A, diag, INSERT_VALUES));
11213     PetscCall(VecDestroy(&diag));
11214     PetscCall(ISDestroy(&zerorows));
11215   }
11216   PetscFunctionReturn(PETSC_SUCCESS);
11217 }
11218 
11219 /*@C
11220   MatSetOperation - Allows user to set a matrix operation for any matrix type
11221 
11222   Logically Collective
11223 
11224   Input Parameters:
11225 + mat - the matrix
11226 . op  - the name of the operation
11227 - f   - the function that provides the operation
11228 
11229   Level: developer
11230 
11231   Example Usage:
11232 .vb
11233   extern PetscErrorCode usermult(Mat, Vec, Vec);
11234 
11235   PetscCall(MatCreateXXX(comm, ..., &A));
11236   PetscCall(MatSetOperation(A, MATOP_MULT, (PetscVoidFn *)usermult));
11237 .ve
11238 
11239   Notes:
11240   See the file `include/petscmat.h` for a complete list of matrix
11241   operations, which all have the form MATOP_<OPERATION>, where
11242   <OPERATION> is the name (in all capital letters) of the
11243   user interface routine (e.g., `MatMult()` -> `MATOP_MULT`).
11244 
11245   All user-provided functions (except for `MATOP_DESTROY`) should have the same calling
11246   sequence as the usual matrix interface routines, since they
11247   are intended to be accessed via the usual matrix interface
11248   routines, e.g.,
11249 .vb
11250   MatMult(Mat, Vec, Vec) -> usermult(Mat, Vec, Vec)
11251 .ve
11252 
11253   In particular each function MUST return `PETSC_SUCCESS` on success and
11254   nonzero on failure.
11255 
11256   This routine is distinct from `MatShellSetOperation()` in that it can be called on any matrix type.
11257 
11258 .seealso: [](ch_matrices), `Mat`, `MatGetOperation()`, `MatCreateShell()`, `MatShellSetContext()`, `MatShellSetOperation()`
11259 @*/
11260 PetscErrorCode MatSetOperation(Mat mat, MatOperation op, void (*f)(void))
11261 {
11262   PetscFunctionBegin;
11263   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
11264   if (op == MATOP_VIEW && !mat->ops->viewnative && f != (void (*)(void))mat->ops->view) mat->ops->viewnative = mat->ops->view;
11265   (((void (**)(void))mat->ops)[op]) = f;
11266   PetscFunctionReturn(PETSC_SUCCESS);
11267 }
11268 
11269 /*@C
11270   MatGetOperation - Gets a matrix operation for any matrix type.
11271 
11272   Not Collective
11273 
11274   Input Parameters:
11275 + mat - the matrix
11276 - op  - the name of the operation
11277 
11278   Output Parameter:
11279 . f - the function that provides the operation
11280 
11281   Level: developer
11282 
11283   Example Usage:
11284 .vb
11285   PetscErrorCode (*usermult)(Mat, Vec, Vec);
11286 
11287   MatGetOperation(A, MATOP_MULT, (void (**)(void))&usermult);
11288 .ve
11289 
11290   Notes:
11291   See the file include/petscmat.h for a complete list of matrix
11292   operations, which all have the form MATOP_<OPERATION>, where
11293   <OPERATION> is the name (in all capital letters) of the
11294   user interface routine (e.g., `MatMult()` -> `MATOP_MULT`).
11295 
11296   This routine is distinct from `MatShellGetOperation()` in that it can be called on any matrix type.
11297 
11298 .seealso: [](ch_matrices), `Mat`, `MatSetOperation()`, `MatCreateShell()`, `MatShellGetContext()`, `MatShellGetOperation()`
11299 @*/
11300 PetscErrorCode MatGetOperation(Mat mat, MatOperation op, void (**f)(void))
11301 {
11302   PetscFunctionBegin;
11303   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
11304   *f = (((void (**)(void))mat->ops)[op]);
11305   PetscFunctionReturn(PETSC_SUCCESS);
11306 }
11307 
11308 /*@
11309   MatHasOperation - Determines whether the given matrix supports the particular operation.
11310 
11311   Not Collective
11312 
11313   Input Parameters:
11314 + mat - the matrix
11315 - op  - the operation, for example, `MATOP_GET_DIAGONAL`
11316 
11317   Output Parameter:
11318 . has - either `PETSC_TRUE` or `PETSC_FALSE`
11319 
11320   Level: advanced
11321 
11322   Note:
11323   See `MatSetOperation()` for additional discussion on naming convention and usage of `op`.
11324 
11325 .seealso: [](ch_matrices), `Mat`, `MatCreateShell()`, `MatGetOperation()`, `MatSetOperation()`
11326 @*/
11327 PetscErrorCode MatHasOperation(Mat mat, MatOperation op, PetscBool *has)
11328 {
11329   PetscFunctionBegin;
11330   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
11331   PetscAssertPointer(has, 3);
11332   if (mat->ops->hasoperation) {
11333     PetscUseTypeMethod(mat, hasoperation, op, has);
11334   } else {
11335     if (((void **)mat->ops)[op]) *has = PETSC_TRUE;
11336     else {
11337       *has = PETSC_FALSE;
11338       if (op == MATOP_CREATE_SUBMATRIX) {
11339         PetscMPIInt size;
11340 
11341         PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)mat), &size));
11342         if (size == 1) PetscCall(MatHasOperation(mat, MATOP_CREATE_SUBMATRICES, has));
11343       }
11344     }
11345   }
11346   PetscFunctionReturn(PETSC_SUCCESS);
11347 }
11348 
11349 /*@
11350   MatHasCongruentLayouts - Determines whether the rows and columns layouts of the matrix are congruent
11351 
11352   Collective
11353 
11354   Input Parameter:
11355 . mat - the matrix
11356 
11357   Output Parameter:
11358 . cong - either `PETSC_TRUE` or `PETSC_FALSE`
11359 
11360   Level: beginner
11361 
11362 .seealso: [](ch_matrices), `Mat`, `MatCreate()`, `MatSetSizes()`, `PetscLayout`
11363 @*/
11364 PetscErrorCode MatHasCongruentLayouts(Mat mat, PetscBool *cong)
11365 {
11366   PetscFunctionBegin;
11367   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
11368   PetscValidType(mat, 1);
11369   PetscAssertPointer(cong, 2);
11370   if (!mat->rmap || !mat->cmap) {
11371     *cong = mat->rmap == mat->cmap ? PETSC_TRUE : PETSC_FALSE;
11372     PetscFunctionReturn(PETSC_SUCCESS);
11373   }
11374   if (mat->congruentlayouts == PETSC_DECIDE) { /* first time we compare rows and cols layouts */
11375     PetscCall(PetscLayoutSetUp(mat->rmap));
11376     PetscCall(PetscLayoutSetUp(mat->cmap));
11377     PetscCall(PetscLayoutCompare(mat->rmap, mat->cmap, cong));
11378     if (*cong) mat->congruentlayouts = 1;
11379     else mat->congruentlayouts = 0;
11380   } else *cong = mat->congruentlayouts ? PETSC_TRUE : PETSC_FALSE;
11381   PetscFunctionReturn(PETSC_SUCCESS);
11382 }
11383 
11384 PetscErrorCode MatSetInf(Mat A)
11385 {
11386   PetscFunctionBegin;
11387   PetscUseTypeMethod(A, setinf);
11388   PetscFunctionReturn(PETSC_SUCCESS);
11389 }
11390 
11391 /*@
11392   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
11393   and possibly removes small values from the graph structure.
11394 
11395   Collective
11396 
11397   Input Parameters:
11398 + A       - the matrix
11399 . sym     - `PETSC_TRUE` indicates that the graph should be symmetrized
11400 . scale   - `PETSC_TRUE` indicates that the graph edge weights should be symmetrically scaled with the diagonal entry
11401 . filter  - filter value - < 0: does nothing; == 0: removes only 0.0 entries; otherwise: removes entries with abs(entries) <= value
11402 . num_idx - size of 'index' array
11403 - index   - array of block indices to use for graph strength of connection weight
11404 
11405   Output Parameter:
11406 . graph - the resulting graph
11407 
11408   Level: advanced
11409 
11410 .seealso: [](ch_matrices), `Mat`, `MatCreate()`, `PCGAMG`
11411 @*/
11412 PetscErrorCode MatCreateGraph(Mat A, PetscBool sym, PetscBool scale, PetscReal filter, PetscInt num_idx, PetscInt index[], Mat *graph)
11413 {
11414   PetscFunctionBegin;
11415   PetscValidHeaderSpecific(A, MAT_CLASSID, 1);
11416   PetscValidType(A, 1);
11417   PetscValidLogicalCollectiveBool(A, scale, 3);
11418   PetscAssertPointer(graph, 7);
11419   PetscUseTypeMethod(A, creategraph, sym, scale, filter, num_idx, index, graph);
11420   PetscFunctionReturn(PETSC_SUCCESS);
11421 }
11422 
11423 /*@
11424   MatEliminateZeros - eliminate the nondiagonal zero entries in place from the nonzero structure of a sparse `Mat` in place,
11425   meaning the same memory is used for the matrix, and no new memory is allocated.
11426 
11427   Collective
11428 
11429   Input Parameters:
11430 + A    - the matrix
11431 - 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
11432 
11433   Level: intermediate
11434 
11435   Developer Note:
11436   The entries in the sparse matrix data structure are shifted to fill in the unneeded locations in the data. Thus the end
11437   of the arrays in the data structure are unneeded.
11438 
11439 .seealso: [](ch_matrices), `Mat`, `MatCreate()`, `MatCreateGraph()`, `MatFilter()`
11440 @*/
11441 PetscErrorCode MatEliminateZeros(Mat A, PetscBool keep)
11442 {
11443   PetscFunctionBegin;
11444   PetscValidHeaderSpecific(A, MAT_CLASSID, 1);
11445   PetscUseTypeMethod(A, eliminatezeros, keep);
11446   PetscFunctionReturn(PETSC_SUCCESS);
11447 }
11448