xref: /petsc/src/mat/interface/matrix.c (revision ccfb0f9f40a0131988d7995ed9679700dae2a75a)
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_CreateGraph;
40 PetscLogEvent MAT_SetValuesBatch;
41 PetscLogEvent MAT_ViennaCLCopyToGPU;
42 PetscLogEvent MAT_CUDACopyToGPU, MAT_HIPCopyToGPU;
43 PetscLogEvent MAT_DenseCopyToGPU, MAT_DenseCopyFromGPU;
44 PetscLogEvent MAT_Merge, MAT_Residual, MAT_SetRandom;
45 PetscLogEvent MAT_FactorFactS, MAT_FactorInvS;
46 PetscLogEvent MATCOLORING_Apply, MATCOLORING_Comm, MATCOLORING_Local, MATCOLORING_ISCreate, MATCOLORING_SetUp, MATCOLORING_Weights;
47 PetscLogEvent MAT_H2Opus_Build, MAT_H2Opus_Compress, MAT_H2Opus_Orthog, MAT_H2Opus_LR;
48 
49 const char *const MatFactorTypes[] = {"NONE", "LU", "CHOLESKY", "ILU", "ICC", "ILUDT", "QR", "MatFactorType", "MAT_FACTOR_", NULL};
50 
51 /*@
52   MatSetRandom - Sets all components of a matrix to random numbers.
53 
54   Logically Collective
55 
56   Input Parameters:
57 + x    - the matrix
58 - rctx - the `PetscRandom` object, formed by `PetscRandomCreate()`, or `NULL` and
59           it will create one internally.
60 
61   Example:
62 .vb
63      PetscRandomCreate(PETSC_COMM_WORLD,&rctx);
64      MatSetRandom(x,rctx);
65      PetscRandomDestroy(rctx);
66 .ve
67 
68   Level: intermediate
69 
70   Notes:
71   For sparse matrices that have been preallocated but not been assembled, it randomly selects appropriate locations,
72 
73   for sparse matrices that already have nonzero locations, it fills the locations with random numbers.
74 
75   It generates an error if used on unassembled sparse matrices that have not been preallocated.
76 
77 .seealso: [](ch_matrices), `Mat`, `PetscRandom`, `PetscRandomCreate()`, `MatZeroEntries()`, `MatSetValues()`, `PetscRandomDestroy()`
78 @*/
79 PetscErrorCode MatSetRandom(Mat x, PetscRandom rctx)
80 {
81   PetscRandom randObj = NULL;
82 
83   PetscFunctionBegin;
84   PetscValidHeaderSpecific(x, MAT_CLASSID, 1);
85   if (rctx) PetscValidHeaderSpecific(rctx, PETSC_RANDOM_CLASSID, 2);
86   PetscValidType(x, 1);
87   MatCheckPreallocated(x, 1);
88 
89   if (!rctx) {
90     MPI_Comm comm;
91     PetscCall(PetscObjectGetComm((PetscObject)x, &comm));
92     PetscCall(PetscRandomCreate(comm, &randObj));
93     PetscCall(PetscRandomSetType(randObj, x->defaultrandtype));
94     PetscCall(PetscRandomSetFromOptions(randObj));
95     rctx = randObj;
96   }
97   PetscCall(PetscLogEventBegin(MAT_SetRandom, x, rctx, 0, 0));
98   PetscUseTypeMethod(x, setrandom, rctx);
99   PetscCall(PetscLogEventEnd(MAT_SetRandom, x, rctx, 0, 0));
100 
101   PetscCall(MatAssemblyBegin(x, MAT_FINAL_ASSEMBLY));
102   PetscCall(MatAssemblyEnd(x, MAT_FINAL_ASSEMBLY));
103   PetscCall(PetscRandomDestroy(&randObj));
104   PetscFunctionReturn(PETSC_SUCCESS);
105 }
106 
107 /*@
108   MatCopyHashToXAIJ - copy hash table entries into an XAIJ matrix type
109 
110   Logically Collective
111 
112   Input Parameter:
113 . A - A matrix in unassembled, hash table form
114 
115   Output Parameter:
116 . B - The XAIJ matrix. This can either be `A` or some matrix of equivalent size, e.g. obtained from `A` via `MatDuplicate()`
117 
118   Example:
119 .vb
120      PetscCall(MatDuplicate(A, MAT_DO_NOT_COPY_VALUES, &B));
121      PetscCall(MatCopyHashToXAIJ(A, B));
122 .ve
123 
124   Level: advanced
125 
126   Notes:
127   If `B` is `A`, then the hash table data structure will be destroyed. `B` is assembled
128 
129 .seealso: [](ch_matrices), `Mat`, `MAT_USE_HASH_TABLE`
130 @*/
131 PetscErrorCode MatCopyHashToXAIJ(Mat A, Mat B)
132 {
133   PetscFunctionBegin;
134   PetscValidHeaderSpecific(A, MAT_CLASSID, 1);
135   PetscUseTypeMethod(A, copyhashtoxaij, B);
136   PetscFunctionReturn(PETSC_SUCCESS);
137 }
138 
139 /*@
140   MatFactorGetErrorZeroPivot - returns the pivot value that was determined to be zero and the row it occurred in
141 
142   Logically Collective
143 
144   Input Parameter:
145 . mat - the factored matrix
146 
147   Output Parameters:
148 + pivot - the pivot value computed
149 - row   - the row that the zero pivot occurred. This row value must be interpreted carefully due to row reorderings and which processes
150          the share the matrix
151 
152   Level: advanced
153 
154   Notes:
155   This routine does not work for factorizations done with external packages.
156 
157   This routine should only be called if `MatGetFactorError()` returns a value of `MAT_FACTOR_NUMERIC_ZEROPIVOT`
158 
159   This can also be called on non-factored matrices that come from, for example, matrices used in SOR.
160 
161 .seealso: [](ch_matrices), `Mat`, `MatZeroEntries()`, `MatFactor()`, `MatGetFactor()`,
162 `MatLUFactorSymbolic()`, `MatCholeskyFactorSymbolic()`, `MatFactorClearError()`,
163 `MAT_FACTOR_NUMERIC_ZEROPIVOT`
164 @*/
165 PetscErrorCode MatFactorGetErrorZeroPivot(Mat mat, PetscReal *pivot, PetscInt *row)
166 {
167   PetscFunctionBegin;
168   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
169   PetscAssertPointer(pivot, 2);
170   PetscAssertPointer(row, 3);
171   *pivot = mat->factorerror_zeropivot_value;
172   *row   = mat->factorerror_zeropivot_row;
173   PetscFunctionReturn(PETSC_SUCCESS);
174 }
175 
176 /*@
177   MatFactorGetError - gets the error code from a factorization
178 
179   Logically Collective
180 
181   Input Parameter:
182 . mat - the factored matrix
183 
184   Output Parameter:
185 . err - the error code
186 
187   Level: advanced
188 
189   Note:
190   This can also be called on non-factored matrices that come from, for example, matrices used in SOR.
191 
192 .seealso: [](ch_matrices), `Mat`, `MatZeroEntries()`, `MatFactor()`, `MatGetFactor()`, `MatLUFactorSymbolic()`, `MatCholeskyFactorSymbolic()`,
193           `MatFactorClearError()`, `MatFactorGetErrorZeroPivot()`, `MatFactorError`
194 @*/
195 PetscErrorCode MatFactorGetError(Mat mat, MatFactorError *err)
196 {
197   PetscFunctionBegin;
198   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
199   PetscAssertPointer(err, 2);
200   *err = mat->factorerrortype;
201   PetscFunctionReturn(PETSC_SUCCESS);
202 }
203 
204 /*@
205   MatFactorClearError - clears the error code in a factorization
206 
207   Logically Collective
208 
209   Input Parameter:
210 . mat - the factored matrix
211 
212   Level: developer
213 
214   Note:
215   This can also be called on non-factored matrices that come from, for example, matrices used in SOR.
216 
217 .seealso: [](ch_matrices), `Mat`, `MatZeroEntries()`, `MatFactor()`, `MatGetFactor()`, `MatLUFactorSymbolic()`, `MatCholeskyFactorSymbolic()`, `MatFactorGetError()`, `MatFactorGetErrorZeroPivot()`,
218           `MatGetErrorCode()`, `MatFactorError`
219 @*/
220 PetscErrorCode MatFactorClearError(Mat mat)
221 {
222   PetscFunctionBegin;
223   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
224   mat->factorerrortype             = MAT_FACTOR_NOERROR;
225   mat->factorerror_zeropivot_value = 0.0;
226   mat->factorerror_zeropivot_row   = 0;
227   PetscFunctionReturn(PETSC_SUCCESS);
228 }
229 
230 PetscErrorCode MatFindNonzeroRowsOrCols_Basic(Mat mat, PetscBool cols, PetscReal tol, IS *nonzero)
231 {
232   Vec                r, l;
233   const PetscScalar *al;
234   PetscInt           i, nz, gnz, N, n, st;
235 
236   PetscFunctionBegin;
237   PetscCall(MatCreateVecs(mat, &r, &l));
238   if (!cols) { /* nonzero rows */
239     PetscCall(MatGetOwnershipRange(mat, &st, NULL));
240     PetscCall(MatGetSize(mat, &N, NULL));
241     PetscCall(MatGetLocalSize(mat, &n, NULL));
242     PetscCall(VecSet(l, 0.0));
243     PetscCall(VecSetRandom(r, NULL));
244     PetscCall(MatMult(mat, r, l));
245     PetscCall(VecGetArrayRead(l, &al));
246   } else { /* nonzero columns */
247     PetscCall(MatGetOwnershipRangeColumn(mat, &st, NULL));
248     PetscCall(MatGetSize(mat, NULL, &N));
249     PetscCall(MatGetLocalSize(mat, NULL, &n));
250     PetscCall(VecSet(r, 0.0));
251     PetscCall(VecSetRandom(l, NULL));
252     PetscCall(MatMultTranspose(mat, l, r));
253     PetscCall(VecGetArrayRead(r, &al));
254   }
255   if (tol <= 0.0) {
256     for (i = 0, nz = 0; i < n; i++)
257       if (al[i] != 0.0) nz++;
258   } else {
259     for (i = 0, nz = 0; i < n; i++)
260       if (PetscAbsScalar(al[i]) > tol) nz++;
261   }
262   PetscCallMPI(MPIU_Allreduce(&nz, &gnz, 1, MPIU_INT, MPI_SUM, PetscObjectComm((PetscObject)mat)));
263   if (gnz != N) {
264     PetscInt *nzr;
265     PetscCall(PetscMalloc1(nz, &nzr));
266     if (nz) {
267       if (tol < 0) {
268         for (i = 0, nz = 0; i < n; i++)
269           if (al[i] != 0.0) nzr[nz++] = i + st;
270       } else {
271         for (i = 0, nz = 0; i < n; i++)
272           if (PetscAbsScalar(al[i]) > tol) nzr[nz++] = i + st;
273       }
274     }
275     PetscCall(ISCreateGeneral(PetscObjectComm((PetscObject)mat), nz, nzr, PETSC_OWN_POINTER, nonzero));
276   } else *nonzero = NULL;
277   if (!cols) { /* nonzero rows */
278     PetscCall(VecRestoreArrayRead(l, &al));
279   } else {
280     PetscCall(VecRestoreArrayRead(r, &al));
281   }
282   PetscCall(VecDestroy(&l));
283   PetscCall(VecDestroy(&r));
284   PetscFunctionReturn(PETSC_SUCCESS);
285 }
286 
287 /*@
288   MatFindNonzeroRows - Locate all rows that are not completely zero in the matrix
289 
290   Input Parameter:
291 . mat - the matrix
292 
293   Output Parameter:
294 . keptrows - the rows that are not completely zero
295 
296   Level: intermediate
297 
298   Note:
299   `keptrows` is set to `NULL` if all rows are nonzero.
300 
301   Developer Note:
302   If `keptrows` is not `NULL`, it must be sorted.
303 
304 .seealso: [](ch_matrices), `Mat`, `MatFindZeroRows()`
305  @*/
306 PetscErrorCode MatFindNonzeroRows(Mat mat, IS *keptrows)
307 {
308   PetscFunctionBegin;
309   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
310   PetscValidType(mat, 1);
311   PetscAssertPointer(keptrows, 2);
312   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
313   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
314   if (mat->ops->findnonzerorows) PetscUseTypeMethod(mat, findnonzerorows, keptrows);
315   else PetscCall(MatFindNonzeroRowsOrCols_Basic(mat, PETSC_FALSE, 0.0, keptrows));
316   if (keptrows && *keptrows) PetscCall(ISSetInfo(*keptrows, IS_SORTED, IS_GLOBAL, PETSC_FALSE, PETSC_TRUE));
317   PetscFunctionReturn(PETSC_SUCCESS);
318 }
319 
320 /*@
321   MatFindZeroRows - Locate all rows that are completely zero in the matrix
322 
323   Input Parameter:
324 . mat - the matrix
325 
326   Output Parameter:
327 . zerorows - the rows that are completely zero
328 
329   Level: intermediate
330 
331   Note:
332   `zerorows` is set to `NULL` if no rows are zero.
333 
334 .seealso: [](ch_matrices), `Mat`, `MatFindNonzeroRows()`
335  @*/
336 PetscErrorCode MatFindZeroRows(Mat mat, IS *zerorows)
337 {
338   IS       keptrows;
339   PetscInt m, n;
340 
341   PetscFunctionBegin;
342   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
343   PetscValidType(mat, 1);
344   PetscAssertPointer(zerorows, 2);
345   PetscCall(MatFindNonzeroRows(mat, &keptrows));
346   /* MatFindNonzeroRows sets keptrows to NULL if there are no zero rows.
347      In keeping with this convention, we set zerorows to NULL if there are no zero
348      rows. */
349   if (keptrows == NULL) {
350     *zerorows = NULL;
351   } else {
352     PetscCall(MatGetOwnershipRange(mat, &m, &n));
353     PetscCall(ISComplement(keptrows, m, n, zerorows));
354     PetscCall(ISDestroy(&keptrows));
355   }
356   PetscFunctionReturn(PETSC_SUCCESS);
357 }
358 
359 /*@
360   MatGetDiagonalBlock - Returns the part of the matrix associated with the on-process coupling
361 
362   Not Collective
363 
364   Input Parameter:
365 . A - the matrix
366 
367   Output Parameter:
368 . a - the diagonal part (which is a SEQUENTIAL matrix)
369 
370   Level: advanced
371 
372   Notes:
373   See `MatCreateAIJ()` for more information on the "diagonal part" of the matrix.
374 
375   Use caution, as the reference count on the returned matrix is not incremented and it is used as part of `A`'s normal operation.
376 
377 .seealso: [](ch_matrices), `Mat`, `MatCreateAIJ()`, `MATAIJ`, `MATBAIJ`, `MATSBAIJ`
378 @*/
379 PetscErrorCode MatGetDiagonalBlock(Mat A, Mat *a)
380 {
381   PetscFunctionBegin;
382   PetscValidHeaderSpecific(A, MAT_CLASSID, 1);
383   PetscValidType(A, 1);
384   PetscAssertPointer(a, 2);
385   PetscCheck(!A->factortype, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
386   if (A->ops->getdiagonalblock) PetscUseTypeMethod(A, getdiagonalblock, a);
387   else {
388     PetscMPIInt size;
389 
390     PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)A), &size));
391     PetscCheck(size == 1, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "Not for parallel matrix type %s", ((PetscObject)A)->type_name);
392     *a = A;
393   }
394   PetscFunctionReturn(PETSC_SUCCESS);
395 }
396 
397 /*@
398   MatGetTrace - Gets the trace of a matrix. The sum of the diagonal entries.
399 
400   Collective
401 
402   Input Parameter:
403 . mat - the matrix
404 
405   Output Parameter:
406 . trace - the sum of the diagonal entries
407 
408   Level: advanced
409 
410 .seealso: [](ch_matrices), `Mat`
411 @*/
412 PetscErrorCode MatGetTrace(Mat mat, PetscScalar *trace)
413 {
414   Vec diag;
415 
416   PetscFunctionBegin;
417   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
418   PetscAssertPointer(trace, 2);
419   PetscCall(MatCreateVecs(mat, &diag, NULL));
420   PetscCall(MatGetDiagonal(mat, diag));
421   PetscCall(VecSum(diag, trace));
422   PetscCall(VecDestroy(&diag));
423   PetscFunctionReturn(PETSC_SUCCESS);
424 }
425 
426 /*@
427   MatRealPart - Zeros out the imaginary part of the matrix
428 
429   Logically Collective
430 
431   Input Parameter:
432 . mat - the matrix
433 
434   Level: advanced
435 
436 .seealso: [](ch_matrices), `Mat`, `MatImaginaryPart()`
437 @*/
438 PetscErrorCode MatRealPart(Mat mat)
439 {
440   PetscFunctionBegin;
441   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
442   PetscValidType(mat, 1);
443   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
444   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
445   MatCheckPreallocated(mat, 1);
446   PetscUseTypeMethod(mat, realpart);
447   PetscFunctionReturn(PETSC_SUCCESS);
448 }
449 
450 /*@C
451   MatGetGhosts - Get the global indices of all ghost nodes defined by the sparse matrix
452 
453   Collective
454 
455   Input Parameter:
456 . mat - the matrix
457 
458   Output Parameters:
459 + nghosts - number of ghosts (for `MATBAIJ` and `MATSBAIJ` matrices there is one ghost for each matrix block)
460 - ghosts  - the global indices of the ghost points
461 
462   Level: advanced
463 
464   Note:
465   `nghosts` and `ghosts` are suitable to pass into `VecCreateGhost()` or `VecCreateGhostBlock()`
466 
467 .seealso: [](ch_matrices), `Mat`, `VecCreateGhost()`, `VecCreateGhostBlock()`
468 @*/
469 PetscErrorCode MatGetGhosts(Mat mat, PetscInt *nghosts, const PetscInt *ghosts[])
470 {
471   PetscFunctionBegin;
472   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
473   PetscValidType(mat, 1);
474   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
475   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
476   if (mat->ops->getghosts) PetscUseTypeMethod(mat, getghosts, nghosts, ghosts);
477   else {
478     if (nghosts) *nghosts = 0;
479     if (ghosts) *ghosts = NULL;
480   }
481   PetscFunctionReturn(PETSC_SUCCESS);
482 }
483 
484 /*@
485   MatImaginaryPart - Moves the imaginary part of the matrix to the real part and zeros the imaginary part
486 
487   Logically Collective
488 
489   Input Parameter:
490 . mat - the matrix
491 
492   Level: advanced
493 
494 .seealso: [](ch_matrices), `Mat`, `MatRealPart()`
495 @*/
496 PetscErrorCode MatImaginaryPart(Mat mat)
497 {
498   PetscFunctionBegin;
499   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
500   PetscValidType(mat, 1);
501   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
502   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
503   MatCheckPreallocated(mat, 1);
504   PetscUseTypeMethod(mat, imaginarypart);
505   PetscFunctionReturn(PETSC_SUCCESS);
506 }
507 
508 /*@
509   MatMissingDiagonal - Determine if sparse matrix is missing a diagonal entry (or block entry for `MATBAIJ` and `MATSBAIJ` matrices) in the nonzero structure
510 
511   Not Collective
512 
513   Input Parameter:
514 . mat - the matrix
515 
516   Output Parameters:
517 + missing - is any diagonal entry missing
518 - dd      - first diagonal entry that is missing (optional) on this process
519 
520   Level: advanced
521 
522   Note:
523   This does not return diagonal entries that are in the nonzero structure but happen to have a zero numerical value
524 
525 .seealso: [](ch_matrices), `Mat`
526 @*/
527 PetscErrorCode MatMissingDiagonal(Mat mat, PetscBool *missing, PetscInt *dd)
528 {
529   PetscFunctionBegin;
530   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
531   PetscValidType(mat, 1);
532   PetscAssertPointer(missing, 2);
533   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix %s", ((PetscObject)mat)->type_name);
534   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
535   PetscUseTypeMethod(mat, missingdiagonal, missing, dd);
536   PetscFunctionReturn(PETSC_SUCCESS);
537 }
538 
539 // PetscClangLinter pragma disable: -fdoc-section-header-unknown
540 /*@C
541   MatGetRow - Gets a row of a matrix.  You MUST call `MatRestoreRow()`
542   for each row that you get to ensure that your application does
543   not bleed memory.
544 
545   Not Collective
546 
547   Input Parameters:
548 + mat - the matrix
549 - row - the row to get
550 
551   Output Parameters:
552 + ncols - if not `NULL`, the number of nonzeros in `row`
553 . cols  - if not `NULL`, the column numbers
554 - vals  - if not `NULL`, the numerical values
555 
556   Level: advanced
557 
558   Notes:
559   This routine is provided for people who need to have direct access
560   to the structure of a matrix.  We hope that we provide enough
561   high-level matrix routines that few users will need it.
562 
563   `MatGetRow()` always returns 0-based column indices, regardless of
564   whether the internal representation is 0-based (default) or 1-based.
565 
566   For better efficiency, set `cols` and/or `vals` to `NULL` if you do
567   not wish to extract these quantities.
568 
569   The user can only examine the values extracted with `MatGetRow()`;
570   the values CANNOT be altered.  To change the matrix entries, one
571   must use `MatSetValues()`.
572 
573   You can only have one call to `MatGetRow()` outstanding for a particular
574   matrix at a time, per processor. `MatGetRow()` can only obtain rows
575   associated with the given processor, it cannot get rows from the
576   other processors; for that we suggest using `MatCreateSubMatrices()`, then
577   `MatGetRow()` on the submatrix. The row index passed to `MatGetRow()`
578   is in the global number of rows.
579 
580   Use `MatGetRowIJ()` and `MatRestoreRowIJ()` to access all the local indices of the sparse matrix.
581 
582   Use `MatSeqAIJGetArray()` and similar functions to access the numerical values for certain matrix types directly.
583 
584   Fortran Note:
585 .vb
586   PetscInt, pointer :: cols(:)
587   PetscScalar, pointer :: vals(:)
588 .ve
589 
590 .seealso: [](ch_matrices), `Mat`, `MatRestoreRow()`, `MatSetValues()`, `MatGetValues()`, `MatCreateSubMatrices()`, `MatGetDiagonal()`, `MatGetRowIJ()`, `MatRestoreRowIJ()`
591 @*/
592 PetscErrorCode MatGetRow(Mat mat, PetscInt row, PetscInt *ncols, const PetscInt *cols[], const PetscScalar *vals[])
593 {
594   PetscInt incols;
595 
596   PetscFunctionBegin;
597   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
598   PetscValidType(mat, 1);
599   PetscCheck(mat->assembled, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
600   PetscCheck(!mat->factortype, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
601   MatCheckPreallocated(mat, 1);
602   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);
603   PetscCall(PetscLogEventBegin(MAT_GetRow, mat, 0, 0, 0));
604   PetscUseTypeMethod(mat, getrow, row, &incols, (PetscInt **)cols, (PetscScalar **)vals);
605   if (ncols) *ncols = incols;
606   PetscCall(PetscLogEventEnd(MAT_GetRow, mat, 0, 0, 0));
607   PetscFunctionReturn(PETSC_SUCCESS);
608 }
609 
610 /*@
611   MatConjugate - replaces the matrix values with their complex conjugates
612 
613   Logically Collective
614 
615   Input Parameter:
616 . mat - the matrix
617 
618   Level: advanced
619 
620 .seealso: [](ch_matrices), `Mat`, `MatRealPart()`, `MatImaginaryPart()`, `VecConjugate()`, `MatTranspose()`
621 @*/
622 PetscErrorCode MatConjugate(Mat mat)
623 {
624   PetscFunctionBegin;
625   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
626   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
627   if (PetscDefined(USE_COMPLEX) && mat->hermitian != PETSC_BOOL3_TRUE) {
628     PetscUseTypeMethod(mat, conjugate);
629     PetscCall(PetscObjectStateIncrease((PetscObject)mat));
630   }
631   PetscFunctionReturn(PETSC_SUCCESS);
632 }
633 
634 /*@C
635   MatRestoreRow - Frees any temporary space allocated by `MatGetRow()`.
636 
637   Not Collective
638 
639   Input Parameters:
640 + mat   - the matrix
641 . row   - the row to get
642 . ncols - the number of nonzeros
643 . cols  - the columns of the nonzeros
644 - vals  - if nonzero the column values
645 
646   Level: advanced
647 
648   Notes:
649   This routine should be called after you have finished examining the entries.
650 
651   This routine zeros out `ncols`, `cols`, and `vals`. This is to prevent accidental
652   us of the array after it has been restored. If you pass `NULL`, it will
653   not zero the pointers.  Use of `cols` or `vals` after `MatRestoreRow()` is invalid.
654 
655   Fortran Note:
656 .vb
657   PetscInt, pointer :: cols(:)
658   PetscScalar, pointer :: vals(:)
659 .ve
660 
661 .seealso: [](ch_matrices), `Mat`, `MatGetRow()`
662 @*/
663 PetscErrorCode MatRestoreRow(Mat mat, PetscInt row, PetscInt *ncols, const PetscInt *cols[], const PetscScalar *vals[])
664 {
665   PetscFunctionBegin;
666   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
667   if (ncols) PetscAssertPointer(ncols, 3);
668   PetscCheck(mat->assembled, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
669   PetscTryTypeMethod(mat, restorerow, row, ncols, (PetscInt **)cols, (PetscScalar **)vals);
670   if (ncols) *ncols = 0;
671   if (cols) *cols = NULL;
672   if (vals) *vals = NULL;
673   PetscFunctionReturn(PETSC_SUCCESS);
674 }
675 
676 /*@
677   MatGetRowUpperTriangular - Sets a flag to enable calls to `MatGetRow()` for matrix in `MATSBAIJ` format.
678   You should call `MatRestoreRowUpperTriangular()` after calling` MatGetRow()` and `MatRestoreRow()` to disable the flag.
679 
680   Not Collective
681 
682   Input Parameter:
683 . mat - the matrix
684 
685   Level: advanced
686 
687   Note:
688   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.
689 
690 .seealso: [](ch_matrices), `Mat`, `MATSBAIJ`, `MatRestoreRowUpperTriangular()`
691 @*/
692 PetscErrorCode MatGetRowUpperTriangular(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   PetscTryTypeMethod(mat, getrowuppertriangular);
701   PetscFunctionReturn(PETSC_SUCCESS);
702 }
703 
704 /*@
705   MatRestoreRowUpperTriangular - Disable calls to `MatGetRow()` for matrix in `MATSBAIJ` format.
706 
707   Not Collective
708 
709   Input Parameter:
710 . mat - the matrix
711 
712   Level: advanced
713 
714   Note:
715   This routine should be called after you have finished calls to `MatGetRow()` and `MatRestoreRow()`.
716 
717 .seealso: [](ch_matrices), `Mat`, `MATSBAIJ`, `MatGetRowUpperTriangular()`
718 @*/
719 PetscErrorCode MatRestoreRowUpperTriangular(Mat mat)
720 {
721   PetscFunctionBegin;
722   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
723   PetscValidType(mat, 1);
724   PetscCheck(mat->assembled, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
725   PetscCheck(!mat->factortype, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
726   MatCheckPreallocated(mat, 1);
727   PetscTryTypeMethod(mat, restorerowuppertriangular);
728   PetscFunctionReturn(PETSC_SUCCESS);
729 }
730 
731 /*@
732   MatSetOptionsPrefix - Sets the prefix used for searching for all
733   `Mat` options in the database.
734 
735   Logically Collective
736 
737   Input Parameters:
738 + A      - the matrix
739 - prefix - the prefix to prepend to all option names
740 
741   Level: advanced
742 
743   Notes:
744   A hyphen (-) must NOT be given at the beginning of the prefix name.
745   The first character of all runtime options is AUTOMATICALLY the hyphen.
746 
747   This is NOT used for options for the factorization of the matrix. Normally the
748   prefix is automatically passed in from the PC calling the factorization. To set
749   it directly use  `MatSetOptionsPrefixFactor()`
750 
751 .seealso: [](ch_matrices), `Mat`, `MatSetFromOptions()`, `MatSetOptionsPrefixFactor()`
752 @*/
753 PetscErrorCode MatSetOptionsPrefix(Mat A, const char prefix[])
754 {
755   PetscFunctionBegin;
756   PetscValidHeaderSpecific(A, MAT_CLASSID, 1);
757   PetscCall(PetscObjectSetOptionsPrefix((PetscObject)A, prefix));
758   PetscTryMethod(A, "MatSetOptionsPrefix_C", (Mat, const char[]), (A, prefix));
759   PetscFunctionReturn(PETSC_SUCCESS);
760 }
761 
762 /*@
763   MatSetOptionsPrefixFactor - Sets the prefix used for searching for all matrix factor options in the database for
764   for matrices created with `MatGetFactor()`
765 
766   Logically Collective
767 
768   Input Parameters:
769 + A      - the matrix
770 - prefix - the prefix to prepend to all option names for the factored matrix
771 
772   Level: developer
773 
774   Notes:
775   A hyphen (-) must NOT be given at the beginning of the prefix name.
776   The first character of all runtime options is AUTOMATICALLY the hyphen.
777 
778   Normally the prefix is automatically passed in from the `PC` calling the factorization. To set
779   it directly when not using `KSP`/`PC` use  `MatSetOptionsPrefixFactor()`
780 
781 .seealso: [](ch_matrices), `Mat`,   [Matrix Factorization](sec_matfactor), `MatGetFactor()`, `MatSetFromOptions()`, `MatSetOptionsPrefix()`, `MatAppendOptionsPrefixFactor()`
782 @*/
783 PetscErrorCode MatSetOptionsPrefixFactor(Mat A, const char prefix[])
784 {
785   PetscFunctionBegin;
786   PetscValidHeaderSpecific(A, MAT_CLASSID, 1);
787   if (prefix) {
788     PetscAssertPointer(prefix, 2);
789     PetscCheck(prefix[0] != '-', PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_WRONG, "Options prefix should not begin with a hyphen");
790     if (prefix != A->factorprefix) {
791       PetscCall(PetscFree(A->factorprefix));
792       PetscCall(PetscStrallocpy(prefix, &A->factorprefix));
793     }
794   } else PetscCall(PetscFree(A->factorprefix));
795   PetscFunctionReturn(PETSC_SUCCESS);
796 }
797 
798 /*@
799   MatAppendOptionsPrefixFactor - Appends to the prefix used for searching for all matrix factor options in the database for
800   for matrices created with `MatGetFactor()`
801 
802   Logically Collective
803 
804   Input Parameters:
805 + A      - the matrix
806 - prefix - the prefix to prepend to all option names for the factored matrix
807 
808   Level: developer
809 
810   Notes:
811   A hyphen (-) must NOT be given at the beginning of the prefix name.
812   The first character of all runtime options is AUTOMATICALLY the hyphen.
813 
814   Normally the prefix is automatically passed in from the `PC` calling the factorization. To set
815   it directly when not using `KSP`/`PC` use  `MatAppendOptionsPrefixFactor()`
816 
817 .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatGetFactor()`, `PetscOptionsCreate()`, `PetscOptionsDestroy()`, `PetscObjectSetOptionsPrefix()`, `PetscObjectPrependOptionsPrefix()`,
818           `PetscObjectGetOptionsPrefix()`, `TSAppendOptionsPrefix()`, `SNESAppendOptionsPrefix()`, `KSPAppendOptionsPrefix()`, `MatSetOptionsPrefixFactor()`,
819           `MatSetOptionsPrefix()`
820 @*/
821 PetscErrorCode MatAppendOptionsPrefixFactor(Mat A, const char prefix[])
822 {
823   size_t len1, len2, new_len;
824 
825   PetscFunctionBegin;
826   PetscValidHeader(A, 1);
827   if (!prefix) PetscFunctionReturn(PETSC_SUCCESS);
828   if (!A->factorprefix) {
829     PetscCall(MatSetOptionsPrefixFactor(A, prefix));
830     PetscFunctionReturn(PETSC_SUCCESS);
831   }
832   PetscCheck(prefix[0] != '-', PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_WRONG, "Options prefix should not begin with a hyphen");
833 
834   PetscCall(PetscStrlen(A->factorprefix, &len1));
835   PetscCall(PetscStrlen(prefix, &len2));
836   new_len = len1 + len2 + 1;
837   PetscCall(PetscRealloc(new_len * sizeof(*A->factorprefix), &A->factorprefix));
838   PetscCall(PetscStrncpy(A->factorprefix + len1, prefix, len2 + 1));
839   PetscFunctionReturn(PETSC_SUCCESS);
840 }
841 
842 /*@
843   MatAppendOptionsPrefix - Appends to the prefix used for searching for all
844   matrix options in the database.
845 
846   Logically Collective
847 
848   Input Parameters:
849 + A      - the matrix
850 - prefix - the prefix to prepend to all option names
851 
852   Level: advanced
853 
854   Note:
855   A hyphen (-) must NOT be given at the beginning of the prefix name.
856   The first character of all runtime options is AUTOMATICALLY the hyphen.
857 
858 .seealso: [](ch_matrices), `Mat`, `MatGetOptionsPrefix()`, `MatAppendOptionsPrefixFactor()`, `MatSetOptionsPrefix()`
859 @*/
860 PetscErrorCode MatAppendOptionsPrefix(Mat A, const char prefix[])
861 {
862   PetscFunctionBegin;
863   PetscValidHeaderSpecific(A, MAT_CLASSID, 1);
864   PetscCall(PetscObjectAppendOptionsPrefix((PetscObject)A, prefix));
865   PetscTryMethod(A, "MatAppendOptionsPrefix_C", (Mat, const char[]), (A, prefix));
866   PetscFunctionReturn(PETSC_SUCCESS);
867 }
868 
869 /*@
870   MatGetOptionsPrefix - Gets the prefix used for searching for all
871   matrix options in the database.
872 
873   Not Collective
874 
875   Input Parameter:
876 . A - the matrix
877 
878   Output Parameter:
879 . prefix - pointer to the prefix string used
880 
881   Level: advanced
882 
883 .seealso: [](ch_matrices), `Mat`, `MatAppendOptionsPrefix()`, `MatSetOptionsPrefix()`, `MatAppendOptionsPrefixFactor()`, `MatSetOptionsPrefixFactor()`
884 @*/
885 PetscErrorCode MatGetOptionsPrefix(Mat A, const char *prefix[])
886 {
887   PetscFunctionBegin;
888   PetscValidHeaderSpecific(A, MAT_CLASSID, 1);
889   PetscAssertPointer(prefix, 2);
890   PetscCall(PetscObjectGetOptionsPrefix((PetscObject)A, prefix));
891   PetscFunctionReturn(PETSC_SUCCESS);
892 }
893 
894 /*@
895   MatGetState - Gets the state of a `Mat`. Same value as returned by `PetscObjectStateGet()`
896 
897   Not Collective
898 
899   Input Parameter:
900 . A - the matrix
901 
902   Output Parameter:
903 . state - the object state
904 
905   Level: advanced
906 
907   Note:
908   Object state is an integer which gets increased every time
909   the object is changed. By saving and later querying the object state
910   one can determine whether information about the object is still current.
911 
912   See `MatGetNonzeroState()` to determine if the nonzero structure of the matrix has changed.
913 
914 .seealso: [](ch_matrices), `Mat`, `MatCreate()`, `PetscObjectStateGet()`, `MatGetNonzeroState()`
915 @*/
916 PetscErrorCode MatGetState(Mat A, PetscObjectState *state)
917 {
918   PetscFunctionBegin;
919   PetscValidHeaderSpecific(A, MAT_CLASSID, 1);
920   PetscAssertPointer(state, 2);
921   PetscCall(PetscObjectStateGet((PetscObject)A, state));
922   PetscFunctionReturn(PETSC_SUCCESS);
923 }
924 
925 /*@
926   MatResetPreallocation - Reset matrix to use the original preallocation values provided by the user, for example with `MatXAIJSetPreallocation()`
927 
928   Collective
929 
930   Input Parameter:
931 . A - the matrix
932 
933   Level: beginner
934 
935   Notes:
936   After calling `MatAssemblyBegin()` and `MatAssemblyEnd()` with `MAT_FINAL_ASSEMBLY` the matrix data structures represent the nonzeros assigned to the
937   matrix. If that space is less than the preallocated space that extra preallocated space is no longer available to take on new values. `MatResetPreallocation()`
938   makes all of the preallocation space available
939 
940   Current values in the matrix are lost in this call
941 
942   Currently only supported for  `MATAIJ` matrices.
943 
944 .seealso: [](ch_matrices), `Mat`, `MatSeqAIJSetPreallocation()`, `MatMPIAIJSetPreallocation()`, `MatXAIJSetPreallocation()`
945 @*/
946 PetscErrorCode MatResetPreallocation(Mat A)
947 {
948   PetscFunctionBegin;
949   PetscValidHeaderSpecific(A, MAT_CLASSID, 1);
950   PetscValidType(A, 1);
951   PetscUseMethod(A, "MatResetPreallocation_C", (Mat), (A));
952   PetscFunctionReturn(PETSC_SUCCESS);
953 }
954 
955 /*@
956   MatResetHash - Reset the matrix so that it will use a hash table for the next round of `MatSetValues()` and `MatAssemblyBegin()`/`MatAssemblyEnd()`.
957 
958   Collective
959 
960   Input Parameter:
961 . A - the matrix
962 
963   Level: intermediate
964 
965   Notes:
966   The matrix will again delete the hash table data structures after following calls to `MatAssemblyBegin()`/`MatAssemblyEnd()` with `MAT_FINAL_ASSEMBLY`.
967 
968   Currently only supported for `MATAIJ` matrices.
969 
970 .seealso: [](ch_matrices), `Mat`, `MatResetPreallocation()`
971 @*/
972 PetscErrorCode MatResetHash(Mat A)
973 {
974   PetscFunctionBegin;
975   PetscValidHeaderSpecific(A, MAT_CLASSID, 1);
976   PetscValidType(A, 1);
977   PetscCheck(A->insertmode == NOT_SET_VALUES, PETSC_COMM_SELF, PETSC_ERR_SUP, "Cannot reset to hash state after setting some values but not yet calling MatAssemblyBegin()/MatAssemblyEnd()");
978   if (A->num_ass == 0) PetscFunctionReturn(PETSC_SUCCESS);
979   PetscUseMethod(A, "MatResetHash_C", (Mat), (A));
980   /* These flags are used to determine whether certain setups occur */
981   A->was_assembled = PETSC_FALSE;
982   A->assembled     = PETSC_FALSE;
983   /* Log that the state of this object has changed; this will help guarantee that preconditioners get re-setup */
984   PetscCall(PetscObjectStateIncrease((PetscObject)A));
985   PetscFunctionReturn(PETSC_SUCCESS);
986 }
987 
988 /*@
989   MatSetUp - Sets up the internal matrix data structures for later use by the matrix
990 
991   Collective
992 
993   Input Parameter:
994 . A - the matrix
995 
996   Level: advanced
997 
998   Notes:
999   If the user has not set preallocation for this matrix then an efficient algorithm will be used for the first round of
1000   setting values in the matrix.
1001 
1002   This routine is called internally by other `Mat` functions when needed so rarely needs to be called by users
1003 
1004 .seealso: [](ch_matrices), `Mat`, `MatMult()`, `MatCreate()`, `MatDestroy()`, `MatXAIJSetPreallocation()`
1005 @*/
1006 PetscErrorCode MatSetUp(Mat A)
1007 {
1008   PetscFunctionBegin;
1009   PetscValidHeaderSpecific(A, MAT_CLASSID, 1);
1010   if (!((PetscObject)A)->type_name) {
1011     PetscMPIInt size;
1012 
1013     PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)A), &size));
1014     PetscCall(MatSetType(A, size == 1 ? MATSEQAIJ : MATMPIAIJ));
1015   }
1016   if (!A->preallocated) PetscTryTypeMethod(A, setup);
1017   PetscCall(PetscLayoutSetUp(A->rmap));
1018   PetscCall(PetscLayoutSetUp(A->cmap));
1019   A->preallocated = PETSC_TRUE;
1020   PetscFunctionReturn(PETSC_SUCCESS);
1021 }
1022 
1023 #if defined(PETSC_HAVE_SAWS)
1024   #include <petscviewersaws.h>
1025 #endif
1026 
1027 /*
1028    If threadsafety is on extraneous matrices may be printed
1029 
1030    This flag cannot be stored in the matrix because the original matrix in MatView() may assemble a new matrix which is passed into MatViewFromOptions()
1031 */
1032 #if !defined(PETSC_HAVE_THREADSAFETY)
1033 static PetscInt insidematview = 0;
1034 #endif
1035 
1036 /*@
1037   MatViewFromOptions - View properties of the matrix based on options set in the options database
1038 
1039   Collective
1040 
1041   Input Parameters:
1042 + A    - the matrix
1043 . obj  - optional additional object that provides the options prefix to use
1044 - name - command line option
1045 
1046   Options Database Key:
1047 . -mat_view [viewertype]:... - the viewer and its options
1048 
1049   Level: intermediate
1050 
1051   Note:
1052 .vb
1053     If no value is provided ascii:stdout is used
1054        ascii[:[filename][:[format][:append]]]    defaults to stdout - format can be one of ascii_info, ascii_info_detail, or ascii_matlab,
1055                                                   for example ascii::ascii_info prints just the information about the object not all details
1056                                                   unless :append is given filename opens in write mode, overwriting what was already there
1057        binary[:[filename][:[format][:append]]]   defaults to the file binaryoutput
1058        draw[:drawtype[:filename]]                for example, draw:tikz, draw:tikz:figure.tex  or draw:x
1059        socket[:port]                             defaults to the standard output port
1060        saws[:communicatorname]                    publishes object to the Scientific Application Webserver (SAWs)
1061 .ve
1062 
1063 .seealso: [](ch_matrices), `Mat`, `MatView()`, `PetscObjectViewFromOptions()`, `MatCreate()`
1064 @*/
1065 PetscErrorCode MatViewFromOptions(Mat A, PetscObject obj, const char name[])
1066 {
1067   PetscFunctionBegin;
1068   PetscValidHeaderSpecific(A, MAT_CLASSID, 1);
1069 #if !defined(PETSC_HAVE_THREADSAFETY)
1070   if (insidematview) PetscFunctionReturn(PETSC_SUCCESS);
1071 #endif
1072   PetscCall(PetscObjectViewFromOptions((PetscObject)A, obj, name));
1073   PetscFunctionReturn(PETSC_SUCCESS);
1074 }
1075 
1076 /*@
1077   MatView - display information about a matrix in a variety ways
1078 
1079   Collective on viewer
1080 
1081   Input Parameters:
1082 + mat    - the matrix
1083 - viewer - visualization context
1084 
1085   Options Database Keys:
1086 + -mat_view ::ascii_info           - Prints info on matrix at conclusion of `MatAssemblyEnd()`
1087 . -mat_view ::ascii_info_detail    - Prints more detailed info
1088 . -mat_view                        - Prints matrix in ASCII format
1089 . -mat_view ::ascii_matlab         - Prints matrix in MATLAB format
1090 . -mat_view draw                   - PetscDraws nonzero structure of matrix, using `MatView()` and `PetscDrawOpenX()`.
1091 . -display <name>                  - Sets display name (default is host)
1092 . -draw_pause <sec>                - Sets number of seconds to pause after display
1093 . -mat_view socket                 - Sends matrix to socket, can be accessed from MATLAB (see Users-Manual: ch_matlab for details)
1094 . -viewer_socket_machine <machine> - -
1095 . -viewer_socket_port <port>       - -
1096 . -mat_view binary                 - save matrix to file in binary format
1097 - -viewer_binary_filename <name>   - -
1098 
1099   Level: beginner
1100 
1101   Notes:
1102   The available visualization contexts include
1103 +    `PETSC_VIEWER_STDOUT_SELF`   - for sequential matrices
1104 .    `PETSC_VIEWER_STDOUT_WORLD`  - for parallel matrices created on `PETSC_COMM_WORLD`
1105 .    `PETSC_VIEWER_STDOUT_`(comm) - for matrices created on MPI communicator comm
1106 -     `PETSC_VIEWER_DRAW_WORLD`   - graphical display of nonzero structure
1107 
1108   The user can open alternative visualization contexts with
1109 +    `PetscViewerASCIIOpen()`  - Outputs matrix to a specified file
1110 .    `PetscViewerBinaryOpen()` - Outputs matrix in binary to a  specified file; corresponding input uses `MatLoad()`
1111 .    `PetscViewerDrawOpen()`   - Outputs nonzero matrix nonzero structure to an X window display
1112 -    `PetscViewerSocketOpen()` - Outputs matrix to Socket viewer, `PETSCVIEWERSOCKET`. Only the `MATSEQDENSE` and `MATAIJ` types support this viewer.
1113 
1114   The user can call `PetscViewerPushFormat()` to specify the output
1115   format of ASCII printed objects (when using `PETSC_VIEWER_STDOUT_SELF`,
1116   `PETSC_VIEWER_STDOUT_WORLD` and `PetscViewerASCIIOpen()`).  Available formats include
1117 +    `PETSC_VIEWER_DEFAULT`           - default, prints matrix contents
1118 .    `PETSC_VIEWER_ASCII_MATLAB`      - prints matrix contents in MATLAB format
1119 .    `PETSC_VIEWER_ASCII_DENSE`       - prints entire matrix including zeros
1120 .    `PETSC_VIEWER_ASCII_COMMON`      - prints matrix contents, using a sparse  format common among all matrix types
1121 .    `PETSC_VIEWER_ASCII_IMPL`        - prints matrix contents, using an implementation-specific format (which is in many cases the same as the default)
1122 .    `PETSC_VIEWER_ASCII_INFO`        - prints basic information about the matrix size and structure (not the matrix entries)
1123 -    `PETSC_VIEWER_ASCII_INFO_DETAIL` - prints more detailed information about the matrix nonzero structure (still not vector or matrix entries)
1124 
1125   The ASCII viewers are only recommended for small matrices on at most a moderate number of processes,
1126   the program will seemingly hang and take hours for larger matrices, for larger matrices one should use the binary format.
1127 
1128   In the debugger you can do "call MatView(mat,0)" to display the matrix. (The same holds for any PETSc object viewer).
1129 
1130   See the manual page for `MatLoad()` for the exact format of the binary file when the binary
1131   viewer is used.
1132 
1133   See share/petsc/matlab/PetscBinaryRead.m for a MATLAB code that can read in the binary file when the binary
1134   viewer is used and lib/petsc/bin/PetscBinaryIO.py for loading them into Python.
1135 
1136   One can use '-mat_view draw -draw_pause -1' to pause the graphical display of matrix nonzero structure,
1137   and then use the following mouse functions.
1138 .vb
1139   left mouse: zoom in
1140   middle mouse: zoom out
1141   right mouse: continue with the simulation
1142 .ve
1143 
1144 .seealso: [](ch_matrices), `Mat`, `PetscViewerPushFormat()`, `PetscViewerASCIIOpen()`, `PetscViewerDrawOpen()`, `PetscViewer`,
1145           `PetscViewerSocketOpen()`, `PetscViewerBinaryOpen()`, `MatLoad()`, `MatViewFromOptions()`
1146 @*/
1147 PetscErrorCode MatView(Mat mat, PetscViewer viewer)
1148 {
1149   PetscInt          rows, cols, rbs, cbs;
1150   PetscBool         isascii, isstring, issaws;
1151   PetscViewerFormat format;
1152   PetscMPIInt       size;
1153 
1154   PetscFunctionBegin;
1155   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
1156   PetscValidType(mat, 1);
1157   if (!viewer) PetscCall(PetscViewerASCIIGetStdout(PetscObjectComm((PetscObject)mat), &viewer));
1158   PetscValidHeaderSpecific(viewer, PETSC_VIEWER_CLASSID, 2);
1159 
1160   PetscCall(PetscViewerGetFormat(viewer, &format));
1161   PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)viewer), &size));
1162   if (size == 1 && format == PETSC_VIEWER_LOAD_BALANCE) PetscFunctionReturn(PETSC_SUCCESS);
1163 
1164 #if !defined(PETSC_HAVE_THREADSAFETY)
1165   insidematview++;
1166 #endif
1167   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERSTRING, &isstring));
1168   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERASCII, &isascii));
1169   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERSAWS, &issaws));
1170   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");
1171 
1172   PetscCall(PetscLogEventBegin(MAT_View, mat, viewer, 0, 0));
1173   if (isascii) {
1174     if (!mat->preallocated) {
1175       PetscCall(PetscViewerASCIIPrintf(viewer, "Matrix has not been preallocated yet\n"));
1176 #if !defined(PETSC_HAVE_THREADSAFETY)
1177       insidematview--;
1178 #endif
1179       PetscCall(PetscLogEventEnd(MAT_View, mat, viewer, 0, 0));
1180       PetscFunctionReturn(PETSC_SUCCESS);
1181     }
1182     if (!mat->assembled) {
1183       PetscCall(PetscViewerASCIIPrintf(viewer, "Matrix has not been assembled yet\n"));
1184 #if !defined(PETSC_HAVE_THREADSAFETY)
1185       insidematview--;
1186 #endif
1187       PetscCall(PetscLogEventEnd(MAT_View, mat, viewer, 0, 0));
1188       PetscFunctionReturn(PETSC_SUCCESS);
1189     }
1190     PetscCall(PetscObjectPrintClassNamePrefixType((PetscObject)mat, viewer));
1191     if (format == PETSC_VIEWER_ASCII_INFO || format == PETSC_VIEWER_ASCII_INFO_DETAIL) {
1192       MatNullSpace nullsp, transnullsp;
1193 
1194       PetscCall(PetscViewerASCIIPushTab(viewer));
1195       PetscCall(MatGetSize(mat, &rows, &cols));
1196       PetscCall(MatGetBlockSizes(mat, &rbs, &cbs));
1197       if (rbs != 1 || cbs != 1) {
1198         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" : ""));
1199         else PetscCall(PetscViewerASCIIPrintf(viewer, "rows=%" PetscInt_FMT ", cols=%" PetscInt_FMT ", bs=%" PetscInt_FMT "%s\n", rows, cols, rbs, mat->bsizes ? " variable blocks set" : ""));
1200       } else PetscCall(PetscViewerASCIIPrintf(viewer, "rows=%" PetscInt_FMT ", cols=%" PetscInt_FMT "\n", rows, cols));
1201       if (mat->factortype) {
1202         MatSolverType solver;
1203         PetscCall(MatFactorGetSolverType(mat, &solver));
1204         PetscCall(PetscViewerASCIIPrintf(viewer, "package used to perform factorization: %s\n", solver));
1205       }
1206       if (mat->ops->getinfo) {
1207         PetscBool is_constant_or_diagonal;
1208 
1209         // Don't print nonzero information for constant or diagonal matrices, it just adds noise to the output
1210         PetscCall(PetscObjectTypeCompareAny((PetscObject)mat, &is_constant_or_diagonal, MATCONSTANTDIAGONAL, MATDIAGONAL, ""));
1211         if (!is_constant_or_diagonal) {
1212           MatInfo info;
1213 
1214           PetscCall(MatGetInfo(mat, MAT_GLOBAL_SUM, &info));
1215           PetscCall(PetscViewerASCIIPrintf(viewer, "total: nonzeros=%.f, allocated nonzeros=%.f\n", info.nz_used, info.nz_allocated));
1216           if (!mat->factortype) PetscCall(PetscViewerASCIIPrintf(viewer, "total number of mallocs used during MatSetValues calls=%" PetscInt_FMT "\n", (PetscInt)info.mallocs));
1217         }
1218       }
1219       PetscCall(MatGetNullSpace(mat, &nullsp));
1220       PetscCall(MatGetTransposeNullSpace(mat, &transnullsp));
1221       if (nullsp) PetscCall(PetscViewerASCIIPrintf(viewer, "  has attached null space\n"));
1222       if (transnullsp && transnullsp != nullsp) PetscCall(PetscViewerASCIIPrintf(viewer, "  has attached transposed null space\n"));
1223       PetscCall(MatGetNearNullSpace(mat, &nullsp));
1224       if (nullsp) PetscCall(PetscViewerASCIIPrintf(viewer, "  has attached near null space\n"));
1225       PetscCall(PetscViewerASCIIPushTab(viewer));
1226       PetscCall(MatProductView(mat, viewer));
1227       PetscCall(PetscViewerASCIIPopTab(viewer));
1228       if (mat->bsizes && format == PETSC_VIEWER_ASCII_INFO_DETAIL) {
1229         IS tmp;
1230 
1231         PetscCall(ISCreateGeneral(PetscObjectComm((PetscObject)viewer), mat->nblocks, mat->bsizes, PETSC_USE_POINTER, &tmp));
1232         PetscCall(PetscObjectSetName((PetscObject)tmp, "Block Sizes"));
1233         PetscCall(PetscViewerASCIIPushTab(viewer));
1234         PetscCall(ISView(tmp, viewer));
1235         PetscCall(PetscViewerASCIIPopTab(viewer));
1236         PetscCall(ISDestroy(&tmp));
1237       }
1238     }
1239   } else if (issaws) {
1240 #if defined(PETSC_HAVE_SAWS)
1241     PetscMPIInt rank;
1242 
1243     PetscCall(PetscObjectName((PetscObject)mat));
1244     PetscCallMPI(MPI_Comm_rank(PETSC_COMM_WORLD, &rank));
1245     if (!((PetscObject)mat)->amsmem && rank == 0) PetscCall(PetscObjectViewSAWs((PetscObject)mat, viewer));
1246 #endif
1247   } else if (isstring) {
1248     const char *type;
1249     PetscCall(MatGetType(mat, &type));
1250     PetscCall(PetscViewerStringSPrintf(viewer, " MatType: %-7.7s", type));
1251     PetscTryTypeMethod(mat, view, viewer);
1252   }
1253   if ((format == PETSC_VIEWER_NATIVE || format == PETSC_VIEWER_LOAD_BALANCE) && mat->ops->viewnative) {
1254     PetscCall(PetscViewerASCIIPushTab(viewer));
1255     PetscUseTypeMethod(mat, viewnative, viewer);
1256     PetscCall(PetscViewerASCIIPopTab(viewer));
1257   } else if (mat->ops->view) {
1258     PetscCall(PetscViewerASCIIPushTab(viewer));
1259     PetscUseTypeMethod(mat, view, viewer);
1260     PetscCall(PetscViewerASCIIPopTab(viewer));
1261   }
1262   if (isascii) {
1263     PetscCall(PetscViewerGetFormat(viewer, &format));
1264     if (format == PETSC_VIEWER_ASCII_INFO || format == PETSC_VIEWER_ASCII_INFO_DETAIL) PetscCall(PetscViewerASCIIPopTab(viewer));
1265   }
1266   PetscCall(PetscLogEventEnd(MAT_View, mat, viewer, 0, 0));
1267 #if !defined(PETSC_HAVE_THREADSAFETY)
1268   insidematview--;
1269 #endif
1270   PetscFunctionReturn(PETSC_SUCCESS);
1271 }
1272 
1273 #if defined(PETSC_USE_DEBUG)
1274   #include <../src/sys/totalview/tv_data_display.h>
1275 PETSC_UNUSED static int TV_display_type(const struct _p_Mat *mat)
1276 {
1277   TV_add_row("Local rows", "int", &mat->rmap->n);
1278   TV_add_row("Local columns", "int", &mat->cmap->n);
1279   TV_add_row("Global rows", "int", &mat->rmap->N);
1280   TV_add_row("Global columns", "int", &mat->cmap->N);
1281   TV_add_row("Typename", TV_ascii_string_type, ((PetscObject)mat)->type_name);
1282   return TV_format_OK;
1283 }
1284 #endif
1285 
1286 /*@
1287   MatLoad - Loads a matrix that has been stored in binary/HDF5 format
1288   with `MatView()`.  The matrix format is determined from the options database.
1289   Generates a parallel MPI matrix if the communicator has more than one
1290   processor.  The default matrix type is `MATAIJ`.
1291 
1292   Collective
1293 
1294   Input Parameters:
1295 + mat    - the newly loaded matrix, this needs to have been created with `MatCreate()`
1296             or some related function before a call to `MatLoad()`
1297 - viewer - `PETSCVIEWERBINARY`/`PETSCVIEWERHDF5` file viewer
1298 
1299   Options Database Key:
1300 . -matload_block_size <bs> - set block size
1301 
1302   Level: beginner
1303 
1304   Notes:
1305   If the `Mat` type has not yet been given then `MATAIJ` is used, call `MatSetFromOptions()` on the
1306   `Mat` before calling this routine if you wish to set it from the options database.
1307 
1308   `MatLoad()` automatically loads into the options database any options
1309   given in the file filename.info where filename is the name of the file
1310   that was passed to the `PetscViewerBinaryOpen()`. The options in the info
1311   file will be ignored if you use the -viewer_binary_skip_info option.
1312 
1313   If the type or size of mat is not set before a call to `MatLoad()`, PETSc
1314   sets the default matrix type AIJ and sets the local and global sizes.
1315   If type and/or size is already set, then the same are used.
1316 
1317   In parallel, each processor can load a subset of rows (or the
1318   entire matrix).  This routine is especially useful when a large
1319   matrix is stored on disk and only part of it is desired on each
1320   processor.  For example, a parallel solver may access only some of
1321   the rows from each processor.  The algorithm used here reads
1322   relatively small blocks of data rather than reading the entire
1323   matrix and then subsetting it.
1324 
1325   Viewer's `PetscViewerType` must be either `PETSCVIEWERBINARY` or `PETSCVIEWERHDF5`.
1326   Such viewer can be created using `PetscViewerBinaryOpen()` or `PetscViewerHDF5Open()`,
1327   or the sequence like
1328 .vb
1329     `PetscViewer` v;
1330     `PetscViewerCreate`(`PETSC_COMM_WORLD`,&v);
1331     `PetscViewerSetType`(v,`PETSCVIEWERBINARY`);
1332     `PetscViewerSetFromOptions`(v);
1333     `PetscViewerFileSetMode`(v,`FILE_MODE_READ`);
1334     `PetscViewerFileSetName`(v,"datafile");
1335 .ve
1336   The optional `PetscViewerSetFromOptions()` call allows overriding `PetscViewerSetType()` using the option
1337 .vb
1338   -viewer_type {binary, hdf5}
1339 .ve
1340 
1341   See the example src/ksp/ksp/tutorials/ex27.c with the first approach,
1342   and src/mat/tutorials/ex10.c with the second approach.
1343 
1344   In case of `PETSCVIEWERBINARY`, a native PETSc binary format is used. Each of the blocks
1345   is read onto MPI rank 0 and then shipped to its destination MPI rank, one after another.
1346   Multiple objects, both matrices and vectors, can be stored within the same file.
1347   Their `PetscObject` name is ignored; they are loaded in the order of their storage.
1348 
1349   Most users should not need to know the details of the binary storage
1350   format, since `MatLoad()` and `MatView()` completely hide these details.
1351   But for anyone who is interested, the standard binary matrix storage
1352   format is
1353 
1354 .vb
1355     PetscInt    MAT_FILE_CLASSID
1356     PetscInt    number of rows
1357     PetscInt    number of columns
1358     PetscInt    total number of nonzeros
1359     PetscInt    *number nonzeros in each row
1360     PetscInt    *column indices of all nonzeros (starting index is zero)
1361     PetscScalar *values of all nonzeros
1362 .ve
1363   If PETSc was not configured with `--with-64-bit-indices` then only `MATMPIAIJ` matrices with more than `PETSC_INT_MAX` non-zeros can be
1364   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
1365   case will not fit in a (32-bit) `PetscInt` the value `PETSC_INT_MAX` is used for the header entry `total number of nonzeros`.
1366 
1367   PETSc automatically does the byte swapping for
1368   machines that store the bytes reversed. Thus if you write your own binary
1369   read/write routines you have to swap the bytes; see `PetscBinaryRead()`
1370   and `PetscBinaryWrite()` to see how this may be done.
1371 
1372   In case of `PETSCVIEWERHDF5`, a parallel HDF5 reader is used.
1373   Each processor's chunk is loaded independently by its owning MPI process.
1374   Multiple objects, both matrices and vectors, can be stored within the same file.
1375   They are looked up by their PetscObject name.
1376 
1377   As the MATLAB MAT-File Version 7.3 format is also a HDF5 flavor, we decided to use
1378   by default the same structure and naming of the AIJ arrays and column count
1379   within the HDF5 file. This means that a MAT file saved with -v7.3 flag, e.g.
1380 .vb
1381   save example.mat A b -v7.3
1382 .ve
1383   can be directly read by this routine (see Reference 1 for details).
1384 
1385   Depending on your MATLAB version, this format might be a default,
1386   otherwise you can set it as default in Preferences.
1387 
1388   Unless -nocompression flag is used to save the file in MATLAB,
1389   PETSc must be configured with ZLIB package.
1390 
1391   See also examples src/mat/tutorials/ex10.c and src/ksp/ksp/tutorials/ex27.c
1392 
1393   This reader currently supports only real `MATSEQAIJ`, `MATMPIAIJ`, `MATSEQDENSE` and `MATMPIDENSE` matrices for `PETSCVIEWERHDF5`
1394 
1395   Corresponding `MatView()` is not yet implemented.
1396 
1397   The loaded matrix is actually a transpose of the original one in MATLAB,
1398   unless you push `PETSC_VIEWER_HDF5_MAT` format (see examples above).
1399   With this format, matrix is automatically transposed by PETSc,
1400   unless the matrix is marked as SPD or symmetric
1401   (see `MatSetOption()`, `MAT_SPD`, `MAT_SYMMETRIC`).
1402 
1403   See MATLAB Documentation on `save()`, <https://www.mathworks.com/help/matlab/ref/save.html#btox10b-1-version>
1404 
1405 .seealso: [](ch_matrices), `Mat`, `PetscViewerBinaryOpen()`, `PetscViewerSetType()`, `MatView()`, `VecLoad()`
1406  @*/
1407 PetscErrorCode MatLoad(Mat mat, PetscViewer viewer)
1408 {
1409   PetscBool flg;
1410 
1411   PetscFunctionBegin;
1412   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
1413   PetscValidHeaderSpecific(viewer, PETSC_VIEWER_CLASSID, 2);
1414 
1415   if (!((PetscObject)mat)->type_name) PetscCall(MatSetType(mat, MATAIJ));
1416 
1417   flg = PETSC_FALSE;
1418   PetscCall(PetscOptionsGetBool(((PetscObject)mat)->options, ((PetscObject)mat)->prefix, "-matload_symmetric", &flg, NULL));
1419   if (flg) {
1420     PetscCall(MatSetOption(mat, MAT_SYMMETRIC, PETSC_TRUE));
1421     PetscCall(MatSetOption(mat, MAT_SYMMETRY_ETERNAL, PETSC_TRUE));
1422   }
1423   flg = PETSC_FALSE;
1424   PetscCall(PetscOptionsGetBool(((PetscObject)mat)->options, ((PetscObject)mat)->prefix, "-matload_spd", &flg, NULL));
1425   if (flg) PetscCall(MatSetOption(mat, MAT_SPD, PETSC_TRUE));
1426 
1427   PetscCall(PetscLogEventBegin(MAT_Load, mat, viewer, 0, 0));
1428   PetscUseTypeMethod(mat, load, viewer);
1429   PetscCall(PetscLogEventEnd(MAT_Load, mat, viewer, 0, 0));
1430   PetscFunctionReturn(PETSC_SUCCESS);
1431 }
1432 
1433 static PetscErrorCode MatDestroy_Redundant(Mat_Redundant **redundant)
1434 {
1435   Mat_Redundant *redund = *redundant;
1436 
1437   PetscFunctionBegin;
1438   if (redund) {
1439     if (redund->matseq) { /* via MatCreateSubMatrices()  */
1440       PetscCall(ISDestroy(&redund->isrow));
1441       PetscCall(ISDestroy(&redund->iscol));
1442       PetscCall(MatDestroySubMatrices(1, &redund->matseq));
1443     } else {
1444       PetscCall(PetscFree2(redund->send_rank, redund->recv_rank));
1445       PetscCall(PetscFree(redund->sbuf_j));
1446       PetscCall(PetscFree(redund->sbuf_a));
1447       for (PetscInt i = 0; i < redund->nrecvs; i++) {
1448         PetscCall(PetscFree(redund->rbuf_j[i]));
1449         PetscCall(PetscFree(redund->rbuf_a[i]));
1450       }
1451       PetscCall(PetscFree4(redund->sbuf_nz, redund->rbuf_nz, redund->rbuf_j, redund->rbuf_a));
1452     }
1453 
1454     if (redund->subcomm) PetscCall(PetscCommDestroy(&redund->subcomm));
1455     PetscCall(PetscFree(redund));
1456   }
1457   PetscFunctionReturn(PETSC_SUCCESS);
1458 }
1459 
1460 /*@
1461   MatDestroy - Frees space taken by a matrix.
1462 
1463   Collective
1464 
1465   Input Parameter:
1466 . A - the matrix
1467 
1468   Level: beginner
1469 
1470   Developer Note:
1471   Some special arrays of matrices are not destroyed in this routine but instead by the routines called by
1472   `MatDestroySubMatrices()`. Thus one must be sure that any changes here must also be made in those routines.
1473   `MatHeaderMerge()` and `MatHeaderReplace()` also manipulate the data in the `Mat` object and likely need changes
1474   if changes are needed here.
1475 
1476 .seealso: [](ch_matrices), `Mat`, `MatCreate()`
1477 @*/
1478 PetscErrorCode MatDestroy(Mat *A)
1479 {
1480   PetscFunctionBegin;
1481   if (!*A) PetscFunctionReturn(PETSC_SUCCESS);
1482   PetscValidHeaderSpecific(*A, MAT_CLASSID, 1);
1483   if (--((PetscObject)*A)->refct > 0) {
1484     *A = NULL;
1485     PetscFunctionReturn(PETSC_SUCCESS);
1486   }
1487 
1488   /* if memory was published with SAWs then destroy it */
1489   PetscCall(PetscObjectSAWsViewOff((PetscObject)*A));
1490   PetscTryTypeMethod(*A, destroy);
1491 
1492   PetscCall(PetscFree((*A)->factorprefix));
1493   PetscCall(PetscFree((*A)->defaultvectype));
1494   PetscCall(PetscFree((*A)->defaultrandtype));
1495   PetscCall(PetscFree((*A)->bsizes));
1496   PetscCall(PetscFree((*A)->solvertype));
1497   for (PetscInt i = 0; i < MAT_FACTOR_NUM_TYPES; i++) PetscCall(PetscFree((*A)->preferredordering[i]));
1498   if ((*A)->redundant && (*A)->redundant->matseq[0] == *A) (*A)->redundant->matseq[0] = NULL;
1499   PetscCall(MatDestroy_Redundant(&(*A)->redundant));
1500   PetscCall(MatProductClear(*A));
1501   PetscCall(MatNullSpaceDestroy(&(*A)->nullsp));
1502   PetscCall(MatNullSpaceDestroy(&(*A)->transnullsp));
1503   PetscCall(MatNullSpaceDestroy(&(*A)->nearnullsp));
1504   PetscCall(MatDestroy(&(*A)->schur));
1505   PetscCall(PetscLayoutDestroy(&(*A)->rmap));
1506   PetscCall(PetscLayoutDestroy(&(*A)->cmap));
1507   PetscCall(PetscHeaderDestroy(A));
1508   PetscFunctionReturn(PETSC_SUCCESS);
1509 }
1510 
1511 // PetscClangLinter pragma disable: -fdoc-section-header-unknown
1512 /*@
1513   MatSetValues - Inserts or adds a block of values into a matrix.
1514   These values may be cached, so `MatAssemblyBegin()` and `MatAssemblyEnd()`
1515   MUST be called after all calls to `MatSetValues()` have been completed.
1516 
1517   Not Collective
1518 
1519   Input Parameters:
1520 + mat  - the matrix
1521 . m    - the number of rows
1522 . idxm - the global indices of the rows
1523 . n    - the number of columns
1524 . idxn - the global indices of the columns
1525 . v    - a one-dimensional array that contains the values implicitly stored as a two-dimensional array, by default in row-major order.
1526          See `MAT_ROW_ORIENTED` in `MatSetOption()` for how to use column-major order.
1527 - addv - either `ADD_VALUES` to add values to any existing entries, or `INSERT_VALUES` to replace existing entries with new values
1528 
1529   Level: beginner
1530 
1531   Notes:
1532   Calls to `MatSetValues()` with the `INSERT_VALUES` and `ADD_VALUES`
1533   options cannot be mixed without intervening calls to the assembly
1534   routines.
1535 
1536   `MatSetValues()` uses 0-based row and column numbers in Fortran
1537   as well as in C.
1538 
1539   Negative indices may be passed in `idxm` and `idxn`, these rows and columns are
1540   simply ignored. This allows easily inserting element stiffness matrices
1541   with homogeneous Dirichlet boundary conditions that you don't want represented
1542   in the matrix.
1543 
1544   Efficiency Alert:
1545   The routine `MatSetValuesBlocked()` may offer much better efficiency
1546   for users of block sparse formats (`MATSEQBAIJ` and `MATMPIBAIJ`).
1547 
1548   Fortran Notes:
1549   If any of `idxm`, `idxn`, and `v` are scalars pass them using, for example,
1550 .vb
1551   call MatSetValues(mat, one, [idxm], one, [idxn], [v], INSERT_VALUES, ierr)
1552 .ve
1553 
1554   If `v` is a two-dimensional array use `reshape()` to pass it as a one dimensional array
1555 
1556   Developer Note:
1557   This is labeled with C so does not automatically generate Fortran stubs and interfaces
1558   because it requires multiple Fortran interfaces depending on which arguments are scalar or arrays.
1559 
1560 .seealso: [](ch_matrices), `Mat`, `MatSetOption()`, `MatAssemblyBegin()`, `MatAssemblyEnd()`, `MatSetValuesBlocked()`, `MatSetValuesLocal()`,
1561           `InsertMode`, `INSERT_VALUES`, `ADD_VALUES`
1562 @*/
1563 PetscErrorCode MatSetValues(Mat mat, PetscInt m, const PetscInt idxm[], PetscInt n, const PetscInt idxn[], const PetscScalar v[], InsertMode addv)
1564 {
1565   PetscFunctionBeginHot;
1566   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
1567   PetscValidType(mat, 1);
1568   if (!m || !n) PetscFunctionReturn(PETSC_SUCCESS); /* no values to insert */
1569   PetscAssertPointer(idxm, 3);
1570   PetscAssertPointer(idxn, 5);
1571   MatCheckPreallocated(mat, 1);
1572 
1573   if (mat->insertmode == NOT_SET_VALUES) mat->insertmode = addv;
1574   else PetscCheck(mat->insertmode == addv, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Cannot mix add values and insert values");
1575 
1576   if (PetscDefined(USE_DEBUG)) {
1577     PetscInt i, j;
1578 
1579     PetscCheck(!mat->factortype, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
1580     if (v) {
1581       for (i = 0; i < m; i++) {
1582         for (j = 0; j < n; j++) {
1583           if (mat->erroriffailure && PetscIsInfOrNanScalar(v[i * n + j]))
1584 #if defined(PETSC_USE_COMPLEX)
1585             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]);
1586 #else
1587             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]);
1588 #endif
1589         }
1590       }
1591     }
1592     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);
1593     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);
1594   }
1595 
1596   if (mat->assembled) {
1597     mat->was_assembled = PETSC_TRUE;
1598     mat->assembled     = PETSC_FALSE;
1599   }
1600   PetscCall(PetscLogEventBegin(MAT_SetValues, mat, 0, 0, 0));
1601   PetscUseTypeMethod(mat, setvalues, m, idxm, n, idxn, v, addv);
1602   PetscCall(PetscLogEventEnd(MAT_SetValues, mat, 0, 0, 0));
1603   PetscFunctionReturn(PETSC_SUCCESS);
1604 }
1605 
1606 // PetscClangLinter pragma disable: -fdoc-section-header-unknown
1607 /*@
1608   MatSetValuesIS - Inserts or adds a block of values into a matrix using an `IS` to indicate the rows and columns
1609   These values may be cached, so `MatAssemblyBegin()` and `MatAssemblyEnd()`
1610   MUST be called after all calls to `MatSetValues()` have been completed.
1611 
1612   Not Collective
1613 
1614   Input Parameters:
1615 + mat  - the matrix
1616 . ism  - the rows to provide
1617 . isn  - the columns to provide
1618 . v    - a one-dimensional array that contains the values implicitly stored as a two-dimensional array, by default in row-major order.
1619          See `MAT_ROW_ORIENTED` in `MatSetOption()` for how to use column-major order.
1620 - addv - either `ADD_VALUES` to add values to any existing entries, or `INSERT_VALUES` to replace existing entries with new values
1621 
1622   Level: beginner
1623 
1624   Notes:
1625   By default, the values, `v`, are stored in row-major order. See `MAT_ROW_ORIENTED` in `MatSetOption()` for how to use column-major order.
1626 
1627   Calls to `MatSetValues()` with the `INSERT_VALUES` and `ADD_VALUES`
1628   options cannot be mixed without intervening calls to the assembly
1629   routines.
1630 
1631   `MatSetValues()` uses 0-based row and column numbers in Fortran
1632   as well as in C.
1633 
1634   Negative indices may be passed in `ism` and `isn`, these rows and columns are
1635   simply ignored. This allows easily inserting element stiffness matrices
1636   with homogeneous Dirichlet boundary conditions that you don't want represented
1637   in the matrix.
1638 
1639   Fortran Note:
1640   If `v` is a two-dimensional array use `reshape()` to pass it as a one dimensional array
1641 
1642   Efficiency Alert:
1643   The routine `MatSetValuesBlocked()` may offer much better efficiency
1644   for users of block sparse formats (`MATSEQBAIJ` and `MATMPIBAIJ`).
1645 
1646   This is currently not optimized for any particular `ISType`
1647 
1648 .seealso: [](ch_matrices), `Mat`, `MatSetOption()`, `MatSetValues()`, `MatAssemblyBegin()`, `MatAssemblyEnd()`, `MatSetValuesBlocked()`, `MatSetValuesLocal()`,
1649           `InsertMode`, `INSERT_VALUES`, `ADD_VALUES`
1650 @*/
1651 PetscErrorCode MatSetValuesIS(Mat mat, IS ism, IS isn, const PetscScalar v[], InsertMode addv)
1652 {
1653   PetscInt        m, n;
1654   const PetscInt *rows, *cols;
1655 
1656   PetscFunctionBeginHot;
1657   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
1658   PetscCall(ISGetIndices(ism, &rows));
1659   PetscCall(ISGetIndices(isn, &cols));
1660   PetscCall(ISGetLocalSize(ism, &m));
1661   PetscCall(ISGetLocalSize(isn, &n));
1662   PetscCall(MatSetValues(mat, m, rows, n, cols, v, addv));
1663   PetscCall(ISRestoreIndices(ism, &rows));
1664   PetscCall(ISRestoreIndices(isn, &cols));
1665   PetscFunctionReturn(PETSC_SUCCESS);
1666 }
1667 
1668 /*@
1669   MatSetValuesRowLocal - Inserts a row (block row for `MATBAIJ` matrices) of nonzero
1670   values into a matrix
1671 
1672   Not Collective
1673 
1674   Input Parameters:
1675 + mat - the matrix
1676 . row - the (block) row to set
1677 - v   - a one-dimensional array that contains the values. For `MATBAIJ` they are implicitly stored as a two-dimensional array, by default in row-major order.
1678         See `MAT_ROW_ORIENTED` in `MatSetOption()` for how to use column-major order.
1679 
1680   Level: intermediate
1681 
1682   Notes:
1683   The values, `v`, are column-oriented (for the block version) and sorted
1684 
1685   All the nonzero values in `row` must be provided
1686 
1687   The matrix must have previously had its column indices set, likely by having been assembled.
1688 
1689   `row` must belong to this MPI process
1690 
1691   Fortran Note:
1692   If `v` is a two-dimensional array use `reshape()` to pass it as a one dimensional array
1693 
1694 .seealso: [](ch_matrices), `Mat`, `MatSetOption()`, `MatAssemblyBegin()`, `MatAssemblyEnd()`, `MatSetValuesBlocked()`, `MatSetValuesLocal()`,
1695           `InsertMode`, `INSERT_VALUES`, `ADD_VALUES`, `MatSetValues()`, `MatSetValuesRow()`, `MatSetLocalToGlobalMapping()`
1696 @*/
1697 PetscErrorCode MatSetValuesRowLocal(Mat mat, PetscInt row, const PetscScalar v[])
1698 {
1699   PetscInt globalrow;
1700 
1701   PetscFunctionBegin;
1702   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
1703   PetscValidType(mat, 1);
1704   PetscAssertPointer(v, 3);
1705   PetscCall(ISLocalToGlobalMappingApply(mat->rmap->mapping, 1, &row, &globalrow));
1706   PetscCall(MatSetValuesRow(mat, globalrow, v));
1707   PetscFunctionReturn(PETSC_SUCCESS);
1708 }
1709 
1710 /*@
1711   MatSetValuesRow - Inserts a row (block row for `MATBAIJ` matrices) of nonzero
1712   values into a matrix
1713 
1714   Not Collective
1715 
1716   Input Parameters:
1717 + mat - the matrix
1718 . row - the (block) row to set
1719 - 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
1720 
1721   Level: advanced
1722 
1723   Notes:
1724   The values, `v`, are column-oriented for the block version.
1725 
1726   All the nonzeros in `row` must be provided
1727 
1728   THE MATRIX MUST HAVE PREVIOUSLY HAD ITS COLUMN INDICES SET. IT IS RARE THAT THIS ROUTINE IS USED, usually `MatSetValues()` is used.
1729 
1730   `row` must belong to this process
1731 
1732 .seealso: [](ch_matrices), `Mat`, `MatSetValues()`, `MatSetOption()`, `MatAssemblyBegin()`, `MatAssemblyEnd()`, `MatSetValuesBlocked()`, `MatSetValuesLocal()`,
1733           `InsertMode`, `INSERT_VALUES`, `ADD_VALUES`
1734 @*/
1735 PetscErrorCode MatSetValuesRow(Mat mat, PetscInt row, const PetscScalar v[])
1736 {
1737   PetscFunctionBeginHot;
1738   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
1739   PetscValidType(mat, 1);
1740   MatCheckPreallocated(mat, 1);
1741   PetscAssertPointer(v, 3);
1742   PetscCheck(mat->insertmode != ADD_VALUES, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Cannot mix add and insert values");
1743   PetscCheck(!mat->factortype, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
1744   mat->insertmode = INSERT_VALUES;
1745 
1746   if (mat->assembled) {
1747     mat->was_assembled = PETSC_TRUE;
1748     mat->assembled     = PETSC_FALSE;
1749   }
1750   PetscCall(PetscLogEventBegin(MAT_SetValues, mat, 0, 0, 0));
1751   PetscUseTypeMethod(mat, setvaluesrow, row, v);
1752   PetscCall(PetscLogEventEnd(MAT_SetValues, mat, 0, 0, 0));
1753   PetscFunctionReturn(PETSC_SUCCESS);
1754 }
1755 
1756 // PetscClangLinter pragma disable: -fdoc-section-header-unknown
1757 /*@
1758   MatSetValuesStencil - Inserts or adds a block of values into a matrix.
1759   Using structured grid indexing
1760 
1761   Not Collective
1762 
1763   Input Parameters:
1764 + mat  - the matrix
1765 . m    - number of rows being entered
1766 . idxm - grid coordinates (and component number when dof > 1) for matrix rows being entered
1767 . n    - number of columns being entered
1768 . idxn - grid coordinates (and component number when dof > 1) for matrix columns being entered
1769 . v    - a one-dimensional array that contains the values implicitly stored as a two-dimensional array, by default in row-major order.
1770          See `MAT_ROW_ORIENTED` in `MatSetOption()` for how to use column-major order.
1771 - addv - either `ADD_VALUES` to add to existing entries at that location or `INSERT_VALUES` to replace existing entries with new values
1772 
1773   Level: beginner
1774 
1775   Notes:
1776   By default the values, `v`, are row-oriented.  See `MatSetOption()` for other options.
1777 
1778   Calls to `MatSetValuesStencil()` with the `INSERT_VALUES` and `ADD_VALUES`
1779   options cannot be mixed without intervening calls to the assembly
1780   routines.
1781 
1782   The grid coordinates are across the entire grid, not just the local portion
1783 
1784   `MatSetValuesStencil()` uses 0-based row and column numbers in Fortran
1785   as well as in C.
1786 
1787   For setting/accessing vector values via array coordinates you can use the `DMDAVecGetArray()` routine
1788 
1789   In order to use this routine you must either obtain the matrix with `DMCreateMatrix()`
1790   or call `MatSetLocalToGlobalMapping()` and `MatSetStencil()` first.
1791 
1792   The columns and rows in the stencil passed in MUST be contained within the
1793   ghost region of the given process as set with DMDACreateXXX() or `MatSetStencil()`. For example,
1794   if you create a `DMDA` with an overlap of one grid level and on a particular process its first
1795   local nonghost x logical coordinate is 6 (so its first ghost x logical coordinate is 5) the
1796   first i index you can use in your column and row indices in `MatSetStencil()` is 5.
1797 
1798   For periodic boundary conditions use negative indices for values to the left (below 0; that are to be
1799   obtained by wrapping values from right edge). For values to the right of the last entry using that index plus one
1800   etc to obtain values that obtained by wrapping the values from the left edge. This does not work for anything but the
1801   `DM_BOUNDARY_PERIODIC` boundary type.
1802 
1803   For indices that don't mean anything for your case (like the k index when working in 2d) or the c index when you have
1804   a single value per point) you can skip filling those indices.
1805 
1806   Inspired by the structured grid interface to the HYPRE package
1807   (https://computation.llnl.gov/projects/hypre-scalable-linear-solvers-multigrid-methods)
1808 
1809   Fortran Note:
1810   If `y` is a two-dimensional array use `reshape()` to pass it as a one dimensional array
1811 
1812   Efficiency Alert:
1813   The routine `MatSetValuesBlockedStencil()` may offer much better efficiency
1814   for users of block sparse formats (`MATSEQBAIJ` and `MATMPIBAIJ`).
1815 
1816 .seealso: [](ch_matrices), `Mat`, `DMDA`, `MatSetOption()`, `MatAssemblyBegin()`, `MatAssemblyEnd()`, `MatSetValuesBlocked()`, `MatSetValuesLocal()`
1817           `MatSetValues()`, `MatSetValuesBlockedStencil()`, `MatSetStencil()`, `DMCreateMatrix()`, `DMDAVecGetArray()`, `MatStencil`
1818 @*/
1819 PetscErrorCode MatSetValuesStencil(Mat mat, PetscInt m, const MatStencil idxm[], PetscInt n, const MatStencil idxn[], const PetscScalar v[], InsertMode addv)
1820 {
1821   PetscInt  buf[8192], *bufm = NULL, *bufn = NULL, *jdxm, *jdxn;
1822   PetscInt  j, i, dim = mat->stencil.dim, *dims = mat->stencil.dims + 1, tmp;
1823   PetscInt *starts = mat->stencil.starts, *dxm = (PetscInt *)idxm, *dxn = (PetscInt *)idxn, sdim = dim - (1 - (PetscInt)mat->stencil.noc);
1824 
1825   PetscFunctionBegin;
1826   if (!m || !n) PetscFunctionReturn(PETSC_SUCCESS); /* no values to insert */
1827   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
1828   PetscValidType(mat, 1);
1829   PetscAssertPointer(idxm, 3);
1830   PetscAssertPointer(idxn, 5);
1831 
1832   if ((m + n) <= (PetscInt)PETSC_STATIC_ARRAY_LENGTH(buf)) {
1833     jdxm = buf;
1834     jdxn = buf + m;
1835   } else {
1836     PetscCall(PetscMalloc2(m, &bufm, n, &bufn));
1837     jdxm = bufm;
1838     jdxn = bufn;
1839   }
1840   for (i = 0; i < m; i++) {
1841     for (j = 0; j < 3 - sdim; j++) dxm++;
1842     tmp = *dxm++ - starts[0];
1843     for (j = 0; j < dim - 1; j++) {
1844       if ((*dxm++ - starts[j + 1]) < 0 || tmp < 0) tmp = -1;
1845       else tmp = tmp * dims[j] + *(dxm - 1) - starts[j + 1];
1846     }
1847     if (mat->stencil.noc) dxm++;
1848     jdxm[i] = tmp;
1849   }
1850   for (i = 0; i < n; i++) {
1851     for (j = 0; j < 3 - sdim; j++) dxn++;
1852     tmp = *dxn++ - starts[0];
1853     for (j = 0; j < dim - 1; j++) {
1854       if ((*dxn++ - starts[j + 1]) < 0 || tmp < 0) tmp = -1;
1855       else tmp = tmp * dims[j] + *(dxn - 1) - starts[j + 1];
1856     }
1857     if (mat->stencil.noc) dxn++;
1858     jdxn[i] = tmp;
1859   }
1860   PetscCall(MatSetValuesLocal(mat, m, jdxm, n, jdxn, v, addv));
1861   PetscCall(PetscFree2(bufm, bufn));
1862   PetscFunctionReturn(PETSC_SUCCESS);
1863 }
1864 
1865 /*@
1866   MatSetValuesBlockedStencil - Inserts or adds a block of values into a matrix.
1867   Using structured grid indexing
1868 
1869   Not Collective
1870 
1871   Input Parameters:
1872 + mat  - the matrix
1873 . m    - number of rows being entered
1874 . idxm - grid coordinates for matrix rows being entered
1875 . n    - number of columns being entered
1876 . idxn - grid coordinates for matrix columns being entered
1877 . v    - a one-dimensional array that contains the values implicitly stored as a two-dimensional array, by default in row-major order.
1878          See `MAT_ROW_ORIENTED` in `MatSetOption()` for how to use column-major order.
1879 - addv - either `ADD_VALUES` to add to existing entries or `INSERT_VALUES` to replace existing entries with new values
1880 
1881   Level: beginner
1882 
1883   Notes:
1884   By default the values, `v`, are row-oriented and unsorted.
1885   See `MatSetOption()` for other options.
1886 
1887   Calls to `MatSetValuesBlockedStencil()` with the `INSERT_VALUES` and `ADD_VALUES`
1888   options cannot be mixed without intervening calls to the assembly
1889   routines.
1890 
1891   The grid coordinates are across the entire grid, not just the local portion
1892 
1893   `MatSetValuesBlockedStencil()` uses 0-based row and column numbers in Fortran
1894   as well as in C.
1895 
1896   For setting/accessing vector values via array coordinates you can use the `DMDAVecGetArray()` routine
1897 
1898   In order to use this routine you must either obtain the matrix with `DMCreateMatrix()`
1899   or call `MatSetBlockSize()`, `MatSetLocalToGlobalMapping()` and `MatSetStencil()` first.
1900 
1901   The columns and rows in the stencil passed in MUST be contained within the
1902   ghost region of the given process as set with DMDACreateXXX() or `MatSetStencil()`. For example,
1903   if you create a `DMDA` with an overlap of one grid level and on a particular process its first
1904   local nonghost x logical coordinate is 6 (so its first ghost x logical coordinate is 5) the
1905   first i index you can use in your column and row indices in `MatSetStencil()` is 5.
1906 
1907   Negative indices may be passed in `idxm` and `idxn`, these rows and columns are
1908   simply ignored. This allows easily inserting element stiffness matrices
1909   with homogeneous Dirichlet boundary conditions that you don't want represented
1910   in the matrix.
1911 
1912   Inspired by the structured grid interface to the HYPRE package
1913   (https://computation.llnl.gov/projects/hypre-scalable-linear-solvers-multigrid-methods)
1914 
1915   Fortran Notes:
1916   `idxm` and `idxn` should be declared as
1917 .vb
1918     MatStencil idxm(4,m),idxn(4,n)
1919 .ve
1920   and the values inserted using
1921 .vb
1922     idxm(MatStencil_i,1) = i
1923     idxm(MatStencil_j,1) = j
1924     idxm(MatStencil_k,1) = k
1925    etc
1926 .ve
1927 
1928   If `v` is a two-dimensional array use `reshape()` to pass it as a one dimensional array
1929 
1930 .seealso: [](ch_matrices), `Mat`, `DMDA`, `MatSetOption()`, `MatAssemblyBegin()`, `MatAssemblyEnd()`, `MatSetValuesBlocked()`, `MatSetValuesLocal()`
1931           `MatSetValues()`, `MatSetValuesStencil()`, `MatSetStencil()`, `DMCreateMatrix()`, `DMDAVecGetArray()`, `MatStencil`,
1932           `MatSetBlockSize()`, `MatSetLocalToGlobalMapping()`
1933 @*/
1934 PetscErrorCode MatSetValuesBlockedStencil(Mat mat, PetscInt m, const MatStencil idxm[], PetscInt n, const MatStencil idxn[], const PetscScalar v[], InsertMode addv)
1935 {
1936   PetscInt  buf[8192], *bufm = NULL, *bufn = NULL, *jdxm, *jdxn;
1937   PetscInt  j, i, dim = mat->stencil.dim, *dims = mat->stencil.dims + 1, tmp;
1938   PetscInt *starts = mat->stencil.starts, *dxm = (PetscInt *)idxm, *dxn = (PetscInt *)idxn, sdim = dim - (1 - (PetscInt)mat->stencil.noc);
1939 
1940   PetscFunctionBegin;
1941   if (!m || !n) PetscFunctionReturn(PETSC_SUCCESS); /* no values to insert */
1942   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
1943   PetscValidType(mat, 1);
1944   PetscAssertPointer(idxm, 3);
1945   PetscAssertPointer(idxn, 5);
1946   PetscAssertPointer(v, 6);
1947 
1948   if ((m + n) <= (PetscInt)PETSC_STATIC_ARRAY_LENGTH(buf)) {
1949     jdxm = buf;
1950     jdxn = buf + m;
1951   } else {
1952     PetscCall(PetscMalloc2(m, &bufm, n, &bufn));
1953     jdxm = bufm;
1954     jdxn = bufn;
1955   }
1956   for (i = 0; i < m; i++) {
1957     for (j = 0; j < 3 - sdim; j++) dxm++;
1958     tmp = *dxm++ - starts[0];
1959     for (j = 0; j < sdim - 1; j++) {
1960       if ((*dxm++ - starts[j + 1]) < 0 || tmp < 0) tmp = -1;
1961       else tmp = tmp * dims[j] + *(dxm - 1) - starts[j + 1];
1962     }
1963     dxm++;
1964     jdxm[i] = tmp;
1965   }
1966   for (i = 0; i < n; i++) {
1967     for (j = 0; j < 3 - sdim; j++) dxn++;
1968     tmp = *dxn++ - starts[0];
1969     for (j = 0; j < sdim - 1; j++) {
1970       if ((*dxn++ - starts[j + 1]) < 0 || tmp < 0) tmp = -1;
1971       else tmp = tmp * dims[j] + *(dxn - 1) - starts[j + 1];
1972     }
1973     dxn++;
1974     jdxn[i] = tmp;
1975   }
1976   PetscCall(MatSetValuesBlockedLocal(mat, m, jdxm, n, jdxn, v, addv));
1977   PetscCall(PetscFree2(bufm, bufn));
1978   PetscFunctionReturn(PETSC_SUCCESS);
1979 }
1980 
1981 /*@
1982   MatSetStencil - Sets the grid information for setting values into a matrix via
1983   `MatSetValuesStencil()`
1984 
1985   Not Collective
1986 
1987   Input Parameters:
1988 + mat    - the matrix
1989 . dim    - dimension of the grid 1, 2, or 3
1990 . dims   - number of grid points in x, y, and z direction, including ghost points on your processor
1991 . starts - starting point of ghost nodes on your processor in x, y, and z direction
1992 - dof    - number of degrees of freedom per node
1993 
1994   Level: beginner
1995 
1996   Notes:
1997   Inspired by the structured grid interface to the HYPRE package
1998   (www.llnl.gov/CASC/hyper)
1999 
2000   For matrices generated with `DMCreateMatrix()` this routine is automatically called and so not needed by the
2001   user.
2002 
2003 .seealso: [](ch_matrices), `Mat`, `MatStencil`, `MatSetOption()`, `MatAssemblyBegin()`, `MatAssemblyEnd()`, `MatSetValuesBlocked()`, `MatSetValuesLocal()`
2004           `MatSetValues()`, `MatSetValuesBlockedStencil()`, `MatSetValuesStencil()`
2005 @*/
2006 PetscErrorCode MatSetStencil(Mat mat, PetscInt dim, const PetscInt dims[], const PetscInt starts[], PetscInt dof)
2007 {
2008   PetscFunctionBegin;
2009   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
2010   PetscAssertPointer(dims, 3);
2011   PetscAssertPointer(starts, 4);
2012 
2013   mat->stencil.dim = dim + (dof > 1);
2014   for (PetscInt i = 0; i < dim; i++) {
2015     mat->stencil.dims[i]   = dims[dim - i - 1]; /* copy the values in backwards */
2016     mat->stencil.starts[i] = starts[dim - i - 1];
2017   }
2018   mat->stencil.dims[dim]   = dof;
2019   mat->stencil.starts[dim] = 0;
2020   mat->stencil.noc         = (PetscBool)(dof == 1);
2021   PetscFunctionReturn(PETSC_SUCCESS);
2022 }
2023 
2024 /*@
2025   MatSetValuesBlocked - Inserts or adds a block of values into a matrix.
2026 
2027   Not Collective
2028 
2029   Input Parameters:
2030 + mat  - the matrix
2031 . m    - the number of block rows
2032 . idxm - the global block indices
2033 . n    - the number of block columns
2034 . idxn - the global block indices
2035 . v    - a one-dimensional array that contains the values implicitly stored as a two-dimensional array, by default in row-major order.
2036          See `MAT_ROW_ORIENTED` in `MatSetOption()` for how to use column-major order.
2037 - addv - either `ADD_VALUES` to add values to any existing entries, or `INSERT_VALUES` replaces existing entries with new values
2038 
2039   Level: intermediate
2040 
2041   Notes:
2042   If you create the matrix yourself (that is not with a call to `DMCreateMatrix()`) then you MUST call
2043   MatXXXXSetPreallocation() or `MatSetUp()` before using this routine.
2044 
2045   The `m` and `n` count the NUMBER of blocks in the row direction and column direction,
2046   NOT the total number of rows/columns; for example, if the block size is 2 and
2047   you are passing in values for rows 2,3,4,5  then `m` would be 2 (not 4).
2048   The values in `idxm` would be 1 2; that is the first index for each block divided by
2049   the block size.
2050 
2051   You must call `MatSetBlockSize()` when constructing this matrix (before
2052   preallocating it).
2053 
2054   By default, the values, `v`, are stored in row-major order. See `MAT_ROW_ORIENTED` in `MatSetOption()` for how to use column-major order.
2055 
2056   Calls to `MatSetValuesBlocked()` with the `INSERT_VALUES` and `ADD_VALUES`
2057   options cannot be mixed without intervening calls to the assembly
2058   routines.
2059 
2060   `MatSetValuesBlocked()` uses 0-based row and column numbers in Fortran
2061   as well as in C.
2062 
2063   Negative indices may be passed in `idxm` and `idxn`, these rows and columns are
2064   simply ignored. This allows easily inserting element stiffness matrices
2065   with homogeneous Dirichlet boundary conditions that you don't want represented
2066   in the matrix.
2067 
2068   Each time an entry is set within a sparse matrix via `MatSetValues()`,
2069   internal searching must be done to determine where to place the
2070   data in the matrix storage space.  By instead inserting blocks of
2071   entries via `MatSetValuesBlocked()`, the overhead of matrix assembly is
2072   reduced.
2073 
2074   Example:
2075 .vb
2076    Suppose m=n=2 and block size(bs) = 2 The array is
2077 
2078    1  2  | 3  4
2079    5  6  | 7  8
2080    - - - | - - -
2081    9  10 | 11 12
2082    13 14 | 15 16
2083 
2084    v[] should be passed in like
2085    v[] = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]
2086 
2087   If you are not using row-oriented storage of v (that is you called MatSetOption(mat,MAT_ROW_ORIENTED,PETSC_FALSE)) then
2088    v[] = [1,5,9,13,2,6,10,14,3,7,11,15,4,8,12,16]
2089 .ve
2090 
2091   Fortran Notes:
2092   If any of `idmx`, `idxn`, and `v` are scalars pass them using, for example,
2093 .vb
2094   call MatSetValuesBlocked(mat, one, [idxm], one, [idxn], [v], INSERT_VALUES, ierr)
2095 .ve
2096 
2097   If `v` is a two-dimensional array use `reshape()` to pass it as a one dimensional array
2098 
2099 .seealso: [](ch_matrices), `Mat`, `MatSetBlockSize()`, `MatSetOption()`, `MatAssemblyBegin()`, `MatAssemblyEnd()`, `MatSetValues()`, `MatSetValuesBlockedLocal()`
2100 @*/
2101 PetscErrorCode MatSetValuesBlocked(Mat mat, PetscInt m, const PetscInt idxm[], PetscInt n, const PetscInt idxn[], const PetscScalar v[], InsertMode addv)
2102 {
2103   PetscFunctionBeginHot;
2104   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
2105   PetscValidType(mat, 1);
2106   if (!m || !n) PetscFunctionReturn(PETSC_SUCCESS); /* no values to insert */
2107   PetscAssertPointer(idxm, 3);
2108   PetscAssertPointer(idxn, 5);
2109   MatCheckPreallocated(mat, 1);
2110   if (mat->insertmode == NOT_SET_VALUES) mat->insertmode = addv;
2111   else PetscCheck(mat->insertmode == addv, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Cannot mix add values and insert values");
2112   if (PetscDefined(USE_DEBUG)) {
2113     PetscCheck(!mat->factortype, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
2114     PetscCheck(mat->ops->setvaluesblocked || mat->ops->setvalues, PETSC_COMM_SELF, PETSC_ERR_SUP, "Mat type %s", ((PetscObject)mat)->type_name);
2115   }
2116   if (PetscDefined(USE_DEBUG)) {
2117     PetscInt rbs, cbs, M, N, i;
2118     PetscCall(MatGetBlockSizes(mat, &rbs, &cbs));
2119     PetscCall(MatGetSize(mat, &M, &N));
2120     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);
2121     for (i = 0; i < n; i++)
2122       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);
2123   }
2124   if (mat->assembled) {
2125     mat->was_assembled = PETSC_TRUE;
2126     mat->assembled     = PETSC_FALSE;
2127   }
2128   PetscCall(PetscLogEventBegin(MAT_SetValues, mat, 0, 0, 0));
2129   if (mat->ops->setvaluesblocked) {
2130     PetscUseTypeMethod(mat, setvaluesblocked, m, idxm, n, idxn, v, addv);
2131   } else {
2132     PetscInt buf[8192], *bufr = NULL, *bufc = NULL, *iidxm, *iidxn;
2133     PetscInt i, j, bs, cbs;
2134 
2135     PetscCall(MatGetBlockSizes(mat, &bs, &cbs));
2136     if ((m * bs + n * cbs) <= (PetscInt)PETSC_STATIC_ARRAY_LENGTH(buf)) {
2137       iidxm = buf;
2138       iidxn = buf + m * bs;
2139     } else {
2140       PetscCall(PetscMalloc2(m * bs, &bufr, n * cbs, &bufc));
2141       iidxm = bufr;
2142       iidxn = bufc;
2143     }
2144     for (i = 0; i < m; i++) {
2145       for (j = 0; j < bs; j++) iidxm[i * bs + j] = bs * idxm[i] + j;
2146     }
2147     if (m != n || bs != cbs || idxm != idxn) {
2148       for (i = 0; i < n; i++) {
2149         for (j = 0; j < cbs; j++) iidxn[i * cbs + j] = cbs * idxn[i] + j;
2150       }
2151     } else iidxn = iidxm;
2152     PetscCall(MatSetValues(mat, m * bs, iidxm, n * cbs, iidxn, v, addv));
2153     PetscCall(PetscFree2(bufr, bufc));
2154   }
2155   PetscCall(PetscLogEventEnd(MAT_SetValues, mat, 0, 0, 0));
2156   PetscFunctionReturn(PETSC_SUCCESS);
2157 }
2158 
2159 /*@
2160   MatGetValues - Gets a block of local values from a matrix.
2161 
2162   Not Collective; can only return values that are owned by the give process
2163 
2164   Input Parameters:
2165 + mat  - the matrix
2166 . v    - a logically two-dimensional array for storing the values
2167 . m    - the number of rows
2168 . idxm - the  global indices of the rows
2169 . n    - the number of columns
2170 - idxn - the global indices of the columns
2171 
2172   Level: advanced
2173 
2174   Notes:
2175   The user must allocate space (m*n `PetscScalar`s) for the values, `v`.
2176   The values, `v`, are then returned in a row-oriented format,
2177   analogous to that used by default in `MatSetValues()`.
2178 
2179   `MatGetValues()` uses 0-based row and column numbers in
2180   Fortran as well as in C.
2181 
2182   `MatGetValues()` requires that the matrix has been assembled
2183   with `MatAssemblyBegin()`/`MatAssemblyEnd()`.  Thus, calls to
2184   `MatSetValues()` and `MatGetValues()` CANNOT be made in succession
2185   without intermediate matrix assembly.
2186 
2187   Negative row or column indices will be ignored and those locations in `v` will be
2188   left unchanged.
2189 
2190   For the standard row-based matrix formats, `idxm` can only contain rows owned by the requesting MPI process.
2191   That is, rows with global index greater than or equal to rstart and less than rend where rstart and rend are obtainable
2192   from `MatGetOwnershipRange`(mat,&rstart,&rend).
2193 
2194 .seealso: [](ch_matrices), `Mat`, `MatGetRow()`, `MatCreateSubMatrices()`, `MatSetValues()`, `MatGetOwnershipRange()`, `MatGetValuesLocal()`, `MatGetValue()`
2195 @*/
2196 PetscErrorCode MatGetValues(Mat mat, PetscInt m, const PetscInt idxm[], PetscInt n, const PetscInt idxn[], PetscScalar v[])
2197 {
2198   PetscFunctionBegin;
2199   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
2200   PetscValidType(mat, 1);
2201   if (!m || !n) PetscFunctionReturn(PETSC_SUCCESS);
2202   PetscAssertPointer(idxm, 3);
2203   PetscAssertPointer(idxn, 5);
2204   PetscAssertPointer(v, 6);
2205   PetscCheck(mat->assembled, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
2206   PetscCheck(!mat->factortype, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
2207   MatCheckPreallocated(mat, 1);
2208 
2209   PetscCall(PetscLogEventBegin(MAT_GetValues, mat, 0, 0, 0));
2210   PetscUseTypeMethod(mat, getvalues, m, idxm, n, idxn, v);
2211   PetscCall(PetscLogEventEnd(MAT_GetValues, mat, 0, 0, 0));
2212   PetscFunctionReturn(PETSC_SUCCESS);
2213 }
2214 
2215 /*@
2216   MatGetValuesLocal - retrieves values from certain locations in a matrix using the local numbering of the indices
2217   defined previously by `MatSetLocalToGlobalMapping()`
2218 
2219   Not Collective
2220 
2221   Input Parameters:
2222 + mat  - the matrix
2223 . nrow - number of rows
2224 . irow - the row local indices
2225 . ncol - number of columns
2226 - icol - the column local indices
2227 
2228   Output Parameter:
2229 . y - a one-dimensional array that contains the values implicitly stored as a two-dimensional array, by default in row-major order.
2230       See `MAT_ROW_ORIENTED` in `MatSetOption()` for how to use column-major order.
2231 
2232   Level: advanced
2233 
2234   Notes:
2235   If you create the matrix yourself (that is not with a call to `DMCreateMatrix()`) then you MUST call `MatSetLocalToGlobalMapping()` before using this routine.
2236 
2237   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,
2238   are greater than or equal to rstart and less than rend where rstart and rend are obtainable from `MatGetOwnershipRange`(mat,&rstart,&rend). One can
2239   determine if the resulting global row associated with the local row r is owned by the requesting MPI process by applying the `ISLocalToGlobalMapping` set
2240   with `MatSetLocalToGlobalMapping()`.
2241 
2242 .seealso: [](ch_matrices), `Mat`, `MatAssemblyBegin()`, `MatAssemblyEnd()`, `MatSetValues()`, `MatSetLocalToGlobalMapping()`,
2243           `MatSetValuesLocal()`, `MatGetValues()`
2244 @*/
2245 PetscErrorCode MatGetValuesLocal(Mat mat, PetscInt nrow, const PetscInt irow[], PetscInt ncol, const PetscInt icol[], PetscScalar y[])
2246 {
2247   PetscFunctionBeginHot;
2248   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
2249   PetscValidType(mat, 1);
2250   MatCheckPreallocated(mat, 1);
2251   if (!nrow || !ncol) PetscFunctionReturn(PETSC_SUCCESS); /* no values to retrieve */
2252   PetscAssertPointer(irow, 3);
2253   PetscAssertPointer(icol, 5);
2254   if (PetscDefined(USE_DEBUG)) {
2255     PetscCheck(!mat->factortype, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
2256     PetscCheck(mat->ops->getvalueslocal || mat->ops->getvalues, PETSC_COMM_SELF, PETSC_ERR_SUP, "Mat type %s", ((PetscObject)mat)->type_name);
2257   }
2258   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
2259   PetscCall(PetscLogEventBegin(MAT_GetValues, mat, 0, 0, 0));
2260   if (mat->ops->getvalueslocal) PetscUseTypeMethod(mat, getvalueslocal, nrow, irow, ncol, icol, y);
2261   else {
2262     PetscInt buf[8192], *bufr = NULL, *bufc = NULL, *irowm, *icolm;
2263     if ((nrow + ncol) <= (PetscInt)PETSC_STATIC_ARRAY_LENGTH(buf)) {
2264       irowm = buf;
2265       icolm = buf + nrow;
2266     } else {
2267       PetscCall(PetscMalloc2(nrow, &bufr, ncol, &bufc));
2268       irowm = bufr;
2269       icolm = bufc;
2270     }
2271     PetscCheck(mat->rmap->mapping, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "MatGetValuesLocal() cannot proceed without local-to-global row mapping (See MatSetLocalToGlobalMapping()).");
2272     PetscCheck(mat->cmap->mapping, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "MatGetValuesLocal() cannot proceed without local-to-global column mapping (See MatSetLocalToGlobalMapping()).");
2273     PetscCall(ISLocalToGlobalMappingApply(mat->rmap->mapping, nrow, irow, irowm));
2274     PetscCall(ISLocalToGlobalMappingApply(mat->cmap->mapping, ncol, icol, icolm));
2275     PetscCall(MatGetValues(mat, nrow, irowm, ncol, icolm, y));
2276     PetscCall(PetscFree2(bufr, bufc));
2277   }
2278   PetscCall(PetscLogEventEnd(MAT_GetValues, mat, 0, 0, 0));
2279   PetscFunctionReturn(PETSC_SUCCESS);
2280 }
2281 
2282 /*@
2283   MatSetValuesBatch - Adds (`ADD_VALUES`) many blocks of values into a matrix at once. The blocks must all be square and
2284   the same size. Currently, this can only be called once and creates the given matrix.
2285 
2286   Not Collective
2287 
2288   Input Parameters:
2289 + mat  - the matrix
2290 . nb   - the number of blocks
2291 . bs   - the number of rows (and columns) in each block
2292 . rows - a concatenation of the rows for each block
2293 - v    - a concatenation of logically two-dimensional arrays of values
2294 
2295   Level: advanced
2296 
2297   Notes:
2298   `MatSetPreallocationCOO()` and `MatSetValuesCOO()` may be a better way to provide the values
2299 
2300   In the future, we will extend this routine to handle rectangular blocks, and to allow multiple calls for a given matrix.
2301 
2302 .seealso: [](ch_matrices), `Mat`, `MatSetOption()`, `MatAssemblyBegin()`, `MatAssemblyEnd()`, `MatSetValuesBlocked()`, `MatSetValuesLocal()`,
2303           `InsertMode`, `INSERT_VALUES`, `ADD_VALUES`, `MatSetValues()`, `MatSetPreallocationCOO()`, `MatSetValuesCOO()`
2304 @*/
2305 PetscErrorCode MatSetValuesBatch(Mat mat, PetscInt nb, PetscInt bs, PetscInt rows[], const PetscScalar v[])
2306 {
2307   PetscFunctionBegin;
2308   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
2309   PetscValidType(mat, 1);
2310   PetscAssertPointer(rows, 4);
2311   PetscAssertPointer(v, 5);
2312   PetscAssert(!mat->factortype, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
2313 
2314   PetscCall(PetscLogEventBegin(MAT_SetValuesBatch, mat, 0, 0, 0));
2315   if (mat->ops->setvaluesbatch) PetscUseTypeMethod(mat, setvaluesbatch, nb, bs, rows, v);
2316   else {
2317     for (PetscInt b = 0; b < nb; ++b) PetscCall(MatSetValues(mat, bs, &rows[b * bs], bs, &rows[b * bs], &v[b * bs * bs], ADD_VALUES));
2318   }
2319   PetscCall(PetscLogEventEnd(MAT_SetValuesBatch, mat, 0, 0, 0));
2320   PetscFunctionReturn(PETSC_SUCCESS);
2321 }
2322 
2323 /*@
2324   MatSetLocalToGlobalMapping - Sets a local-to-global numbering for use by
2325   the routine `MatSetValuesLocal()` to allow users to insert matrix entries
2326   using a local (per-processor) numbering.
2327 
2328   Not Collective
2329 
2330   Input Parameters:
2331 + x        - the matrix
2332 . rmapping - row mapping created with `ISLocalToGlobalMappingCreate()` or `ISLocalToGlobalMappingCreateIS()`
2333 - cmapping - column mapping
2334 
2335   Level: intermediate
2336 
2337   Note:
2338   If the matrix is obtained with `DMCreateMatrix()` then this may already have been called on the matrix
2339 
2340 .seealso: [](ch_matrices), `Mat`, `DM`, `DMCreateMatrix()`, `MatGetLocalToGlobalMapping()`, `MatAssemblyBegin()`, `MatAssemblyEnd()`, `MatSetValues()`, `MatSetValuesLocal()`, `MatGetValuesLocal()`
2341 @*/
2342 PetscErrorCode MatSetLocalToGlobalMapping(Mat x, ISLocalToGlobalMapping rmapping, ISLocalToGlobalMapping cmapping)
2343 {
2344   PetscFunctionBegin;
2345   PetscValidHeaderSpecific(x, MAT_CLASSID, 1);
2346   PetscValidType(x, 1);
2347   if (rmapping) PetscValidHeaderSpecific(rmapping, IS_LTOGM_CLASSID, 2);
2348   if (cmapping) PetscValidHeaderSpecific(cmapping, IS_LTOGM_CLASSID, 3);
2349   if (x->ops->setlocaltoglobalmapping) PetscUseTypeMethod(x, setlocaltoglobalmapping, rmapping, cmapping);
2350   else {
2351     PetscCall(PetscLayoutSetISLocalToGlobalMapping(x->rmap, rmapping));
2352     PetscCall(PetscLayoutSetISLocalToGlobalMapping(x->cmap, cmapping));
2353   }
2354   PetscFunctionReturn(PETSC_SUCCESS);
2355 }
2356 
2357 /*@
2358   MatGetLocalToGlobalMapping - Gets the local-to-global numbering set by `MatSetLocalToGlobalMapping()`
2359 
2360   Not Collective
2361 
2362   Input Parameter:
2363 . A - the matrix
2364 
2365   Output Parameters:
2366 + rmapping - row mapping
2367 - cmapping - column mapping
2368 
2369   Level: advanced
2370 
2371 .seealso: [](ch_matrices), `Mat`, `MatSetLocalToGlobalMapping()`, `MatSetValuesLocal()`
2372 @*/
2373 PetscErrorCode MatGetLocalToGlobalMapping(Mat A, ISLocalToGlobalMapping *rmapping, ISLocalToGlobalMapping *cmapping)
2374 {
2375   PetscFunctionBegin;
2376   PetscValidHeaderSpecific(A, MAT_CLASSID, 1);
2377   PetscValidType(A, 1);
2378   if (rmapping) {
2379     PetscAssertPointer(rmapping, 2);
2380     *rmapping = A->rmap->mapping;
2381   }
2382   if (cmapping) {
2383     PetscAssertPointer(cmapping, 3);
2384     *cmapping = A->cmap->mapping;
2385   }
2386   PetscFunctionReturn(PETSC_SUCCESS);
2387 }
2388 
2389 /*@
2390   MatSetLayouts - Sets the `PetscLayout` objects for rows and columns of a matrix
2391 
2392   Logically Collective
2393 
2394   Input Parameters:
2395 + A    - the matrix
2396 . rmap - row layout
2397 - cmap - column layout
2398 
2399   Level: advanced
2400 
2401   Note:
2402   The `PetscLayout` objects are usually created automatically for the matrix so this routine rarely needs to be called.
2403 
2404 .seealso: [](ch_matrices), `Mat`, `PetscLayout`, `MatCreateVecs()`, `MatGetLocalToGlobalMapping()`, `MatGetLayouts()`
2405 @*/
2406 PetscErrorCode MatSetLayouts(Mat A, PetscLayout rmap, PetscLayout cmap)
2407 {
2408   PetscFunctionBegin;
2409   PetscValidHeaderSpecific(A, MAT_CLASSID, 1);
2410   PetscCall(PetscLayoutReference(rmap, &A->rmap));
2411   PetscCall(PetscLayoutReference(cmap, &A->cmap));
2412   PetscFunctionReturn(PETSC_SUCCESS);
2413 }
2414 
2415 /*@
2416   MatGetLayouts - Gets the `PetscLayout` objects for rows and columns
2417 
2418   Not Collective
2419 
2420   Input Parameter:
2421 . A - the matrix
2422 
2423   Output Parameters:
2424 + rmap - row layout
2425 - cmap - column layout
2426 
2427   Level: advanced
2428 
2429 .seealso: [](ch_matrices), `Mat`, [Matrix Layouts](sec_matlayout), `PetscLayout`, `MatCreateVecs()`, `MatGetLocalToGlobalMapping()`, `MatSetLayouts()`
2430 @*/
2431 PetscErrorCode MatGetLayouts(Mat A, PetscLayout *rmap, PetscLayout *cmap)
2432 {
2433   PetscFunctionBegin;
2434   PetscValidHeaderSpecific(A, MAT_CLASSID, 1);
2435   PetscValidType(A, 1);
2436   if (rmap) {
2437     PetscAssertPointer(rmap, 2);
2438     *rmap = A->rmap;
2439   }
2440   if (cmap) {
2441     PetscAssertPointer(cmap, 3);
2442     *cmap = A->cmap;
2443   }
2444   PetscFunctionReturn(PETSC_SUCCESS);
2445 }
2446 
2447 /*@
2448   MatSetValuesLocal - Inserts or adds values into certain locations of a matrix,
2449   using a local numbering of the rows and columns.
2450 
2451   Not Collective
2452 
2453   Input Parameters:
2454 + mat  - the matrix
2455 . nrow - number of rows
2456 . irow - the row local indices
2457 . ncol - number of columns
2458 . icol - the column local indices
2459 . y    - a one-dimensional array that contains the values implicitly stored as a two-dimensional array, by default in row-major order.
2460          See `MAT_ROW_ORIENTED` in `MatSetOption()` for how to use column-major order.
2461 - addv - either `ADD_VALUES` to add values to any existing entries, or `INSERT_VALUES` to replace existing entries with new values
2462 
2463   Level: intermediate
2464 
2465   Notes:
2466   If you create the matrix yourself (that is not with a call to `DMCreateMatrix()`) then you MUST call `MatSetLocalToGlobalMapping()` before using this routine
2467 
2468   Calls to `MatSetValuesLocal()` with the `INSERT_VALUES` and `ADD_VALUES`
2469   options cannot be mixed without intervening calls to the assembly
2470   routines.
2471 
2472   These values may be cached, so `MatAssemblyBegin()` and `MatAssemblyEnd()`
2473   MUST be called after all calls to `MatSetValuesLocal()` have been completed.
2474 
2475   Fortran Notes:
2476   If any of `irow`, `icol`, and `y` are scalars pass them using, for example,
2477 .vb
2478   call MatSetValuesLocal(mat, one, [irow], one, [icol], [y], INSERT_VALUES, ierr)
2479 .ve
2480 
2481   If `y` is a two-dimensional array use `reshape()` to pass it as a one dimensional array
2482 
2483 .seealso: [](ch_matrices), `Mat`, `MatAssemblyBegin()`, `MatAssemblyEnd()`, `MatSetValues()`, `MatSetLocalToGlobalMapping()`,
2484           `MatGetValuesLocal()`
2485 @*/
2486 PetscErrorCode MatSetValuesLocal(Mat mat, PetscInt nrow, const PetscInt irow[], PetscInt ncol, const PetscInt icol[], const PetscScalar y[], InsertMode addv)
2487 {
2488   PetscFunctionBeginHot;
2489   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
2490   PetscValidType(mat, 1);
2491   MatCheckPreallocated(mat, 1);
2492   if (!nrow || !ncol) PetscFunctionReturn(PETSC_SUCCESS); /* no values to insert */
2493   PetscAssertPointer(irow, 3);
2494   PetscAssertPointer(icol, 5);
2495   if (mat->insertmode == NOT_SET_VALUES) mat->insertmode = addv;
2496   else PetscCheck(mat->insertmode == addv, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Cannot mix add values and insert values");
2497   if (PetscDefined(USE_DEBUG)) {
2498     PetscCheck(!mat->factortype, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
2499     PetscCheck(mat->ops->setvalueslocal || mat->ops->setvalues, PETSC_COMM_SELF, PETSC_ERR_SUP, "Mat type %s", ((PetscObject)mat)->type_name);
2500   }
2501 
2502   if (mat->assembled) {
2503     mat->was_assembled = PETSC_TRUE;
2504     mat->assembled     = PETSC_FALSE;
2505   }
2506   PetscCall(PetscLogEventBegin(MAT_SetValues, mat, 0, 0, 0));
2507   if (mat->ops->setvalueslocal) PetscUseTypeMethod(mat, setvalueslocal, nrow, irow, ncol, icol, y, addv);
2508   else {
2509     PetscInt        buf[8192], *bufr = NULL, *bufc = NULL;
2510     const PetscInt *irowm, *icolm;
2511 
2512     if ((!mat->rmap->mapping && !mat->cmap->mapping) || (nrow + ncol) <= (PetscInt)PETSC_STATIC_ARRAY_LENGTH(buf)) {
2513       bufr  = buf;
2514       bufc  = buf + nrow;
2515       irowm = bufr;
2516       icolm = bufc;
2517     } else {
2518       PetscCall(PetscMalloc2(nrow, &bufr, ncol, &bufc));
2519       irowm = bufr;
2520       icolm = bufc;
2521     }
2522     if (mat->rmap->mapping) PetscCall(ISLocalToGlobalMappingApply(mat->rmap->mapping, nrow, irow, bufr));
2523     else irowm = irow;
2524     if (mat->cmap->mapping) {
2525       if (mat->cmap->mapping != mat->rmap->mapping || ncol != nrow || icol != irow) PetscCall(ISLocalToGlobalMappingApply(mat->cmap->mapping, ncol, icol, bufc));
2526       else icolm = irowm;
2527     } else icolm = icol;
2528     PetscCall(MatSetValues(mat, nrow, irowm, ncol, icolm, y, addv));
2529     if (bufr != buf) PetscCall(PetscFree2(bufr, bufc));
2530   }
2531   PetscCall(PetscLogEventEnd(MAT_SetValues, mat, 0, 0, 0));
2532   PetscFunctionReturn(PETSC_SUCCESS);
2533 }
2534 
2535 /*@
2536   MatSetValuesBlockedLocal - Inserts or adds values into certain locations of a matrix,
2537   using a local ordering of the nodes a block at a time.
2538 
2539   Not Collective
2540 
2541   Input Parameters:
2542 + mat  - the matrix
2543 . nrow - number of rows
2544 . irow - the row local indices
2545 . ncol - number of columns
2546 . icol - the column local indices
2547 . y    - a one-dimensional array that contains the values implicitly stored as a two-dimensional array, by default in row-major order.
2548          See `MAT_ROW_ORIENTED` in `MatSetOption()` for how to use column-major order.
2549 - addv - either `ADD_VALUES` to add values to any existing entries, or `INSERT_VALUES` to replace existing entries with new values
2550 
2551   Level: intermediate
2552 
2553   Notes:
2554   If you create the matrix yourself (that is not with a call to `DMCreateMatrix()`) then you MUST call `MatSetBlockSize()` and `MatSetLocalToGlobalMapping()`
2555   before using this routineBefore calling `MatSetValuesLocal()`, the user must first set the
2556 
2557   Calls to `MatSetValuesBlockedLocal()` with the `INSERT_VALUES` and `ADD_VALUES`
2558   options cannot be mixed without intervening calls to the assembly
2559   routines.
2560 
2561   These values may be cached, so `MatAssemblyBegin()` and `MatAssemblyEnd()`
2562   MUST be called after all calls to `MatSetValuesBlockedLocal()` have been completed.
2563 
2564   Fortran Notes:
2565   If any of `irow`, `icol`, and `y` are scalars pass them using, for example,
2566 .vb
2567   call MatSetValuesBlockedLocal(mat, one, [irow], one, [icol], [y], INSERT_VALUES, ierr)
2568 .ve
2569 
2570   If `y` is a two-dimensional array use `reshape()` to pass it as a one dimensional array
2571 
2572 .seealso: [](ch_matrices), `Mat`, `MatSetBlockSize()`, `MatSetLocalToGlobalMapping()`, `MatAssemblyBegin()`, `MatAssemblyEnd()`,
2573           `MatSetValuesLocal()`, `MatSetValuesBlocked()`
2574 @*/
2575 PetscErrorCode MatSetValuesBlockedLocal(Mat mat, PetscInt nrow, const PetscInt irow[], PetscInt ncol, const PetscInt icol[], const PetscScalar y[], InsertMode addv)
2576 {
2577   PetscFunctionBeginHot;
2578   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
2579   PetscValidType(mat, 1);
2580   MatCheckPreallocated(mat, 1);
2581   if (!nrow || !ncol) PetscFunctionReturn(PETSC_SUCCESS); /* no values to insert */
2582   PetscAssertPointer(irow, 3);
2583   PetscAssertPointer(icol, 5);
2584   if (mat->insertmode == NOT_SET_VALUES) mat->insertmode = addv;
2585   else PetscCheck(mat->insertmode == addv, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Cannot mix add values and insert values");
2586   if (PetscDefined(USE_DEBUG)) {
2587     PetscCheck(!mat->factortype, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
2588     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);
2589   }
2590 
2591   if (mat->assembled) {
2592     mat->was_assembled = PETSC_TRUE;
2593     mat->assembled     = PETSC_FALSE;
2594   }
2595   if (PetscUnlikelyDebug(mat->rmap->mapping)) { /* Condition on the mapping existing, because MatSetValuesBlockedLocal_IS does not require it to be set. */
2596     PetscInt irbs, rbs;
2597     PetscCall(MatGetBlockSizes(mat, &rbs, NULL));
2598     PetscCall(ISLocalToGlobalMappingGetBlockSize(mat->rmap->mapping, &irbs));
2599     PetscCheck(rbs == irbs, PetscObjectComm((PetscObject)mat), PETSC_ERR_SUP, "Different row block sizes! mat %" PetscInt_FMT ", row l2g map %" PetscInt_FMT, rbs, irbs);
2600   }
2601   if (PetscUnlikelyDebug(mat->cmap->mapping)) {
2602     PetscInt icbs, cbs;
2603     PetscCall(MatGetBlockSizes(mat, NULL, &cbs));
2604     PetscCall(ISLocalToGlobalMappingGetBlockSize(mat->cmap->mapping, &icbs));
2605     PetscCheck(cbs == icbs, PetscObjectComm((PetscObject)mat), PETSC_ERR_SUP, "Different col block sizes! mat %" PetscInt_FMT ", col l2g map %" PetscInt_FMT, cbs, icbs);
2606   }
2607   PetscCall(PetscLogEventBegin(MAT_SetValues, mat, 0, 0, 0));
2608   if (mat->ops->setvaluesblockedlocal) PetscUseTypeMethod(mat, setvaluesblockedlocal, nrow, irow, ncol, icol, y, addv);
2609   else {
2610     PetscInt        buf[8192], *bufr = NULL, *bufc = NULL;
2611     const PetscInt *irowm, *icolm;
2612 
2613     if ((!mat->rmap->mapping && !mat->cmap->mapping) || (nrow + ncol) <= ((PetscInt)PETSC_STATIC_ARRAY_LENGTH(buf))) {
2614       bufr  = buf;
2615       bufc  = buf + nrow;
2616       irowm = bufr;
2617       icolm = bufc;
2618     } else {
2619       PetscCall(PetscMalloc2(nrow, &bufr, ncol, &bufc));
2620       irowm = bufr;
2621       icolm = bufc;
2622     }
2623     if (mat->rmap->mapping) PetscCall(ISLocalToGlobalMappingApplyBlock(mat->rmap->mapping, nrow, irow, bufr));
2624     else irowm = irow;
2625     if (mat->cmap->mapping) {
2626       if (mat->cmap->mapping != mat->rmap->mapping || ncol != nrow || icol != irow) PetscCall(ISLocalToGlobalMappingApplyBlock(mat->cmap->mapping, ncol, icol, bufc));
2627       else icolm = irowm;
2628     } else icolm = icol;
2629     PetscCall(MatSetValuesBlocked(mat, nrow, irowm, ncol, icolm, y, addv));
2630     if (bufr != buf) PetscCall(PetscFree2(bufr, bufc));
2631   }
2632   PetscCall(PetscLogEventEnd(MAT_SetValues, mat, 0, 0, 0));
2633   PetscFunctionReturn(PETSC_SUCCESS);
2634 }
2635 
2636 /*@
2637   MatMultDiagonalBlock - Computes the matrix-vector product, $y = Dx$. Where `D` is defined by the inode or block structure of the diagonal
2638 
2639   Collective
2640 
2641   Input Parameters:
2642 + mat - the matrix
2643 - x   - the vector to be multiplied
2644 
2645   Output Parameter:
2646 . y - the result
2647 
2648   Level: developer
2649 
2650   Note:
2651   The vectors `x` and `y` cannot be the same.  I.e., one cannot
2652   call `MatMultDiagonalBlock`(A,y,y).
2653 
2654 .seealso: [](ch_matrices), `Mat`, `MatMult()`, `MatMultTranspose()`, `MatMultAdd()`, `MatMultTransposeAdd()`
2655 @*/
2656 PetscErrorCode MatMultDiagonalBlock(Mat mat, Vec x, Vec y)
2657 {
2658   PetscFunctionBegin;
2659   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
2660   PetscValidType(mat, 1);
2661   PetscValidHeaderSpecific(x, VEC_CLASSID, 2);
2662   PetscValidHeaderSpecific(y, VEC_CLASSID, 3);
2663 
2664   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
2665   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
2666   PetscCheck(x != y, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "x and y must be different vectors");
2667   MatCheckPreallocated(mat, 1);
2668 
2669   PetscUseTypeMethod(mat, multdiagonalblock, x, y);
2670   PetscCall(PetscObjectStateIncrease((PetscObject)y));
2671   PetscFunctionReturn(PETSC_SUCCESS);
2672 }
2673 
2674 /*@
2675   MatMult - Computes the matrix-vector product, $y = Ax$.
2676 
2677   Neighbor-wise Collective
2678 
2679   Input Parameters:
2680 + mat - the matrix
2681 - x   - the vector to be multiplied
2682 
2683   Output Parameter:
2684 . y - the result
2685 
2686   Level: beginner
2687 
2688   Note:
2689   The vectors `x` and `y` cannot be the same.  I.e., one cannot
2690   call `MatMult`(A,y,y).
2691 
2692 .seealso: [](ch_matrices), `Mat`, `MatMultTranspose()`, `MatMultAdd()`, `MatMultTransposeAdd()`
2693 @*/
2694 PetscErrorCode MatMult(Mat mat, Vec x, Vec y)
2695 {
2696   PetscFunctionBegin;
2697   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
2698   PetscValidType(mat, 1);
2699   PetscValidHeaderSpecific(x, VEC_CLASSID, 2);
2700   VecCheckAssembled(x);
2701   PetscValidHeaderSpecific(y, VEC_CLASSID, 3);
2702   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
2703   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
2704   PetscCheck(x != y, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "x and y must be different vectors");
2705   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);
2706   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);
2707   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);
2708   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);
2709   PetscCall(VecSetErrorIfLocked(y, 3));
2710   if (mat->erroriffailure) PetscCall(VecValidValues_Internal(x, 2, PETSC_TRUE));
2711   MatCheckPreallocated(mat, 1);
2712 
2713   PetscCall(VecLockReadPush(x));
2714   PetscCall(PetscLogEventBegin(MAT_Mult, mat, x, y, 0));
2715   PetscUseTypeMethod(mat, mult, x, y);
2716   PetscCall(PetscLogEventEnd(MAT_Mult, mat, x, y, 0));
2717   if (mat->erroriffailure) PetscCall(VecValidValues_Internal(y, 3, PETSC_FALSE));
2718   PetscCall(VecLockReadPop(x));
2719   PetscFunctionReturn(PETSC_SUCCESS);
2720 }
2721 
2722 /*@
2723   MatMultTranspose - Computes matrix transpose times a vector $y = A^T * x$.
2724 
2725   Neighbor-wise Collective
2726 
2727   Input Parameters:
2728 + mat - the matrix
2729 - x   - the vector to be multiplied
2730 
2731   Output Parameter:
2732 . y - the result
2733 
2734   Level: beginner
2735 
2736   Notes:
2737   The vectors `x` and `y` cannot be the same.  I.e., one cannot
2738   call `MatMultTranspose`(A,y,y).
2739 
2740   For complex numbers this does NOT compute the Hermitian (complex conjugate) transpose multiple,
2741   use `MatMultHermitianTranspose()`
2742 
2743 .seealso: [](ch_matrices), `Mat`, `MatMult()`, `MatMultAdd()`, `MatMultTransposeAdd()`, `MatMultHermitianTranspose()`, `MatTranspose()`
2744 @*/
2745 PetscErrorCode MatMultTranspose(Mat mat, Vec x, Vec y)
2746 {
2747   PetscErrorCode (*op)(Mat, Vec, Vec) = NULL;
2748 
2749   PetscFunctionBegin;
2750   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
2751   PetscValidType(mat, 1);
2752   PetscValidHeaderSpecific(x, VEC_CLASSID, 2);
2753   VecCheckAssembled(x);
2754   PetscValidHeaderSpecific(y, VEC_CLASSID, 3);
2755 
2756   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
2757   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
2758   PetscCheck(x != y, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "x and y must be different vectors");
2759   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);
2760   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);
2761   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);
2762   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);
2763   if (mat->erroriffailure) PetscCall(VecValidValues_Internal(x, 2, PETSC_TRUE));
2764   MatCheckPreallocated(mat, 1);
2765 
2766   if (!mat->ops->multtranspose) {
2767     if (mat->symmetric == PETSC_BOOL3_TRUE && mat->ops->mult) op = mat->ops->mult;
2768     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);
2769   } else op = mat->ops->multtranspose;
2770   PetscCall(PetscLogEventBegin(MAT_MultTranspose, mat, x, y, 0));
2771   PetscCall(VecLockReadPush(x));
2772   PetscCall((*op)(mat, x, y));
2773   PetscCall(VecLockReadPop(x));
2774   PetscCall(PetscLogEventEnd(MAT_MultTranspose, mat, x, y, 0));
2775   PetscCall(PetscObjectStateIncrease((PetscObject)y));
2776   if (mat->erroriffailure) PetscCall(VecValidValues_Internal(y, 3, PETSC_FALSE));
2777   PetscFunctionReturn(PETSC_SUCCESS);
2778 }
2779 
2780 /*@
2781   MatMultHermitianTranspose - Computes matrix Hermitian-transpose times a vector $y = A^H * x$.
2782 
2783   Neighbor-wise Collective
2784 
2785   Input Parameters:
2786 + mat - the matrix
2787 - x   - the vector to be multiplied
2788 
2789   Output Parameter:
2790 . y - the result
2791 
2792   Level: beginner
2793 
2794   Notes:
2795   The vectors `x` and `y` cannot be the same.  I.e., one cannot
2796   call `MatMultHermitianTranspose`(A,y,y).
2797 
2798   Also called the conjugate transpose, complex conjugate transpose, or adjoint.
2799 
2800   For real numbers `MatMultTranspose()` and `MatMultHermitianTranspose()` are identical.
2801 
2802 .seealso: [](ch_matrices), `Mat`, `MatMult()`, `MatMultAdd()`, `MatMultHermitianTransposeAdd()`, `MatMultTranspose()`
2803 @*/
2804 PetscErrorCode MatMultHermitianTranspose(Mat mat, Vec x, Vec y)
2805 {
2806   PetscFunctionBegin;
2807   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
2808   PetscValidType(mat, 1);
2809   PetscValidHeaderSpecific(x, VEC_CLASSID, 2);
2810   PetscValidHeaderSpecific(y, VEC_CLASSID, 3);
2811 
2812   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
2813   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
2814   PetscCheck(x != y, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "x and y must be different vectors");
2815   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);
2816   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);
2817   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);
2818   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);
2819   MatCheckPreallocated(mat, 1);
2820 
2821   PetscCall(PetscLogEventBegin(MAT_MultHermitianTranspose, mat, x, y, 0));
2822 #if defined(PETSC_USE_COMPLEX)
2823   if (mat->ops->multhermitiantranspose || (mat->hermitian == PETSC_BOOL3_TRUE && mat->ops->mult)) {
2824     PetscCall(VecLockReadPush(x));
2825     if (mat->ops->multhermitiantranspose) PetscUseTypeMethod(mat, multhermitiantranspose, x, y);
2826     else PetscUseTypeMethod(mat, mult, x, y);
2827     PetscCall(VecLockReadPop(x));
2828   } else {
2829     Vec w;
2830     PetscCall(VecDuplicate(x, &w));
2831     PetscCall(VecCopy(x, w));
2832     PetscCall(VecConjugate(w));
2833     PetscCall(MatMultTranspose(mat, w, y));
2834     PetscCall(VecDestroy(&w));
2835     PetscCall(VecConjugate(y));
2836   }
2837   PetscCall(PetscObjectStateIncrease((PetscObject)y));
2838 #else
2839   PetscCall(MatMultTranspose(mat, x, y));
2840 #endif
2841   PetscCall(PetscLogEventEnd(MAT_MultHermitianTranspose, mat, x, y, 0));
2842   PetscFunctionReturn(PETSC_SUCCESS);
2843 }
2844 
2845 /*@
2846   MatMultAdd -  Computes $v3 = v2 + A * v1$.
2847 
2848   Neighbor-wise Collective
2849 
2850   Input Parameters:
2851 + mat - the matrix
2852 . v1  - the vector to be multiplied by `mat`
2853 - v2  - the vector to be added to the result
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 `MatMultAdd`(A,v1,v2,v1).
2863 
2864 .seealso: [](ch_matrices), `Mat`, `MatMultTranspose()`, `MatMult()`, `MatMultTransposeAdd()`
2865 @*/
2866 PetscErrorCode MatMultAdd(Mat mat, Vec v1, Vec v2, Vec v3)
2867 {
2868   PetscFunctionBegin;
2869   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
2870   PetscValidType(mat, 1);
2871   PetscValidHeaderSpecific(v1, VEC_CLASSID, 2);
2872   PetscValidHeaderSpecific(v2, VEC_CLASSID, 3);
2873   PetscValidHeaderSpecific(v3, VEC_CLASSID, 4);
2874 
2875   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
2876   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
2877   PetscCheck(mat->cmap->N == v1->map->N, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_SIZ, "Mat mat,Vec v1: global dim %" PetscInt_FMT " %" PetscInt_FMT, mat->cmap->N, v1->map->N);
2878   /* PetscCheck(mat->rmap->N == v2->map->N,PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Mat mat,Vec v2: global dim %" PetscInt_FMT " %" PetscInt_FMT,mat->rmap->N,v2->map->N);
2879      PetscCheck(mat->rmap->N == v3->map->N,PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Mat mat,Vec v3: global dim %" PetscInt_FMT " %" PetscInt_FMT,mat->rmap->N,v3->map->N); */
2880   PetscCheck(mat->rmap->n == v3->map->n, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Mat mat,Vec v3: local dim %" PetscInt_FMT " %" PetscInt_FMT, mat->rmap->n, v3->map->n);
2881   PetscCheck(mat->rmap->n == v2->map->n, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Mat mat,Vec v2: local dim %" PetscInt_FMT " %" PetscInt_FMT, mat->rmap->n, v2->map->n);
2882   PetscCheck(v1 != v3, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_IDN, "v1 and v3 must be different vectors");
2883   MatCheckPreallocated(mat, 1);
2884 
2885   PetscCall(PetscLogEventBegin(MAT_MultAdd, mat, v1, v2, v3));
2886   PetscCall(VecLockReadPush(v1));
2887   PetscUseTypeMethod(mat, multadd, v1, v2, v3);
2888   PetscCall(VecLockReadPop(v1));
2889   PetscCall(PetscLogEventEnd(MAT_MultAdd, mat, v1, v2, v3));
2890   PetscCall(PetscObjectStateIncrease((PetscObject)v3));
2891   PetscFunctionReturn(PETSC_SUCCESS);
2892 }
2893 
2894 /*@
2895   MatMultTransposeAdd - Computes $v3 = v2 + A^T * v1$.
2896 
2897   Neighbor-wise Collective
2898 
2899   Input Parameters:
2900 + mat - the matrix
2901 . v1  - the vector to be multiplied by the transpose of the matrix
2902 - v2  - the vector to be added to the result
2903 
2904   Output Parameter:
2905 . v3 - the result
2906 
2907   Level: beginner
2908 
2909   Note:
2910   The vectors `v1` and `v3` cannot be the same.  I.e., one cannot
2911   call `MatMultTransposeAdd`(A,v1,v2,v1).
2912 
2913 .seealso: [](ch_matrices), `Mat`, `MatMultTranspose()`, `MatMultAdd()`, `MatMult()`
2914 @*/
2915 PetscErrorCode MatMultTransposeAdd(Mat mat, Vec v1, Vec v2, Vec v3)
2916 {
2917   PetscErrorCode (*op)(Mat, Vec, Vec, Vec) = (!mat->ops->multtransposeadd && mat->symmetric) ? mat->ops->multadd : mat->ops->multtransposeadd;
2918 
2919   PetscFunctionBegin;
2920   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
2921   PetscValidType(mat, 1);
2922   PetscValidHeaderSpecific(v1, VEC_CLASSID, 2);
2923   PetscValidHeaderSpecific(v2, VEC_CLASSID, 3);
2924   PetscValidHeaderSpecific(v3, VEC_CLASSID, 4);
2925 
2926   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
2927   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
2928   PetscCheck(mat->rmap->N == v1->map->N, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_SIZ, "Mat mat,Vec v1: global dim %" PetscInt_FMT " %" PetscInt_FMT, mat->rmap->N, v1->map->N);
2929   PetscCheck(mat->cmap->N == v2->map->N, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_SIZ, "Mat mat,Vec v2: global dim %" PetscInt_FMT " %" PetscInt_FMT, mat->cmap->N, v2->map->N);
2930   PetscCheck(mat->cmap->N == v3->map->N, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_SIZ, "Mat mat,Vec v3: global dim %" PetscInt_FMT " %" PetscInt_FMT, mat->cmap->N, v3->map->N);
2931   PetscCheck(v1 != v3, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_IDN, "v1 and v3 must be different vectors");
2932   PetscCheck(op, PetscObjectComm((PetscObject)mat), PETSC_ERR_SUP, "Mat type %s", ((PetscObject)mat)->type_name);
2933   MatCheckPreallocated(mat, 1);
2934 
2935   PetscCall(PetscLogEventBegin(MAT_MultTransposeAdd, mat, v1, v2, v3));
2936   PetscCall(VecLockReadPush(v1));
2937   PetscCall((*op)(mat, v1, v2, v3));
2938   PetscCall(VecLockReadPop(v1));
2939   PetscCall(PetscLogEventEnd(MAT_MultTransposeAdd, mat, v1, v2, v3));
2940   PetscCall(PetscObjectStateIncrease((PetscObject)v3));
2941   PetscFunctionReturn(PETSC_SUCCESS);
2942 }
2943 
2944 /*@
2945   MatMultHermitianTransposeAdd - Computes $v3 = v2 + A^H * v1$.
2946 
2947   Neighbor-wise Collective
2948 
2949   Input Parameters:
2950 + mat - the matrix
2951 . v1  - the vector to be multiplied by the Hermitian transpose
2952 - v2  - the vector to be added to the result
2953 
2954   Output Parameter:
2955 . v3 - the result
2956 
2957   Level: beginner
2958 
2959   Note:
2960   The vectors `v1` and `v3` cannot be the same.  I.e., one cannot
2961   call `MatMultHermitianTransposeAdd`(A,v1,v2,v1).
2962 
2963 .seealso: [](ch_matrices), `Mat`, `MatMultHermitianTranspose()`, `MatMultTranspose()`, `MatMultAdd()`, `MatMult()`
2964 @*/
2965 PetscErrorCode MatMultHermitianTransposeAdd(Mat mat, Vec v1, Vec v2, Vec v3)
2966 {
2967   PetscFunctionBegin;
2968   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
2969   PetscValidType(mat, 1);
2970   PetscValidHeaderSpecific(v1, VEC_CLASSID, 2);
2971   PetscValidHeaderSpecific(v2, VEC_CLASSID, 3);
2972   PetscValidHeaderSpecific(v3, VEC_CLASSID, 4);
2973 
2974   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
2975   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
2976   PetscCheck(v1 != v3, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_IDN, "v1 and v3 must be different vectors");
2977   PetscCheck(mat->rmap->N == v1->map->N, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_SIZ, "Mat mat,Vec v1: global dim %" PetscInt_FMT " %" PetscInt_FMT, mat->rmap->N, v1->map->N);
2978   PetscCheck(mat->cmap->N == v2->map->N, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_SIZ, "Mat mat,Vec v2: global dim %" PetscInt_FMT " %" PetscInt_FMT, mat->cmap->N, v2->map->N);
2979   PetscCheck(mat->cmap->N == v3->map->N, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_SIZ, "Mat mat,Vec v3: global dim %" PetscInt_FMT " %" PetscInt_FMT, mat->cmap->N, v3->map->N);
2980   MatCheckPreallocated(mat, 1);
2981 
2982   PetscCall(PetscLogEventBegin(MAT_MultHermitianTransposeAdd, mat, v1, v2, v3));
2983   PetscCall(VecLockReadPush(v1));
2984   if (mat->ops->multhermitiantransposeadd) PetscUseTypeMethod(mat, multhermitiantransposeadd, v1, v2, v3);
2985   else {
2986     Vec w, z;
2987     PetscCall(VecDuplicate(v1, &w));
2988     PetscCall(VecCopy(v1, w));
2989     PetscCall(VecConjugate(w));
2990     PetscCall(VecDuplicate(v3, &z));
2991     PetscCall(MatMultTranspose(mat, w, z));
2992     PetscCall(VecDestroy(&w));
2993     PetscCall(VecConjugate(z));
2994     if (v2 != v3) {
2995       PetscCall(VecWAXPY(v3, 1.0, v2, z));
2996     } else {
2997       PetscCall(VecAXPY(v3, 1.0, z));
2998     }
2999     PetscCall(VecDestroy(&z));
3000   }
3001   PetscCall(VecLockReadPop(v1));
3002   PetscCall(PetscLogEventEnd(MAT_MultHermitianTransposeAdd, mat, v1, v2, v3));
3003   PetscCall(PetscObjectStateIncrease((PetscObject)v3));
3004   PetscFunctionReturn(PETSC_SUCCESS);
3005 }
3006 
3007 /*@
3008   MatGetFactorType - gets the type of factorization a matrix is
3009 
3010   Not Collective
3011 
3012   Input Parameter:
3013 . mat - the matrix
3014 
3015   Output Parameter:
3016 . 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`
3017 
3018   Level: intermediate
3019 
3020 .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatFactorType`, `MatGetFactor()`, `MatSetFactorType()`, `MAT_FACTOR_NONE`, `MAT_FACTOR_LU`, `MAT_FACTOR_CHOLESKY`, `MAT_FACTOR_ILU`,
3021           `MAT_FACTOR_ICC`,`MAT_FACTOR_ILUDT`, `MAT_FACTOR_QR`
3022 @*/
3023 PetscErrorCode MatGetFactorType(Mat mat, MatFactorType *t)
3024 {
3025   PetscFunctionBegin;
3026   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
3027   PetscValidType(mat, 1);
3028   PetscAssertPointer(t, 2);
3029   *t = mat->factortype;
3030   PetscFunctionReturn(PETSC_SUCCESS);
3031 }
3032 
3033 /*@
3034   MatSetFactorType - sets the type of factorization a matrix is
3035 
3036   Logically Collective
3037 
3038   Input Parameters:
3039 + mat - the matrix
3040 - 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`
3041 
3042   Level: intermediate
3043 
3044 .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatFactorType`, `MatGetFactor()`, `MatGetFactorType()`, `MAT_FACTOR_NONE`, `MAT_FACTOR_LU`, `MAT_FACTOR_CHOLESKY`, `MAT_FACTOR_ILU`,
3045           `MAT_FACTOR_ICC`,`MAT_FACTOR_ILUDT`, `MAT_FACTOR_QR`
3046 @*/
3047 PetscErrorCode MatSetFactorType(Mat mat, MatFactorType t)
3048 {
3049   PetscFunctionBegin;
3050   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
3051   PetscValidType(mat, 1);
3052   mat->factortype = t;
3053   PetscFunctionReturn(PETSC_SUCCESS);
3054 }
3055 
3056 /*@
3057   MatGetInfo - Returns information about matrix storage (number of
3058   nonzeros, memory, etc.).
3059 
3060   Collective if `MAT_GLOBAL_MAX` or `MAT_GLOBAL_SUM` is used as the flag
3061 
3062   Input Parameters:
3063 + mat  - the matrix
3064 - 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)
3065 
3066   Output Parameter:
3067 . info - matrix information context
3068 
3069   Options Database Key:
3070 . -mat_view ::ascii_info - print matrix info to `PETSC_STDOUT`
3071 
3072   Level: intermediate
3073 
3074   Notes:
3075   The `MatInfo` context contains a variety of matrix data, including
3076   number of nonzeros allocated and used, number of mallocs during
3077   matrix assembly, etc.  Additional information for factored matrices
3078   is provided (such as the fill ratio, number of mallocs during
3079   factorization, etc.).
3080 
3081   Example:
3082   See the file ${PETSC_DIR}/include/petscmat.h for a complete list of
3083   data within the `MatInfo` context.  For example,
3084 .vb
3085       MatInfo info;
3086       Mat     A;
3087       double  mal, nz_a, nz_u;
3088 
3089       MatGetInfo(A, MAT_LOCAL, &info);
3090       mal  = info.mallocs;
3091       nz_a = info.nz_allocated;
3092 .ve
3093 
3094 .seealso: [](ch_matrices), `Mat`, `MatInfo`, `MatStashGetInfo()`
3095 @*/
3096 PetscErrorCode MatGetInfo(Mat mat, MatInfoType flag, MatInfo *info)
3097 {
3098   PetscFunctionBegin;
3099   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
3100   PetscValidType(mat, 1);
3101   PetscAssertPointer(info, 3);
3102   MatCheckPreallocated(mat, 1);
3103   PetscUseTypeMethod(mat, getinfo, flag, info);
3104   PetscFunctionReturn(PETSC_SUCCESS);
3105 }
3106 
3107 /*
3108    This is used by external packages where it is not easy to get the info from the actual
3109    matrix factorization.
3110 */
3111 PetscErrorCode MatGetInfo_External(Mat A, MatInfoType flag, MatInfo *info)
3112 {
3113   PetscFunctionBegin;
3114   PetscCall(PetscMemzero(info, sizeof(MatInfo)));
3115   PetscFunctionReturn(PETSC_SUCCESS);
3116 }
3117 
3118 /*@
3119   MatLUFactor - Performs in-place LU factorization of matrix.
3120 
3121   Collective
3122 
3123   Input Parameters:
3124 + mat  - the matrix
3125 . row  - row permutation
3126 . col  - column permutation
3127 - info - options for factorization, includes
3128 .vb
3129           fill - expected fill as ratio of original fill.
3130           dtcol - pivot tolerance (0 no pivot, 1 full column pivoting)
3131                    Run with the option -info to determine an optimal value to use
3132 .ve
3133 
3134   Level: developer
3135 
3136   Notes:
3137   Most users should employ the `KSP` interface for linear solvers
3138   instead of working directly with matrix algebra routines such as this.
3139   See, e.g., `KSPCreate()`.
3140 
3141   This changes the state of the matrix to a factored matrix; it cannot be used
3142   for example with `MatSetValues()` unless one first calls `MatSetUnfactored()`.
3143 
3144   This is really in-place only for dense matrices, the preferred approach is to use `MatGetFactor()`, `MatLUFactorSymbolic()`, and `MatLUFactorNumeric()`
3145   when not using `KSP`.
3146 
3147   Fortran Note:
3148   A valid (non-null) `info` argument must be provided
3149 
3150 .seealso: [](ch_matrices), [Matrix Factorization](sec_matfactor), `Mat`, `MatFactorType`, `MatLUFactorSymbolic()`, `MatLUFactorNumeric()`, `MatCholeskyFactor()`,
3151           `MatGetOrdering()`, `MatSetUnfactored()`, `MatFactorInfo`, `MatGetFactor()`
3152 @*/
3153 PetscErrorCode MatLUFactor(Mat mat, IS row, IS col, const MatFactorInfo *info)
3154 {
3155   MatFactorInfo tinfo;
3156 
3157   PetscFunctionBegin;
3158   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
3159   if (row) PetscValidHeaderSpecific(row, IS_CLASSID, 2);
3160   if (col) PetscValidHeaderSpecific(col, IS_CLASSID, 3);
3161   if (info) PetscAssertPointer(info, 4);
3162   PetscValidType(mat, 1);
3163   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
3164   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
3165   MatCheckPreallocated(mat, 1);
3166   if (!info) {
3167     PetscCall(MatFactorInfoInitialize(&tinfo));
3168     info = &tinfo;
3169   }
3170 
3171   PetscCall(PetscLogEventBegin(MAT_LUFactor, mat, row, col, 0));
3172   PetscUseTypeMethod(mat, lufactor, row, col, info);
3173   PetscCall(PetscLogEventEnd(MAT_LUFactor, mat, row, col, 0));
3174   PetscCall(PetscObjectStateIncrease((PetscObject)mat));
3175   PetscFunctionReturn(PETSC_SUCCESS);
3176 }
3177 
3178 /*@
3179   MatILUFactor - Performs in-place ILU factorization of matrix.
3180 
3181   Collective
3182 
3183   Input Parameters:
3184 + mat  - the matrix
3185 . row  - row permutation
3186 . col  - column permutation
3187 - info - structure containing
3188 .vb
3189       levels - number of levels of fill.
3190       expected fill - as ratio of original fill.
3191       1 or 0 - indicating force fill on diagonal (improves robustness for matrices
3192                 missing diagonal entries)
3193 .ve
3194 
3195   Level: developer
3196 
3197   Notes:
3198   Most users should employ the `KSP` interface for linear solvers
3199   instead of working directly with matrix algebra routines such as this.
3200   See, e.g., `KSPCreate()`.
3201 
3202   Probably really in-place only when level of fill is zero, otherwise allocates
3203   new space to store factored matrix and deletes previous memory. The preferred approach is to use `MatGetFactor()`, `MatILUFactorSymbolic()`, and `MatILUFactorNumeric()`
3204   when not using `KSP`.
3205 
3206   Fortran Note:
3207   A valid (non-null) `info` argument must be provided
3208 
3209 .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatILUFactorSymbolic()`, `MatLUFactorNumeric()`, `MatCholeskyFactor()`, `MatFactorInfo`
3210 @*/
3211 PetscErrorCode MatILUFactor(Mat mat, IS row, IS col, const MatFactorInfo *info)
3212 {
3213   PetscFunctionBegin;
3214   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
3215   if (row) PetscValidHeaderSpecific(row, IS_CLASSID, 2);
3216   if (col) PetscValidHeaderSpecific(col, IS_CLASSID, 3);
3217   PetscAssertPointer(info, 4);
3218   PetscValidType(mat, 1);
3219   PetscCheck(mat->rmap->N == mat->cmap->N, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONG, "matrix must be square");
3220   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
3221   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
3222   MatCheckPreallocated(mat, 1);
3223 
3224   PetscCall(PetscLogEventBegin(MAT_ILUFactor, mat, row, col, 0));
3225   PetscUseTypeMethod(mat, ilufactor, row, col, info);
3226   PetscCall(PetscLogEventEnd(MAT_ILUFactor, mat, row, col, 0));
3227   PetscCall(PetscObjectStateIncrease((PetscObject)mat));
3228   PetscFunctionReturn(PETSC_SUCCESS);
3229 }
3230 
3231 /*@
3232   MatLUFactorSymbolic - Performs symbolic LU factorization of matrix.
3233   Call this routine before calling `MatLUFactorNumeric()` and after `MatGetFactor()`.
3234 
3235   Collective
3236 
3237   Input Parameters:
3238 + fact - the factor matrix obtained with `MatGetFactor()`
3239 . mat  - the matrix
3240 . row  - the row permutation
3241 . col  - the column permutation
3242 - info - options for factorization, includes
3243 .vb
3244           fill - expected fill as ratio of original fill. Run with the option -info to determine an optimal value to use
3245           dtcol - pivot tolerance (0 no pivot, 1 full column pivoting)
3246 .ve
3247 
3248   Level: developer
3249 
3250   Notes:
3251   See [Matrix Factorization](sec_matfactor) for additional information about factorizations
3252 
3253   Most users should employ the simplified `KSP` interface for linear solvers
3254   instead of working directly with matrix algebra routines such as this.
3255   See, e.g., `KSPCreate()`.
3256 
3257   Fortran Note:
3258   A valid (non-null) `info` argument must be provided
3259 
3260 .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatGetFactor()`, `MatLUFactor()`, `MatLUFactorNumeric()`, `MatCholeskyFactor()`, `MatFactorInfo`, `MatFactorInfoInitialize()`
3261 @*/
3262 PetscErrorCode MatLUFactorSymbolic(Mat fact, Mat mat, IS row, IS col, const MatFactorInfo *info)
3263 {
3264   MatFactorInfo tinfo;
3265 
3266   PetscFunctionBegin;
3267   PetscValidHeaderSpecific(fact, MAT_CLASSID, 1);
3268   PetscValidHeaderSpecific(mat, MAT_CLASSID, 2);
3269   if (row) PetscValidHeaderSpecific(row, IS_CLASSID, 3);
3270   if (col) PetscValidHeaderSpecific(col, IS_CLASSID, 4);
3271   if (info) PetscAssertPointer(info, 5);
3272   PetscValidType(fact, 1);
3273   PetscValidType(mat, 2);
3274   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
3275   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
3276   MatCheckPreallocated(mat, 2);
3277   if (!info) {
3278     PetscCall(MatFactorInfoInitialize(&tinfo));
3279     info = &tinfo;
3280   }
3281 
3282   if (!fact->trivialsymbolic) PetscCall(PetscLogEventBegin(MAT_LUFactorSymbolic, mat, row, col, 0));
3283   PetscUseTypeMethod(fact, lufactorsymbolic, mat, row, col, info);
3284   if (!fact->trivialsymbolic) PetscCall(PetscLogEventEnd(MAT_LUFactorSymbolic, mat, row, col, 0));
3285   PetscCall(PetscObjectStateIncrease((PetscObject)fact));
3286   PetscFunctionReturn(PETSC_SUCCESS);
3287 }
3288 
3289 /*@
3290   MatLUFactorNumeric - Performs numeric LU factorization of a matrix.
3291   Call this routine after first calling `MatLUFactorSymbolic()` and `MatGetFactor()`.
3292 
3293   Collective
3294 
3295   Input Parameters:
3296 + fact - the factor matrix obtained with `MatGetFactor()`
3297 . mat  - the matrix
3298 - info - options for factorization
3299 
3300   Level: developer
3301 
3302   Notes:
3303   See `MatLUFactor()` for in-place factorization.  See
3304   `MatCholeskyFactorNumeric()` for the symmetric, positive definite case.
3305 
3306   Most users should employ the `KSP` interface for linear solvers
3307   instead of working directly with matrix algebra routines such as this.
3308   See, e.g., `KSPCreate()`.
3309 
3310   Fortran Note:
3311   A valid (non-null) `info` argument must be provided
3312 
3313 .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatGetFactor()`, `MatFactorInfo`, `MatLUFactorSymbolic()`, `MatLUFactor()`, `MatCholeskyFactor()`
3314 @*/
3315 PetscErrorCode MatLUFactorNumeric(Mat fact, Mat mat, const MatFactorInfo *info)
3316 {
3317   MatFactorInfo tinfo;
3318 
3319   PetscFunctionBegin;
3320   PetscValidHeaderSpecific(fact, MAT_CLASSID, 1);
3321   PetscValidHeaderSpecific(mat, MAT_CLASSID, 2);
3322   PetscValidType(fact, 1);
3323   PetscValidType(mat, 2);
3324   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
3325   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,
3326              mat->rmap->N, (fact)->rmap->N, mat->cmap->N, (fact)->cmap->N);
3327 
3328   MatCheckPreallocated(mat, 2);
3329   if (!info) {
3330     PetscCall(MatFactorInfoInitialize(&tinfo));
3331     info = &tinfo;
3332   }
3333 
3334   if (!fact->trivialsymbolic) PetscCall(PetscLogEventBegin(MAT_LUFactorNumeric, mat, fact, 0, 0));
3335   else PetscCall(PetscLogEventBegin(MAT_LUFactor, mat, fact, 0, 0));
3336   PetscUseTypeMethod(fact, lufactornumeric, mat, info);
3337   if (!fact->trivialsymbolic) PetscCall(PetscLogEventEnd(MAT_LUFactorNumeric, mat, fact, 0, 0));
3338   else PetscCall(PetscLogEventEnd(MAT_LUFactor, mat, fact, 0, 0));
3339   PetscCall(MatViewFromOptions(fact, NULL, "-mat_factor_view"));
3340   PetscCall(PetscObjectStateIncrease((PetscObject)fact));
3341   PetscFunctionReturn(PETSC_SUCCESS);
3342 }
3343 
3344 /*@
3345   MatCholeskyFactor - Performs in-place Cholesky factorization of a
3346   symmetric matrix.
3347 
3348   Collective
3349 
3350   Input Parameters:
3351 + mat  - the matrix
3352 . perm - row and column permutations
3353 - info - expected fill as ratio of original fill
3354 
3355   Level: developer
3356 
3357   Notes:
3358   See `MatLUFactor()` for the nonsymmetric case.  See also `MatGetFactor()`,
3359   `MatCholeskyFactorSymbolic()`, and `MatCholeskyFactorNumeric()`.
3360 
3361   Most users should employ the `KSP` interface for linear solvers
3362   instead of working directly with matrix algebra routines such as this.
3363   See, e.g., `KSPCreate()`.
3364 
3365   Fortran Note:
3366   A valid (non-null) `info` argument must be provided
3367 
3368 .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatGetFactor()`, `MatFactorInfo`, `MatLUFactor()`, `MatCholeskyFactorSymbolic()`, `MatCholeskyFactorNumeric()`
3369           `MatGetOrdering()`
3370 @*/
3371 PetscErrorCode MatCholeskyFactor(Mat mat, IS perm, const MatFactorInfo *info)
3372 {
3373   MatFactorInfo tinfo;
3374 
3375   PetscFunctionBegin;
3376   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
3377   if (perm) PetscValidHeaderSpecific(perm, IS_CLASSID, 2);
3378   if (info) PetscAssertPointer(info, 3);
3379   PetscValidType(mat, 1);
3380   PetscCheck(mat->rmap->N == mat->cmap->N, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONG, "Matrix must be square");
3381   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
3382   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
3383   MatCheckPreallocated(mat, 1);
3384   if (!info) {
3385     PetscCall(MatFactorInfoInitialize(&tinfo));
3386     info = &tinfo;
3387   }
3388 
3389   PetscCall(PetscLogEventBegin(MAT_CholeskyFactor, mat, perm, 0, 0));
3390   PetscUseTypeMethod(mat, choleskyfactor, perm, info);
3391   PetscCall(PetscLogEventEnd(MAT_CholeskyFactor, mat, perm, 0, 0));
3392   PetscCall(PetscObjectStateIncrease((PetscObject)mat));
3393   PetscFunctionReturn(PETSC_SUCCESS);
3394 }
3395 
3396 /*@
3397   MatCholeskyFactorSymbolic - Performs symbolic Cholesky factorization
3398   of a symmetric matrix.
3399 
3400   Collective
3401 
3402   Input Parameters:
3403 + fact - the factor matrix obtained with `MatGetFactor()`
3404 . mat  - the matrix
3405 . perm - row and column permutations
3406 - info - options for factorization, includes
3407 .vb
3408           fill - expected fill as ratio of original fill.
3409           dtcol - pivot tolerance (0 no pivot, 1 full column pivoting)
3410                    Run with the option -info to determine an optimal value to use
3411 .ve
3412 
3413   Level: developer
3414 
3415   Notes:
3416   See `MatLUFactorSymbolic()` for the nonsymmetric case.  See also
3417   `MatCholeskyFactor()` and `MatCholeskyFactorNumeric()`.
3418 
3419   Most users should employ the `KSP` interface for linear solvers
3420   instead of working directly with matrix algebra routines such as this.
3421   See, e.g., `KSPCreate()`.
3422 
3423   Fortran Note:
3424   A valid (non-null) `info` argument must be provided
3425 
3426 .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatFactorInfo`, `MatGetFactor()`, `MatLUFactorSymbolic()`, `MatCholeskyFactor()`, `MatCholeskyFactorNumeric()`
3427           `MatGetOrdering()`
3428 @*/
3429 PetscErrorCode MatCholeskyFactorSymbolic(Mat fact, Mat mat, IS perm, const MatFactorInfo *info)
3430 {
3431   MatFactorInfo tinfo;
3432 
3433   PetscFunctionBegin;
3434   PetscValidHeaderSpecific(fact, MAT_CLASSID, 1);
3435   PetscValidHeaderSpecific(mat, MAT_CLASSID, 2);
3436   if (perm) PetscValidHeaderSpecific(perm, IS_CLASSID, 3);
3437   if (info) PetscAssertPointer(info, 4);
3438   PetscValidType(fact, 1);
3439   PetscValidType(mat, 2);
3440   PetscCheck(mat->rmap->N == mat->cmap->N, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONG, "Matrix must be square");
3441   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
3442   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
3443   MatCheckPreallocated(mat, 2);
3444   if (!info) {
3445     PetscCall(MatFactorInfoInitialize(&tinfo));
3446     info = &tinfo;
3447   }
3448 
3449   if (!fact->trivialsymbolic) PetscCall(PetscLogEventBegin(MAT_CholeskyFactorSymbolic, mat, perm, 0, 0));
3450   PetscUseTypeMethod(fact, choleskyfactorsymbolic, mat, perm, info);
3451   if (!fact->trivialsymbolic) PetscCall(PetscLogEventEnd(MAT_CholeskyFactorSymbolic, mat, perm, 0, 0));
3452   PetscCall(PetscObjectStateIncrease((PetscObject)fact));
3453   PetscFunctionReturn(PETSC_SUCCESS);
3454 }
3455 
3456 /*@
3457   MatCholeskyFactorNumeric - Performs numeric Cholesky factorization
3458   of a symmetric matrix. Call this routine after first calling `MatGetFactor()` and
3459   `MatCholeskyFactorSymbolic()`.
3460 
3461   Collective
3462 
3463   Input Parameters:
3464 + fact - the factor matrix obtained with `MatGetFactor()`, where the factored values are stored
3465 . mat  - the initial matrix that is to be factored
3466 - info - options for factorization
3467 
3468   Level: developer
3469 
3470   Note:
3471   Most users should employ the `KSP` interface for linear solvers
3472   instead of working directly with matrix algebra routines such as this.
3473   See, e.g., `KSPCreate()`.
3474 
3475   Fortran Note:
3476   A valid (non-null) `info` argument must be provided
3477 
3478 .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatFactorInfo`, `MatGetFactor()`, `MatCholeskyFactorSymbolic()`, `MatCholeskyFactor()`, `MatLUFactorNumeric()`
3479 @*/
3480 PetscErrorCode MatCholeskyFactorNumeric(Mat fact, Mat mat, const MatFactorInfo *info)
3481 {
3482   MatFactorInfo tinfo;
3483 
3484   PetscFunctionBegin;
3485   PetscValidHeaderSpecific(fact, MAT_CLASSID, 1);
3486   PetscValidHeaderSpecific(mat, MAT_CLASSID, 2);
3487   PetscValidType(fact, 1);
3488   PetscValidType(mat, 2);
3489   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
3490   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,
3491              mat->rmap->N, (fact)->rmap->N, mat->cmap->N, (fact)->cmap->N);
3492   MatCheckPreallocated(mat, 2);
3493   if (!info) {
3494     PetscCall(MatFactorInfoInitialize(&tinfo));
3495     info = &tinfo;
3496   }
3497 
3498   if (!fact->trivialsymbolic) PetscCall(PetscLogEventBegin(MAT_CholeskyFactorNumeric, mat, fact, 0, 0));
3499   else PetscCall(PetscLogEventBegin(MAT_CholeskyFactor, mat, fact, 0, 0));
3500   PetscUseTypeMethod(fact, choleskyfactornumeric, mat, info);
3501   if (!fact->trivialsymbolic) PetscCall(PetscLogEventEnd(MAT_CholeskyFactorNumeric, mat, fact, 0, 0));
3502   else PetscCall(PetscLogEventEnd(MAT_CholeskyFactor, mat, fact, 0, 0));
3503   PetscCall(MatViewFromOptions(fact, NULL, "-mat_factor_view"));
3504   PetscCall(PetscObjectStateIncrease((PetscObject)fact));
3505   PetscFunctionReturn(PETSC_SUCCESS);
3506 }
3507 
3508 /*@
3509   MatQRFactor - Performs in-place QR factorization of matrix.
3510 
3511   Collective
3512 
3513   Input Parameters:
3514 + mat  - the matrix
3515 . col  - column permutation
3516 - info - options for factorization, includes
3517 .vb
3518           fill - expected fill as ratio of original fill.
3519           dtcol - pivot tolerance (0 no pivot, 1 full column pivoting)
3520                    Run with the option -info to determine an optimal value to use
3521 .ve
3522 
3523   Level: developer
3524 
3525   Notes:
3526   Most users should employ the `KSP` interface for linear solvers
3527   instead of working directly with matrix algebra routines such as this.
3528   See, e.g., `KSPCreate()`.
3529 
3530   This changes the state of the matrix to a factored matrix; it cannot be used
3531   for example with `MatSetValues()` unless one first calls `MatSetUnfactored()`.
3532 
3533   Fortran Note:
3534   A valid (non-null) `info` argument must be provided
3535 
3536 .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatFactorInfo`, `MatGetFactor()`, `MatQRFactorSymbolic()`, `MatQRFactorNumeric()`, `MatLUFactor()`,
3537           `MatSetUnfactored()`
3538 @*/
3539 PetscErrorCode MatQRFactor(Mat mat, IS col, const MatFactorInfo *info)
3540 {
3541   PetscFunctionBegin;
3542   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
3543   if (col) PetscValidHeaderSpecific(col, IS_CLASSID, 2);
3544   if (info) PetscAssertPointer(info, 3);
3545   PetscValidType(mat, 1);
3546   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
3547   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
3548   MatCheckPreallocated(mat, 1);
3549   PetscCall(PetscLogEventBegin(MAT_QRFactor, mat, col, 0, 0));
3550   PetscUseMethod(mat, "MatQRFactor_C", (Mat, IS, const MatFactorInfo *), (mat, col, info));
3551   PetscCall(PetscLogEventEnd(MAT_QRFactor, mat, col, 0, 0));
3552   PetscCall(PetscObjectStateIncrease((PetscObject)mat));
3553   PetscFunctionReturn(PETSC_SUCCESS);
3554 }
3555 
3556 /*@
3557   MatQRFactorSymbolic - Performs symbolic QR factorization of matrix.
3558   Call this routine after `MatGetFactor()` but before calling `MatQRFactorNumeric()`.
3559 
3560   Collective
3561 
3562   Input Parameters:
3563 + fact - the factor matrix obtained with `MatGetFactor()`
3564 . mat  - the matrix
3565 . col  - column permutation
3566 - info - options for factorization, includes
3567 .vb
3568           fill - expected fill as ratio of original fill.
3569           dtcol - pivot tolerance (0 no pivot, 1 full column pivoting)
3570                    Run with the option -info to determine an optimal value to use
3571 .ve
3572 
3573   Level: developer
3574 
3575   Note:
3576   Most users should employ the `KSP` interface for linear solvers
3577   instead of working directly with matrix algebra routines such as this.
3578   See, e.g., `KSPCreate()`.
3579 
3580   Fortran Note:
3581   A valid (non-null) `info` argument must be provided
3582 
3583 .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatGetFactor()`, `MatFactorInfo`, `MatQRFactor()`, `MatQRFactorNumeric()`, `MatLUFactor()`, `MatFactorInfoInitialize()`
3584 @*/
3585 PetscErrorCode MatQRFactorSymbolic(Mat fact, Mat mat, IS col, const MatFactorInfo *info)
3586 {
3587   MatFactorInfo tinfo;
3588 
3589   PetscFunctionBegin;
3590   PetscValidHeaderSpecific(fact, MAT_CLASSID, 1);
3591   PetscValidHeaderSpecific(mat, MAT_CLASSID, 2);
3592   if (col) PetscValidHeaderSpecific(col, IS_CLASSID, 3);
3593   if (info) PetscAssertPointer(info, 4);
3594   PetscValidType(fact, 1);
3595   PetscValidType(mat, 2);
3596   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
3597   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
3598   MatCheckPreallocated(mat, 2);
3599   if (!info) {
3600     PetscCall(MatFactorInfoInitialize(&tinfo));
3601     info = &tinfo;
3602   }
3603 
3604   if (!fact->trivialsymbolic) PetscCall(PetscLogEventBegin(MAT_QRFactorSymbolic, fact, mat, col, 0));
3605   PetscUseMethod(fact, "MatQRFactorSymbolic_C", (Mat, Mat, IS, const MatFactorInfo *), (fact, mat, col, info));
3606   if (!fact->trivialsymbolic) PetscCall(PetscLogEventEnd(MAT_QRFactorSymbolic, fact, mat, col, 0));
3607   PetscCall(PetscObjectStateIncrease((PetscObject)fact));
3608   PetscFunctionReturn(PETSC_SUCCESS);
3609 }
3610 
3611 /*@
3612   MatQRFactorNumeric - Performs numeric QR factorization of a matrix.
3613   Call this routine after first calling `MatGetFactor()`, and `MatQRFactorSymbolic()`.
3614 
3615   Collective
3616 
3617   Input Parameters:
3618 + fact - the factor matrix obtained with `MatGetFactor()`
3619 . mat  - the matrix
3620 - info - options for factorization
3621 
3622   Level: developer
3623 
3624   Notes:
3625   See `MatQRFactor()` for in-place factorization.
3626 
3627   Most users should employ the `KSP` interface for linear solvers
3628   instead of working directly with matrix algebra routines such as this.
3629   See, e.g., `KSPCreate()`.
3630 
3631   Fortran Note:
3632   A valid (non-null) `info` argument must be provided
3633 
3634 .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatFactorInfo`, `MatGetFactor()`, `MatQRFactor()`, `MatQRFactorSymbolic()`, `MatLUFactor()`
3635 @*/
3636 PetscErrorCode MatQRFactorNumeric(Mat fact, Mat mat, const MatFactorInfo *info)
3637 {
3638   MatFactorInfo tinfo;
3639 
3640   PetscFunctionBegin;
3641   PetscValidHeaderSpecific(fact, MAT_CLASSID, 1);
3642   PetscValidHeaderSpecific(mat, MAT_CLASSID, 2);
3643   PetscValidType(fact, 1);
3644   PetscValidType(mat, 2);
3645   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
3646   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,
3647              mat->rmap->N, (fact)->rmap->N, mat->cmap->N, (fact)->cmap->N);
3648 
3649   MatCheckPreallocated(mat, 2);
3650   if (!info) {
3651     PetscCall(MatFactorInfoInitialize(&tinfo));
3652     info = &tinfo;
3653   }
3654 
3655   if (!fact->trivialsymbolic) PetscCall(PetscLogEventBegin(MAT_QRFactorNumeric, mat, fact, 0, 0));
3656   else PetscCall(PetscLogEventBegin(MAT_QRFactor, mat, fact, 0, 0));
3657   PetscUseMethod(fact, "MatQRFactorNumeric_C", (Mat, Mat, const MatFactorInfo *), (fact, mat, info));
3658   if (!fact->trivialsymbolic) PetscCall(PetscLogEventEnd(MAT_QRFactorNumeric, mat, fact, 0, 0));
3659   else PetscCall(PetscLogEventEnd(MAT_QRFactor, mat, fact, 0, 0));
3660   PetscCall(MatViewFromOptions(fact, NULL, "-mat_factor_view"));
3661   PetscCall(PetscObjectStateIncrease((PetscObject)fact));
3662   PetscFunctionReturn(PETSC_SUCCESS);
3663 }
3664 
3665 /*@
3666   MatSolve - Solves $A x = b$, given a factored matrix.
3667 
3668   Neighbor-wise Collective
3669 
3670   Input Parameters:
3671 + mat - the factored matrix
3672 - b   - the right-hand-side vector
3673 
3674   Output Parameter:
3675 . x - the result vector
3676 
3677   Level: developer
3678 
3679   Notes:
3680   The vectors `b` and `x` cannot be the same.  I.e., one cannot
3681   call `MatSolve`(A,x,x).
3682 
3683   Most users should employ the `KSP` interface for linear solvers
3684   instead of working directly with matrix algebra routines such as this.
3685   See, e.g., `KSPCreate()`.
3686 
3687 .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatGetFactor()`, `MatLUFactor()`, `MatSolveAdd()`, `MatSolveTranspose()`, `MatSolveTransposeAdd()`
3688 @*/
3689 PetscErrorCode MatSolve(Mat mat, Vec b, Vec x)
3690 {
3691   PetscFunctionBegin;
3692   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
3693   PetscValidType(mat, 1);
3694   PetscValidHeaderSpecific(b, VEC_CLASSID, 2);
3695   PetscValidHeaderSpecific(x, VEC_CLASSID, 3);
3696   PetscCheckSameComm(mat, 1, b, 2);
3697   PetscCheckSameComm(mat, 1, x, 3);
3698   PetscCheck(x != b, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_IDN, "x and b must be different vectors");
3699   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);
3700   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);
3701   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);
3702   if (!mat->rmap->N && !mat->cmap->N) PetscFunctionReturn(PETSC_SUCCESS);
3703   MatCheckPreallocated(mat, 1);
3704 
3705   PetscCall(PetscLogEventBegin(MAT_Solve, mat, b, x, 0));
3706   PetscCall(VecFlag(x, mat->factorerrortype));
3707   if (mat->factorerrortype) PetscCall(PetscInfo(mat, "MatFactorError %d\n", mat->factorerrortype));
3708   else PetscUseTypeMethod(mat, solve, b, x);
3709   PetscCall(PetscLogEventEnd(MAT_Solve, mat, b, x, 0));
3710   PetscCall(PetscObjectStateIncrease((PetscObject)x));
3711   PetscFunctionReturn(PETSC_SUCCESS);
3712 }
3713 
3714 static PetscErrorCode MatMatSolve_Basic(Mat A, Mat B, Mat X, PetscBool trans)
3715 {
3716   Vec      b, x;
3717   PetscInt N, i;
3718   PetscErrorCode (*f)(Mat, Vec, Vec);
3719   PetscBool Abound, Bneedconv = PETSC_FALSE, Xneedconv = PETSC_FALSE;
3720 
3721   PetscFunctionBegin;
3722   if (A->factorerrortype) {
3723     PetscCall(PetscInfo(A, "MatFactorError %d\n", A->factorerrortype));
3724     PetscCall(MatSetInf(X));
3725     PetscFunctionReturn(PETSC_SUCCESS);
3726   }
3727   f = (!trans || (!A->ops->solvetranspose && A->symmetric)) ? A->ops->solve : A->ops->solvetranspose;
3728   PetscCheck(f, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "Mat type %s", ((PetscObject)A)->type_name);
3729   PetscCall(MatBoundToCPU(A, &Abound));
3730   if (!Abound) {
3731     PetscCall(PetscObjectTypeCompareAny((PetscObject)B, &Bneedconv, MATSEQDENSE, MATMPIDENSE, ""));
3732     PetscCall(PetscObjectTypeCompareAny((PetscObject)X, &Xneedconv, MATSEQDENSE, MATMPIDENSE, ""));
3733   }
3734 #if PetscDefined(HAVE_CUDA)
3735   if (Bneedconv) PetscCall(MatConvert(B, MATDENSECUDA, MAT_INPLACE_MATRIX, &B));
3736   if (Xneedconv) PetscCall(MatConvert(X, MATDENSECUDA, MAT_INPLACE_MATRIX, &X));
3737 #elif PetscDefined(HAVE_HIP)
3738   if (Bneedconv) PetscCall(MatConvert(B, MATDENSEHIP, MAT_INPLACE_MATRIX, &B));
3739   if (Xneedconv) PetscCall(MatConvert(X, MATDENSEHIP, MAT_INPLACE_MATRIX, &X));
3740 #endif
3741   PetscCall(MatGetSize(B, NULL, &N));
3742   for (i = 0; i < N; i++) {
3743     PetscCall(MatDenseGetColumnVecRead(B, i, &b));
3744     PetscCall(MatDenseGetColumnVecWrite(X, i, &x));
3745     PetscCall((*f)(A, b, x));
3746     PetscCall(MatDenseRestoreColumnVecWrite(X, i, &x));
3747     PetscCall(MatDenseRestoreColumnVecRead(B, i, &b));
3748   }
3749   if (Bneedconv) PetscCall(MatConvert(B, MATDENSE, MAT_INPLACE_MATRIX, &B));
3750   if (Xneedconv) PetscCall(MatConvert(X, MATDENSE, MAT_INPLACE_MATRIX, &X));
3751   PetscFunctionReturn(PETSC_SUCCESS);
3752 }
3753 
3754 /*@
3755   MatMatSolve - Solves $A X = B$, given a factored matrix.
3756 
3757   Neighbor-wise Collective
3758 
3759   Input Parameters:
3760 + A - the factored matrix
3761 - B - the right-hand-side matrix `MATDENSE` (or sparse `MATAIJ`-- when using MUMPS)
3762 
3763   Output Parameter:
3764 . X - the result matrix (dense matrix)
3765 
3766   Level: developer
3767 
3768   Note:
3769   If `B` is a `MATDENSE` matrix then one can call `MatMatSolve`(A,B,B) except with `MATSOLVERMKL_CPARDISO`;
3770   otherwise, `B` and `X` cannot be the same.
3771 
3772 .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatGetFactor()`, `MatSolve()`, `MatMatSolveTranspose()`, `MatLUFactor()`, `MatCholeskyFactor()`
3773 @*/
3774 PetscErrorCode MatMatSolve(Mat A, Mat B, Mat X)
3775 {
3776   PetscFunctionBegin;
3777   PetscValidHeaderSpecific(A, MAT_CLASSID, 1);
3778   PetscValidType(A, 1);
3779   PetscValidHeaderSpecific(B, MAT_CLASSID, 2);
3780   PetscValidHeaderSpecific(X, MAT_CLASSID, 3);
3781   PetscCheckSameComm(A, 1, B, 2);
3782   PetscCheckSameComm(A, 1, X, 3);
3783   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);
3784   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);
3785   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");
3786   if (!A->rmap->N && !A->cmap->N) PetscFunctionReturn(PETSC_SUCCESS);
3787   MatCheckPreallocated(A, 1);
3788 
3789   PetscCall(PetscLogEventBegin(MAT_MatSolve, A, B, X, 0));
3790   if (!A->ops->matsolve) {
3791     PetscCall(PetscInfo(A, "Mat type %s using basic MatMatSolve\n", ((PetscObject)A)->type_name));
3792     PetscCall(MatMatSolve_Basic(A, B, X, PETSC_FALSE));
3793   } else PetscUseTypeMethod(A, matsolve, B, X);
3794   PetscCall(PetscLogEventEnd(MAT_MatSolve, A, B, X, 0));
3795   PetscCall(PetscObjectStateIncrease((PetscObject)X));
3796   PetscFunctionReturn(PETSC_SUCCESS);
3797 }
3798 
3799 /*@
3800   MatMatSolveTranspose - Solves $A^T X = B $, given a factored matrix.
3801 
3802   Neighbor-wise Collective
3803 
3804   Input Parameters:
3805 + A - the factored matrix
3806 - B - the right-hand-side matrix  (`MATDENSE` matrix)
3807 
3808   Output Parameter:
3809 . X - the result matrix (dense matrix)
3810 
3811   Level: developer
3812 
3813   Note:
3814   The matrices `B` and `X` cannot be the same.  I.e., one cannot
3815   call `MatMatSolveTranspose`(A,X,X).
3816 
3817 .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatGetFactor()`, `MatSolveTranspose()`, `MatMatSolve()`, `MatLUFactor()`, `MatCholeskyFactor()`
3818 @*/
3819 PetscErrorCode MatMatSolveTranspose(Mat A, Mat B, Mat X)
3820 {
3821   PetscFunctionBegin;
3822   PetscValidHeaderSpecific(A, MAT_CLASSID, 1);
3823   PetscValidType(A, 1);
3824   PetscValidHeaderSpecific(B, MAT_CLASSID, 2);
3825   PetscValidHeaderSpecific(X, MAT_CLASSID, 3);
3826   PetscCheckSameComm(A, 1, B, 2);
3827   PetscCheckSameComm(A, 1, X, 3);
3828   PetscCheck(X != B, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_IDN, "X and B must be different matrices");
3829   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);
3830   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);
3831   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);
3832   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");
3833   if (!A->rmap->N && !A->cmap->N) PetscFunctionReturn(PETSC_SUCCESS);
3834   MatCheckPreallocated(A, 1);
3835 
3836   PetscCall(PetscLogEventBegin(MAT_MatSolve, A, B, X, 0));
3837   if (!A->ops->matsolvetranspose) {
3838     PetscCall(PetscInfo(A, "Mat type %s using basic MatMatSolveTranspose\n", ((PetscObject)A)->type_name));
3839     PetscCall(MatMatSolve_Basic(A, B, X, PETSC_TRUE));
3840   } else PetscUseTypeMethod(A, matsolvetranspose, B, X);
3841   PetscCall(PetscLogEventEnd(MAT_MatSolve, A, B, X, 0));
3842   PetscCall(PetscObjectStateIncrease((PetscObject)X));
3843   PetscFunctionReturn(PETSC_SUCCESS);
3844 }
3845 
3846 /*@
3847   MatMatTransposeSolve - Solves $A X = B^T$, given a factored matrix.
3848 
3849   Neighbor-wise Collective
3850 
3851   Input Parameters:
3852 + A  - the factored matrix
3853 - Bt - the transpose of right-hand-side matrix as a `MATDENSE`
3854 
3855   Output Parameter:
3856 . X - the result matrix (dense matrix)
3857 
3858   Level: developer
3859 
3860   Note:
3861   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
3862   format on the host processor and call `MatMatTransposeSolve()` to implement MUMPS' `MatMatSolve()`.
3863 
3864 .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatMatSolve()`, `MatMatSolveTranspose()`, `MatLUFactor()`, `MatCholeskyFactor()`
3865 @*/
3866 PetscErrorCode MatMatTransposeSolve(Mat A, Mat Bt, Mat X)
3867 {
3868   PetscFunctionBegin;
3869   PetscValidHeaderSpecific(A, MAT_CLASSID, 1);
3870   PetscValidType(A, 1);
3871   PetscValidHeaderSpecific(Bt, MAT_CLASSID, 2);
3872   PetscValidHeaderSpecific(X, MAT_CLASSID, 3);
3873   PetscCheckSameComm(A, 1, Bt, 2);
3874   PetscCheckSameComm(A, 1, X, 3);
3875 
3876   PetscCheck(X != Bt, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_IDN, "X and B must be different matrices");
3877   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);
3878   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);
3879   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");
3880   if (!A->rmap->N && !A->cmap->N) PetscFunctionReturn(PETSC_SUCCESS);
3881   PetscCheck(A->factortype, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_WRONGSTATE, "Unfactored matrix");
3882   MatCheckPreallocated(A, 1);
3883 
3884   PetscCall(PetscLogEventBegin(MAT_MatTrSolve, A, Bt, X, 0));
3885   PetscUseTypeMethod(A, mattransposesolve, Bt, X);
3886   PetscCall(PetscLogEventEnd(MAT_MatTrSolve, A, Bt, X, 0));
3887   PetscCall(PetscObjectStateIncrease((PetscObject)X));
3888   PetscFunctionReturn(PETSC_SUCCESS);
3889 }
3890 
3891 /*@
3892   MatForwardSolve - Solves $ L x = b $, given a factored matrix, $A = LU $, or
3893   $U^T*D^(1/2) x = b$, given a factored symmetric matrix, $A = U^T*D*U$,
3894 
3895   Neighbor-wise Collective
3896 
3897   Input Parameters:
3898 + mat - the factored matrix
3899 - b   - the right-hand-side vector
3900 
3901   Output Parameter:
3902 . x - the result vector
3903 
3904   Level: developer
3905 
3906   Notes:
3907   `MatSolve()` should be used for most applications, as it performs
3908   a forward solve followed by a backward solve.
3909 
3910   The vectors `b` and `x` cannot be the same,  i.e., one cannot
3911   call `MatForwardSolve`(A,x,x).
3912 
3913   For matrix in `MATSEQBAIJ` format with block size larger than 1,
3914   the diagonal blocks are not implemented as $D = D^(1/2) * D^(1/2)$ yet.
3915   `MatForwardSolve()` solves $U^T*D y = b$, and
3916   `MatBackwardSolve()` solves $U x = y$.
3917   Thus they do not provide a symmetric preconditioner.
3918 
3919 .seealso: [](ch_matrices), `Mat`, `MatBackwardSolve()`, `MatGetFactor()`, `MatSolve()`
3920 @*/
3921 PetscErrorCode MatForwardSolve(Mat mat, Vec b, Vec x)
3922 {
3923   PetscFunctionBegin;
3924   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
3925   PetscValidType(mat, 1);
3926   PetscValidHeaderSpecific(b, VEC_CLASSID, 2);
3927   PetscValidHeaderSpecific(x, VEC_CLASSID, 3);
3928   PetscCheckSameComm(mat, 1, b, 2);
3929   PetscCheckSameComm(mat, 1, x, 3);
3930   PetscCheck(x != b, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_IDN, "x and b must be different vectors");
3931   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);
3932   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);
3933   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);
3934   if (!mat->rmap->N && !mat->cmap->N) PetscFunctionReturn(PETSC_SUCCESS);
3935   MatCheckPreallocated(mat, 1);
3936 
3937   PetscCall(PetscLogEventBegin(MAT_ForwardSolve, mat, b, x, 0));
3938   PetscUseTypeMethod(mat, forwardsolve, b, x);
3939   PetscCall(PetscLogEventEnd(MAT_ForwardSolve, mat, b, x, 0));
3940   PetscCall(PetscObjectStateIncrease((PetscObject)x));
3941   PetscFunctionReturn(PETSC_SUCCESS);
3942 }
3943 
3944 /*@
3945   MatBackwardSolve - Solves $U x = b$, given a factored matrix, $A = LU$.
3946   $D^(1/2) U x = b$, given a factored symmetric matrix, $A = U^T*D*U$,
3947 
3948   Neighbor-wise Collective
3949 
3950   Input Parameters:
3951 + mat - the factored matrix
3952 - b   - the right-hand-side vector
3953 
3954   Output Parameter:
3955 . x - the result vector
3956 
3957   Level: developer
3958 
3959   Notes:
3960   `MatSolve()` should be used for most applications, as it performs
3961   a forward solve followed by a backward solve.
3962 
3963   The vectors `b` and `x` cannot be the same.  I.e., one cannot
3964   call `MatBackwardSolve`(A,x,x).
3965 
3966   For matrix in `MATSEQBAIJ` format with block size larger than 1,
3967   the diagonal blocks are not implemented as $D = D^(1/2) * D^(1/2)$ yet.
3968   `MatForwardSolve()` solves $U^T*D y = b$, and
3969   `MatBackwardSolve()` solves $U x = y$.
3970   Thus they do not provide a symmetric preconditioner.
3971 
3972 .seealso: [](ch_matrices), `Mat`, `MatForwardSolve()`, `MatGetFactor()`, `MatSolve()`
3973 @*/
3974 PetscErrorCode MatBackwardSolve(Mat mat, Vec b, Vec x)
3975 {
3976   PetscFunctionBegin;
3977   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
3978   PetscValidType(mat, 1);
3979   PetscValidHeaderSpecific(b, VEC_CLASSID, 2);
3980   PetscValidHeaderSpecific(x, VEC_CLASSID, 3);
3981   PetscCheckSameComm(mat, 1, b, 2);
3982   PetscCheckSameComm(mat, 1, x, 3);
3983   PetscCheck(x != b, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_IDN, "x and b must be different vectors");
3984   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);
3985   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);
3986   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);
3987   if (!mat->rmap->N && !mat->cmap->N) PetscFunctionReturn(PETSC_SUCCESS);
3988   MatCheckPreallocated(mat, 1);
3989 
3990   PetscCall(PetscLogEventBegin(MAT_BackwardSolve, mat, b, x, 0));
3991   PetscUseTypeMethod(mat, backwardsolve, b, x);
3992   PetscCall(PetscLogEventEnd(MAT_BackwardSolve, mat, b, x, 0));
3993   PetscCall(PetscObjectStateIncrease((PetscObject)x));
3994   PetscFunctionReturn(PETSC_SUCCESS);
3995 }
3996 
3997 /*@
3998   MatSolveAdd - Computes $x = y + A^{-1}*b$, given a factored matrix.
3999 
4000   Neighbor-wise Collective
4001 
4002   Input Parameters:
4003 + mat - the factored matrix
4004 . b   - the right-hand-side vector
4005 - y   - the vector to be added to
4006 
4007   Output Parameter:
4008 . x - the result vector
4009 
4010   Level: developer
4011 
4012   Note:
4013   The vectors `b` and `x` cannot be the same.  I.e., one cannot
4014   call `MatSolveAdd`(A,x,y,x).
4015 
4016 .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatSolve()`, `MatGetFactor()`, `MatSolveTranspose()`, `MatSolveTransposeAdd()`
4017 @*/
4018 PetscErrorCode MatSolveAdd(Mat mat, Vec b, Vec y, Vec x)
4019 {
4020   PetscScalar one = 1.0;
4021   Vec         tmp;
4022 
4023   PetscFunctionBegin;
4024   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
4025   PetscValidType(mat, 1);
4026   PetscValidHeaderSpecific(y, VEC_CLASSID, 3);
4027   PetscValidHeaderSpecific(b, VEC_CLASSID, 2);
4028   PetscValidHeaderSpecific(x, VEC_CLASSID, 4);
4029   PetscCheckSameComm(mat, 1, b, 2);
4030   PetscCheckSameComm(mat, 1, y, 3);
4031   PetscCheckSameComm(mat, 1, x, 4);
4032   PetscCheck(x != b, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_IDN, "x and b must be different vectors");
4033   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);
4034   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);
4035   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);
4036   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);
4037   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);
4038   if (!mat->rmap->N && !mat->cmap->N) PetscFunctionReturn(PETSC_SUCCESS);
4039   MatCheckPreallocated(mat, 1);
4040 
4041   PetscCall(PetscLogEventBegin(MAT_SolveAdd, mat, b, x, y));
4042   PetscCall(VecFlag(x, mat->factorerrortype));
4043   if (mat->factorerrortype) {
4044     PetscCall(PetscInfo(mat, "MatFactorError %d\n", mat->factorerrortype));
4045   } else if (mat->ops->solveadd) {
4046     PetscUseTypeMethod(mat, solveadd, b, y, x);
4047   } else {
4048     /* do the solve then the add manually */
4049     if (x != y) {
4050       PetscCall(MatSolve(mat, b, x));
4051       PetscCall(VecAXPY(x, one, y));
4052     } else {
4053       PetscCall(VecDuplicate(x, &tmp));
4054       PetscCall(VecCopy(x, tmp));
4055       PetscCall(MatSolve(mat, b, x));
4056       PetscCall(VecAXPY(x, one, tmp));
4057       PetscCall(VecDestroy(&tmp));
4058     }
4059   }
4060   PetscCall(PetscLogEventEnd(MAT_SolveAdd, mat, b, x, y));
4061   PetscCall(PetscObjectStateIncrease((PetscObject)x));
4062   PetscFunctionReturn(PETSC_SUCCESS);
4063 }
4064 
4065 /*@
4066   MatSolveTranspose - Solves $A^T x = b$, given a factored matrix.
4067 
4068   Neighbor-wise Collective
4069 
4070   Input Parameters:
4071 + mat - the factored matrix
4072 - b   - the right-hand-side vector
4073 
4074   Output Parameter:
4075 . x - the result vector
4076 
4077   Level: developer
4078 
4079   Notes:
4080   The vectors `b` and `x` cannot be the same.  I.e., one cannot
4081   call `MatSolveTranspose`(A,x,x).
4082 
4083   Most users should employ the `KSP` interface for linear solvers
4084   instead of working directly with matrix algebra routines such as this.
4085   See, e.g., `KSPCreate()`.
4086 
4087 .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `KSP`, `MatSolve()`, `MatSolveAdd()`, `MatSolveTransposeAdd()`
4088 @*/
4089 PetscErrorCode MatSolveTranspose(Mat mat, Vec b, Vec x)
4090 {
4091   PetscErrorCode (*f)(Mat, Vec, Vec) = (!mat->ops->solvetranspose && mat->symmetric) ? mat->ops->solve : mat->ops->solvetranspose;
4092 
4093   PetscFunctionBegin;
4094   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
4095   PetscValidType(mat, 1);
4096   PetscValidHeaderSpecific(b, VEC_CLASSID, 2);
4097   PetscValidHeaderSpecific(x, VEC_CLASSID, 3);
4098   PetscCheckSameComm(mat, 1, b, 2);
4099   PetscCheckSameComm(mat, 1, x, 3);
4100   PetscCheck(x != b, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_IDN, "x and b must be different vectors");
4101   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);
4102   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);
4103   if (!mat->rmap->N && !mat->cmap->N) PetscFunctionReturn(PETSC_SUCCESS);
4104   MatCheckPreallocated(mat, 1);
4105   PetscCall(PetscLogEventBegin(MAT_SolveTranspose, mat, b, x, 0));
4106   PetscCall(VecFlag(x, mat->factorerrortype));
4107   if (mat->factorerrortype) {
4108     PetscCall(PetscInfo(mat, "MatFactorError %d\n", mat->factorerrortype));
4109   } else {
4110     PetscCheck(f, PetscObjectComm((PetscObject)mat), PETSC_ERR_SUP, "Matrix type %s", ((PetscObject)mat)->type_name);
4111     PetscCall((*f)(mat, b, x));
4112   }
4113   PetscCall(PetscLogEventEnd(MAT_SolveTranspose, mat, b, x, 0));
4114   PetscCall(PetscObjectStateIncrease((PetscObject)x));
4115   PetscFunctionReturn(PETSC_SUCCESS);
4116 }
4117 
4118 /*@
4119   MatSolveTransposeAdd - Computes $x = y + A^{-T} b$
4120   factored matrix.
4121 
4122   Neighbor-wise Collective
4123 
4124   Input Parameters:
4125 + mat - the factored matrix
4126 . b   - the right-hand-side vector
4127 - y   - the vector to be added to
4128 
4129   Output Parameter:
4130 . x - the result vector
4131 
4132   Level: developer
4133 
4134   Note:
4135   The vectors `b` and `x` cannot be the same.  I.e., one cannot
4136   call `MatSolveTransposeAdd`(A,x,y,x).
4137 
4138 .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatSolve()`, `MatSolveAdd()`, `MatSolveTranspose()`
4139 @*/
4140 PetscErrorCode MatSolveTransposeAdd(Mat mat, Vec b, Vec y, Vec x)
4141 {
4142   PetscScalar one = 1.0;
4143   Vec         tmp;
4144   PetscErrorCode (*f)(Mat, Vec, Vec, Vec) = (!mat->ops->solvetransposeadd && mat->symmetric) ? mat->ops->solveadd : mat->ops->solvetransposeadd;
4145 
4146   PetscFunctionBegin;
4147   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
4148   PetscValidType(mat, 1);
4149   PetscValidHeaderSpecific(y, VEC_CLASSID, 3);
4150   PetscValidHeaderSpecific(b, VEC_CLASSID, 2);
4151   PetscValidHeaderSpecific(x, VEC_CLASSID, 4);
4152   PetscCheckSameComm(mat, 1, b, 2);
4153   PetscCheckSameComm(mat, 1, y, 3);
4154   PetscCheckSameComm(mat, 1, x, 4);
4155   PetscCheck(x != b, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_IDN, "x and b must be different vectors");
4156   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);
4157   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);
4158   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);
4159   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);
4160   if (!mat->rmap->N && !mat->cmap->N) PetscFunctionReturn(PETSC_SUCCESS);
4161   MatCheckPreallocated(mat, 1);
4162 
4163   PetscCall(PetscLogEventBegin(MAT_SolveTransposeAdd, mat, b, x, y));
4164   PetscCall(VecFlag(x, mat->factorerrortype));
4165   if (mat->factorerrortype) {
4166     PetscCall(PetscInfo(mat, "MatFactorError %d\n", mat->factorerrortype));
4167   } else if (f) {
4168     PetscCall((*f)(mat, b, y, x));
4169   } else {
4170     /* do the solve then the add manually */
4171     if (x != y) {
4172       PetscCall(MatSolveTranspose(mat, b, x));
4173       PetscCall(VecAXPY(x, one, y));
4174     } else {
4175       PetscCall(VecDuplicate(x, &tmp));
4176       PetscCall(VecCopy(x, tmp));
4177       PetscCall(MatSolveTranspose(mat, b, x));
4178       PetscCall(VecAXPY(x, one, tmp));
4179       PetscCall(VecDestroy(&tmp));
4180     }
4181   }
4182   PetscCall(PetscLogEventEnd(MAT_SolveTransposeAdd, mat, b, x, y));
4183   PetscCall(PetscObjectStateIncrease((PetscObject)x));
4184   PetscFunctionReturn(PETSC_SUCCESS);
4185 }
4186 
4187 // PetscClangLinter pragma disable: -fdoc-section-header-unknown
4188 /*@
4189   MatSOR - Computes relaxation (SOR, Gauss-Seidel) sweeps.
4190 
4191   Neighbor-wise Collective
4192 
4193   Input Parameters:
4194 + mat   - the matrix
4195 . b     - the right-hand side
4196 . omega - the relaxation factor
4197 . flag  - flag indicating the type of SOR (see below)
4198 . shift - diagonal shift
4199 . its   - the number of iterations
4200 - lits  - the number of local iterations
4201 
4202   Output Parameter:
4203 . x - the solution (can contain an initial guess, use option `SOR_ZERO_INITIAL_GUESS` to indicate no guess)
4204 
4205   SOR Flags:
4206 +     `SOR_FORWARD_SWEEP` - forward SOR
4207 .     `SOR_BACKWARD_SWEEP` - backward SOR
4208 .     `SOR_SYMMETRIC_SWEEP` - SSOR (symmetric SOR)
4209 .     `SOR_LOCAL_FORWARD_SWEEP` - local forward SOR
4210 .     `SOR_LOCAL_BACKWARD_SWEEP` - local forward SOR
4211 .     `SOR_LOCAL_SYMMETRIC_SWEEP` - local SSOR
4212 .     `SOR_EISENSTAT` - SOR with Eisenstat trick
4213 .     `SOR_APPLY_UPPER`, `SOR_APPLY_LOWER` - applies upper/lower triangular part of matrix to vector (with `omega`)
4214 -     `SOR_ZERO_INITIAL_GUESS` - zero initial guess
4215 
4216   Level: developer
4217 
4218   Notes:
4219   `SOR_LOCAL_FORWARD_SWEEP`, `SOR_LOCAL_BACKWARD_SWEEP`, and
4220   `SOR_LOCAL_SYMMETRIC_SWEEP` perform separate independent smoothings
4221   on each processor.
4222 
4223   Application programmers will not generally use `MatSOR()` directly,
4224   but instead will employ `PCSOR` or `PCEISENSTAT`
4225 
4226   For `MATBAIJ`, `MATSBAIJ`, and `MATAIJ` matrices with inodes, this does a block SOR smoothing, otherwise it does a pointwise smoothing.
4227   For `MATAIJ` matrices with inodes, the block sizes are determined by the inode sizes, not the block size set with `MatSetBlockSize()`
4228 
4229   Vectors `x` and `b` CANNOT be the same
4230 
4231   The flags are implemented as bitwise inclusive or operations.
4232   For example, use (`SOR_ZERO_INITIAL_GUESS` | `SOR_SYMMETRIC_SWEEP`)
4233   to specify a zero initial guess for SSOR.
4234 
4235   Developer Note:
4236   We should add block SOR support for `MATAIJ` matrices with block size set to greater than one and no inodes
4237 
4238 .seealso: [](ch_matrices), `Mat`, `MatMult()`, `KSP`, `PC`, `MatGetFactor()`
4239 @*/
4240 PetscErrorCode MatSOR(Mat mat, Vec b, PetscReal omega, MatSORType flag, PetscReal shift, PetscInt its, PetscInt lits, Vec x)
4241 {
4242   PetscFunctionBegin;
4243   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
4244   PetscValidType(mat, 1);
4245   PetscValidHeaderSpecific(b, VEC_CLASSID, 2);
4246   PetscValidHeaderSpecific(x, VEC_CLASSID, 8);
4247   PetscCheckSameComm(mat, 1, b, 2);
4248   PetscCheckSameComm(mat, 1, x, 8);
4249   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
4250   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
4251   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);
4252   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);
4253   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);
4254   PetscCheck(its > 0, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Relaxation requires global its %" PetscInt_FMT " positive", its);
4255   PetscCheck(lits > 0, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Relaxation requires local its %" PetscInt_FMT " positive", lits);
4256   PetscCheck(b != x, PETSC_COMM_SELF, PETSC_ERR_ARG_IDN, "b and x vector cannot be the same");
4257 
4258   MatCheckPreallocated(mat, 1);
4259   PetscCall(PetscLogEventBegin(MAT_SOR, mat, b, x, 0));
4260   PetscUseTypeMethod(mat, sor, b, omega, flag, shift, its, lits, x);
4261   PetscCall(PetscLogEventEnd(MAT_SOR, mat, b, x, 0));
4262   PetscCall(PetscObjectStateIncrease((PetscObject)x));
4263   PetscFunctionReturn(PETSC_SUCCESS);
4264 }
4265 
4266 /*
4267       Default matrix copy routine.
4268 */
4269 PetscErrorCode MatCopy_Basic(Mat A, Mat B, MatStructure str)
4270 {
4271   PetscInt           i, rstart = 0, rend = 0, nz;
4272   const PetscInt    *cwork;
4273   const PetscScalar *vwork;
4274 
4275   PetscFunctionBegin;
4276   if (B->assembled) PetscCall(MatZeroEntries(B));
4277   if (str == SAME_NONZERO_PATTERN) {
4278     PetscCall(MatGetOwnershipRange(A, &rstart, &rend));
4279     for (i = rstart; i < rend; i++) {
4280       PetscCall(MatGetRow(A, i, &nz, &cwork, &vwork));
4281       PetscCall(MatSetValues(B, 1, &i, nz, cwork, vwork, INSERT_VALUES));
4282       PetscCall(MatRestoreRow(A, i, &nz, &cwork, &vwork));
4283     }
4284   } else {
4285     PetscCall(MatAYPX(B, 0.0, A, str));
4286   }
4287   PetscCall(MatAssemblyBegin(B, MAT_FINAL_ASSEMBLY));
4288   PetscCall(MatAssemblyEnd(B, MAT_FINAL_ASSEMBLY));
4289   PetscFunctionReturn(PETSC_SUCCESS);
4290 }
4291 
4292 /*@
4293   MatCopy - Copies a matrix to another matrix.
4294 
4295   Collective
4296 
4297   Input Parameters:
4298 + A   - the matrix
4299 - str - `SAME_NONZERO_PATTERN` or `DIFFERENT_NONZERO_PATTERN`
4300 
4301   Output Parameter:
4302 . B - where the copy is put
4303 
4304   Level: intermediate
4305 
4306   Notes:
4307   If you use `SAME_NONZERO_PATTERN`, then the two matrices must have the same nonzero pattern or the routine will crash.
4308 
4309   `MatCopy()` copies the matrix entries of a matrix to another existing
4310   matrix (after first zeroing the second matrix).  A related routine is
4311   `MatConvert()`, which first creates a new matrix and then copies the data.
4312 
4313 .seealso: [](ch_matrices), `Mat`, `MatConvert()`, `MatDuplicate()`
4314 @*/
4315 PetscErrorCode MatCopy(Mat A, Mat B, MatStructure str)
4316 {
4317   PetscInt i;
4318 
4319   PetscFunctionBegin;
4320   PetscValidHeaderSpecific(A, MAT_CLASSID, 1);
4321   PetscValidHeaderSpecific(B, MAT_CLASSID, 2);
4322   PetscValidType(A, 1);
4323   PetscValidType(B, 2);
4324   PetscCheckSameComm(A, 1, B, 2);
4325   MatCheckPreallocated(B, 2);
4326   PetscCheck(A->assembled, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
4327   PetscCheck(!A->factortype, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
4328   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,
4329              A->cmap->N, B->cmap->N);
4330   MatCheckPreallocated(A, 1);
4331   if (A == B) PetscFunctionReturn(PETSC_SUCCESS);
4332 
4333   PetscCall(PetscLogEventBegin(MAT_Copy, A, B, 0, 0));
4334   if (A->ops->copy) PetscUseTypeMethod(A, copy, B, str);
4335   else PetscCall(MatCopy_Basic(A, B, str));
4336 
4337   B->stencil.dim = A->stencil.dim;
4338   B->stencil.noc = A->stencil.noc;
4339   for (i = 0; i <= A->stencil.dim + (A->stencil.noc ? 0 : -1); i++) {
4340     B->stencil.dims[i]   = A->stencil.dims[i];
4341     B->stencil.starts[i] = A->stencil.starts[i];
4342   }
4343 
4344   PetscCall(PetscLogEventEnd(MAT_Copy, A, B, 0, 0));
4345   PetscCall(PetscObjectStateIncrease((PetscObject)B));
4346   PetscFunctionReturn(PETSC_SUCCESS);
4347 }
4348 
4349 /*@
4350   MatConvert - Converts a matrix to another matrix, either of the same
4351   or different type.
4352 
4353   Collective
4354 
4355   Input Parameters:
4356 + mat     - the matrix
4357 . newtype - new matrix type.  Use `MATSAME` to create a new matrix of the
4358             same type as the original matrix.
4359 - reuse   - denotes if the destination matrix is to be created or reused.
4360             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
4361             `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).
4362 
4363   Output Parameter:
4364 . M - pointer to place new matrix
4365 
4366   Level: intermediate
4367 
4368   Notes:
4369   `MatConvert()` first creates a new matrix and then copies the data from
4370   the first matrix.  A related routine is `MatCopy()`, which copies the matrix
4371   entries of one matrix to another already existing matrix context.
4372 
4373   Cannot be used to convert a sequential matrix to parallel or parallel to sequential,
4374   the MPI communicator of the generated matrix is always the same as the communicator
4375   of the input matrix.
4376 
4377 .seealso: [](ch_matrices), `Mat`, `MatCopy()`, `MatDuplicate()`, `MAT_INITIAL_MATRIX`, `MAT_REUSE_MATRIX`, `MAT_INPLACE_MATRIX`
4378 @*/
4379 PetscErrorCode MatConvert(Mat mat, MatType newtype, MatReuse reuse, Mat *M)
4380 {
4381   PetscBool  sametype, issame, flg;
4382   PetscBool3 issymmetric, ishermitian;
4383   char       convname[256], mtype[256];
4384   Mat        B;
4385 
4386   PetscFunctionBegin;
4387   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
4388   PetscValidType(mat, 1);
4389   PetscAssertPointer(M, 4);
4390   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
4391   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
4392   MatCheckPreallocated(mat, 1);
4393 
4394   PetscCall(PetscOptionsGetString(((PetscObject)mat)->options, ((PetscObject)mat)->prefix, "-matconvert_type", mtype, sizeof(mtype), &flg));
4395   if (flg) newtype = mtype;
4396 
4397   PetscCall(PetscObjectTypeCompare((PetscObject)mat, newtype, &sametype));
4398   PetscCall(PetscStrcmp(newtype, "same", &issame));
4399   PetscCheck(!(reuse == MAT_INPLACE_MATRIX) || !(mat != *M), PetscObjectComm((PetscObject)mat), PETSC_ERR_SUP, "MAT_INPLACE_MATRIX requires same input and output matrix");
4400   if (reuse == MAT_REUSE_MATRIX) {
4401     PetscValidHeaderSpecific(*M, MAT_CLASSID, 4);
4402     PetscCheck(mat != *M, PetscObjectComm((PetscObject)mat), PETSC_ERR_SUP, "MAT_REUSE_MATRIX means reuse matrix in final argument, perhaps you mean MAT_INPLACE_MATRIX");
4403   }
4404 
4405   if ((reuse == MAT_INPLACE_MATRIX) && (issame || sametype)) {
4406     PetscCall(PetscInfo(mat, "Early return for inplace %s %d %d\n", ((PetscObject)mat)->type_name, sametype, issame));
4407     PetscFunctionReturn(PETSC_SUCCESS);
4408   }
4409 
4410   /* Cache Mat options because some converters use MatHeaderReplace  */
4411   issymmetric = mat->symmetric;
4412   ishermitian = mat->hermitian;
4413 
4414   if ((sametype || issame) && (reuse == MAT_INITIAL_MATRIX) && mat->ops->duplicate) {
4415     PetscCall(PetscInfo(mat, "Calling duplicate for initial matrix %s %d %d\n", ((PetscObject)mat)->type_name, sametype, issame));
4416     PetscUseTypeMethod(mat, duplicate, MAT_COPY_VALUES, M);
4417   } else {
4418     PetscErrorCode (*conv)(Mat, MatType, MatReuse, Mat *) = NULL;
4419     const char *prefix[3]                                 = {"seq", "mpi", ""};
4420     PetscInt    i;
4421     /*
4422        Order of precedence:
4423        0) See if newtype is a superclass of the current matrix.
4424        1) See if a specialized converter is known to the current matrix.
4425        2) See if a specialized converter is known to the desired matrix class.
4426        3) See if a good general converter is registered for the desired class
4427           (as of 6/27/03 only MATMPIADJ falls into this category).
4428        4) See if a good general converter is known for the current matrix.
4429        5) Use a really basic converter.
4430     */
4431 
4432     /* 0) See if newtype is a superclass of the current matrix.
4433           i.e mat is mpiaij and newtype is aij */
4434     for (i = 0; i < (PetscInt)PETSC_STATIC_ARRAY_LENGTH(prefix); i++) {
4435       PetscCall(PetscStrncpy(convname, prefix[i], sizeof(convname)));
4436       PetscCall(PetscStrlcat(convname, newtype, sizeof(convname)));
4437       PetscCall(PetscStrcmp(convname, ((PetscObject)mat)->type_name, &flg));
4438       PetscCall(PetscInfo(mat, "Check superclass %s %s -> %d\n", convname, ((PetscObject)mat)->type_name, flg));
4439       if (flg) {
4440         if (reuse == MAT_INPLACE_MATRIX) {
4441           PetscCall(PetscInfo(mat, "Early return\n"));
4442           PetscFunctionReturn(PETSC_SUCCESS);
4443         } else if (reuse == MAT_INITIAL_MATRIX && mat->ops->duplicate) {
4444           PetscCall(PetscInfo(mat, "Calling MatDuplicate\n"));
4445           PetscUseTypeMethod(mat, duplicate, MAT_COPY_VALUES, M);
4446           PetscFunctionReturn(PETSC_SUCCESS);
4447         } else if (reuse == MAT_REUSE_MATRIX && mat->ops->copy) {
4448           PetscCall(PetscInfo(mat, "Calling MatCopy\n"));
4449           PetscCall(MatCopy(mat, *M, SAME_NONZERO_PATTERN));
4450           PetscFunctionReturn(PETSC_SUCCESS);
4451         }
4452       }
4453     }
4454     /* 1) See if a specialized converter is known to the current matrix and the desired class */
4455     for (i = 0; i < (PetscInt)PETSC_STATIC_ARRAY_LENGTH(prefix); i++) {
4456       PetscCall(PetscStrncpy(convname, "MatConvert_", sizeof(convname)));
4457       PetscCall(PetscStrlcat(convname, ((PetscObject)mat)->type_name, sizeof(convname)));
4458       PetscCall(PetscStrlcat(convname, "_", sizeof(convname)));
4459       PetscCall(PetscStrlcat(convname, prefix[i], sizeof(convname)));
4460       PetscCall(PetscStrlcat(convname, issame ? ((PetscObject)mat)->type_name : newtype, sizeof(convname)));
4461       PetscCall(PetscStrlcat(convname, "_C", sizeof(convname)));
4462       PetscCall(PetscObjectQueryFunction((PetscObject)mat, convname, &conv));
4463       PetscCall(PetscInfo(mat, "Check specialized (1) %s (%s) -> %d\n", convname, ((PetscObject)mat)->type_name, !!conv));
4464       if (conv) goto foundconv;
4465     }
4466 
4467     /* 2)  See if a specialized converter is known to the desired matrix class. */
4468     PetscCall(MatCreate(PetscObjectComm((PetscObject)mat), &B));
4469     PetscCall(MatSetSizes(B, mat->rmap->n, mat->cmap->n, mat->rmap->N, mat->cmap->N));
4470     PetscCall(MatSetType(B, newtype));
4471     for (i = 0; i < (PetscInt)PETSC_STATIC_ARRAY_LENGTH(prefix); i++) {
4472       PetscCall(PetscStrncpy(convname, "MatConvert_", sizeof(convname)));
4473       PetscCall(PetscStrlcat(convname, ((PetscObject)mat)->type_name, sizeof(convname)));
4474       PetscCall(PetscStrlcat(convname, "_", sizeof(convname)));
4475       PetscCall(PetscStrlcat(convname, prefix[i], sizeof(convname)));
4476       PetscCall(PetscStrlcat(convname, newtype, sizeof(convname)));
4477       PetscCall(PetscStrlcat(convname, "_C", sizeof(convname)));
4478       PetscCall(PetscObjectQueryFunction((PetscObject)B, convname, &conv));
4479       PetscCall(PetscInfo(mat, "Check specialized (2) %s (%s) -> %d\n", convname, ((PetscObject)B)->type_name, !!conv));
4480       if (conv) {
4481         PetscCall(MatDestroy(&B));
4482         goto foundconv;
4483       }
4484     }
4485 
4486     /* 3) See if a good general converter is registered for the desired class */
4487     conv = B->ops->convertfrom;
4488     PetscCall(PetscInfo(mat, "Check convertfrom (%s) -> %d\n", ((PetscObject)B)->type_name, !!conv));
4489     PetscCall(MatDestroy(&B));
4490     if (conv) goto foundconv;
4491 
4492     /* 4) See if a good general converter is known for the current matrix */
4493     if (mat->ops->convert) conv = mat->ops->convert;
4494     PetscCall(PetscInfo(mat, "Check general convert (%s) -> %d\n", ((PetscObject)mat)->type_name, !!conv));
4495     if (conv) goto foundconv;
4496 
4497     /* 5) Use a really basic converter. */
4498     PetscCall(PetscInfo(mat, "Using MatConvert_Basic\n"));
4499     conv = MatConvert_Basic;
4500 
4501   foundconv:
4502     PetscCall(PetscLogEventBegin(MAT_Convert, mat, 0, 0, 0));
4503     PetscCall((*conv)(mat, newtype, reuse, M));
4504     if (mat->rmap->mapping && mat->cmap->mapping && !(*M)->rmap->mapping && !(*M)->cmap->mapping) {
4505       /* the block sizes must be same if the mappings are copied over */
4506       (*M)->rmap->bs = mat->rmap->bs;
4507       (*M)->cmap->bs = mat->cmap->bs;
4508       PetscCall(PetscObjectReference((PetscObject)mat->rmap->mapping));
4509       PetscCall(PetscObjectReference((PetscObject)mat->cmap->mapping));
4510       (*M)->rmap->mapping = mat->rmap->mapping;
4511       (*M)->cmap->mapping = mat->cmap->mapping;
4512     }
4513     (*M)->stencil.dim = mat->stencil.dim;
4514     (*M)->stencil.noc = mat->stencil.noc;
4515     for (i = 0; i <= mat->stencil.dim + (mat->stencil.noc ? 0 : -1); i++) {
4516       (*M)->stencil.dims[i]   = mat->stencil.dims[i];
4517       (*M)->stencil.starts[i] = mat->stencil.starts[i];
4518     }
4519     PetscCall(PetscLogEventEnd(MAT_Convert, mat, 0, 0, 0));
4520   }
4521   PetscCall(PetscObjectStateIncrease((PetscObject)*M));
4522 
4523   /* Copy Mat options */
4524   if (issymmetric == PETSC_BOOL3_TRUE) PetscCall(MatSetOption(*M, MAT_SYMMETRIC, PETSC_TRUE));
4525   else if (issymmetric == PETSC_BOOL3_FALSE) PetscCall(MatSetOption(*M, MAT_SYMMETRIC, PETSC_FALSE));
4526   if (ishermitian == PETSC_BOOL3_TRUE) PetscCall(MatSetOption(*M, MAT_HERMITIAN, PETSC_TRUE));
4527   else if (ishermitian == PETSC_BOOL3_FALSE) PetscCall(MatSetOption(*M, MAT_HERMITIAN, PETSC_FALSE));
4528   PetscFunctionReturn(PETSC_SUCCESS);
4529 }
4530 
4531 /*@
4532   MatFactorGetSolverType - Returns name of the package providing the factorization routines
4533 
4534   Not Collective
4535 
4536   Input Parameter:
4537 . mat - the matrix, must be a factored matrix
4538 
4539   Output Parameter:
4540 . type - the string name of the package (do not free this string)
4541 
4542   Level: intermediate
4543 
4544 .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatGetFactor()`, `MatSolverType`, `MatCopy()`, `MatDuplicate()`, `MatGetFactorAvailable()`
4545 @*/
4546 PetscErrorCode MatFactorGetSolverType(Mat mat, MatSolverType *type)
4547 {
4548   PetscErrorCode (*conv)(Mat, MatSolverType *);
4549 
4550   PetscFunctionBegin;
4551   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
4552   PetscValidType(mat, 1);
4553   PetscAssertPointer(type, 2);
4554   PetscCheck(mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Only for factored matrix");
4555   PetscCall(PetscObjectQueryFunction((PetscObject)mat, "MatFactorGetSolverType_C", &conv));
4556   if (conv) PetscCall((*conv)(mat, type));
4557   else *type = MATSOLVERPETSC;
4558   PetscFunctionReturn(PETSC_SUCCESS);
4559 }
4560 
4561 typedef struct _MatSolverTypeForSpecifcType *MatSolverTypeForSpecifcType;
4562 struct _MatSolverTypeForSpecifcType {
4563   MatType mtype;
4564   /* no entry for MAT_FACTOR_NONE */
4565   PetscErrorCode (*createfactor[MAT_FACTOR_NUM_TYPES - 1])(Mat, MatFactorType, Mat *);
4566   MatSolverTypeForSpecifcType next;
4567 };
4568 
4569 typedef struct _MatSolverTypeHolder *MatSolverTypeHolder;
4570 struct _MatSolverTypeHolder {
4571   char                       *name;
4572   MatSolverTypeForSpecifcType handlers;
4573   MatSolverTypeHolder         next;
4574 };
4575 
4576 static MatSolverTypeHolder MatSolverTypeHolders = NULL;
4577 
4578 /*@C
4579   MatSolverTypeRegister - Registers a `MatSolverType` that works for a particular matrix type
4580 
4581   Logically Collective, No Fortran Support
4582 
4583   Input Parameters:
4584 + package      - name of the package, for example `petsc` or `superlu`
4585 . mtype        - the matrix type that works with this package
4586 . ftype        - the type of factorization supported by the package
4587 - createfactor - routine that will create the factored matrix ready to be used
4588 
4589   Level: developer
4590 
4591 .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatFactorGetSolverType()`, `MatCopy()`, `MatDuplicate()`, `MatGetFactorAvailable()`,
4592   `MatGetFactor()`
4593 @*/
4594 PetscErrorCode MatSolverTypeRegister(MatSolverType package, MatType mtype, MatFactorType ftype, PetscErrorCode (*createfactor)(Mat, MatFactorType, Mat *))
4595 {
4596   MatSolverTypeHolder         next = MatSolverTypeHolders, prev = NULL;
4597   PetscBool                   flg;
4598   MatSolverTypeForSpecifcType inext, iprev = NULL;
4599 
4600   PetscFunctionBegin;
4601   PetscCall(MatInitializePackage());
4602   if (!next) {
4603     PetscCall(PetscNew(&MatSolverTypeHolders));
4604     PetscCall(PetscStrallocpy(package, &MatSolverTypeHolders->name));
4605     PetscCall(PetscNew(&MatSolverTypeHolders->handlers));
4606     PetscCall(PetscStrallocpy(mtype, (char **)&MatSolverTypeHolders->handlers->mtype));
4607     MatSolverTypeHolders->handlers->createfactor[(int)ftype - 1] = createfactor;
4608     PetscFunctionReturn(PETSC_SUCCESS);
4609   }
4610   while (next) {
4611     PetscCall(PetscStrcasecmp(package, next->name, &flg));
4612     if (flg) {
4613       PetscCheck(next->handlers, PETSC_COMM_SELF, PETSC_ERR_PLIB, "MatSolverTypeHolder is missing handlers");
4614       inext = next->handlers;
4615       while (inext) {
4616         PetscCall(PetscStrcasecmp(mtype, inext->mtype, &flg));
4617         if (flg) {
4618           inext->createfactor[(int)ftype - 1] = createfactor;
4619           PetscFunctionReturn(PETSC_SUCCESS);
4620         }
4621         iprev = inext;
4622         inext = inext->next;
4623       }
4624       PetscCall(PetscNew(&iprev->next));
4625       PetscCall(PetscStrallocpy(mtype, (char **)&iprev->next->mtype));
4626       iprev->next->createfactor[(int)ftype - 1] = createfactor;
4627       PetscFunctionReturn(PETSC_SUCCESS);
4628     }
4629     prev = next;
4630     next = next->next;
4631   }
4632   PetscCall(PetscNew(&prev->next));
4633   PetscCall(PetscStrallocpy(package, &prev->next->name));
4634   PetscCall(PetscNew(&prev->next->handlers));
4635   PetscCall(PetscStrallocpy(mtype, (char **)&prev->next->handlers->mtype));
4636   prev->next->handlers->createfactor[(int)ftype - 1] = createfactor;
4637   PetscFunctionReturn(PETSC_SUCCESS);
4638 }
4639 
4640 /*@C
4641   MatSolverTypeGet - Gets the function that creates the factor matrix if it exist
4642 
4643   Input Parameters:
4644 + 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
4645 . ftype - the type of factorization supported by the type
4646 - mtype - the matrix type that works with this type
4647 
4648   Output Parameters:
4649 + foundtype    - `PETSC_TRUE` if the type was registered
4650 . foundmtype   - `PETSC_TRUE` if the type supports the requested mtype
4651 - createfactor - routine that will create the factored matrix ready to be used or `NULL` if not found
4652 
4653   Calling sequence of `createfactor`:
4654 + A     - the matrix providing the factor matrix
4655 . ftype - the `MatFactorType` of the factor requested
4656 - B     - the new factor matrix that responds to MatXXFactorSymbolic,Numeric() functions, such as `MatLUFactorSymbolic()`
4657 
4658   Level: developer
4659 
4660   Note:
4661   When `type` is `NULL` the available functions are searched for based on the order of the calls to `MatSolverTypeRegister()` in `MatInitializePackage()`.
4662   Since different PETSc configurations may have different external solvers, seemingly identical runs with different PETSc configurations may use a different solver.
4663   For example if one configuration had `--download-mumps` while a different one had `--download-superlu_dist`.
4664 
4665 .seealso: [](ch_matrices), `Mat`, `MatFactorType`, `MatType`, `MatCopy()`, `MatDuplicate()`, `MatGetFactorAvailable()`, `MatSolverTypeRegister()`, `MatGetFactor()`,
4666           `MatInitializePackage()`
4667 @*/
4668 PetscErrorCode MatSolverTypeGet(MatSolverType type, MatType mtype, MatFactorType ftype, PetscBool *foundtype, PetscBool *foundmtype, PetscErrorCode (**createfactor)(Mat A, MatFactorType ftype, Mat *B))
4669 {
4670   MatSolverTypeHolder         next = MatSolverTypeHolders;
4671   PetscBool                   flg;
4672   MatSolverTypeForSpecifcType inext;
4673 
4674   PetscFunctionBegin;
4675   if (foundtype) *foundtype = PETSC_FALSE;
4676   if (foundmtype) *foundmtype = PETSC_FALSE;
4677   if (createfactor) *createfactor = NULL;
4678 
4679   if (type) {
4680     while (next) {
4681       PetscCall(PetscStrcasecmp(type, next->name, &flg));
4682       if (flg) {
4683         if (foundtype) *foundtype = PETSC_TRUE;
4684         inext = next->handlers;
4685         while (inext) {
4686           PetscCall(PetscStrbeginswith(mtype, inext->mtype, &flg));
4687           if (flg) {
4688             if (foundmtype) *foundmtype = PETSC_TRUE;
4689             if (createfactor) *createfactor = inext->createfactor[(int)ftype - 1];
4690             PetscFunctionReturn(PETSC_SUCCESS);
4691           }
4692           inext = inext->next;
4693         }
4694       }
4695       next = next->next;
4696     }
4697   } else {
4698     while (next) {
4699       inext = next->handlers;
4700       while (inext) {
4701         PetscCall(PetscStrcmp(mtype, inext->mtype, &flg));
4702         if (flg && inext->createfactor[(int)ftype - 1]) {
4703           if (foundtype) *foundtype = PETSC_TRUE;
4704           if (foundmtype) *foundmtype = PETSC_TRUE;
4705           if (createfactor) *createfactor = inext->createfactor[(int)ftype - 1];
4706           PetscFunctionReturn(PETSC_SUCCESS);
4707         }
4708         inext = inext->next;
4709       }
4710       next = next->next;
4711     }
4712     /* try with base classes inext->mtype */
4713     next = MatSolverTypeHolders;
4714     while (next) {
4715       inext = next->handlers;
4716       while (inext) {
4717         PetscCall(PetscStrbeginswith(mtype, inext->mtype, &flg));
4718         if (flg && inext->createfactor[(int)ftype - 1]) {
4719           if (foundtype) *foundtype = PETSC_TRUE;
4720           if (foundmtype) *foundmtype = PETSC_TRUE;
4721           if (createfactor) *createfactor = inext->createfactor[(int)ftype - 1];
4722           PetscFunctionReturn(PETSC_SUCCESS);
4723         }
4724         inext = inext->next;
4725       }
4726       next = next->next;
4727     }
4728   }
4729   PetscFunctionReturn(PETSC_SUCCESS);
4730 }
4731 
4732 PetscErrorCode MatSolverTypeDestroy(void)
4733 {
4734   MatSolverTypeHolder         next = MatSolverTypeHolders, prev;
4735   MatSolverTypeForSpecifcType inext, iprev;
4736 
4737   PetscFunctionBegin;
4738   while (next) {
4739     PetscCall(PetscFree(next->name));
4740     inext = next->handlers;
4741     while (inext) {
4742       PetscCall(PetscFree(inext->mtype));
4743       iprev = inext;
4744       inext = inext->next;
4745       PetscCall(PetscFree(iprev));
4746     }
4747     prev = next;
4748     next = next->next;
4749     PetscCall(PetscFree(prev));
4750   }
4751   MatSolverTypeHolders = NULL;
4752   PetscFunctionReturn(PETSC_SUCCESS);
4753 }
4754 
4755 /*@
4756   MatFactorGetCanUseOrdering - Indicates if the factorization can use the ordering provided in `MatLUFactorSymbolic()`, `MatCholeskyFactorSymbolic()`
4757 
4758   Logically Collective
4759 
4760   Input Parameter:
4761 . mat - the matrix
4762 
4763   Output Parameter:
4764 . flg - `PETSC_TRUE` if uses the ordering
4765 
4766   Level: developer
4767 
4768   Note:
4769   Most internal PETSc factorizations use the ordering passed to the factorization routine but external
4770   packages do not, thus we want to skip generating the ordering when it is not needed or used.
4771 
4772 .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatCopy()`, `MatDuplicate()`, `MatGetFactorAvailable()`, `MatGetFactor()`, `MatLUFactorSymbolic()`, `MatCholeskyFactorSymbolic()`
4773 @*/
4774 PetscErrorCode MatFactorGetCanUseOrdering(Mat mat, PetscBool *flg)
4775 {
4776   PetscFunctionBegin;
4777   *flg = mat->canuseordering;
4778   PetscFunctionReturn(PETSC_SUCCESS);
4779 }
4780 
4781 /*@
4782   MatFactorGetPreferredOrdering - The preferred ordering for a particular matrix factor object
4783 
4784   Logically Collective
4785 
4786   Input Parameters:
4787 + mat   - the matrix obtained with `MatGetFactor()`
4788 - ftype - the factorization type to be used
4789 
4790   Output Parameter:
4791 . otype - the preferred ordering type
4792 
4793   Level: developer
4794 
4795 .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatFactorType`, `MatOrderingType`, `MatCopy()`, `MatDuplicate()`, `MatGetFactorAvailable()`, `MatGetFactor()`, `MatLUFactorSymbolic()`, `MatCholeskyFactorSymbolic()`
4796 @*/
4797 PetscErrorCode MatFactorGetPreferredOrdering(Mat mat, MatFactorType ftype, MatOrderingType *otype)
4798 {
4799   PetscFunctionBegin;
4800   *otype = mat->preferredordering[ftype];
4801   PetscCheck(*otype, PETSC_COMM_SELF, PETSC_ERR_PLIB, "MatFactor did not have a preferred ordering");
4802   PetscFunctionReturn(PETSC_SUCCESS);
4803 }
4804 
4805 /*@
4806   MatGetFactor - Returns a matrix suitable to calls to MatXXFactorSymbolic,Numeric()
4807 
4808   Collective
4809 
4810   Input Parameters:
4811 + mat   - the matrix
4812 . 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
4813           the other criteria is returned
4814 - ftype - factor type, `MAT_FACTOR_LU`, `MAT_FACTOR_CHOLESKY`, `MAT_FACTOR_ICC`, `MAT_FACTOR_ILU`, `MAT_FACTOR_QR`
4815 
4816   Output Parameter:
4817 . f - the factor matrix used with MatXXFactorSymbolic,Numeric() calls. Can be `NULL` in some cases, see notes below.
4818 
4819   Options Database Keys:
4820 + -pc_factor_mat_solver_type <type>    - choose the type at run time. When using `KSP` solvers
4821 . -pc_factor_mat_factor_on_host <bool> - do mat factorization on host (with device matrices). Default is doing it on device
4822 - -pc_factor_mat_solve_on_host <bool>  - do mat solve on host (with device matrices). Default is doing it on device
4823 
4824   Level: intermediate
4825 
4826   Notes:
4827   The return matrix can be `NULL` if the requested factorization is not available, since some combinations of matrix types and factorization
4828   types registered with `MatSolverTypeRegister()` cannot be fully tested if not at runtime.
4829 
4830   Users usually access the factorization solvers via `KSP`
4831 
4832   Some PETSc matrix formats have alternative solvers available that are contained in alternative packages
4833   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
4834 
4835   When `type` is `NULL` the available results are searched for based on the order of the calls to `MatSolverTypeRegister()` in `MatInitializePackage()`.
4836   Since different PETSc configurations may have different external solvers, seemingly identical runs with different PETSc configurations may use a different solver.
4837   For example if one configuration had --download-mumps while a different one had --download-superlu_dist.
4838 
4839   Some of the packages have options for controlling the factorization, these are in the form -prefix_mat_packagename_packageoption
4840   where prefix is normally obtained from the calling `KSP`/`PC`. If `MatGetFactor()` is called directly one can set
4841   call `MatSetOptionsPrefixFactor()` on the originating matrix or  `MatSetOptionsPrefix()` on the resulting factor matrix.
4842 
4843   Developer Note:
4844   This should actually be called `MatCreateFactor()` since it creates a new factor object
4845 
4846 .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `KSP`, `MatSolverType`, `MatFactorType`, `MatCopy()`, `MatDuplicate()`,
4847           `MatGetFactorAvailable()`, `MatFactorGetCanUseOrdering()`, `MatSolverTypeRegister()`, `MatSolverTypeGet()`
4848           `MAT_FACTOR_LU`, `MAT_FACTOR_CHOLESKY`, `MAT_FACTOR_ICC`, `MAT_FACTOR_ILU`, `MAT_FACTOR_QR`, `MatInitializePackage()`
4849 @*/
4850 PetscErrorCode MatGetFactor(Mat mat, MatSolverType type, MatFactorType ftype, Mat *f)
4851 {
4852   PetscBool foundtype, foundmtype, shell, hasop = PETSC_FALSE;
4853   PetscErrorCode (*conv)(Mat, MatFactorType, Mat *);
4854 
4855   PetscFunctionBegin;
4856   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
4857   PetscValidType(mat, 1);
4858 
4859   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
4860   MatCheckPreallocated(mat, 1);
4861 
4862   PetscCall(MatIsShell(mat, &shell));
4863   if (shell) PetscCall(MatHasOperation(mat, MATOP_GET_FACTOR, &hasop));
4864   if (hasop) {
4865     PetscUseTypeMethod(mat, getfactor, type, ftype, f);
4866     PetscFunctionReturn(PETSC_SUCCESS);
4867   }
4868 
4869   PetscCall(MatSolverTypeGet(type, ((PetscObject)mat)->type_name, ftype, &foundtype, &foundmtype, &conv));
4870   if (!foundtype) {
4871     if (type) {
4872       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],
4873               ((PetscObject)mat)->type_name, type);
4874     } else {
4875       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);
4876     }
4877   }
4878   PetscCheck(foundmtype, PetscObjectComm((PetscObject)mat), PETSC_ERR_MISSING_FACTOR, "MatSolverType %s does not support matrix type %s", type, ((PetscObject)mat)->type_name);
4879   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);
4880 
4881   PetscCall((*conv)(mat, ftype, f));
4882   if (mat->factorprefix) PetscCall(MatSetOptionsPrefix(*f, mat->factorprefix));
4883   PetscFunctionReturn(PETSC_SUCCESS);
4884 }
4885 
4886 /*@
4887   MatGetFactorAvailable - Returns a flag if matrix supports particular type and factor type
4888 
4889   Not Collective
4890 
4891   Input Parameters:
4892 + mat   - the matrix
4893 . type  - name of solver type, for example, `superlu`, `petsc` (to use PETSc's default)
4894 - ftype - factor type, `MAT_FACTOR_LU`, `MAT_FACTOR_CHOLESKY`, `MAT_FACTOR_ICC`, `MAT_FACTOR_ILU`, `MAT_FACTOR_QR`
4895 
4896   Output Parameter:
4897 . flg - PETSC_TRUE if the factorization is available
4898 
4899   Level: intermediate
4900 
4901   Notes:
4902   Some PETSc matrix formats have alternative solvers available that are contained in alternative packages
4903   such as pastix, superlu, mumps etc.
4904 
4905   PETSc must have been ./configure to use the external solver, using the option --download-package
4906 
4907   Developer Note:
4908   This should actually be called `MatCreateFactorAvailable()` since `MatGetFactor()` creates a new factor object
4909 
4910 .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatSolverType`, `MatFactorType`, `MatGetFactor()`, `MatCopy()`, `MatDuplicate()`, `MatSolverTypeRegister()`,
4911           `MAT_FACTOR_LU`, `MAT_FACTOR_CHOLESKY`, `MAT_FACTOR_ICC`, `MAT_FACTOR_ILU`, `MAT_FACTOR_QR`, `MatSolverTypeGet()`
4912 @*/
4913 PetscErrorCode MatGetFactorAvailable(Mat mat, MatSolverType type, MatFactorType ftype, PetscBool *flg)
4914 {
4915   PetscErrorCode (*gconv)(Mat, MatFactorType, Mat *);
4916 
4917   PetscFunctionBegin;
4918   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
4919   PetscAssertPointer(flg, 4);
4920 
4921   *flg = PETSC_FALSE;
4922   if (!((PetscObject)mat)->type_name) PetscFunctionReturn(PETSC_SUCCESS);
4923 
4924   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
4925   MatCheckPreallocated(mat, 1);
4926 
4927   PetscCall(MatSolverTypeGet(type, ((PetscObject)mat)->type_name, ftype, NULL, NULL, &gconv));
4928   *flg = gconv ? PETSC_TRUE : PETSC_FALSE;
4929   PetscFunctionReturn(PETSC_SUCCESS);
4930 }
4931 
4932 /*@
4933   MatDuplicate - Duplicates a matrix including the non-zero structure.
4934 
4935   Collective
4936 
4937   Input Parameters:
4938 + mat - the matrix
4939 - op  - One of `MAT_DO_NOT_COPY_VALUES`, `MAT_COPY_VALUES`, or `MAT_SHARE_NONZERO_PATTERN`.
4940         See the manual page for `MatDuplicateOption()` for an explanation of these options.
4941 
4942   Output Parameter:
4943 . M - pointer to place new matrix
4944 
4945   Level: intermediate
4946 
4947   Notes:
4948   You cannot change the nonzero pattern for the parent or child matrix later if you use `MAT_SHARE_NONZERO_PATTERN`.
4949 
4950   If `op` is not `MAT_COPY_VALUES` the numerical values in the new matrix are zeroed.
4951 
4952   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.
4953 
4954   When original mat is a product of matrix operation, e.g., an output of `MatMatMult()` or `MatCreateSubMatrix()`, only the matrix data structure of `mat`
4955   is duplicated and the internal data structures created for the reuse of previous matrix operations are not duplicated.
4956   User should not use `MatDuplicate()` to create new matrix `M` if `M` is intended to be reused as the product of matrix operation.
4957 
4958 .seealso: [](ch_matrices), `Mat`, `MatCopy()`, `MatConvert()`, `MatDuplicateOption`
4959 @*/
4960 PetscErrorCode MatDuplicate(Mat mat, MatDuplicateOption op, Mat *M)
4961 {
4962   Mat               B;
4963   VecType           vtype;
4964   PetscInt          i;
4965   PetscObject       dm, container_h, container_d;
4966   PetscErrorCodeFn *viewf;
4967 
4968   PetscFunctionBegin;
4969   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
4970   PetscValidType(mat, 1);
4971   PetscAssertPointer(M, 3);
4972   PetscCheck(op != MAT_COPY_VALUES || mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "MAT_COPY_VALUES not allowed for unassembled matrix");
4973   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
4974   MatCheckPreallocated(mat, 1);
4975 
4976   PetscCall(PetscLogEventBegin(MAT_Convert, mat, 0, 0, 0));
4977   PetscUseTypeMethod(mat, duplicate, op, M);
4978   PetscCall(PetscLogEventEnd(MAT_Convert, mat, 0, 0, 0));
4979   B = *M;
4980 
4981   PetscCall(MatGetOperation(mat, MATOP_VIEW, &viewf));
4982   if (viewf) PetscCall(MatSetOperation(B, MATOP_VIEW, viewf));
4983   PetscCall(MatGetVecType(mat, &vtype));
4984   PetscCall(MatSetVecType(B, vtype));
4985 
4986   B->stencil.dim = mat->stencil.dim;
4987   B->stencil.noc = mat->stencil.noc;
4988   for (i = 0; i <= mat->stencil.dim + (mat->stencil.noc ? 0 : -1); i++) {
4989     B->stencil.dims[i]   = mat->stencil.dims[i];
4990     B->stencil.starts[i] = mat->stencil.starts[i];
4991   }
4992 
4993   B->nooffproczerorows = mat->nooffproczerorows;
4994   B->nooffprocentries  = mat->nooffprocentries;
4995 
4996   PetscCall(PetscObjectQuery((PetscObject)mat, "__PETSc_dm", &dm));
4997   if (dm) PetscCall(PetscObjectCompose((PetscObject)B, "__PETSc_dm", dm));
4998   PetscCall(PetscObjectQuery((PetscObject)mat, "__PETSc_MatCOOStruct_Host", &container_h));
4999   if (container_h) PetscCall(PetscObjectCompose((PetscObject)B, "__PETSc_MatCOOStruct_Host", container_h));
5000   PetscCall(PetscObjectQuery((PetscObject)mat, "__PETSc_MatCOOStruct_Device", &container_d));
5001   if (container_d) PetscCall(PetscObjectCompose((PetscObject)B, "__PETSc_MatCOOStruct_Device", container_d));
5002   if (op == MAT_COPY_VALUES) PetscCall(MatPropagateSymmetryOptions(mat, B));
5003   PetscCall(PetscObjectStateIncrease((PetscObject)B));
5004   PetscFunctionReturn(PETSC_SUCCESS);
5005 }
5006 
5007 /*@
5008   MatGetDiagonal - Gets the diagonal of a matrix as a `Vec`
5009 
5010   Logically Collective
5011 
5012   Input Parameter:
5013 . mat - the matrix
5014 
5015   Output Parameter:
5016 . v - the diagonal of the matrix
5017 
5018   Level: intermediate
5019 
5020   Note:
5021   If `mat` has local sizes `n` x `m`, this routine fills the first `ndiag = min(n, m)` entries
5022   of `v` with the diagonal values. Thus `v` must have local size of at least `ndiag`. If `v`
5023   is larger than `ndiag`, the values of the remaining entries are unspecified.
5024 
5025   Currently only correct in parallel for square matrices.
5026 
5027 .seealso: [](ch_matrices), `Mat`, `Vec`, `MatGetRow()`, `MatCreateSubMatrices()`, `MatCreateSubMatrix()`, `MatGetRowMaxAbs()`
5028 @*/
5029 PetscErrorCode MatGetDiagonal(Mat mat, Vec v)
5030 {
5031   PetscFunctionBegin;
5032   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
5033   PetscValidType(mat, 1);
5034   PetscValidHeaderSpecific(v, VEC_CLASSID, 2);
5035   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
5036   MatCheckPreallocated(mat, 1);
5037   if (PetscDefined(USE_DEBUG)) {
5038     PetscInt nv, row, col, ndiag;
5039 
5040     PetscCall(VecGetLocalSize(v, &nv));
5041     PetscCall(MatGetLocalSize(mat, &row, &col));
5042     ndiag = PetscMin(row, col);
5043     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);
5044   }
5045 
5046   PetscUseTypeMethod(mat, getdiagonal, v);
5047   PetscCall(PetscObjectStateIncrease((PetscObject)v));
5048   PetscFunctionReturn(PETSC_SUCCESS);
5049 }
5050 
5051 /*@
5052   MatGetRowMin - Gets the minimum value (of the real part) of each
5053   row of the matrix
5054 
5055   Logically Collective
5056 
5057   Input Parameter:
5058 . mat - the matrix
5059 
5060   Output Parameters:
5061 + v   - the vector for storing the maximums
5062 - idx - the indices of the column found for each row (optional, pass `NULL` if not needed)
5063 
5064   Level: intermediate
5065 
5066   Note:
5067   The result of this call are the same as if one converted the matrix to dense format
5068   and found the minimum value in each row (i.e. the implicit zeros are counted as zeros).
5069 
5070   This code is only implemented for a couple of matrix formats.
5071 
5072 .seealso: [](ch_matrices), `Mat`, `MatGetDiagonal()`, `MatCreateSubMatrices()`, `MatCreateSubMatrix()`, `MatGetRowMaxAbs()`, `MatGetRowMinAbs()`,
5073           `MatGetRowMax()`
5074 @*/
5075 PetscErrorCode MatGetRowMin(Mat mat, Vec v, PetscInt idx[])
5076 {
5077   PetscFunctionBegin;
5078   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
5079   PetscValidType(mat, 1);
5080   PetscValidHeaderSpecific(v, VEC_CLASSID, 2);
5081   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
5082 
5083   if (!mat->cmap->N) {
5084     PetscCall(VecSet(v, PETSC_MAX_REAL));
5085     if (idx) {
5086       PetscInt i, m = mat->rmap->n;
5087       for (i = 0; i < m; i++) idx[i] = -1;
5088     }
5089   } else {
5090     MatCheckPreallocated(mat, 1);
5091   }
5092   PetscUseTypeMethod(mat, getrowmin, v, idx);
5093   PetscCall(PetscObjectStateIncrease((PetscObject)v));
5094   PetscFunctionReturn(PETSC_SUCCESS);
5095 }
5096 
5097 /*@
5098   MatGetRowMinAbs - Gets the minimum value (in absolute value) of each
5099   row of the matrix
5100 
5101   Logically Collective
5102 
5103   Input Parameter:
5104 . mat - the matrix
5105 
5106   Output Parameters:
5107 + v   - the vector for storing the minimums
5108 - idx - the indices of the column found for each row (or `NULL` if not needed)
5109 
5110   Level: intermediate
5111 
5112   Notes:
5113   if a row is completely empty or has only 0.0 values, then the `idx` value for that
5114   row is 0 (the first column).
5115 
5116   This code is only implemented for a couple of matrix formats.
5117 
5118 .seealso: [](ch_matrices), `Mat`, `MatGetDiagonal()`, `MatCreateSubMatrices()`, `MatCreateSubMatrix()`, `MatGetRowMax()`, `MatGetRowMaxAbs()`, `MatGetRowMin()`
5119 @*/
5120 PetscErrorCode MatGetRowMinAbs(Mat mat, Vec v, PetscInt idx[])
5121 {
5122   PetscFunctionBegin;
5123   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
5124   PetscValidType(mat, 1);
5125   PetscValidHeaderSpecific(v, VEC_CLASSID, 2);
5126   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
5127   PetscCheck(!mat->factortype, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
5128 
5129   if (!mat->cmap->N) {
5130     PetscCall(VecSet(v, 0.0));
5131     if (idx) {
5132       PetscInt i, m = mat->rmap->n;
5133       for (i = 0; i < m; i++) idx[i] = -1;
5134     }
5135   } else {
5136     MatCheckPreallocated(mat, 1);
5137     if (idx) PetscCall(PetscArrayzero(idx, mat->rmap->n));
5138     PetscUseTypeMethod(mat, getrowminabs, v, idx);
5139   }
5140   PetscCall(PetscObjectStateIncrease((PetscObject)v));
5141   PetscFunctionReturn(PETSC_SUCCESS);
5142 }
5143 
5144 /*@
5145   MatGetRowMax - Gets the maximum value (of the real part) of each
5146   row of the matrix
5147 
5148   Logically Collective
5149 
5150   Input Parameter:
5151 . mat - the matrix
5152 
5153   Output Parameters:
5154 + v   - the vector for storing the maximums
5155 - idx - the indices of the column found for each row (optional, otherwise pass `NULL`)
5156 
5157   Level: intermediate
5158 
5159   Notes:
5160   The result of this call are the same as if one converted the matrix to dense format
5161   and found the minimum value in each row (i.e. the implicit zeros are counted as zeros).
5162 
5163   This code is only implemented for a couple of matrix formats.
5164 
5165 .seealso: [](ch_matrices), `Mat`, `MatGetDiagonal()`, `MatCreateSubMatrices()`, `MatCreateSubMatrix()`, `MatGetRowMaxAbs()`, `MatGetRowMin()`, `MatGetRowMinAbs()`
5166 @*/
5167 PetscErrorCode MatGetRowMax(Mat mat, Vec v, PetscInt idx[])
5168 {
5169   PetscFunctionBegin;
5170   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
5171   PetscValidType(mat, 1);
5172   PetscValidHeaderSpecific(v, VEC_CLASSID, 2);
5173   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
5174 
5175   if (!mat->cmap->N) {
5176     PetscCall(VecSet(v, PETSC_MIN_REAL));
5177     if (idx) {
5178       PetscInt i, m = mat->rmap->n;
5179       for (i = 0; i < m; i++) idx[i] = -1;
5180     }
5181   } else {
5182     MatCheckPreallocated(mat, 1);
5183     PetscUseTypeMethod(mat, getrowmax, v, idx);
5184   }
5185   PetscCall(PetscObjectStateIncrease((PetscObject)v));
5186   PetscFunctionReturn(PETSC_SUCCESS);
5187 }
5188 
5189 /*@
5190   MatGetRowMaxAbs - Gets the maximum value (in absolute value) of each
5191   row of the matrix
5192 
5193   Logically Collective
5194 
5195   Input Parameter:
5196 . mat - the matrix
5197 
5198   Output Parameters:
5199 + v   - the vector for storing the maximums
5200 - idx - the indices of the column found for each row (or `NULL` if not needed)
5201 
5202   Level: intermediate
5203 
5204   Notes:
5205   if a row is completely empty or has only 0.0 values, then the `idx` value for that
5206   row is 0 (the first column).
5207 
5208   This code is only implemented for a couple of matrix formats.
5209 
5210 .seealso: [](ch_matrices), `Mat`, `MatGetDiagonal()`, `MatCreateSubMatrices()`, `MatCreateSubMatrix()`, `MatGetRowSum()`, `MatGetRowMin()`, `MatGetRowMinAbs()`
5211 @*/
5212 PetscErrorCode MatGetRowMaxAbs(Mat mat, Vec v, PetscInt idx[])
5213 {
5214   PetscFunctionBegin;
5215   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
5216   PetscValidType(mat, 1);
5217   PetscValidHeaderSpecific(v, VEC_CLASSID, 2);
5218   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
5219 
5220   if (!mat->cmap->N) {
5221     PetscCall(VecSet(v, 0.0));
5222     if (idx) {
5223       PetscInt i, m = mat->rmap->n;
5224       for (i = 0; i < m; i++) idx[i] = -1;
5225     }
5226   } else {
5227     MatCheckPreallocated(mat, 1);
5228     if (idx) PetscCall(PetscArrayzero(idx, mat->rmap->n));
5229     PetscUseTypeMethod(mat, getrowmaxabs, v, idx);
5230   }
5231   PetscCall(PetscObjectStateIncrease((PetscObject)v));
5232   PetscFunctionReturn(PETSC_SUCCESS);
5233 }
5234 
5235 /*@
5236   MatGetRowSumAbs - Gets the sum value (in absolute value) of each row of the matrix
5237 
5238   Logically Collective
5239 
5240   Input Parameter:
5241 . mat - the matrix
5242 
5243   Output Parameter:
5244 . v - the vector for storing the sum
5245 
5246   Level: intermediate
5247 
5248   This code is only implemented for a couple of matrix formats.
5249 
5250 .seealso: [](ch_matrices), `Mat`, `MatGetDiagonal()`, `MatCreateSubMatrices()`, `MatCreateSubMatrix()`, `MatGetRowMax()`, `MatGetRowMin()`, `MatGetRowMinAbs()`
5251 @*/
5252 PetscErrorCode MatGetRowSumAbs(Mat mat, Vec v)
5253 {
5254   PetscFunctionBegin;
5255   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
5256   PetscValidType(mat, 1);
5257   PetscValidHeaderSpecific(v, VEC_CLASSID, 2);
5258   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
5259 
5260   if (!mat->cmap->N) {
5261     PetscCall(VecSet(v, 0.0));
5262   } else {
5263     MatCheckPreallocated(mat, 1);
5264     PetscUseTypeMethod(mat, getrowsumabs, v);
5265   }
5266   PetscCall(PetscObjectStateIncrease((PetscObject)v));
5267   PetscFunctionReturn(PETSC_SUCCESS);
5268 }
5269 
5270 /*@
5271   MatGetRowSum - Gets the sum of each row of the matrix
5272 
5273   Logically or Neighborhood Collective
5274 
5275   Input Parameter:
5276 . mat - the matrix
5277 
5278   Output Parameter:
5279 . v - the vector for storing the sum of rows
5280 
5281   Level: intermediate
5282 
5283   Note:
5284   This code is slow since it is not currently specialized for different formats
5285 
5286 .seealso: [](ch_matrices), `Mat`, `MatGetDiagonal()`, `MatCreateSubMatrices()`, `MatCreateSubMatrix()`, `MatGetRowMax()`, `MatGetRowMin()`, `MatGetRowMaxAbs()`, `MatGetRowMinAbs()`, `MatGetRowSumAbs()`
5287 @*/
5288 PetscErrorCode MatGetRowSum(Mat mat, Vec v)
5289 {
5290   Vec ones;
5291 
5292   PetscFunctionBegin;
5293   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
5294   PetscValidType(mat, 1);
5295   PetscValidHeaderSpecific(v, VEC_CLASSID, 2);
5296   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
5297   MatCheckPreallocated(mat, 1);
5298   PetscCall(MatCreateVecs(mat, &ones, NULL));
5299   PetscCall(VecSet(ones, 1.));
5300   PetscCall(MatMult(mat, ones, v));
5301   PetscCall(VecDestroy(&ones));
5302   PetscFunctionReturn(PETSC_SUCCESS);
5303 }
5304 
5305 /*@
5306   MatTransposeSetPrecursor - Set the matrix from which the second matrix will receive numerical transpose data with a call to `MatTranspose`(A,`MAT_REUSE_MATRIX`,&B)
5307   when B was not obtained with `MatTranspose`(A,`MAT_INITIAL_MATRIX`,&B)
5308 
5309   Collective
5310 
5311   Input Parameter:
5312 . mat - the matrix to provide the transpose
5313 
5314   Output Parameter:
5315 . 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
5316 
5317   Level: advanced
5318 
5319   Note:
5320   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
5321   routine allows bypassing that call.
5322 
5323 .seealso: [](ch_matrices), `Mat`, `MatTransposeSymbolic()`, `MatTranspose()`, `MatMultTranspose()`, `MatMultTransposeAdd()`, `MatIsTranspose()`, `MatReuse`, `MAT_INITIAL_MATRIX`, `MAT_REUSE_MATRIX`, `MAT_INPLACE_MATRIX`
5324 @*/
5325 PetscErrorCode MatTransposeSetPrecursor(Mat mat, Mat B)
5326 {
5327   MatParentState *rb = NULL;
5328 
5329   PetscFunctionBegin;
5330   PetscCall(PetscNew(&rb));
5331   rb->id    = ((PetscObject)mat)->id;
5332   rb->state = 0;
5333   PetscCall(MatGetNonzeroState(mat, &rb->nonzerostate));
5334   PetscCall(PetscObjectContainerCompose((PetscObject)B, "MatTransposeParent", rb, PetscCtxDestroyDefault));
5335   PetscFunctionReturn(PETSC_SUCCESS);
5336 }
5337 
5338 /*@
5339   MatTranspose - Computes the transpose of a matrix, either in-place or out-of-place.
5340 
5341   Collective
5342 
5343   Input Parameters:
5344 + mat   - the matrix to transpose
5345 - reuse - either `MAT_INITIAL_MATRIX`, `MAT_REUSE_MATRIX`, or `MAT_INPLACE_MATRIX`
5346 
5347   Output Parameter:
5348 . B - the transpose of the matrix
5349 
5350   Level: intermediate
5351 
5352   Notes:
5353   If you use `MAT_INPLACE_MATRIX` then you must pass in `&mat` for `B`
5354 
5355   `MAT_REUSE_MATRIX` uses the `B` matrix obtained from a previous call to this function with `MAT_INITIAL_MATRIX` to store the transpose. If you already have a matrix to contain the
5356   transpose, call `MatTransposeSetPrecursor(mat, B)` before calling this routine.
5357 
5358   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.
5359 
5360   Consider using `MatCreateTranspose()` instead if you only need a matrix that behaves like the transpose but don't need the storage to be changed.
5361   For example, the result of `MatCreateTranspose()` will compute the transpose of the given matrix times a vector for matrix-vector products computed with `MatMult()`.
5362 
5363   If `mat` is unchanged from the last call this function returns immediately without recomputing the result
5364 
5365   If you only need the symbolic transpose of a matrix, and not the numerical values, use `MatTransposeSymbolic()`
5366 
5367 .seealso: [](ch_matrices), `Mat`, `MatTransposeSetPrecursor()`, `MatMultTranspose()`, `MatMultTransposeAdd()`, `MatIsTranspose()`, `MatReuse`, `MAT_INITIAL_MATRIX`, `MAT_REUSE_MATRIX`, `MAT_INPLACE_MATRIX`,
5368           `MatTransposeSymbolic()`, `MatCreateTranspose()`
5369 @*/
5370 PetscErrorCode MatTranspose(Mat mat, MatReuse reuse, Mat *B)
5371 {
5372   PetscContainer  rB = NULL;
5373   MatParentState *rb = NULL;
5374 
5375   PetscFunctionBegin;
5376   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
5377   PetscValidType(mat, 1);
5378   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
5379   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
5380   PetscCheck(reuse != MAT_INPLACE_MATRIX || mat == *B, PetscObjectComm((PetscObject)mat), PETSC_ERR_SUP, "MAT_INPLACE_MATRIX requires last matrix to match first");
5381   PetscCheck(reuse != MAT_REUSE_MATRIX || mat != *B, PetscObjectComm((PetscObject)mat), PETSC_ERR_SUP, "Perhaps you mean MAT_INPLACE_MATRIX");
5382   MatCheckPreallocated(mat, 1);
5383   if (reuse == MAT_REUSE_MATRIX) {
5384     PetscCall(PetscObjectQuery((PetscObject)*B, "MatTransposeParent", (PetscObject *)&rB));
5385     PetscCheck(rB, PetscObjectComm((PetscObject)*B), PETSC_ERR_ARG_WRONG, "Reuse matrix used was not generated from call to MatTranspose(). Suggest MatTransposeSetPrecursor().");
5386     PetscCall(PetscContainerGetPointer(rB, (void **)&rb));
5387     PetscCheck(rb->id == ((PetscObject)mat)->id, PetscObjectComm((PetscObject)*B), PETSC_ERR_ARG_WRONG, "Reuse matrix used was not generated from input matrix");
5388     if (rb->state == ((PetscObject)mat)->state) PetscFunctionReturn(PETSC_SUCCESS);
5389   }
5390 
5391   PetscCall(PetscLogEventBegin(MAT_Transpose, mat, 0, 0, 0));
5392   if (reuse != MAT_INPLACE_MATRIX || mat->symmetric != PETSC_BOOL3_TRUE) {
5393     PetscUseTypeMethod(mat, transpose, reuse, B);
5394     PetscCall(PetscObjectStateIncrease((PetscObject)*B));
5395   }
5396   PetscCall(PetscLogEventEnd(MAT_Transpose, mat, 0, 0, 0));
5397 
5398   if (reuse == MAT_INITIAL_MATRIX) PetscCall(MatTransposeSetPrecursor(mat, *B));
5399   if (reuse != MAT_INPLACE_MATRIX) {
5400     PetscCall(PetscObjectQuery((PetscObject)*B, "MatTransposeParent", (PetscObject *)&rB));
5401     PetscCall(PetscContainerGetPointer(rB, (void **)&rb));
5402     rb->state        = ((PetscObject)mat)->state;
5403     rb->nonzerostate = mat->nonzerostate;
5404   }
5405   PetscFunctionReturn(PETSC_SUCCESS);
5406 }
5407 
5408 /*@
5409   MatTransposeSymbolic - Computes the symbolic part of the transpose of a matrix.
5410 
5411   Collective
5412 
5413   Input Parameter:
5414 . A - the matrix to transpose
5415 
5416   Output Parameter:
5417 . 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
5418       numerical portion.
5419 
5420   Level: intermediate
5421 
5422   Note:
5423   This is not supported for many matrix types, use `MatTranspose()` in those cases
5424 
5425 .seealso: [](ch_matrices), `Mat`, `MatTransposeSetPrecursor()`, `MatTranspose()`, `MatMultTranspose()`, `MatMultTransposeAdd()`, `MatIsTranspose()`, `MatReuse`, `MAT_INITIAL_MATRIX`, `MAT_REUSE_MATRIX`, `MAT_INPLACE_MATRIX`
5426 @*/
5427 PetscErrorCode MatTransposeSymbolic(Mat A, Mat *B)
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(PetscLogEventBegin(MAT_Transpose, A, 0, 0, 0));
5435   PetscUseTypeMethod(A, transposesymbolic, B);
5436   PetscCall(PetscLogEventEnd(MAT_Transpose, A, 0, 0, 0));
5437 
5438   PetscCall(MatTransposeSetPrecursor(A, *B));
5439   PetscFunctionReturn(PETSC_SUCCESS);
5440 }
5441 
5442 PetscErrorCode MatTransposeCheckNonzeroState_Private(Mat A, Mat B)
5443 {
5444   PetscContainer  rB;
5445   MatParentState *rb;
5446 
5447   PetscFunctionBegin;
5448   PetscValidHeaderSpecific(A, MAT_CLASSID, 1);
5449   PetscValidType(A, 1);
5450   PetscCheck(A->assembled, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
5451   PetscCheck(!A->factortype, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
5452   PetscCall(PetscObjectQuery((PetscObject)B, "MatTransposeParent", (PetscObject *)&rB));
5453   PetscCheck(rB, PetscObjectComm((PetscObject)B), PETSC_ERR_ARG_WRONG, "Reuse matrix used was not generated from call to MatTranspose()");
5454   PetscCall(PetscContainerGetPointer(rB, (void **)&rb));
5455   PetscCheck(rb->id == ((PetscObject)A)->id, PetscObjectComm((PetscObject)B), PETSC_ERR_ARG_WRONG, "Reuse matrix used was not generated from input matrix");
5456   PetscCheck(rb->nonzerostate == A->nonzerostate, PetscObjectComm((PetscObject)B), PETSC_ERR_ARG_WRONGSTATE, "Reuse matrix has changed nonzero structure");
5457   PetscFunctionReturn(PETSC_SUCCESS);
5458 }
5459 
5460 /*@
5461   MatIsTranspose - Test whether a matrix is another one's transpose,
5462   or its own, in which case it tests symmetry.
5463 
5464   Collective
5465 
5466   Input Parameters:
5467 + A   - the matrix to test
5468 . B   - the matrix to test against, this can equal the first parameter
5469 - tol - tolerance, differences between entries smaller than this are counted as zero
5470 
5471   Output Parameter:
5472 . flg - the result
5473 
5474   Level: intermediate
5475 
5476   Notes:
5477   The sequential algorithm has a running time of the order of the number of nonzeros; the parallel
5478   test involves parallel copies of the block off-diagonal parts of the matrix.
5479 
5480 .seealso: [](ch_matrices), `Mat`, `MatTranspose()`, `MatIsSymmetric()`, `MatIsHermitian()`
5481 @*/
5482 PetscErrorCode MatIsTranspose(Mat A, Mat B, PetscReal tol, PetscBool *flg)
5483 {
5484   PetscErrorCode (*f)(Mat, Mat, PetscReal, PetscBool *), (*g)(Mat, Mat, PetscReal, PetscBool *);
5485 
5486   PetscFunctionBegin;
5487   PetscValidHeaderSpecific(A, MAT_CLASSID, 1);
5488   PetscValidHeaderSpecific(B, MAT_CLASSID, 2);
5489   PetscAssertPointer(flg, 4);
5490   PetscCall(PetscObjectQueryFunction((PetscObject)A, "MatIsTranspose_C", &f));
5491   PetscCall(PetscObjectQueryFunction((PetscObject)B, "MatIsTranspose_C", &g));
5492   *flg = PETSC_FALSE;
5493   if (f && g) {
5494     PetscCheck(f == g, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_NOTSAMETYPE, "Matrices do not have the same comparator for symmetry test");
5495     PetscCall((*f)(A, B, tol, flg));
5496   } else {
5497     MatType mattype;
5498 
5499     PetscCall(MatGetType(f ? B : A, &mattype));
5500     SETERRQ(PETSC_COMM_SELF, PETSC_ERR_SUP, "Matrix of type %s does not support checking for transpose", mattype);
5501   }
5502   PetscFunctionReturn(PETSC_SUCCESS);
5503 }
5504 
5505 /*@
5506   MatHermitianTranspose - Computes an in-place or out-of-place Hermitian transpose of a matrix in complex conjugate.
5507 
5508   Collective
5509 
5510   Input Parameters:
5511 + mat   - the matrix to transpose and complex conjugate
5512 - reuse - either `MAT_INITIAL_MATRIX`, `MAT_REUSE_MATRIX`, or `MAT_INPLACE_MATRIX`
5513 
5514   Output Parameter:
5515 . B - the Hermitian transpose
5516 
5517   Level: intermediate
5518 
5519 .seealso: [](ch_matrices), `Mat`, `MatTranspose()`, `MatMultTranspose()`, `MatMultTransposeAdd()`, `MatIsTranspose()`, `MatReuse`
5520 @*/
5521 PetscErrorCode MatHermitianTranspose(Mat mat, MatReuse reuse, Mat *B)
5522 {
5523   PetscFunctionBegin;
5524   PetscCall(MatTranspose(mat, reuse, B));
5525 #if defined(PETSC_USE_COMPLEX)
5526   PetscCall(MatConjugate(*B));
5527 #endif
5528   PetscFunctionReturn(PETSC_SUCCESS);
5529 }
5530 
5531 /*@
5532   MatIsHermitianTranspose - Test whether a matrix is another one's Hermitian transpose,
5533 
5534   Collective
5535 
5536   Input Parameters:
5537 + A   - the matrix to test
5538 . B   - the matrix to test against, this can equal the first parameter
5539 - tol - tolerance, differences between entries smaller than this are counted as zero
5540 
5541   Output Parameter:
5542 . flg - the result
5543 
5544   Level: intermediate
5545 
5546   Notes:
5547   Only available for `MATAIJ` matrices.
5548 
5549   The sequential algorithm
5550   has a running time of the order of the number of nonzeros; the parallel
5551   test involves parallel copies of the block off-diagonal parts of the matrix.
5552 
5553 .seealso: [](ch_matrices), `Mat`, `MatTranspose()`, `MatIsSymmetric()`, `MatIsHermitian()`, `MatIsTranspose()`
5554 @*/
5555 PetscErrorCode MatIsHermitianTranspose(Mat A, Mat B, PetscReal tol, PetscBool *flg)
5556 {
5557   PetscErrorCode (*f)(Mat, Mat, PetscReal, PetscBool *), (*g)(Mat, Mat, PetscReal, PetscBool *);
5558 
5559   PetscFunctionBegin;
5560   PetscValidHeaderSpecific(A, MAT_CLASSID, 1);
5561   PetscValidHeaderSpecific(B, MAT_CLASSID, 2);
5562   PetscAssertPointer(flg, 4);
5563   PetscCall(PetscObjectQueryFunction((PetscObject)A, "MatIsHermitianTranspose_C", &f));
5564   PetscCall(PetscObjectQueryFunction((PetscObject)B, "MatIsHermitianTranspose_C", &g));
5565   if (f && g) {
5566     PetscCheck(f != g, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_NOTSAMETYPE, "Matrices do not have the same comparator for Hermitian test");
5567     PetscCall((*f)(A, B, tol, flg));
5568   }
5569   PetscFunctionReturn(PETSC_SUCCESS);
5570 }
5571 
5572 /*@
5573   MatPermute - Creates a new matrix with rows and columns permuted from the
5574   original.
5575 
5576   Collective
5577 
5578   Input Parameters:
5579 + mat - the matrix to permute
5580 . row - row permutation, each processor supplies only the permutation for its rows
5581 - col - column permutation, each processor supplies only the permutation for its columns
5582 
5583   Output Parameter:
5584 . B - the permuted matrix
5585 
5586   Level: advanced
5587 
5588   Note:
5589   The index sets map from row/col of permuted matrix to row/col of original matrix.
5590   The index sets should be on the same communicator as mat and have the same local sizes.
5591 
5592   Developer Note:
5593   If you want to implement `MatPermute()` for a matrix type, and your approach doesn't
5594   exploit the fact that row and col are permutations, consider implementing the
5595   more general `MatCreateSubMatrix()` instead.
5596 
5597 .seealso: [](ch_matrices), `Mat`, `MatGetOrdering()`, `ISAllGather()`, `MatCreateSubMatrix()`
5598 @*/
5599 PetscErrorCode MatPermute(Mat mat, IS row, IS col, Mat *B)
5600 {
5601   PetscFunctionBegin;
5602   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
5603   PetscValidType(mat, 1);
5604   PetscValidHeaderSpecific(row, IS_CLASSID, 2);
5605   PetscValidHeaderSpecific(col, IS_CLASSID, 3);
5606   PetscAssertPointer(B, 4);
5607   PetscCheckSameComm(mat, 1, row, 2);
5608   if (row != col) PetscCheckSameComm(row, 2, col, 3);
5609   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
5610   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
5611   PetscCheck(mat->ops->permute || mat->ops->createsubmatrix, PETSC_COMM_SELF, PETSC_ERR_SUP, "MatPermute not available for Mat type %s", ((PetscObject)mat)->type_name);
5612   MatCheckPreallocated(mat, 1);
5613 
5614   if (mat->ops->permute) {
5615     PetscUseTypeMethod(mat, permute, row, col, B);
5616     PetscCall(PetscObjectStateIncrease((PetscObject)*B));
5617   } else {
5618     PetscCall(MatCreateSubMatrix(mat, row, col, MAT_INITIAL_MATRIX, B));
5619   }
5620   PetscFunctionReturn(PETSC_SUCCESS);
5621 }
5622 
5623 /*@
5624   MatEqual - Compares two matrices.
5625 
5626   Collective
5627 
5628   Input Parameters:
5629 + A - the first matrix
5630 - B - the second matrix
5631 
5632   Output Parameter:
5633 . flg - `PETSC_TRUE` if the matrices are equal; `PETSC_FALSE` otherwise.
5634 
5635   Level: intermediate
5636 
5637   Note:
5638   If either of the matrix is "matrix-free", meaning the matrix entries are not stored explicitly then equality is determined by comparing
5639   the results of several matrix-vector product using randomly created vectors, see `MatMultEqual()`.
5640 
5641 .seealso: [](ch_matrices), `Mat`, `MatMultEqual()`
5642 @*/
5643 PetscErrorCode MatEqual(Mat A, Mat B, PetscBool *flg)
5644 {
5645   PetscFunctionBegin;
5646   PetscValidHeaderSpecific(A, MAT_CLASSID, 1);
5647   PetscValidHeaderSpecific(B, MAT_CLASSID, 2);
5648   PetscValidType(A, 1);
5649   PetscValidType(B, 2);
5650   PetscAssertPointer(flg, 3);
5651   PetscCheckSameComm(A, 1, B, 2);
5652   MatCheckPreallocated(A, 1);
5653   MatCheckPreallocated(B, 2);
5654   PetscCheck(A->assembled, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
5655   PetscCheck(B->assembled, PetscObjectComm((PetscObject)B), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
5656   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,
5657              B->cmap->N);
5658   if (A->ops->equal && A->ops->equal == B->ops->equal) {
5659     PetscUseTypeMethod(A, equal, B, flg);
5660   } else {
5661     PetscCall(MatMultEqual(A, B, 10, flg));
5662   }
5663   PetscFunctionReturn(PETSC_SUCCESS);
5664 }
5665 
5666 /*@
5667   MatDiagonalScale - Scales a matrix on the left and right by diagonal
5668   matrices that are stored as vectors.  Either of the two scaling
5669   matrices can be `NULL`.
5670 
5671   Collective
5672 
5673   Input Parameters:
5674 + mat - the matrix to be scaled
5675 . l   - the left scaling vector (or `NULL`)
5676 - r   - the right scaling vector (or `NULL`)
5677 
5678   Level: intermediate
5679 
5680   Note:
5681   `MatDiagonalScale()` computes $A = LAR$, where
5682   L = a diagonal matrix (stored as a vector), R = a diagonal matrix (stored as a vector)
5683   The L scales the rows of the matrix, the R scales the columns of the matrix.
5684 
5685 .seealso: [](ch_matrices), `Mat`, `MatScale()`, `MatShift()`, `MatDiagonalSet()`
5686 @*/
5687 PetscErrorCode MatDiagonalScale(Mat mat, Vec l, Vec r)
5688 {
5689   PetscFunctionBegin;
5690   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
5691   PetscValidType(mat, 1);
5692   if (l) {
5693     PetscValidHeaderSpecific(l, VEC_CLASSID, 2);
5694     PetscCheckSameComm(mat, 1, l, 2);
5695   }
5696   if (r) {
5697     PetscValidHeaderSpecific(r, VEC_CLASSID, 3);
5698     PetscCheckSameComm(mat, 1, r, 3);
5699   }
5700   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
5701   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
5702   MatCheckPreallocated(mat, 1);
5703   if (!l && !r) PetscFunctionReturn(PETSC_SUCCESS);
5704 
5705   PetscCall(PetscLogEventBegin(MAT_Scale, mat, 0, 0, 0));
5706   PetscUseTypeMethod(mat, diagonalscale, l, r);
5707   PetscCall(PetscLogEventEnd(MAT_Scale, mat, 0, 0, 0));
5708   PetscCall(PetscObjectStateIncrease((PetscObject)mat));
5709   if (l != r) mat->symmetric = PETSC_BOOL3_FALSE;
5710   PetscFunctionReturn(PETSC_SUCCESS);
5711 }
5712 
5713 /*@
5714   MatScale - Scales all elements of a matrix by a given number.
5715 
5716   Logically Collective
5717 
5718   Input Parameters:
5719 + mat - the matrix to be scaled
5720 - a   - the scaling value
5721 
5722   Level: intermediate
5723 
5724 .seealso: [](ch_matrices), `Mat`, `MatDiagonalScale()`
5725 @*/
5726 PetscErrorCode MatScale(Mat mat, PetscScalar a)
5727 {
5728   PetscFunctionBegin;
5729   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
5730   PetscValidType(mat, 1);
5731   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
5732   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
5733   PetscValidLogicalCollectiveScalar(mat, a, 2);
5734   MatCheckPreallocated(mat, 1);
5735 
5736   PetscCall(PetscLogEventBegin(MAT_Scale, mat, 0, 0, 0));
5737   if (a != (PetscScalar)1.0) {
5738     PetscUseTypeMethod(mat, scale, a);
5739     PetscCall(PetscObjectStateIncrease((PetscObject)mat));
5740   }
5741   PetscCall(PetscLogEventEnd(MAT_Scale, mat, 0, 0, 0));
5742   PetscFunctionReturn(PETSC_SUCCESS);
5743 }
5744 
5745 /*@
5746   MatNorm - Calculates various norms of a matrix.
5747 
5748   Collective
5749 
5750   Input Parameters:
5751 + mat  - the matrix
5752 - type - the type of norm, `NORM_1`, `NORM_FROBENIUS`, `NORM_INFINITY`
5753 
5754   Output Parameter:
5755 . nrm - the resulting norm
5756 
5757   Level: intermediate
5758 
5759 .seealso: [](ch_matrices), `Mat`
5760 @*/
5761 PetscErrorCode MatNorm(Mat mat, NormType type, PetscReal *nrm)
5762 {
5763   PetscFunctionBegin;
5764   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
5765   PetscValidType(mat, 1);
5766   PetscAssertPointer(nrm, 3);
5767 
5768   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
5769   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
5770   MatCheckPreallocated(mat, 1);
5771 
5772   PetscUseTypeMethod(mat, norm, type, nrm);
5773   PetscFunctionReturn(PETSC_SUCCESS);
5774 }
5775 
5776 /*
5777      This variable is used to prevent counting of MatAssemblyBegin() that
5778    are called from within a MatAssemblyEnd().
5779 */
5780 static PetscInt MatAssemblyEnd_InUse = 0;
5781 /*@
5782   MatAssemblyBegin - Begins assembling the matrix.  This routine should
5783   be called after completing all calls to `MatSetValues()`.
5784 
5785   Collective
5786 
5787   Input Parameters:
5788 + mat  - the matrix
5789 - type - type of assembly, either `MAT_FLUSH_ASSEMBLY` or `MAT_FINAL_ASSEMBLY`
5790 
5791   Level: beginner
5792 
5793   Notes:
5794   `MatSetValues()` generally caches the values that belong to other MPI processes.  The matrix is ready to
5795   use only after `MatAssemblyBegin()` and `MatAssemblyEnd()` have been called.
5796 
5797   Use `MAT_FLUSH_ASSEMBLY` when switching between `ADD_VALUES` and `INSERT_VALUES`
5798   in `MatSetValues()`; use `MAT_FINAL_ASSEMBLY` for the final assembly before
5799   using the matrix.
5800 
5801   ALL processes that share a matrix MUST call `MatAssemblyBegin()` and `MatAssemblyEnd()` the SAME NUMBER of times, and each time with the
5802   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
5803   a global collective operation requiring all processes that share the matrix.
5804 
5805   Space for preallocated nonzeros that is not filled by a call to `MatSetValues()` or a related routine are compressed
5806   out by assembly. If you intend to use that extra space on a subsequent assembly, be sure to insert explicit zeros
5807   before `MAT_FINAL_ASSEMBLY` so the space is not compressed out.
5808 
5809 .seealso: [](ch_matrices), `Mat`, `MatAssemblyEnd()`, `MatSetValues()`, `MatAssembled()`
5810 @*/
5811 PetscErrorCode MatAssemblyBegin(Mat mat, MatAssemblyType type)
5812 {
5813   PetscFunctionBegin;
5814   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
5815   PetscValidType(mat, 1);
5816   MatCheckPreallocated(mat, 1);
5817   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix. Did you forget to call MatSetUnfactored()?");
5818   if (mat->assembled) {
5819     mat->was_assembled = PETSC_TRUE;
5820     mat->assembled     = PETSC_FALSE;
5821   }
5822 
5823   if (!MatAssemblyEnd_InUse) {
5824     PetscCall(PetscLogEventBegin(MAT_AssemblyBegin, mat, 0, 0, 0));
5825     PetscTryTypeMethod(mat, assemblybegin, type);
5826     PetscCall(PetscLogEventEnd(MAT_AssemblyBegin, mat, 0, 0, 0));
5827   } else PetscTryTypeMethod(mat, assemblybegin, type);
5828   PetscFunctionReturn(PETSC_SUCCESS);
5829 }
5830 
5831 /*@
5832   MatAssembled - Indicates if a matrix has been assembled and is ready for
5833   use; for example, in matrix-vector product.
5834 
5835   Not Collective
5836 
5837   Input Parameter:
5838 . mat - the matrix
5839 
5840   Output Parameter:
5841 . assembled - `PETSC_TRUE` or `PETSC_FALSE`
5842 
5843   Level: advanced
5844 
5845 .seealso: [](ch_matrices), `Mat`, `MatAssemblyEnd()`, `MatSetValues()`, `MatAssemblyBegin()`
5846 @*/
5847 PetscErrorCode MatAssembled(Mat mat, PetscBool *assembled)
5848 {
5849   PetscFunctionBegin;
5850   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
5851   PetscAssertPointer(assembled, 2);
5852   *assembled = mat->assembled;
5853   PetscFunctionReturn(PETSC_SUCCESS);
5854 }
5855 
5856 /*@
5857   MatAssemblyEnd - Completes assembling the matrix.  This routine should
5858   be called after `MatAssemblyBegin()`.
5859 
5860   Collective
5861 
5862   Input Parameters:
5863 + mat  - the matrix
5864 - type - type of assembly, either `MAT_FLUSH_ASSEMBLY` or `MAT_FINAL_ASSEMBLY`
5865 
5866   Options Database Keys:
5867 + -mat_view ::ascii_info             - Prints info on matrix at conclusion of `MatAssemblyEnd()`
5868 . -mat_view ::ascii_info_detail      - Prints more detailed info
5869 . -mat_view                          - Prints matrix in ASCII format
5870 . -mat_view ::ascii_matlab           - Prints matrix in MATLAB format
5871 . -mat_view draw                     - draws nonzero structure of matrix, using `MatView()` and `PetscDrawOpenX()`.
5872 . -display <name>                    - Sets display name (default is host)
5873 . -draw_pause <sec>                  - Sets number of seconds to pause after display
5874 . -mat_view socket                   - Sends matrix to socket, can be accessed from MATLAB (See [Using MATLAB with PETSc](ch_matlab))
5875 . -viewer_socket_machine <machine>   - Machine to use for socket
5876 . -viewer_socket_port <port>         - Port number to use for socket
5877 - -mat_view binary:filename[:append] - Save matrix to file in binary format
5878 
5879   Level: beginner
5880 
5881 .seealso: [](ch_matrices), `Mat`, `MatAssemblyBegin()`, `MatSetValues()`, `PetscDrawOpenX()`, `PetscDrawCreate()`, `MatView()`, `MatAssembled()`, `PetscViewerSocketOpen()`
5882 @*/
5883 PetscErrorCode MatAssemblyEnd(Mat mat, MatAssemblyType type)
5884 {
5885   static PetscInt inassm = 0;
5886   PetscBool       flg    = PETSC_FALSE;
5887 
5888   PetscFunctionBegin;
5889   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
5890   PetscValidType(mat, 1);
5891 
5892   inassm++;
5893   MatAssemblyEnd_InUse++;
5894   if (MatAssemblyEnd_InUse == 1) { /* Do the logging only the first time through */
5895     PetscCall(PetscLogEventBegin(MAT_AssemblyEnd, mat, 0, 0, 0));
5896     PetscTryTypeMethod(mat, assemblyend, type);
5897     PetscCall(PetscLogEventEnd(MAT_AssemblyEnd, mat, 0, 0, 0));
5898   } else PetscTryTypeMethod(mat, assemblyend, type);
5899 
5900   /* Flush assembly is not a true assembly */
5901   if (type != MAT_FLUSH_ASSEMBLY) {
5902     if (mat->num_ass) {
5903       if (!mat->symmetry_eternal) {
5904         mat->symmetric = PETSC_BOOL3_UNKNOWN;
5905         mat->hermitian = PETSC_BOOL3_UNKNOWN;
5906       }
5907       if (!mat->structural_symmetry_eternal && mat->ass_nonzerostate != mat->nonzerostate) mat->structurally_symmetric = PETSC_BOOL3_UNKNOWN;
5908       if (!mat->spd_eternal) mat->spd = PETSC_BOOL3_UNKNOWN;
5909     }
5910     mat->num_ass++;
5911     mat->assembled        = PETSC_TRUE;
5912     mat->ass_nonzerostate = mat->nonzerostate;
5913   }
5914 
5915   mat->insertmode = NOT_SET_VALUES;
5916   MatAssemblyEnd_InUse--;
5917   PetscCall(PetscObjectStateIncrease((PetscObject)mat));
5918   if (inassm == 1 && type != MAT_FLUSH_ASSEMBLY) {
5919     PetscCall(MatViewFromOptions(mat, NULL, "-mat_view"));
5920 
5921     if (mat->checksymmetryonassembly) {
5922       PetscCall(MatIsSymmetric(mat, mat->checksymmetrytol, &flg));
5923       if (flg) {
5924         PetscCall(PetscPrintf(PetscObjectComm((PetscObject)mat), "Matrix is symmetric (tolerance %g)\n", (double)mat->checksymmetrytol));
5925       } else {
5926         PetscCall(PetscPrintf(PetscObjectComm((PetscObject)mat), "Matrix is not symmetric (tolerance %g)\n", (double)mat->checksymmetrytol));
5927       }
5928     }
5929     if (mat->nullsp && mat->checknullspaceonassembly) PetscCall(MatNullSpaceTest(mat->nullsp, mat, NULL));
5930   }
5931   inassm--;
5932   PetscFunctionReturn(PETSC_SUCCESS);
5933 }
5934 
5935 // PetscClangLinter pragma disable: -fdoc-section-header-unknown
5936 /*@
5937   MatSetOption - Sets a parameter option for a matrix. Some options
5938   may be specific to certain storage formats.  Some options
5939   determine how values will be inserted (or added). Sorted,
5940   row-oriented input will generally assemble the fastest. The default
5941   is row-oriented.
5942 
5943   Logically Collective for certain operations, such as `MAT_SPD`, not collective for `MAT_ROW_ORIENTED`, see `MatOption`
5944 
5945   Input Parameters:
5946 + mat - the matrix
5947 . op  - the option, one of those listed below (and possibly others),
5948 - flg - turn the option on (`PETSC_TRUE`) or off (`PETSC_FALSE`)
5949 
5950   Options Describing Matrix Structure:
5951 + `MAT_SPD`                         - symmetric positive definite
5952 . `MAT_SYMMETRIC`                   - symmetric in terms of both structure and value
5953 . `MAT_HERMITIAN`                   - transpose is the complex conjugation
5954 . `MAT_STRUCTURALLY_SYMMETRIC`      - symmetric nonzero structure
5955 . `MAT_SYMMETRY_ETERNAL`            - indicates the symmetry (or Hermitian structure) or its absence will persist through any changes to the matrix
5956 . `MAT_STRUCTURAL_SYMMETRY_ETERNAL` - indicates the structural symmetry or its absence will persist through any changes to the matrix
5957 . `MAT_SPD_ETERNAL`                 - indicates the value of `MAT_SPD` (true or false) will persist through any changes to the matrix
5958 
5959    These are not really options of the matrix, they are knowledge about the structure of the matrix that users may provide so that they
5960    do not need to be computed (usually at a high cost)
5961 
5962    Options For Use with `MatSetValues()`:
5963    Insert a logically dense subblock, which can be
5964 . `MAT_ROW_ORIENTED`                - row-oriented (default)
5965 
5966    These options reflect the data you pass in with `MatSetValues()`; it has
5967    nothing to do with how the data is stored internally in the matrix
5968    data structure.
5969 
5970    When (re)assembling a matrix, we can restrict the input for
5971    efficiency/debugging purposes.  These options include
5972 . `MAT_NEW_NONZERO_LOCATIONS`       - additional insertions will be allowed if they generate a new nonzero (slow)
5973 . `MAT_FORCE_DIAGONAL_ENTRIES`      - forces diagonal entries to be allocated
5974 . `MAT_IGNORE_OFF_PROC_ENTRIES`     - drops off-processor entries
5975 . `MAT_NEW_NONZERO_LOCATION_ERR`    - generates an error for new matrix entry
5976 . `MAT_USE_HASH_TABLE`              - uses a hash table to speed up matrix assembly
5977 . `MAT_NO_OFF_PROC_ENTRIES`         - you know each process will only set values for its own rows, will generate an error if
5978         any process sets values for another process. This avoids all reductions in the MatAssembly routines and thus improves
5979         performance for very large process counts.
5980 - `MAT_SUBSET_OFF_PROC_ENTRIES`     - you know that the first assembly after setting this flag will set a superset
5981         of the off-process entries required for all subsequent assemblies. This avoids a rendezvous step in the MatAssembly
5982         functions, instead sending only neighbor messages.
5983 
5984   Level: intermediate
5985 
5986   Notes:
5987   Except for `MAT_UNUSED_NONZERO_LOCATION_ERR` and  `MAT_ROW_ORIENTED` all processes that share the matrix must pass the same value in flg!
5988 
5989   Some options are relevant only for particular matrix types and
5990   are thus ignored by others.  Other options are not supported by
5991   certain matrix types and will generate an error message if set.
5992 
5993   If using Fortran to compute a matrix, one may need to
5994   use the column-oriented option (or convert to the row-oriented
5995   format).
5996 
5997   `MAT_NEW_NONZERO_LOCATIONS` set to `PETSC_FALSE` indicates that any add or insertion
5998   that would generate a new entry in the nonzero structure is instead
5999   ignored.  Thus, if memory has not already been allocated for this particular
6000   data, then the insertion is ignored. For dense matrices, in which
6001   the entire array is allocated, no entries are ever ignored.
6002   Set after the first `MatAssemblyEnd()`. If this option is set, then the `MatAssemblyBegin()`/`MatAssemblyEnd()` processes has one less global reduction
6003 
6004   `MAT_NEW_NONZERO_LOCATION_ERR` set to PETSC_TRUE indicates that any add or insertion
6005   that would generate a new entry in the nonzero structure instead produces
6006   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
6007 
6008   `MAT_NEW_NONZERO_ALLOCATION_ERR` set to `PETSC_TRUE` indicates that any add or insertion
6009   that would generate a new entry that has not been preallocated will
6010   instead produce an error. (Currently supported for `MATAIJ` and `MATBAIJ` formats
6011   only.) This is a useful flag when debugging matrix memory preallocation.
6012   If this option is set, then the `MatAssemblyBegin()`/`MatAssemblyEnd()` processes has one less global reduction
6013 
6014   `MAT_IGNORE_OFF_PROC_ENTRIES` set to `PETSC_TRUE` indicates entries destined for
6015   other processors should be dropped, rather than stashed.
6016   This is useful if you know that the "owning" processor is also
6017   always generating the correct matrix entries, so that PETSc need
6018   not transfer duplicate entries generated on another processor.
6019 
6020   `MAT_USE_HASH_TABLE` indicates that a hash table be used to improve the
6021   searches during matrix assembly. When this flag is set, the hash table
6022   is created during the first matrix assembly. This hash table is
6023   used the next time through, during `MatSetValues()`/`MatSetValuesBlocked()`
6024   to improve the searching of indices. `MAT_NEW_NONZERO_LOCATIONS` flag
6025   should be used with `MAT_USE_HASH_TABLE` flag. This option is currently
6026   supported by `MATMPIBAIJ` format only.
6027 
6028   `MAT_KEEP_NONZERO_PATTERN` indicates when `MatZeroRows()` is called the zeroed entries
6029   are kept in the nonzero structure. This flag is not used for `MatZeroRowsColumns()`
6030 
6031   `MAT_IGNORE_ZERO_ENTRIES` - for `MATAIJ` and `MATIS` matrices this will stop zero values from creating
6032   a zero location in the matrix
6033 
6034   `MAT_USE_INODES` - indicates using inode version of the code - works with `MATAIJ` matrix types
6035 
6036   `MAT_NO_OFF_PROC_ZERO_ROWS` - you know each process will only zero its own rows. This avoids all reductions in the
6037   zero row routines and thus improves performance for very large process counts.
6038 
6039   `MAT_IGNORE_LOWER_TRIANGULAR` - For `MATSBAIJ` matrices will ignore any insertions you make in the lower triangular
6040   part of the matrix (since they should match the upper triangular part).
6041 
6042   `MAT_SORTED_FULL` - each process provides exactly its local rows; all column indices for a given row are passed in a
6043   single call to `MatSetValues()`, preallocation is perfect, row-oriented, `INSERT_VALUES` is used. Common
6044   with finite difference schemes with non-periodic boundary conditions.
6045 
6046   Developer Note:
6047   `MAT_SYMMETRY_ETERNAL`, `MAT_STRUCTURAL_SYMMETRY_ETERNAL`, and `MAT_SPD_ETERNAL` are used by `MatAssemblyEnd()` and in other
6048   places where otherwise the value of `MAT_SYMMETRIC`, `MAT_STRUCTURALLY_SYMMETRIC` or `MAT_SPD` would need to be changed back
6049   to `PETSC_BOOL3_UNKNOWN` because the matrix values had changed so the code cannot be certain that the related property had
6050   not changed.
6051 
6052 .seealso: [](ch_matrices), `MatOption`, `Mat`, `MatGetOption()`
6053 @*/
6054 PetscErrorCode MatSetOption(Mat mat, MatOption op, PetscBool flg)
6055 {
6056   PetscFunctionBegin;
6057   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
6058   if (op > 0) {
6059     PetscValidLogicalCollectiveEnum(mat, op, 2);
6060     PetscValidLogicalCollectiveBool(mat, flg, 3);
6061   }
6062 
6063   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);
6064 
6065   switch (op) {
6066   case MAT_FORCE_DIAGONAL_ENTRIES:
6067     mat->force_diagonals = flg;
6068     PetscFunctionReturn(PETSC_SUCCESS);
6069   case MAT_NO_OFF_PROC_ENTRIES:
6070     mat->nooffprocentries = flg;
6071     PetscFunctionReturn(PETSC_SUCCESS);
6072   case MAT_SUBSET_OFF_PROC_ENTRIES:
6073     mat->assembly_subset = flg;
6074     if (!mat->assembly_subset) { /* See the same logic in VecAssembly wrt VEC_SUBSET_OFF_PROC_ENTRIES */
6075 #if !defined(PETSC_HAVE_MPIUNI)
6076       PetscCall(MatStashScatterDestroy_BTS(&mat->stash));
6077 #endif
6078       mat->stash.first_assembly_done = PETSC_FALSE;
6079     }
6080     PetscFunctionReturn(PETSC_SUCCESS);
6081   case MAT_NO_OFF_PROC_ZERO_ROWS:
6082     mat->nooffproczerorows = flg;
6083     PetscFunctionReturn(PETSC_SUCCESS);
6084   case MAT_SPD:
6085     if (flg) {
6086       mat->spd                    = PETSC_BOOL3_TRUE;
6087       mat->symmetric              = PETSC_BOOL3_TRUE;
6088       mat->structurally_symmetric = PETSC_BOOL3_TRUE;
6089     } else {
6090       mat->spd = PETSC_BOOL3_FALSE;
6091     }
6092     break;
6093   case MAT_SYMMETRIC:
6094     mat->symmetric = PetscBoolToBool3(flg);
6095     if (flg) mat->structurally_symmetric = PETSC_BOOL3_TRUE;
6096 #if !defined(PETSC_USE_COMPLEX)
6097     mat->hermitian = PetscBoolToBool3(flg);
6098 #endif
6099     break;
6100   case MAT_HERMITIAN:
6101     mat->hermitian = PetscBoolToBool3(flg);
6102     if (flg) mat->structurally_symmetric = PETSC_BOOL3_TRUE;
6103 #if !defined(PETSC_USE_COMPLEX)
6104     mat->symmetric = PetscBoolToBool3(flg);
6105 #endif
6106     break;
6107   case MAT_STRUCTURALLY_SYMMETRIC:
6108     mat->structurally_symmetric = PetscBoolToBool3(flg);
6109     break;
6110   case MAT_SYMMETRY_ETERNAL:
6111     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");
6112     mat->symmetry_eternal = flg;
6113     if (flg) mat->structural_symmetry_eternal = PETSC_TRUE;
6114     break;
6115   case MAT_STRUCTURAL_SYMMETRY_ETERNAL:
6116     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");
6117     mat->structural_symmetry_eternal = flg;
6118     break;
6119   case MAT_SPD_ETERNAL:
6120     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");
6121     mat->spd_eternal = flg;
6122     if (flg) {
6123       mat->structural_symmetry_eternal = PETSC_TRUE;
6124       mat->symmetry_eternal            = PETSC_TRUE;
6125     }
6126     break;
6127   case MAT_STRUCTURE_ONLY:
6128     mat->structure_only = flg;
6129     break;
6130   case MAT_SORTED_FULL:
6131     mat->sortedfull = flg;
6132     break;
6133   default:
6134     break;
6135   }
6136   PetscTryTypeMethod(mat, setoption, op, flg);
6137   PetscFunctionReturn(PETSC_SUCCESS);
6138 }
6139 
6140 /*@
6141   MatGetOption - Gets a parameter option that has been set for a matrix.
6142 
6143   Logically Collective
6144 
6145   Input Parameters:
6146 + mat - the matrix
6147 - op  - the option, this only responds to certain options, check the code for which ones
6148 
6149   Output Parameter:
6150 . flg - turn the option on (`PETSC_TRUE`) or off (`PETSC_FALSE`)
6151 
6152   Level: intermediate
6153 
6154   Notes:
6155   Can only be called after `MatSetSizes()` and `MatSetType()` have been set.
6156 
6157   Certain option values may be unknown, for those use the routines `MatIsSymmetric()`, `MatIsHermitian()`, `MatIsStructurallySymmetric()`, or
6158   `MatIsSymmetricKnown()`, `MatIsHermitianKnown()`, `MatIsStructurallySymmetricKnown()`
6159 
6160 .seealso: [](ch_matrices), `Mat`, `MatOption`, `MatSetOption()`, `MatIsSymmetric()`, `MatIsHermitian()`, `MatIsStructurallySymmetric()`,
6161     `MatIsSymmetricKnown()`, `MatIsHermitianKnown()`, `MatIsStructurallySymmetricKnown()`
6162 @*/
6163 PetscErrorCode MatGetOption(Mat mat, MatOption op, PetscBool *flg)
6164 {
6165   PetscFunctionBegin;
6166   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
6167   PetscValidType(mat, 1);
6168 
6169   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);
6170   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()");
6171 
6172   switch (op) {
6173   case MAT_NO_OFF_PROC_ENTRIES:
6174     *flg = mat->nooffprocentries;
6175     break;
6176   case MAT_NO_OFF_PROC_ZERO_ROWS:
6177     *flg = mat->nooffproczerorows;
6178     break;
6179   case MAT_SYMMETRIC:
6180     SETERRQ(PetscObjectComm((PetscObject)mat), PETSC_ERR_SUP, "Use MatIsSymmetric() or MatIsSymmetricKnown()");
6181     break;
6182   case MAT_HERMITIAN:
6183     SETERRQ(PetscObjectComm((PetscObject)mat), PETSC_ERR_SUP, "Use MatIsHermitian() or MatIsHermitianKnown()");
6184     break;
6185   case MAT_STRUCTURALLY_SYMMETRIC:
6186     SETERRQ(PetscObjectComm((PetscObject)mat), PETSC_ERR_SUP, "Use MatIsStructurallySymmetric() or MatIsStructurallySymmetricKnown()");
6187     break;
6188   case MAT_SPD:
6189     SETERRQ(PetscObjectComm((PetscObject)mat), PETSC_ERR_SUP, "Use MatIsSPDKnown()");
6190     break;
6191   case MAT_SYMMETRY_ETERNAL:
6192     *flg = mat->symmetry_eternal;
6193     break;
6194   case MAT_STRUCTURAL_SYMMETRY_ETERNAL:
6195     *flg = mat->symmetry_eternal;
6196     break;
6197   default:
6198     break;
6199   }
6200   PetscFunctionReturn(PETSC_SUCCESS);
6201 }
6202 
6203 /*@
6204   MatZeroEntries - Zeros all entries of a matrix.  For sparse matrices
6205   this routine retains the old nonzero structure.
6206 
6207   Logically Collective
6208 
6209   Input Parameter:
6210 . mat - the matrix
6211 
6212   Level: intermediate
6213 
6214   Note:
6215   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.
6216   See the Performance chapter of the users manual for information on preallocating matrices.
6217 
6218 .seealso: [](ch_matrices), `Mat`, `MatZeroRows()`, `MatZeroRowsColumns()`
6219 @*/
6220 PetscErrorCode MatZeroEntries(Mat mat)
6221 {
6222   PetscFunctionBegin;
6223   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
6224   PetscValidType(mat, 1);
6225   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
6226   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");
6227   MatCheckPreallocated(mat, 1);
6228 
6229   PetscCall(PetscLogEventBegin(MAT_ZeroEntries, mat, 0, 0, 0));
6230   PetscUseTypeMethod(mat, zeroentries);
6231   PetscCall(PetscLogEventEnd(MAT_ZeroEntries, mat, 0, 0, 0));
6232   PetscCall(PetscObjectStateIncrease((PetscObject)mat));
6233   PetscFunctionReturn(PETSC_SUCCESS);
6234 }
6235 
6236 /*@
6237   MatZeroRowsColumns - Zeros all entries (except possibly the main diagonal)
6238   of a set of rows and columns of a matrix.
6239 
6240   Collective
6241 
6242   Input Parameters:
6243 + mat     - the matrix
6244 . numRows - the number of rows/columns to zero
6245 . rows    - the global row indices
6246 . diag    - value put in the diagonal of the eliminated rows
6247 . x       - optional vector of the solution for zeroed rows (other entries in vector are not used), these must be set before this call
6248 - b       - optional vector of the right-hand side, that will be adjusted by provided solution entries
6249 
6250   Level: intermediate
6251 
6252   Notes:
6253   This routine, along with `MatZeroRows()`, is typically used to eliminate known Dirichlet boundary conditions from a linear system.
6254 
6255   For each zeroed row, the value of the corresponding `b` is set to diag times the value of the corresponding `x`.
6256   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
6257 
6258   If the resulting linear system is to be solved with `KSP` then one can (but does not have to) call `KSPSetInitialGuessNonzero()` to allow the
6259   Krylov method to take advantage of the known solution on the zeroed rows.
6260 
6261   For the parallel case, all processes that share the matrix (i.e.,
6262   those in the communicator used for matrix creation) MUST call this
6263   routine, regardless of whether any rows being zeroed are owned by
6264   them.
6265 
6266   Unlike `MatZeroRows()`, this ignores the `MAT_KEEP_NONZERO_PATTERN` option value set with `MatSetOption()`, it merely zeros those entries in the matrix, but never
6267   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
6268   missing.
6269 
6270   Each processor can indicate any rows in the entire matrix to be zeroed (i.e. each process does NOT have to
6271   list only rows local to itself).
6272 
6273   The option `MAT_NO_OFF_PROC_ZERO_ROWS` does not apply to this routine.
6274 
6275 .seealso: [](ch_matrices), `Mat`, `MatZeroRowsIS()`, `MatZeroRows()`, `MatZeroRowsLocalIS()`, `MatZeroRowsStencil()`, `MatZeroEntries()`, `MatZeroRowsLocal()`, `MatSetOption()`,
6276           `MatZeroRowsColumnsLocal()`, `MatZeroRowsColumnsLocalIS()`, `MatZeroRowsColumnsIS()`, `MatZeroRowsColumnsStencil()`
6277 @*/
6278 PetscErrorCode MatZeroRowsColumns(Mat mat, PetscInt numRows, const PetscInt rows[], PetscScalar diag, Vec x, Vec b)
6279 {
6280   PetscFunctionBegin;
6281   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
6282   PetscValidType(mat, 1);
6283   if (numRows) PetscAssertPointer(rows, 3);
6284   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
6285   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
6286   MatCheckPreallocated(mat, 1);
6287 
6288   PetscUseTypeMethod(mat, zerorowscolumns, numRows, rows, diag, x, b);
6289   PetscCall(MatViewFromOptions(mat, NULL, "-mat_view"));
6290   PetscCall(PetscObjectStateIncrease((PetscObject)mat));
6291   PetscFunctionReturn(PETSC_SUCCESS);
6292 }
6293 
6294 /*@
6295   MatZeroRowsColumnsIS - Zeros all entries (except possibly the main diagonal)
6296   of a set of rows and columns of a matrix.
6297 
6298   Collective
6299 
6300   Input Parameters:
6301 + mat  - the matrix
6302 . is   - the rows to zero
6303 . diag - value put in all diagonals of eliminated rows (0.0 will even eliminate diagonal entry)
6304 . x    - optional vector of solutions for zeroed rows (other entries in vector are not used)
6305 - b    - optional vector of right-hand side, that will be adjusted by provided solution
6306 
6307   Level: intermediate
6308 
6309   Note:
6310   See `MatZeroRowsColumns()` for details on how this routine operates.
6311 
6312 .seealso: [](ch_matrices), `Mat`, `MatZeroRowsIS()`, `MatZeroRowsColumns()`, `MatZeroRowsLocalIS()`, `MatZeroRowsStencil()`, `MatZeroEntries()`, `MatZeroRowsLocal()`, `MatSetOption()`,
6313           `MatZeroRowsColumnsLocal()`, `MatZeroRowsColumnsLocalIS()`, `MatZeroRows()`, `MatZeroRowsColumnsStencil()`
6314 @*/
6315 PetscErrorCode MatZeroRowsColumnsIS(Mat mat, IS is, PetscScalar diag, Vec x, Vec b)
6316 {
6317   PetscInt        numRows;
6318   const PetscInt *rows;
6319 
6320   PetscFunctionBegin;
6321   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
6322   PetscValidHeaderSpecific(is, IS_CLASSID, 2);
6323   PetscValidType(mat, 1);
6324   PetscValidType(is, 2);
6325   PetscCall(ISGetLocalSize(is, &numRows));
6326   PetscCall(ISGetIndices(is, &rows));
6327   PetscCall(MatZeroRowsColumns(mat, numRows, rows, diag, x, b));
6328   PetscCall(ISRestoreIndices(is, &rows));
6329   PetscFunctionReturn(PETSC_SUCCESS);
6330 }
6331 
6332 /*@
6333   MatZeroRows - Zeros all entries (except possibly the main diagonal)
6334   of a set of rows of a matrix.
6335 
6336   Collective
6337 
6338   Input Parameters:
6339 + mat     - the matrix
6340 . numRows - the number of rows to zero
6341 . rows    - the global row indices
6342 . diag    - value put in the diagonal of the zeroed rows
6343 . x       - optional vector of solutions for zeroed rows (other entries in vector are not used), these must be set before this call
6344 - b       - optional vector of right-hand side, that will be adjusted by provided solution entries
6345 
6346   Level: intermediate
6347 
6348   Notes:
6349   This routine, along with `MatZeroRowsColumns()`, is typically used to eliminate known Dirichlet boundary conditions from a linear system.
6350 
6351   For each zeroed row, the value of the corresponding `b` is set to `diag` times the value of the corresponding `x`.
6352 
6353   If the resulting linear system is to be solved with `KSP` then one can (but does not have to) call `KSPSetInitialGuessNonzero()` to allow the
6354   Krylov method to take advantage of the known solution on the zeroed rows.
6355 
6356   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)
6357   from the matrix.
6358 
6359   Unlike `MatZeroRowsColumns()` for the `MATAIJ` and `MATBAIJ` matrix formats this removes the old nonzero structure, from the eliminated rows of the matrix
6360   but does not release memory.  Because of this removal matrix-vector products with the adjusted matrix will be a bit faster. For the dense
6361   formats this does not alter the nonzero structure.
6362 
6363   If the option `MatSetOption`(mat,`MAT_KEEP_NONZERO_PATTERN`,`PETSC_TRUE`) the nonzero structure
6364   of the matrix is not changed the values are
6365   merely zeroed.
6366 
6367   The user can set a value in the diagonal entry (or for the `MATAIJ` format
6368   formats can optionally remove the main diagonal entry from the
6369   nonzero structure as well, by passing 0.0 as the final argument).
6370 
6371   For the parallel case, all processes that share the matrix (i.e.,
6372   those in the communicator used for matrix creation) MUST call this
6373   routine, regardless of whether any rows being zeroed are owned by
6374   them.
6375 
6376   Each processor can indicate any rows in the entire matrix to be zeroed (i.e. each process does NOT have to
6377   list only rows local to itself).
6378 
6379   You can call `MatSetOption`(mat,`MAT_NO_OFF_PROC_ZERO_ROWS`,`PETSC_TRUE`) if each process indicates only rows it
6380   owns that are to be zeroed. This saves a global synchronization in the implementation.
6381 
6382 .seealso: [](ch_matrices), `Mat`, `MatZeroRowsIS()`, `MatZeroRowsColumns()`, `MatZeroRowsLocalIS()`, `MatZeroRowsStencil()`, `MatZeroEntries()`, `MatZeroRowsLocal()`, `MatSetOption()`,
6383           `MatZeroRowsColumnsLocal()`, `MatZeroRowsColumnsLocalIS()`, `MatZeroRowsColumnsIS()`, `MatZeroRowsColumnsStencil()`, `PCREDISTRIBUTE`, `MAT_KEEP_NONZERO_PATTERN`
6384 @*/
6385 PetscErrorCode MatZeroRows(Mat mat, PetscInt numRows, const PetscInt rows[], PetscScalar diag, Vec x, Vec b)
6386 {
6387   PetscFunctionBegin;
6388   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
6389   PetscValidType(mat, 1);
6390   if (numRows) PetscAssertPointer(rows, 3);
6391   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
6392   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
6393   MatCheckPreallocated(mat, 1);
6394 
6395   PetscUseTypeMethod(mat, zerorows, numRows, rows, diag, x, b);
6396   PetscCall(MatViewFromOptions(mat, NULL, "-mat_view"));
6397   PetscCall(PetscObjectStateIncrease((PetscObject)mat));
6398   PetscFunctionReturn(PETSC_SUCCESS);
6399 }
6400 
6401 /*@
6402   MatZeroRowsIS - Zeros all entries (except possibly the main diagonal)
6403   of a set of rows of a matrix indicated by an `IS`
6404 
6405   Collective
6406 
6407   Input Parameters:
6408 + mat  - the matrix
6409 . is   - index set, `IS`, of rows to remove (if `NULL` then no row is removed)
6410 . diag - value put in all diagonals of eliminated rows
6411 . x    - optional vector of solutions for zeroed rows (other entries in vector are not used)
6412 - b    - optional vector of right-hand side, that will be adjusted by provided solution
6413 
6414   Level: intermediate
6415 
6416   Note:
6417   See `MatZeroRows()` for details on how this routine operates.
6418 
6419 .seealso: [](ch_matrices), `Mat`, `MatZeroRows()`, `MatZeroRowsColumns()`, `MatZeroRowsLocalIS()`, `MatZeroRowsStencil()`, `MatZeroEntries()`, `MatZeroRowsLocal()`, `MatSetOption()`,
6420           `MatZeroRowsColumnsLocal()`, `MatZeroRowsColumnsLocalIS()`, `MatZeroRowsColumnsIS()`, `MatZeroRowsColumnsStencil()`, `IS`
6421 @*/
6422 PetscErrorCode MatZeroRowsIS(Mat mat, IS is, PetscScalar diag, Vec x, Vec b)
6423 {
6424   PetscInt        numRows = 0;
6425   const PetscInt *rows    = NULL;
6426 
6427   PetscFunctionBegin;
6428   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
6429   PetscValidType(mat, 1);
6430   if (is) {
6431     PetscValidHeaderSpecific(is, IS_CLASSID, 2);
6432     PetscCall(ISGetLocalSize(is, &numRows));
6433     PetscCall(ISGetIndices(is, &rows));
6434   }
6435   PetscCall(MatZeroRows(mat, numRows, rows, diag, x, b));
6436   if (is) PetscCall(ISRestoreIndices(is, &rows));
6437   PetscFunctionReturn(PETSC_SUCCESS);
6438 }
6439 
6440 /*@
6441   MatZeroRowsStencil - Zeros all entries (except possibly the main diagonal)
6442   of a set of rows of a matrix indicated by a `MatStencil`. These rows must be local to the process.
6443 
6444   Collective
6445 
6446   Input Parameters:
6447 + mat     - the matrix
6448 . numRows - the number of rows to remove
6449 . rows    - the grid coordinates (and component number when dof > 1) for matrix rows indicated by an array of `MatStencil`
6450 . diag    - value put in all diagonals of eliminated rows (0.0 will even eliminate diagonal entry)
6451 . x       - optional vector of solutions for zeroed rows (other entries in vector are not used)
6452 - b       - optional vector of right-hand side, that will be adjusted by provided solution
6453 
6454   Level: intermediate
6455 
6456   Notes:
6457   See `MatZeroRows()` for details on how this routine operates.
6458 
6459   The grid coordinates are across the entire grid, not just the local portion
6460 
6461   For periodic boundary conditions use negative indices for values to the left (below 0; that are to be
6462   obtained by wrapping values from right edge). For values to the right of the last entry using that index plus one
6463   etc to obtain values that obtained by wrapping the values from the left edge. This does not work for anything but the
6464   `DM_BOUNDARY_PERIODIC` boundary type.
6465 
6466   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
6467   a single value per point) you can skip filling those indices.
6468 
6469   Fortran Note:
6470   `idxm` and `idxn` should be declared as
6471 .vb
6472     MatStencil idxm(4, m)
6473 .ve
6474   and the values inserted using
6475 .vb
6476     idxm(MatStencil_i, 1) = i
6477     idxm(MatStencil_j, 1) = j
6478     idxm(MatStencil_k, 1) = k
6479     idxm(MatStencil_c, 1) = c
6480    etc
6481 .ve
6482 
6483 .seealso: [](ch_matrices), `Mat`, `MatStencil`, `MatZeroRowsIS()`, `MatZeroRowsColumns()`, `MatZeroRowsLocalIS()`, `MatZeroRows()`, `MatZeroEntries()`, `MatZeroRowsLocal()`, `MatSetOption()`,
6484           `MatZeroRowsColumnsLocal()`, `MatZeroRowsColumnsLocalIS()`, `MatZeroRowsColumnsIS()`, `MatZeroRowsColumnsStencil()`
6485 @*/
6486 PetscErrorCode MatZeroRowsStencil(Mat mat, PetscInt numRows, const MatStencil rows[], PetscScalar diag, Vec x, Vec b)
6487 {
6488   PetscInt  dim    = mat->stencil.dim;
6489   PetscInt  sdim   = dim - (1 - (PetscInt)mat->stencil.noc);
6490   PetscInt *dims   = mat->stencil.dims + 1;
6491   PetscInt *starts = mat->stencil.starts;
6492   PetscInt *dxm    = (PetscInt *)rows;
6493   PetscInt *jdxm, i, j, tmp, numNewRows = 0;
6494 
6495   PetscFunctionBegin;
6496   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
6497   PetscValidType(mat, 1);
6498   if (numRows) PetscAssertPointer(rows, 3);
6499 
6500   PetscCall(PetscMalloc1(numRows, &jdxm));
6501   for (i = 0; i < numRows; ++i) {
6502     /* Skip unused dimensions (they are ordered k, j, i, c) */
6503     for (j = 0; j < 3 - sdim; ++j) dxm++;
6504     /* Local index in X dir */
6505     tmp = *dxm++ - starts[0];
6506     /* Loop over remaining dimensions */
6507     for (j = 0; j < dim - 1; ++j) {
6508       /* If nonlocal, set index to be negative */
6509       if ((*dxm++ - starts[j + 1]) < 0 || tmp < 0) tmp = PETSC_INT_MIN;
6510       /* Update local index */
6511       else tmp = tmp * dims[j] + *(dxm - 1) - starts[j + 1];
6512     }
6513     /* Skip component slot if necessary */
6514     if (mat->stencil.noc) dxm++;
6515     /* Local row number */
6516     if (tmp >= 0) jdxm[numNewRows++] = tmp;
6517   }
6518   PetscCall(MatZeroRowsLocal(mat, numNewRows, jdxm, diag, x, b));
6519   PetscCall(PetscFree(jdxm));
6520   PetscFunctionReturn(PETSC_SUCCESS);
6521 }
6522 
6523 /*@
6524   MatZeroRowsColumnsStencil - Zeros all row and column entries (except possibly the main diagonal)
6525   of a set of rows and columns of a matrix.
6526 
6527   Collective
6528 
6529   Input Parameters:
6530 + mat     - the matrix
6531 . numRows - the number of rows/columns to remove
6532 . rows    - the grid coordinates (and component number when dof > 1) for matrix rows
6533 . diag    - value put in all diagonals of eliminated rows (0.0 will even eliminate diagonal entry)
6534 . x       - optional vector of solutions for zeroed rows (other entries in vector are not used)
6535 - b       - optional vector of right-hand side, that will be adjusted by provided solution
6536 
6537   Level: intermediate
6538 
6539   Notes:
6540   See `MatZeroRowsColumns()` for details on how this routine operates.
6541 
6542   The grid coordinates are across the entire grid, not just the local portion
6543 
6544   For periodic boundary conditions use negative indices for values to the left (below 0; that are to be
6545   obtained by wrapping values from right edge). For values to the right of the last entry using that index plus one
6546   etc to obtain values that obtained by wrapping the values from the left edge. This does not work for anything but the
6547   `DM_BOUNDARY_PERIODIC` boundary type.
6548 
6549   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
6550   a single value per point) you can skip filling those indices.
6551 
6552   Fortran Note:
6553   `idxm` and `idxn` should be declared as
6554 .vb
6555     MatStencil idxm(4, m)
6556 .ve
6557   and the values inserted using
6558 .vb
6559     idxm(MatStencil_i, 1) = i
6560     idxm(MatStencil_j, 1) = j
6561     idxm(MatStencil_k, 1) = k
6562     idxm(MatStencil_c, 1) = c
6563     etc
6564 .ve
6565 
6566 .seealso: [](ch_matrices), `Mat`, `MatZeroRowsIS()`, `MatZeroRowsColumns()`, `MatZeroRowsLocalIS()`, `MatZeroRowsStencil()`, `MatZeroEntries()`, `MatZeroRowsLocal()`, `MatSetOption()`,
6567           `MatZeroRowsColumnsLocal()`, `MatZeroRowsColumnsLocalIS()`, `MatZeroRowsColumnsIS()`, `MatZeroRows()`
6568 @*/
6569 PetscErrorCode MatZeroRowsColumnsStencil(Mat mat, PetscInt numRows, const MatStencil rows[], PetscScalar diag, Vec x, Vec b)
6570 {
6571   PetscInt  dim    = mat->stencil.dim;
6572   PetscInt  sdim   = dim - (1 - (PetscInt)mat->stencil.noc);
6573   PetscInt *dims   = mat->stencil.dims + 1;
6574   PetscInt *starts = mat->stencil.starts;
6575   PetscInt *dxm    = (PetscInt *)rows;
6576   PetscInt *jdxm, i, j, tmp, numNewRows = 0;
6577 
6578   PetscFunctionBegin;
6579   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
6580   PetscValidType(mat, 1);
6581   if (numRows) PetscAssertPointer(rows, 3);
6582 
6583   PetscCall(PetscMalloc1(numRows, &jdxm));
6584   for (i = 0; i < numRows; ++i) {
6585     /* Skip unused dimensions (they are ordered k, j, i, c) */
6586     for (j = 0; j < 3 - sdim; ++j) dxm++;
6587     /* Local index in X dir */
6588     tmp = *dxm++ - starts[0];
6589     /* Loop over remaining dimensions */
6590     for (j = 0; j < dim - 1; ++j) {
6591       /* If nonlocal, set index to be negative */
6592       if ((*dxm++ - starts[j + 1]) < 0 || tmp < 0) tmp = PETSC_INT_MIN;
6593       /* Update local index */
6594       else tmp = tmp * dims[j] + *(dxm - 1) - starts[j + 1];
6595     }
6596     /* Skip component slot if necessary */
6597     if (mat->stencil.noc) dxm++;
6598     /* Local row number */
6599     if (tmp >= 0) jdxm[numNewRows++] = tmp;
6600   }
6601   PetscCall(MatZeroRowsColumnsLocal(mat, numNewRows, jdxm, diag, x, b));
6602   PetscCall(PetscFree(jdxm));
6603   PetscFunctionReturn(PETSC_SUCCESS);
6604 }
6605 
6606 /*@
6607   MatZeroRowsLocal - Zeros all entries (except possibly the main diagonal)
6608   of a set of rows of a matrix; using local numbering of rows.
6609 
6610   Collective
6611 
6612   Input Parameters:
6613 + mat     - the matrix
6614 . numRows - the number of rows to remove
6615 . rows    - the local row indices
6616 . diag    - value put in all diagonals of eliminated rows
6617 . x       - optional vector of solutions for zeroed rows (other entries in vector are not used)
6618 - b       - optional vector of right-hand side, that will be adjusted by provided solution
6619 
6620   Level: intermediate
6621 
6622   Notes:
6623   Before calling `MatZeroRowsLocal()`, the user must first set the
6624   local-to-global mapping by calling MatSetLocalToGlobalMapping(), this is often already set for matrices obtained with `DMCreateMatrix()`.
6625 
6626   See `MatZeroRows()` for details on how this routine operates.
6627 
6628 .seealso: [](ch_matrices), `Mat`, `MatZeroRowsIS()`, `MatZeroRowsColumns()`, `MatZeroRowsLocalIS()`, `MatZeroRowsStencil()`, `MatZeroEntries()`, `MatZeroRows()`, `MatSetOption()`,
6629           `MatZeroRowsColumnsLocal()`, `MatZeroRowsColumnsLocalIS()`, `MatZeroRowsColumnsIS()`, `MatZeroRowsColumnsStencil()`
6630 @*/
6631 PetscErrorCode MatZeroRowsLocal(Mat mat, PetscInt numRows, const PetscInt rows[], PetscScalar diag, Vec x, Vec b)
6632 {
6633   PetscFunctionBegin;
6634   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
6635   PetscValidType(mat, 1);
6636   if (numRows) PetscAssertPointer(rows, 3);
6637   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
6638   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
6639   MatCheckPreallocated(mat, 1);
6640 
6641   if (mat->ops->zerorowslocal) {
6642     PetscUseTypeMethod(mat, zerorowslocal, numRows, rows, diag, x, b);
6643   } else {
6644     IS        is, newis;
6645     PetscInt *newRows, nl = 0;
6646 
6647     PetscCheck(mat->rmap->mapping, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Need to provide local to global mapping to matrix first");
6648     PetscCall(ISCreateGeneral(PETSC_COMM_SELF, numRows, rows, PETSC_USE_POINTER, &is));
6649     PetscCall(ISLocalToGlobalMappingApplyIS(mat->rmap->mapping, is, &newis));
6650     PetscCall(ISGetIndices(newis, (const PetscInt **)&newRows));
6651     for (PetscInt i = 0; i < numRows; i++)
6652       if (newRows[i] > -1) newRows[nl++] = newRows[i];
6653     PetscUseTypeMethod(mat, zerorows, nl, newRows, diag, x, b);
6654     PetscCall(ISRestoreIndices(newis, (const PetscInt **)&newRows));
6655     PetscCall(ISDestroy(&newis));
6656     PetscCall(ISDestroy(&is));
6657   }
6658   PetscCall(PetscObjectStateIncrease((PetscObject)mat));
6659   PetscFunctionReturn(PETSC_SUCCESS);
6660 }
6661 
6662 /*@
6663   MatZeroRowsLocalIS - Zeros all entries (except possibly the main diagonal)
6664   of a set of rows of a matrix; using local numbering of rows.
6665 
6666   Collective
6667 
6668   Input Parameters:
6669 + mat  - the matrix
6670 . is   - index set of rows to remove
6671 . diag - value put in all diagonals of eliminated rows
6672 . x    - optional vector of solutions for zeroed rows (other entries in vector are not used)
6673 - b    - optional vector of right-hand side, that will be adjusted by provided solution
6674 
6675   Level: intermediate
6676 
6677   Notes:
6678   Before calling `MatZeroRowsLocalIS()`, the user must first set the
6679   local-to-global mapping by calling `MatSetLocalToGlobalMapping()`, this is often already set for matrices obtained with `DMCreateMatrix()`.
6680 
6681   See `MatZeroRows()` for details on how this routine operates.
6682 
6683 .seealso: [](ch_matrices), `Mat`, `MatZeroRowsIS()`, `MatZeroRowsColumns()`, `MatZeroRows()`, `MatZeroRowsStencil()`, `MatZeroEntries()`, `MatZeroRowsLocal()`, `MatSetOption()`,
6684           `MatZeroRowsColumnsLocal()`, `MatZeroRowsColumnsLocalIS()`, `MatZeroRowsColumnsIS()`, `MatZeroRowsColumnsStencil()`
6685 @*/
6686 PetscErrorCode MatZeroRowsLocalIS(Mat mat, IS is, PetscScalar diag, Vec x, Vec b)
6687 {
6688   PetscInt        numRows;
6689   const PetscInt *rows;
6690 
6691   PetscFunctionBegin;
6692   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
6693   PetscValidType(mat, 1);
6694   PetscValidHeaderSpecific(is, IS_CLASSID, 2);
6695   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
6696   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
6697   MatCheckPreallocated(mat, 1);
6698 
6699   PetscCall(ISGetLocalSize(is, &numRows));
6700   PetscCall(ISGetIndices(is, &rows));
6701   PetscCall(MatZeroRowsLocal(mat, numRows, rows, diag, x, b));
6702   PetscCall(ISRestoreIndices(is, &rows));
6703   PetscFunctionReturn(PETSC_SUCCESS);
6704 }
6705 
6706 /*@
6707   MatZeroRowsColumnsLocal - Zeros all entries (except possibly the main diagonal)
6708   of a set of rows and columns of a matrix; using local numbering of rows.
6709 
6710   Collective
6711 
6712   Input Parameters:
6713 + mat     - the matrix
6714 . numRows - the number of rows to remove
6715 . rows    - the global row indices
6716 . diag    - value put in all diagonals of eliminated rows
6717 . x       - optional vector of solutions for zeroed rows (other entries in vector are not used)
6718 - b       - optional vector of right-hand side, that will be adjusted by provided solution
6719 
6720   Level: intermediate
6721 
6722   Notes:
6723   Before calling `MatZeroRowsColumnsLocal()`, the user must first set the
6724   local-to-global mapping by calling `MatSetLocalToGlobalMapping()`, this is often already set for matrices obtained with `DMCreateMatrix()`.
6725 
6726   See `MatZeroRowsColumns()` for details on how this routine operates.
6727 
6728 .seealso: [](ch_matrices), `Mat`, `MatZeroRowsIS()`, `MatZeroRowsColumns()`, `MatZeroRowsLocalIS()`, `MatZeroRowsStencil()`, `MatZeroEntries()`, `MatZeroRowsLocal()`, `MatSetOption()`,
6729           `MatZeroRows()`, `MatZeroRowsColumnsLocalIS()`, `MatZeroRowsColumnsIS()`, `MatZeroRowsColumnsStencil()`
6730 @*/
6731 PetscErrorCode MatZeroRowsColumnsLocal(Mat mat, PetscInt numRows, const PetscInt rows[], PetscScalar diag, Vec x, Vec b)
6732 {
6733   PetscFunctionBegin;
6734   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
6735   PetscValidType(mat, 1);
6736   if (numRows) PetscAssertPointer(rows, 3);
6737   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
6738   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
6739   MatCheckPreallocated(mat, 1);
6740 
6741   if (mat->ops->zerorowscolumnslocal) {
6742     PetscUseTypeMethod(mat, zerorowscolumnslocal, numRows, rows, diag, x, b);
6743   } else {
6744     IS        is, newis;
6745     PetscInt *newRows, nl = 0;
6746 
6747     PetscCheck(mat->rmap->mapping, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Need to provide local to global mapping to matrix first");
6748     PetscCall(ISCreateGeneral(PETSC_COMM_SELF, numRows, rows, PETSC_USE_POINTER, &is));
6749     PetscCall(ISLocalToGlobalMappingApplyIS(mat->rmap->mapping, is, &newis));
6750     PetscCall(ISGetIndices(newis, (const PetscInt **)&newRows));
6751     for (PetscInt i = 0; i < numRows; i++)
6752       if (newRows[i] > -1) newRows[nl++] = newRows[i];
6753     PetscUseTypeMethod(mat, zerorowscolumns, nl, newRows, diag, x, b);
6754     PetscCall(ISRestoreIndices(newis, (const PetscInt **)&newRows));
6755     PetscCall(ISDestroy(&newis));
6756     PetscCall(ISDestroy(&is));
6757   }
6758   PetscCall(PetscObjectStateIncrease((PetscObject)mat));
6759   PetscFunctionReturn(PETSC_SUCCESS);
6760 }
6761 
6762 /*@
6763   MatZeroRowsColumnsLocalIS - Zeros all entries (except possibly the main diagonal)
6764   of a set of rows and columns of a matrix; using local numbering of rows.
6765 
6766   Collective
6767 
6768   Input Parameters:
6769 + mat  - the matrix
6770 . is   - index set of rows to remove
6771 . diag - value put in all diagonals of eliminated rows
6772 . x    - optional vector of solutions for zeroed rows (other entries in vector are not used)
6773 - b    - optional vector of right-hand side, that will be adjusted by provided solution
6774 
6775   Level: intermediate
6776 
6777   Notes:
6778   Before calling `MatZeroRowsColumnsLocalIS()`, the user must first set the
6779   local-to-global mapping by calling `MatSetLocalToGlobalMapping()`, this is often already set for matrices obtained with `DMCreateMatrix()`.
6780 
6781   See `MatZeroRowsColumns()` for details on how this routine operates.
6782 
6783 .seealso: [](ch_matrices), `Mat`, `MatZeroRowsIS()`, `MatZeroRowsColumns()`, `MatZeroRowsLocalIS()`, `MatZeroRowsStencil()`, `MatZeroEntries()`, `MatZeroRowsLocal()`, `MatSetOption()`,
6784           `MatZeroRowsColumnsLocal()`, `MatZeroRows()`, `MatZeroRowsColumnsIS()`, `MatZeroRowsColumnsStencil()`
6785 @*/
6786 PetscErrorCode MatZeroRowsColumnsLocalIS(Mat mat, IS is, PetscScalar diag, Vec x, Vec b)
6787 {
6788   PetscInt        numRows;
6789   const PetscInt *rows;
6790 
6791   PetscFunctionBegin;
6792   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
6793   PetscValidType(mat, 1);
6794   PetscValidHeaderSpecific(is, IS_CLASSID, 2);
6795   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
6796   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
6797   MatCheckPreallocated(mat, 1);
6798 
6799   PetscCall(ISGetLocalSize(is, &numRows));
6800   PetscCall(ISGetIndices(is, &rows));
6801   PetscCall(MatZeroRowsColumnsLocal(mat, numRows, rows, diag, x, b));
6802   PetscCall(ISRestoreIndices(is, &rows));
6803   PetscFunctionReturn(PETSC_SUCCESS);
6804 }
6805 
6806 /*@
6807   MatGetSize - Returns the numbers of rows and columns in a matrix.
6808 
6809   Not Collective
6810 
6811   Input Parameter:
6812 . mat - the matrix
6813 
6814   Output Parameters:
6815 + m - the number of global rows
6816 - n - the number of global columns
6817 
6818   Level: beginner
6819 
6820   Note:
6821   Both output parameters can be `NULL` on input.
6822 
6823 .seealso: [](ch_matrices), `Mat`, `MatSetSizes()`, `MatGetLocalSize()`
6824 @*/
6825 PetscErrorCode MatGetSize(Mat mat, PetscInt *m, PetscInt *n)
6826 {
6827   PetscFunctionBegin;
6828   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
6829   if (m) *m = mat->rmap->N;
6830   if (n) *n = mat->cmap->N;
6831   PetscFunctionReturn(PETSC_SUCCESS);
6832 }
6833 
6834 /*@
6835   MatGetLocalSize - For most matrix formats, excluding `MATELEMENTAL` and `MATSCALAPACK`, Returns the number of local rows and local columns
6836   of a matrix. For all matrices this is the local size of the left and right vectors as returned by `MatCreateVecs()`.
6837 
6838   Not Collective
6839 
6840   Input Parameter:
6841 . mat - the matrix
6842 
6843   Output Parameters:
6844 + m - the number of local rows, use `NULL` to not obtain this value
6845 - n - the number of local columns, use `NULL` to not obtain this value
6846 
6847   Level: beginner
6848 
6849 .seealso: [](ch_matrices), `Mat`, `MatSetSizes()`, `MatGetSize()`
6850 @*/
6851 PetscErrorCode MatGetLocalSize(Mat mat, PetscInt *m, PetscInt *n)
6852 {
6853   PetscFunctionBegin;
6854   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
6855   if (m) PetscAssertPointer(m, 2);
6856   if (n) PetscAssertPointer(n, 3);
6857   if (m) *m = mat->rmap->n;
6858   if (n) *n = mat->cmap->n;
6859   PetscFunctionReturn(PETSC_SUCCESS);
6860 }
6861 
6862 /*@
6863   MatGetOwnershipRangeColumn - Returns the range of matrix columns associated with rows of a
6864   vector one multiplies this matrix by that are owned by this processor.
6865 
6866   Not Collective, unless matrix has not been allocated, then collective
6867 
6868   Input Parameter:
6869 . mat - the matrix
6870 
6871   Output Parameters:
6872 + m - the global index of the first local column, use `NULL` to not obtain this value
6873 - n - one more than the global index of the last local column, use `NULL` to not obtain this value
6874 
6875   Level: developer
6876 
6877   Notes:
6878   If the `Mat` was obtained from a `DM` with `DMCreateMatrix()`, then the range values are determined by the specific `DM`.
6879 
6880   If the `Mat` was created directly the range values are determined by the local size passed to `MatSetSizes()` or `MatCreateAIJ()`.
6881   If `PETSC_DECIDE` was passed as the local size, then the vector uses default values for the range using `PetscSplitOwnership()`.
6882 
6883   For certain `DM`, such as `DMDA`, it is better to use `DM` specific routines, such as `DMDAGetGhostCorners()`, to determine
6884   the local values in the matrix.
6885 
6886   Returns the columns of the "diagonal block" for most sparse matrix formats. See [Matrix
6887   Layouts](sec_matlayout) for details on matrix layouts.
6888 
6889 .seealso: [](ch_matrices), `Mat`, `MatGetOwnershipRange()`, `MatGetOwnershipRanges()`, `MatGetOwnershipRangesColumn()`, `PetscLayout`,
6890           `MatSetSizes()`, `MatCreateAIJ()`, `DMDAGetGhostCorners()`, `DM`
6891 @*/
6892 PetscErrorCode MatGetOwnershipRangeColumn(Mat mat, PetscInt *m, PetscInt *n)
6893 {
6894   PetscFunctionBegin;
6895   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
6896   PetscValidType(mat, 1);
6897   if (m) PetscAssertPointer(m, 2);
6898   if (n) PetscAssertPointer(n, 3);
6899   MatCheckPreallocated(mat, 1);
6900   if (m) *m = mat->cmap->rstart;
6901   if (n) *n = mat->cmap->rend;
6902   PetscFunctionReturn(PETSC_SUCCESS);
6903 }
6904 
6905 /*@
6906   MatGetOwnershipRange - For matrices that own values by row, excludes `MATELEMENTAL` and `MATSCALAPACK`, returns the range of matrix rows owned by
6907   this MPI process.
6908 
6909   Not Collective
6910 
6911   Input Parameter:
6912 . mat - the matrix
6913 
6914   Output Parameters:
6915 + m - the global index of the first local row, use `NULL` to not obtain this value
6916 - n - one more than the global index of the last local row, use `NULL` to not obtain this value
6917 
6918   Level: beginner
6919 
6920   Notes:
6921   If the `Mat` was obtained from a `DM` with `DMCreateMatrix()`, then the range values are determined by the specific `DM`.
6922 
6923   If the `Mat` was created directly the range values are determined by the local size passed to `MatSetSizes()` or `MatCreateAIJ()`.
6924   If `PETSC_DECIDE` was passed as the local size, then the vector uses default values for the range using `PetscSplitOwnership()`.
6925 
6926   For certain `DM`, such as `DMDA`, it is better to use `DM` specific routines, such as `DMDAGetGhostCorners()`, to determine
6927   the local values in the matrix.
6928 
6929   The high argument is one more than the last element stored locally.
6930 
6931   For all matrices  it returns the range of matrix rows associated with rows of a vector that
6932   would contain the result of a matrix vector product with this matrix. See [Matrix
6933   Layouts](sec_matlayout) for details on matrix layouts.
6934 
6935 .seealso: [](ch_matrices), `Mat`, `MatGetOwnershipRanges()`, `MatGetOwnershipRangeColumn()`, `MatGetOwnershipRangesColumn()`, `PetscSplitOwnership()`,
6936           `PetscSplitOwnershipBlock()`, `PetscLayout`, `MatSetSizes()`, `MatCreateAIJ()`, `DMDAGetGhostCorners()`, `DM`
6937 @*/
6938 PetscErrorCode MatGetOwnershipRange(Mat mat, PetscInt *m, PetscInt *n)
6939 {
6940   PetscFunctionBegin;
6941   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
6942   PetscValidType(mat, 1);
6943   if (m) PetscAssertPointer(m, 2);
6944   if (n) PetscAssertPointer(n, 3);
6945   MatCheckPreallocated(mat, 1);
6946   if (m) *m = mat->rmap->rstart;
6947   if (n) *n = mat->rmap->rend;
6948   PetscFunctionReturn(PETSC_SUCCESS);
6949 }
6950 
6951 /*@C
6952   MatGetOwnershipRanges - For matrices that own values by row, excludes `MATELEMENTAL` and
6953   `MATSCALAPACK`, returns the range of matrix rows owned by each process.
6954 
6955   Not Collective, unless matrix has not been allocated
6956 
6957   Input Parameter:
6958 . mat - the matrix
6959 
6960   Output Parameter:
6961 . ranges - start of each processors portion plus one more than the total length at the end, of length `size` + 1
6962            where `size` is the number of MPI processes used by `mat`
6963 
6964   Level: beginner
6965 
6966   Notes:
6967   If the `Mat` was obtained from a `DM` with `DMCreateMatrix()`, then the range values are determined by the specific `DM`.
6968 
6969   If the `Mat` was created directly the range values are determined by the local size passed to `MatSetSizes()` or `MatCreateAIJ()`.
6970   If `PETSC_DECIDE` was passed as the local size, then the vector uses default values for the range using `PetscSplitOwnership()`.
6971 
6972   For certain `DM`, such as `DMDA`, it is better to use `DM` specific routines, such as `DMDAGetGhostCorners()`, to determine
6973   the local values in the matrix.
6974 
6975   For all matrices  it returns the ranges of matrix rows associated with rows of a vector that
6976   would contain the result of a matrix vector product with this matrix. See [Matrix
6977   Layouts](sec_matlayout) for details on matrix layouts.
6978 
6979 .seealso: [](ch_matrices), `Mat`, `MatGetOwnershipRange()`, `MatGetOwnershipRangeColumn()`, `MatGetOwnershipRangesColumn()`, `PetscLayout`,
6980           `PetscSplitOwnership()`, `PetscSplitOwnershipBlock()`, `MatSetSizes()`, `MatCreateAIJ()`,
6981           `DMDAGetGhostCorners()`, `DM`
6982 @*/
6983 PetscErrorCode MatGetOwnershipRanges(Mat mat, const PetscInt *ranges[])
6984 {
6985   PetscFunctionBegin;
6986   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
6987   PetscValidType(mat, 1);
6988   MatCheckPreallocated(mat, 1);
6989   PetscCall(PetscLayoutGetRanges(mat->rmap, ranges));
6990   PetscFunctionReturn(PETSC_SUCCESS);
6991 }
6992 
6993 /*@C
6994   MatGetOwnershipRangesColumn - Returns the ranges of matrix columns associated with rows of a
6995   vector one multiplies this vector by that are owned by each processor.
6996 
6997   Not Collective, unless matrix has not been allocated
6998 
6999   Input Parameter:
7000 . mat - the matrix
7001 
7002   Output Parameter:
7003 . ranges - start of each processors portion plus one more than the total length at the end
7004 
7005   Level: beginner
7006 
7007   Notes:
7008   If the `Mat` was obtained from a `DM` with `DMCreateMatrix()`, then the range values are determined by the specific `DM`.
7009 
7010   If the `Mat` was created directly the range values are determined by the local size passed to `MatSetSizes()` or `MatCreateAIJ()`.
7011   If `PETSC_DECIDE` was passed as the local size, then the vector uses default values for the range using `PetscSplitOwnership()`.
7012 
7013   For certain `DM`, such as `DMDA`, it is better to use `DM` specific routines, such as `DMDAGetGhostCorners()`, to determine
7014   the local values in the matrix.
7015 
7016   Returns the columns of the "diagonal blocks", for most sparse matrix formats. See [Matrix
7017   Layouts](sec_matlayout) for details on matrix layouts.
7018 
7019 .seealso: [](ch_matrices), `Mat`, `MatGetOwnershipRange()`, `MatGetOwnershipRangeColumn()`, `MatGetOwnershipRanges()`,
7020           `PetscSplitOwnership()`, `PetscSplitOwnershipBlock()`, `PetscLayout`, `MatSetSizes()`, `MatCreateAIJ()`,
7021           `DMDAGetGhostCorners()`, `DM`
7022 @*/
7023 PetscErrorCode MatGetOwnershipRangesColumn(Mat mat, const PetscInt *ranges[])
7024 {
7025   PetscFunctionBegin;
7026   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
7027   PetscValidType(mat, 1);
7028   MatCheckPreallocated(mat, 1);
7029   PetscCall(PetscLayoutGetRanges(mat->cmap, ranges));
7030   PetscFunctionReturn(PETSC_SUCCESS);
7031 }
7032 
7033 /*@
7034   MatGetOwnershipIS - Get row and column ownership of a matrices' values as index sets.
7035 
7036   Not Collective
7037 
7038   Input Parameter:
7039 . A - matrix
7040 
7041   Output Parameters:
7042 + rows - rows in which this process owns elements, , use `NULL` to not obtain this value
7043 - cols - columns in which this process owns elements, use `NULL` to not obtain this value
7044 
7045   Level: intermediate
7046 
7047   Note:
7048   You should call `ISDestroy()` on the returned `IS`
7049 
7050   For most matrices, excluding `MATELEMENTAL` and `MATSCALAPACK`, this corresponds to values
7051   returned by `MatGetOwnershipRange()`, `MatGetOwnershipRangeColumn()`. For `MATELEMENTAL` and
7052   `MATSCALAPACK` the ownership is more complicated. See [Matrix Layouts](sec_matlayout) for
7053   details on matrix layouts.
7054 
7055 .seealso: [](ch_matrices), `IS`, `Mat`, `MatGetOwnershipRanges()`, `MatSetValues()`, `MATELEMENTAL`, `MATSCALAPACK`
7056 @*/
7057 PetscErrorCode MatGetOwnershipIS(Mat A, IS *rows, IS *cols)
7058 {
7059   PetscErrorCode (*f)(Mat, IS *, IS *);
7060 
7061   PetscFunctionBegin;
7062   PetscValidHeaderSpecific(A, MAT_CLASSID, 1);
7063   PetscValidType(A, 1);
7064   MatCheckPreallocated(A, 1);
7065   PetscCall(PetscObjectQueryFunction((PetscObject)A, "MatGetOwnershipIS_C", &f));
7066   if (f) {
7067     PetscCall((*f)(A, rows, cols));
7068   } else { /* Create a standard row-based partition, each process is responsible for ALL columns in their row block */
7069     if (rows) PetscCall(ISCreateStride(PETSC_COMM_SELF, A->rmap->n, A->rmap->rstart, 1, rows));
7070     if (cols) PetscCall(ISCreateStride(PETSC_COMM_SELF, A->cmap->N, 0, 1, cols));
7071   }
7072   PetscFunctionReturn(PETSC_SUCCESS);
7073 }
7074 
7075 /*@
7076   MatILUFactorSymbolic - Performs symbolic ILU factorization of a matrix obtained with `MatGetFactor()`
7077   Uses levels of fill only, not drop tolerance. Use `MatLUFactorNumeric()`
7078   to complete the factorization.
7079 
7080   Collective
7081 
7082   Input Parameters:
7083 + fact - the factorized matrix obtained with `MatGetFactor()`
7084 . mat  - the matrix
7085 . row  - row permutation
7086 . col  - column permutation
7087 - info - structure containing
7088 .vb
7089       levels - number of levels of fill.
7090       expected fill - as ratio of original fill.
7091       1 or 0 - indicating force fill on diagonal (improves robustness for matrices
7092                 missing diagonal entries)
7093 .ve
7094 
7095   Level: developer
7096 
7097   Notes:
7098   See [Matrix Factorization](sec_matfactor) for additional information.
7099 
7100   Most users should employ the `KSP` interface for linear solvers
7101   instead of working directly with matrix algebra routines such as this.
7102   See, e.g., `KSPCreate()`.
7103 
7104   Uses the definition of level of fill as in Y. Saad, {cite}`saad2003`
7105 
7106   Fortran Note:
7107   A valid (non-null) `info` argument must be provided
7108 
7109 .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatGetFactor()`, `MatLUFactorSymbolic()`, `MatLUFactorNumeric()`, `MatCholeskyFactor()`
7110           `MatGetOrdering()`, `MatFactorInfo`
7111 @*/
7112 PetscErrorCode MatILUFactorSymbolic(Mat fact, Mat mat, IS row, IS col, const MatFactorInfo *info)
7113 {
7114   PetscFunctionBegin;
7115   PetscValidHeaderSpecific(mat, MAT_CLASSID, 2);
7116   PetscValidType(mat, 2);
7117   if (row) PetscValidHeaderSpecific(row, IS_CLASSID, 3);
7118   if (col) PetscValidHeaderSpecific(col, IS_CLASSID, 4);
7119   PetscAssertPointer(info, 5);
7120   PetscAssertPointer(fact, 1);
7121   PetscCheck(info->levels >= 0, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_OUTOFRANGE, "Levels of fill negative %" PetscInt_FMT, (PetscInt)info->levels);
7122   PetscCheck(info->fill >= 1.0, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_OUTOFRANGE, "Expected fill less than 1.0 %g", (double)info->fill);
7123   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
7124   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
7125   MatCheckPreallocated(mat, 2);
7126 
7127   if (!fact->trivialsymbolic) PetscCall(PetscLogEventBegin(MAT_ILUFactorSymbolic, mat, row, col, 0));
7128   PetscUseTypeMethod(fact, ilufactorsymbolic, mat, row, col, info);
7129   if (!fact->trivialsymbolic) PetscCall(PetscLogEventEnd(MAT_ILUFactorSymbolic, mat, row, col, 0));
7130   PetscFunctionReturn(PETSC_SUCCESS);
7131 }
7132 
7133 /*@
7134   MatICCFactorSymbolic - Performs symbolic incomplete
7135   Cholesky factorization for a symmetric matrix.  Use
7136   `MatCholeskyFactorNumeric()` to complete the factorization.
7137 
7138   Collective
7139 
7140   Input Parameters:
7141 + fact - the factorized matrix obtained with `MatGetFactor()`
7142 . mat  - the matrix to be factored
7143 . perm - row and column permutation
7144 - info - structure containing
7145 .vb
7146       levels - number of levels of fill.
7147       expected fill - as ratio of original fill.
7148 .ve
7149 
7150   Level: developer
7151 
7152   Notes:
7153   Most users should employ the `KSP` interface for linear solvers
7154   instead of working directly with matrix algebra routines such as this.
7155   See, e.g., `KSPCreate()`.
7156 
7157   This uses the definition of level of fill as in Y. Saad {cite}`saad2003`
7158 
7159   Fortran Note:
7160   A valid (non-null) `info` argument must be provided
7161 
7162 .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatCholeskyFactorNumeric()`, `MatCholeskyFactor()`, `MatFactorInfo`
7163 @*/
7164 PetscErrorCode MatICCFactorSymbolic(Mat fact, Mat mat, IS perm, const MatFactorInfo *info)
7165 {
7166   PetscFunctionBegin;
7167   PetscValidHeaderSpecific(mat, MAT_CLASSID, 2);
7168   PetscValidType(mat, 2);
7169   if (perm) PetscValidHeaderSpecific(perm, IS_CLASSID, 3);
7170   PetscAssertPointer(info, 4);
7171   PetscAssertPointer(fact, 1);
7172   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
7173   PetscCheck(info->levels >= 0, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_OUTOFRANGE, "Levels negative %" PetscInt_FMT, (PetscInt)info->levels);
7174   PetscCheck(info->fill >= 1.0, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_OUTOFRANGE, "Expected fill less than 1.0 %g", (double)info->fill);
7175   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
7176   MatCheckPreallocated(mat, 2);
7177 
7178   if (!fact->trivialsymbolic) PetscCall(PetscLogEventBegin(MAT_ICCFactorSymbolic, mat, perm, 0, 0));
7179   PetscUseTypeMethod(fact, iccfactorsymbolic, mat, perm, info);
7180   if (!fact->trivialsymbolic) PetscCall(PetscLogEventEnd(MAT_ICCFactorSymbolic, mat, perm, 0, 0));
7181   PetscFunctionReturn(PETSC_SUCCESS);
7182 }
7183 
7184 /*@C
7185   MatCreateSubMatrices - Extracts several submatrices from a matrix. If submat
7186   points to an array of valid matrices, they may be reused to store the new
7187   submatrices.
7188 
7189   Collective
7190 
7191   Input Parameters:
7192 + mat   - the matrix
7193 . n     - the number of submatrixes to be extracted (on this processor, may be zero)
7194 . irow  - index set of rows to extract
7195 . icol  - index set of columns to extract
7196 - scall - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`
7197 
7198   Output Parameter:
7199 . submat - the array of submatrices
7200 
7201   Level: advanced
7202 
7203   Notes:
7204   `MatCreateSubMatrices()` can extract ONLY sequential submatrices
7205   (from both sequential and parallel matrices). Use `MatCreateSubMatrix()`
7206   to extract a parallel submatrix.
7207 
7208   Some matrix types place restrictions on the row and column
7209   indices, such as that they be sorted or that they be equal to each other.
7210 
7211   The index sets may not have duplicate entries.
7212 
7213   When extracting submatrices from a parallel matrix, each processor can
7214   form a different submatrix by setting the rows and columns of its
7215   individual index sets according to the local submatrix desired.
7216 
7217   When finished using the submatrices, the user should destroy
7218   them with `MatDestroySubMatrices()`.
7219 
7220   `MAT_REUSE_MATRIX` can only be used when the nonzero structure of the
7221   original matrix has not changed from that last call to `MatCreateSubMatrices()`.
7222 
7223   This routine creates the matrices in submat; you should NOT create them before
7224   calling it. It also allocates the array of matrix pointers submat.
7225 
7226   For `MATBAIJ` matrices the index sets must respect the block structure, that is if they
7227   request one row/column in a block, they must request all rows/columns that are in
7228   that block. For example, if the block size is 2 you cannot request just row 0 and
7229   column 0.
7230 
7231   Fortran Note:
7232 .vb
7233   Mat, pointer :: submat(:)
7234 .ve
7235 
7236 .seealso: [](ch_matrices), `Mat`, `MatDestroySubMatrices()`, `MatCreateSubMatrix()`, `MatGetRow()`, `MatGetDiagonal()`, `MatReuse`
7237 @*/
7238 PetscErrorCode MatCreateSubMatrices(Mat mat, PetscInt n, const IS irow[], const IS icol[], MatReuse scall, Mat *submat[])
7239 {
7240   PetscInt  i;
7241   PetscBool eq;
7242 
7243   PetscFunctionBegin;
7244   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
7245   PetscValidType(mat, 1);
7246   if (n) {
7247     PetscAssertPointer(irow, 3);
7248     for (i = 0; i < n; i++) PetscValidHeaderSpecific(irow[i], IS_CLASSID, 3);
7249     PetscAssertPointer(icol, 4);
7250     for (i = 0; i < n; i++) PetscValidHeaderSpecific(icol[i], IS_CLASSID, 4);
7251   }
7252   PetscAssertPointer(submat, 6);
7253   if (n && scall == MAT_REUSE_MATRIX) {
7254     PetscAssertPointer(*submat, 6);
7255     for (i = 0; i < n; i++) PetscValidHeaderSpecific((*submat)[i], MAT_CLASSID, 6);
7256   }
7257   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
7258   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
7259   MatCheckPreallocated(mat, 1);
7260   PetscCall(PetscLogEventBegin(MAT_CreateSubMats, mat, 0, 0, 0));
7261   PetscUseTypeMethod(mat, createsubmatrices, n, irow, icol, scall, submat);
7262   PetscCall(PetscLogEventEnd(MAT_CreateSubMats, mat, 0, 0, 0));
7263   for (i = 0; i < n; i++) {
7264     (*submat)[i]->factortype = MAT_FACTOR_NONE; /* in case in place factorization was previously done on submatrix */
7265     PetscCall(ISEqualUnsorted(irow[i], icol[i], &eq));
7266     if (eq) PetscCall(MatPropagateSymmetryOptions(mat, (*submat)[i]));
7267 #if defined(PETSC_HAVE_VIENNACL) || defined(PETSC_HAVE_CUDA) || defined(PETSC_HAVE_HIP)
7268     if (mat->boundtocpu && mat->bindingpropagates) {
7269       PetscCall(MatBindToCPU((*submat)[i], PETSC_TRUE));
7270       PetscCall(MatSetBindingPropagates((*submat)[i], PETSC_TRUE));
7271     }
7272 #endif
7273   }
7274   PetscFunctionReturn(PETSC_SUCCESS);
7275 }
7276 
7277 /*@C
7278   MatCreateSubMatricesMPI - Extracts MPI submatrices across a sub communicator of `mat` (by pairs of `IS` that may live on subcomms).
7279 
7280   Collective
7281 
7282   Input Parameters:
7283 + mat   - the matrix
7284 . n     - the number of submatrixes to be extracted
7285 . irow  - index set of rows to extract
7286 . icol  - index set of columns to extract
7287 - scall - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`
7288 
7289   Output Parameter:
7290 . submat - the array of submatrices
7291 
7292   Level: advanced
7293 
7294   Note:
7295   This is used by `PCGASM`
7296 
7297 .seealso: [](ch_matrices), `Mat`, `PCGASM`, `MatCreateSubMatrices()`, `MatCreateSubMatrix()`, `MatGetRow()`, `MatGetDiagonal()`, `MatReuse`
7298 @*/
7299 PetscErrorCode MatCreateSubMatricesMPI(Mat mat, PetscInt n, const IS irow[], const IS icol[], MatReuse scall, Mat *submat[])
7300 {
7301   PetscInt  i;
7302   PetscBool eq;
7303 
7304   PetscFunctionBegin;
7305   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
7306   PetscValidType(mat, 1);
7307   if (n) {
7308     PetscAssertPointer(irow, 3);
7309     PetscValidHeaderSpecific(*irow, IS_CLASSID, 3);
7310     PetscAssertPointer(icol, 4);
7311     PetscValidHeaderSpecific(*icol, IS_CLASSID, 4);
7312   }
7313   PetscAssertPointer(submat, 6);
7314   if (n && scall == MAT_REUSE_MATRIX) {
7315     PetscAssertPointer(*submat, 6);
7316     PetscValidHeaderSpecific(**submat, MAT_CLASSID, 6);
7317   }
7318   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
7319   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
7320   MatCheckPreallocated(mat, 1);
7321 
7322   PetscCall(PetscLogEventBegin(MAT_CreateSubMats, mat, 0, 0, 0));
7323   PetscUseTypeMethod(mat, createsubmatricesmpi, n, irow, icol, scall, submat);
7324   PetscCall(PetscLogEventEnd(MAT_CreateSubMats, mat, 0, 0, 0));
7325   for (i = 0; i < n; i++) {
7326     PetscCall(ISEqualUnsorted(irow[i], icol[i], &eq));
7327     if (eq) PetscCall(MatPropagateSymmetryOptions(mat, (*submat)[i]));
7328   }
7329   PetscFunctionReturn(PETSC_SUCCESS);
7330 }
7331 
7332 /*@C
7333   MatDestroyMatrices - Destroys an array of matrices
7334 
7335   Collective
7336 
7337   Input Parameters:
7338 + n   - the number of local matrices
7339 - mat - the matrices (this is a pointer to the array of matrices)
7340 
7341   Level: advanced
7342 
7343   Notes:
7344   Frees not only the matrices, but also the array that contains the matrices
7345 
7346   For matrices obtained with  `MatCreateSubMatrices()` use `MatDestroySubMatrices()`
7347 
7348 .seealso: [](ch_matrices), `Mat`, `MatCreateSubMatrices()`, `MatDestroySubMatrices()`
7349 @*/
7350 PetscErrorCode MatDestroyMatrices(PetscInt n, Mat *mat[])
7351 {
7352   PetscInt i;
7353 
7354   PetscFunctionBegin;
7355   if (!*mat) PetscFunctionReturn(PETSC_SUCCESS);
7356   PetscCheck(n >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Trying to destroy negative number of matrices %" PetscInt_FMT, n);
7357   PetscAssertPointer(mat, 2);
7358 
7359   for (i = 0; i < n; i++) PetscCall(MatDestroy(&(*mat)[i]));
7360 
7361   /* memory is allocated even if n = 0 */
7362   PetscCall(PetscFree(*mat));
7363   PetscFunctionReturn(PETSC_SUCCESS);
7364 }
7365 
7366 /*@C
7367   MatDestroySubMatrices - Destroys a set of matrices obtained with `MatCreateSubMatrices()`.
7368 
7369   Collective
7370 
7371   Input Parameters:
7372 + n   - the number of local matrices
7373 - mat - the matrices (this is a pointer to the array of matrices, to match the calling sequence of `MatCreateSubMatrices()`)
7374 
7375   Level: advanced
7376 
7377   Note:
7378   Frees not only the matrices, but also the array that contains the matrices
7379 
7380 .seealso: [](ch_matrices), `Mat`, `MatCreateSubMatrices()`, `MatDestroyMatrices()`
7381 @*/
7382 PetscErrorCode MatDestroySubMatrices(PetscInt n, Mat *mat[])
7383 {
7384   Mat mat0;
7385 
7386   PetscFunctionBegin;
7387   if (!*mat) PetscFunctionReturn(PETSC_SUCCESS);
7388   /* mat[] is an array of length n+1, see MatCreateSubMatrices_xxx() */
7389   PetscCheck(n >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Trying to destroy negative number of matrices %" PetscInt_FMT, n);
7390   PetscAssertPointer(mat, 2);
7391 
7392   mat0 = (*mat)[0];
7393   if (mat0 && mat0->ops->destroysubmatrices) {
7394     PetscCall((*mat0->ops->destroysubmatrices)(n, mat));
7395   } else {
7396     PetscCall(MatDestroyMatrices(n, mat));
7397   }
7398   PetscFunctionReturn(PETSC_SUCCESS);
7399 }
7400 
7401 /*@
7402   MatGetSeqNonzeroStructure - Extracts the nonzero structure from a matrix and stores it, in its entirety, on each process
7403 
7404   Collective
7405 
7406   Input Parameter:
7407 . mat - the matrix
7408 
7409   Output Parameter:
7410 . matstruct - the sequential matrix with the nonzero structure of `mat`
7411 
7412   Level: developer
7413 
7414 .seealso: [](ch_matrices), `Mat`, `MatDestroySeqNonzeroStructure()`, `MatCreateSubMatrices()`, `MatDestroyMatrices()`
7415 @*/
7416 PetscErrorCode MatGetSeqNonzeroStructure(Mat mat, Mat *matstruct)
7417 {
7418   PetscFunctionBegin;
7419   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
7420   PetscAssertPointer(matstruct, 2);
7421 
7422   PetscValidType(mat, 1);
7423   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
7424   MatCheckPreallocated(mat, 1);
7425 
7426   PetscCall(PetscLogEventBegin(MAT_GetSeqNonzeroStructure, mat, 0, 0, 0));
7427   PetscUseTypeMethod(mat, getseqnonzerostructure, matstruct);
7428   PetscCall(PetscLogEventEnd(MAT_GetSeqNonzeroStructure, mat, 0, 0, 0));
7429   PetscFunctionReturn(PETSC_SUCCESS);
7430 }
7431 
7432 /*@C
7433   MatDestroySeqNonzeroStructure - Destroys matrix obtained with `MatGetSeqNonzeroStructure()`.
7434 
7435   Collective
7436 
7437   Input Parameter:
7438 . mat - the matrix
7439 
7440   Level: advanced
7441 
7442   Note:
7443   This is not needed, one can just call `MatDestroy()`
7444 
7445 .seealso: [](ch_matrices), `Mat`, `MatGetSeqNonzeroStructure()`
7446 @*/
7447 PetscErrorCode MatDestroySeqNonzeroStructure(Mat *mat)
7448 {
7449   PetscFunctionBegin;
7450   PetscAssertPointer(mat, 1);
7451   PetscCall(MatDestroy(mat));
7452   PetscFunctionReturn(PETSC_SUCCESS);
7453 }
7454 
7455 /*@
7456   MatIncreaseOverlap - Given a set of submatrices indicated by index sets,
7457   replaces the index sets by larger ones that represent submatrices with
7458   additional overlap.
7459 
7460   Collective
7461 
7462   Input Parameters:
7463 + mat - the matrix
7464 . n   - the number of index sets
7465 . is  - the array of index sets (these index sets will changed during the call)
7466 - ov  - the additional overlap requested
7467 
7468   Options Database Key:
7469 . -mat_increase_overlap_scalable - use a scalable algorithm to compute the overlap (supported by MPIAIJ matrix)
7470 
7471   Level: developer
7472 
7473   Note:
7474   The computed overlap preserves the matrix block sizes when the blocks are square.
7475   That is: if a matrix nonzero for a given block would increase the overlap all columns associated with
7476   that block are included in the overlap regardless of whether each specific column would increase the overlap.
7477 
7478 .seealso: [](ch_matrices), `Mat`, `PCASM`, `MatSetBlockSize()`, `MatIncreaseOverlapSplit()`, `MatCreateSubMatrices()`
7479 @*/
7480 PetscErrorCode MatIncreaseOverlap(Mat mat, PetscInt n, IS is[], PetscInt ov)
7481 {
7482   PetscInt i, bs, cbs;
7483 
7484   PetscFunctionBegin;
7485   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
7486   PetscValidType(mat, 1);
7487   PetscValidLogicalCollectiveInt(mat, n, 2);
7488   PetscCheck(n >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Must have one or more domains, you have %" PetscInt_FMT, n);
7489   if (n) {
7490     PetscAssertPointer(is, 3);
7491     for (i = 0; i < n; i++) PetscValidHeaderSpecific(is[i], IS_CLASSID, 3);
7492   }
7493   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
7494   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
7495   MatCheckPreallocated(mat, 1);
7496 
7497   if (!ov || !n) PetscFunctionReturn(PETSC_SUCCESS);
7498   PetscCall(PetscLogEventBegin(MAT_IncreaseOverlap, mat, 0, 0, 0));
7499   PetscUseTypeMethod(mat, increaseoverlap, n, is, ov);
7500   PetscCall(PetscLogEventEnd(MAT_IncreaseOverlap, mat, 0, 0, 0));
7501   PetscCall(MatGetBlockSizes(mat, &bs, &cbs));
7502   if (bs == cbs) {
7503     for (i = 0; i < n; i++) PetscCall(ISSetBlockSize(is[i], bs));
7504   }
7505   PetscFunctionReturn(PETSC_SUCCESS);
7506 }
7507 
7508 PetscErrorCode MatIncreaseOverlapSplit_Single(Mat, IS *, PetscInt);
7509 
7510 /*@
7511   MatIncreaseOverlapSplit - Given a set of submatrices indicated by index sets across
7512   a sub communicator, replaces the index sets by larger ones that represent submatrices with
7513   additional overlap.
7514 
7515   Collective
7516 
7517   Input Parameters:
7518 + mat - the matrix
7519 . n   - the number of index sets
7520 . is  - the array of index sets (these index sets will changed during the call)
7521 - ov  - the additional overlap requested
7522 
7523   `   Options Database Key:
7524 . -mat_increase_overlap_scalable - use a scalable algorithm to compute the overlap (supported by MPIAIJ matrix)
7525 
7526   Level: developer
7527 
7528 .seealso: [](ch_matrices), `Mat`, `MatCreateSubMatrices()`, `MatIncreaseOverlap()`
7529 @*/
7530 PetscErrorCode MatIncreaseOverlapSplit(Mat mat, PetscInt n, IS is[], PetscInt ov)
7531 {
7532   PetscInt i;
7533 
7534   PetscFunctionBegin;
7535   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
7536   PetscValidType(mat, 1);
7537   PetscCheck(n >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Must have one or more domains, you have %" PetscInt_FMT, n);
7538   if (n) {
7539     PetscAssertPointer(is, 3);
7540     PetscValidHeaderSpecific(*is, IS_CLASSID, 3);
7541   }
7542   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
7543   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
7544   MatCheckPreallocated(mat, 1);
7545   if (!ov) PetscFunctionReturn(PETSC_SUCCESS);
7546   PetscCall(PetscLogEventBegin(MAT_IncreaseOverlap, mat, 0, 0, 0));
7547   for (i = 0; i < n; i++) PetscCall(MatIncreaseOverlapSplit_Single(mat, &is[i], ov));
7548   PetscCall(PetscLogEventEnd(MAT_IncreaseOverlap, mat, 0, 0, 0));
7549   PetscFunctionReturn(PETSC_SUCCESS);
7550 }
7551 
7552 /*@
7553   MatGetBlockSize - Returns the matrix block size.
7554 
7555   Not Collective
7556 
7557   Input Parameter:
7558 . mat - the matrix
7559 
7560   Output Parameter:
7561 . bs - block size
7562 
7563   Level: intermediate
7564 
7565   Notes:
7566   Block row formats are `MATBAIJ` and `MATSBAIJ` ALWAYS have square block storage in the matrix.
7567 
7568   If the block size has not been set yet this routine returns 1.
7569 
7570 .seealso: [](ch_matrices), `Mat`, `MATBAIJ`, `MATSBAIJ`, `MatCreateSeqBAIJ()`, `MatCreateBAIJ()`, `MatGetBlockSizes()`
7571 @*/
7572 PetscErrorCode MatGetBlockSize(Mat mat, PetscInt *bs)
7573 {
7574   PetscFunctionBegin;
7575   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
7576   PetscAssertPointer(bs, 2);
7577   *bs = mat->rmap->bs;
7578   PetscFunctionReturn(PETSC_SUCCESS);
7579 }
7580 
7581 /*@
7582   MatGetBlockSizes - Returns the matrix block row and column sizes.
7583 
7584   Not Collective
7585 
7586   Input Parameter:
7587 . mat - the matrix
7588 
7589   Output Parameters:
7590 + rbs - row block size
7591 - cbs - column block size
7592 
7593   Level: intermediate
7594 
7595   Notes:
7596   Block row formats are `MATBAIJ` and `MATSBAIJ` ALWAYS have square block storage in the matrix.
7597   If you pass a different block size for the columns than the rows, the row block size determines the square block storage.
7598 
7599   If a block size has not been set yet this routine returns 1.
7600 
7601 .seealso: [](ch_matrices), `Mat`, `MATBAIJ`, `MATSBAIJ`, `MatCreateSeqBAIJ()`, `MatCreateBAIJ()`, `MatGetBlockSize()`, `MatSetBlockSize()`, `MatSetBlockSizes()`
7602 @*/
7603 PetscErrorCode MatGetBlockSizes(Mat mat, PetscInt *rbs, PetscInt *cbs)
7604 {
7605   PetscFunctionBegin;
7606   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
7607   if (rbs) PetscAssertPointer(rbs, 2);
7608   if (cbs) PetscAssertPointer(cbs, 3);
7609   if (rbs) *rbs = mat->rmap->bs;
7610   if (cbs) *cbs = mat->cmap->bs;
7611   PetscFunctionReturn(PETSC_SUCCESS);
7612 }
7613 
7614 /*@
7615   MatSetBlockSize - Sets the matrix block size.
7616 
7617   Logically Collective
7618 
7619   Input Parameters:
7620 + mat - the matrix
7621 - bs  - block size
7622 
7623   Level: intermediate
7624 
7625   Notes:
7626   Block row formats are `MATBAIJ` and `MATSBAIJ` formats ALWAYS have square block storage in the matrix.
7627   This must be called before `MatSetUp()` or MatXXXSetPreallocation() (or will default to 1) and the block size cannot be changed later.
7628 
7629   For `MATAIJ` matrix format, this function can be called at a later stage, provided that the specified block size
7630   is compatible with the matrix local sizes.
7631 
7632 .seealso: [](ch_matrices), `Mat`, `MATBAIJ`, `MATSBAIJ`, `MATAIJ`, `MatCreateSeqBAIJ()`, `MatCreateBAIJ()`, `MatGetBlockSize()`, `MatSetBlockSizes()`, `MatGetBlockSizes()`
7633 @*/
7634 PetscErrorCode MatSetBlockSize(Mat mat, PetscInt bs)
7635 {
7636   PetscFunctionBegin;
7637   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
7638   PetscValidLogicalCollectiveInt(mat, bs, 2);
7639   PetscCall(MatSetBlockSizes(mat, bs, bs));
7640   PetscFunctionReturn(PETSC_SUCCESS);
7641 }
7642 
7643 typedef struct {
7644   PetscInt         n;
7645   IS              *is;
7646   Mat             *mat;
7647   PetscObjectState nonzerostate;
7648   Mat              C;
7649 } EnvelopeData;
7650 
7651 static PetscErrorCode EnvelopeDataDestroy(void **ptr)
7652 {
7653   EnvelopeData *edata = (EnvelopeData *)*ptr;
7654 
7655   PetscFunctionBegin;
7656   for (PetscInt i = 0; i < edata->n; i++) PetscCall(ISDestroy(&edata->is[i]));
7657   PetscCall(PetscFree(edata->is));
7658   PetscCall(PetscFree(edata));
7659   PetscFunctionReturn(PETSC_SUCCESS);
7660 }
7661 
7662 /*@
7663   MatComputeVariableBlockEnvelope - Given a matrix whose nonzeros are in blocks along the diagonal this computes and stores
7664   the sizes of these blocks in the matrix. An individual block may lie over several processes.
7665 
7666   Collective
7667 
7668   Input Parameter:
7669 . mat - the matrix
7670 
7671   Level: intermediate
7672 
7673   Notes:
7674   There can be zeros within the blocks
7675 
7676   The blocks can overlap between processes, including laying on more than two processes
7677 
7678 .seealso: [](ch_matrices), `Mat`, `MatInvertVariableBlockEnvelope()`, `MatSetVariableBlockSizes()`
7679 @*/
7680 PetscErrorCode MatComputeVariableBlockEnvelope(Mat mat)
7681 {
7682   PetscInt           n, *sizes, *starts, i = 0, env = 0, tbs = 0, lblocks = 0, rstart, II, ln = 0, cnt = 0, cstart, cend;
7683   PetscInt          *diag, *odiag, sc;
7684   VecScatter         scatter;
7685   PetscScalar       *seqv;
7686   const PetscScalar *parv;
7687   const PetscInt    *ia, *ja;
7688   PetscBool          set, flag, done;
7689   Mat                AA = mat, A;
7690   MPI_Comm           comm;
7691   PetscMPIInt        rank, size, tag;
7692   MPI_Status         status;
7693   PetscContainer     container;
7694   EnvelopeData      *edata;
7695   Vec                seq, par;
7696   IS                 isglobal;
7697 
7698   PetscFunctionBegin;
7699   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
7700   PetscCall(MatIsSymmetricKnown(mat, &set, &flag));
7701   if (!set || !flag) {
7702     /* TODO: only needs nonzero structure of transpose */
7703     PetscCall(MatTranspose(mat, MAT_INITIAL_MATRIX, &AA));
7704     PetscCall(MatAXPY(AA, 1.0, mat, DIFFERENT_NONZERO_PATTERN));
7705   }
7706   PetscCall(MatAIJGetLocalMat(AA, &A));
7707   PetscCall(MatGetRowIJ(A, 0, PETSC_FALSE, PETSC_FALSE, &n, &ia, &ja, &done));
7708   PetscCheck(done, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "Unable to get IJ structure from matrix");
7709 
7710   PetscCall(MatGetLocalSize(mat, &n, NULL));
7711   PetscCall(PetscObjectGetNewTag((PetscObject)mat, &tag));
7712   PetscCall(PetscObjectGetComm((PetscObject)mat, &comm));
7713   PetscCallMPI(MPI_Comm_size(comm, &size));
7714   PetscCallMPI(MPI_Comm_rank(comm, &rank));
7715 
7716   PetscCall(PetscMalloc2(n, &sizes, n, &starts));
7717 
7718   if (rank > 0) {
7719     PetscCallMPI(MPI_Recv(&env, 1, MPIU_INT, rank - 1, tag, comm, &status));
7720     PetscCallMPI(MPI_Recv(&tbs, 1, MPIU_INT, rank - 1, tag, comm, &status));
7721   }
7722   PetscCall(MatGetOwnershipRange(mat, &rstart, NULL));
7723   for (i = 0; i < n; i++) {
7724     env = PetscMax(env, ja[ia[i + 1] - 1]);
7725     II  = rstart + i;
7726     if (env == II) {
7727       starts[lblocks]  = tbs;
7728       sizes[lblocks++] = 1 + II - tbs;
7729       tbs              = 1 + II;
7730     }
7731   }
7732   if (rank < size - 1) {
7733     PetscCallMPI(MPI_Send(&env, 1, MPIU_INT, rank + 1, tag, comm));
7734     PetscCallMPI(MPI_Send(&tbs, 1, MPIU_INT, rank + 1, tag, comm));
7735   }
7736 
7737   PetscCall(MatRestoreRowIJ(A, 0, PETSC_FALSE, PETSC_FALSE, &n, &ia, &ja, &done));
7738   if (!set || !flag) PetscCall(MatDestroy(&AA));
7739   PetscCall(MatDestroy(&A));
7740 
7741   PetscCall(PetscNew(&edata));
7742   PetscCall(MatGetNonzeroState(mat, &edata->nonzerostate));
7743   edata->n = lblocks;
7744   /* create IS needed for extracting blocks from the original matrix */
7745   PetscCall(PetscMalloc1(lblocks, &edata->is));
7746   for (PetscInt i = 0; i < lblocks; i++) PetscCall(ISCreateStride(PETSC_COMM_SELF, sizes[i], starts[i], 1, &edata->is[i]));
7747 
7748   /* Create the resulting inverse matrix nonzero structure with preallocation information */
7749   PetscCall(MatCreate(PetscObjectComm((PetscObject)mat), &edata->C));
7750   PetscCall(MatSetSizes(edata->C, mat->rmap->n, mat->cmap->n, mat->rmap->N, mat->cmap->N));
7751   PetscCall(MatSetBlockSizesFromMats(edata->C, mat, mat));
7752   PetscCall(MatSetType(edata->C, MATAIJ));
7753 
7754   /* Communicate the start and end of each row, from each block to the correct rank */
7755   /* TODO: Use PetscSF instead of VecScatter */
7756   for (PetscInt i = 0; i < lblocks; i++) ln += sizes[i];
7757   PetscCall(VecCreateSeq(PETSC_COMM_SELF, 2 * ln, &seq));
7758   PetscCall(VecGetArrayWrite(seq, &seqv));
7759   for (PetscInt i = 0; i < lblocks; i++) {
7760     for (PetscInt j = 0; j < sizes[i]; j++) {
7761       seqv[cnt]     = starts[i];
7762       seqv[cnt + 1] = starts[i] + sizes[i];
7763       cnt += 2;
7764     }
7765   }
7766   PetscCall(VecRestoreArrayWrite(seq, &seqv));
7767   PetscCallMPI(MPI_Scan(&cnt, &sc, 1, MPIU_INT, MPI_SUM, PetscObjectComm((PetscObject)mat)));
7768   sc -= cnt;
7769   PetscCall(VecCreateMPI(PetscObjectComm((PetscObject)mat), 2 * mat->rmap->n, 2 * mat->rmap->N, &par));
7770   PetscCall(ISCreateStride(PETSC_COMM_SELF, cnt, sc, 1, &isglobal));
7771   PetscCall(VecScatterCreate(seq, NULL, par, isglobal, &scatter));
7772   PetscCall(ISDestroy(&isglobal));
7773   PetscCall(VecScatterBegin(scatter, seq, par, INSERT_VALUES, SCATTER_FORWARD));
7774   PetscCall(VecScatterEnd(scatter, seq, par, INSERT_VALUES, SCATTER_FORWARD));
7775   PetscCall(VecScatterDestroy(&scatter));
7776   PetscCall(VecDestroy(&seq));
7777   PetscCall(MatGetOwnershipRangeColumn(mat, &cstart, &cend));
7778   PetscCall(PetscMalloc2(mat->rmap->n, &diag, mat->rmap->n, &odiag));
7779   PetscCall(VecGetArrayRead(par, &parv));
7780   cnt = 0;
7781   PetscCall(MatGetSize(mat, NULL, &n));
7782   for (PetscInt i = 0; i < mat->rmap->n; i++) {
7783     PetscInt start, end, d = 0, od = 0;
7784 
7785     start = (PetscInt)PetscRealPart(parv[cnt]);
7786     end   = (PetscInt)PetscRealPart(parv[cnt + 1]);
7787     cnt += 2;
7788 
7789     if (start < cstart) {
7790       od += cstart - start + n - cend;
7791       d += cend - cstart;
7792     } else if (start < cend) {
7793       od += n - cend;
7794       d += cend - start;
7795     } else od += n - start;
7796     if (end <= cstart) {
7797       od -= cstart - end + n - cend;
7798       d -= cend - cstart;
7799     } else if (end < cend) {
7800       od -= n - cend;
7801       d -= cend - end;
7802     } else od -= n - end;
7803 
7804     odiag[i] = od;
7805     diag[i]  = d;
7806   }
7807   PetscCall(VecRestoreArrayRead(par, &parv));
7808   PetscCall(VecDestroy(&par));
7809   PetscCall(MatXAIJSetPreallocation(edata->C, mat->rmap->bs, diag, odiag, NULL, NULL));
7810   PetscCall(PetscFree2(diag, odiag));
7811   PetscCall(PetscFree2(sizes, starts));
7812 
7813   PetscCall(PetscContainerCreate(PETSC_COMM_SELF, &container));
7814   PetscCall(PetscContainerSetPointer(container, edata));
7815   PetscCall(PetscContainerSetCtxDestroy(container, EnvelopeDataDestroy));
7816   PetscCall(PetscObjectCompose((PetscObject)mat, "EnvelopeData", (PetscObject)container));
7817   PetscCall(PetscObjectDereference((PetscObject)container));
7818   PetscFunctionReturn(PETSC_SUCCESS);
7819 }
7820 
7821 /*@
7822   MatInvertVariableBlockEnvelope - set matrix C to be the inverted block diagonal of matrix A
7823 
7824   Collective
7825 
7826   Input Parameters:
7827 + A     - the matrix
7828 - reuse - indicates if the `C` matrix was obtained from a previous call to this routine
7829 
7830   Output Parameter:
7831 . C - matrix with inverted block diagonal of `A`
7832 
7833   Level: advanced
7834 
7835   Note:
7836   For efficiency the matrix `A` should have all the nonzero entries clustered in smallish blocks along the diagonal.
7837 
7838 .seealso: [](ch_matrices), `Mat`, `MatInvertBlockDiagonal()`, `MatComputeBlockDiagonal()`
7839 @*/
7840 PetscErrorCode MatInvertVariableBlockEnvelope(Mat A, MatReuse reuse, Mat *C)
7841 {
7842   PetscContainer   container;
7843   EnvelopeData    *edata;
7844   PetscObjectState nonzerostate;
7845 
7846   PetscFunctionBegin;
7847   PetscCall(PetscObjectQuery((PetscObject)A, "EnvelopeData", (PetscObject *)&container));
7848   if (!container) {
7849     PetscCall(MatComputeVariableBlockEnvelope(A));
7850     PetscCall(PetscObjectQuery((PetscObject)A, "EnvelopeData", (PetscObject *)&container));
7851   }
7852   PetscCall(PetscContainerGetPointer(container, (void **)&edata));
7853   PetscCall(MatGetNonzeroState(A, &nonzerostate));
7854   PetscCheck(nonzerostate <= edata->nonzerostate, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "Cannot handle changes to matrix nonzero structure");
7855   PetscCheck(reuse != MAT_REUSE_MATRIX || *C == edata->C, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "C matrix must be the same as previously output");
7856 
7857   PetscCall(MatCreateSubMatrices(A, edata->n, edata->is, edata->is, MAT_INITIAL_MATRIX, &edata->mat));
7858   *C = edata->C;
7859 
7860   for (PetscInt i = 0; i < edata->n; i++) {
7861     Mat          D;
7862     PetscScalar *dvalues;
7863 
7864     PetscCall(MatConvert(edata->mat[i], MATSEQDENSE, MAT_INITIAL_MATRIX, &D));
7865     PetscCall(MatSetOption(*C, MAT_ROW_ORIENTED, PETSC_FALSE));
7866     PetscCall(MatSeqDenseInvert(D));
7867     PetscCall(MatDenseGetArray(D, &dvalues));
7868     PetscCall(MatSetValuesIS(*C, edata->is[i], edata->is[i], dvalues, INSERT_VALUES));
7869     PetscCall(MatDestroy(&D));
7870   }
7871   PetscCall(MatDestroySubMatrices(edata->n, &edata->mat));
7872   PetscCall(MatAssemblyBegin(*C, MAT_FINAL_ASSEMBLY));
7873   PetscCall(MatAssemblyEnd(*C, MAT_FINAL_ASSEMBLY));
7874   PetscFunctionReturn(PETSC_SUCCESS);
7875 }
7876 
7877 /*@
7878   MatSetVariableBlockSizes - Sets diagonal point-blocks of the matrix that need not be of the same size
7879 
7880   Not Collective
7881 
7882   Input Parameters:
7883 + mat     - the matrix
7884 . nblocks - the number of blocks on this process, each block can only exist on a single process
7885 - bsizes  - the block sizes
7886 
7887   Level: intermediate
7888 
7889   Notes:
7890   Currently used by `PCVPBJACOBI` for `MATAIJ` matrices
7891 
7892   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.
7893 
7894 .seealso: [](ch_matrices), `Mat`, `MatCreateSeqBAIJ()`, `MatCreateBAIJ()`, `MatGetBlockSize()`, `MatSetBlockSizes()`, `MatGetBlockSizes()`, `MatGetVariableBlockSizes()`,
7895           `MatComputeVariableBlockEnvelope()`, `PCVPBJACOBI`
7896 @*/
7897 PetscErrorCode MatSetVariableBlockSizes(Mat mat, PetscInt nblocks, const PetscInt bsizes[])
7898 {
7899   PetscInt ncnt = 0, nlocal;
7900 
7901   PetscFunctionBegin;
7902   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
7903   PetscCall(MatGetLocalSize(mat, &nlocal, NULL));
7904   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);
7905   for (PetscInt i = 0; i < nblocks; i++) ncnt += bsizes[i];
7906   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);
7907   PetscCall(PetscFree(mat->bsizes));
7908   mat->nblocks = nblocks;
7909   PetscCall(PetscMalloc1(nblocks, &mat->bsizes));
7910   PetscCall(PetscArraycpy(mat->bsizes, bsizes, nblocks));
7911   PetscFunctionReturn(PETSC_SUCCESS);
7912 }
7913 
7914 /*@C
7915   MatGetVariableBlockSizes - Gets a diagonal blocks of the matrix that need not be of the same size
7916 
7917   Not Collective; No Fortran Support
7918 
7919   Input Parameter:
7920 . mat - the matrix
7921 
7922   Output Parameters:
7923 + nblocks - the number of blocks on this process
7924 - bsizes  - the block sizes
7925 
7926   Level: intermediate
7927 
7928 .seealso: [](ch_matrices), `Mat`, `MatCreateSeqBAIJ()`, `MatCreateBAIJ()`, `MatGetBlockSize()`, `MatSetBlockSizes()`, `MatGetBlockSizes()`, `MatSetVariableBlockSizes()`, `MatComputeVariableBlockEnvelope()`
7929 @*/
7930 PetscErrorCode MatGetVariableBlockSizes(Mat mat, PetscInt *nblocks, const PetscInt *bsizes[])
7931 {
7932   PetscFunctionBegin;
7933   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
7934   if (nblocks) *nblocks = mat->nblocks;
7935   if (bsizes) *bsizes = mat->bsizes;
7936   PetscFunctionReturn(PETSC_SUCCESS);
7937 }
7938 
7939 /*@
7940   MatSelectVariableBlockSizes - When creating a submatrix, pass on the variable block sizes
7941 
7942   Not Collective
7943 
7944   Input Parameter:
7945 + subA  - the submatrix
7946 . A     - the original matrix
7947 - isrow - The `IS` of selected rows for the submatrix, must be sorted
7948 
7949   Level: developer
7950 
7951   Notes:
7952   If the index set is not sorted or contains off-process entries, this function will do nothing.
7953 
7954 .seealso: [](ch_matrices), `Mat`, `MatSetVariableBlockSizes()`, `MatComputeVariableBlockEnvelope()`
7955 @*/
7956 PetscErrorCode MatSelectVariableBlockSizes(Mat subA, Mat A, IS isrow)
7957 {
7958   const PetscInt *rows;
7959   PetscInt        n, rStart, rEnd, Nb = 0;
7960   PetscBool       flg = A->bsizes ? PETSC_TRUE : PETSC_FALSE;
7961 
7962   PetscFunctionBegin;
7963   // The code for block size extraction does not support an unsorted IS
7964   if (flg) PetscCall(ISSorted(isrow, &flg));
7965   // We don't support originally off-diagonal blocks
7966   if (flg) {
7967     PetscCall(MatGetOwnershipRange(A, &rStart, &rEnd));
7968     PetscCall(ISGetLocalSize(isrow, &n));
7969     PetscCall(ISGetIndices(isrow, &rows));
7970     for (PetscInt i = 0; i < n && flg; ++i) {
7971       if (rows[i] < rStart || rows[i] >= rEnd) flg = PETSC_FALSE;
7972     }
7973     PetscCall(ISRestoreIndices(isrow, &rows));
7974   }
7975   // quiet return if we can't extract block size
7976   PetscCallMPI(MPIU_Allreduce(MPI_IN_PLACE, &flg, 1, MPI_C_BOOL, MPI_LAND, PetscObjectComm((PetscObject)subA)));
7977   if (!flg) PetscFunctionReturn(PETSC_SUCCESS);
7978 
7979   // extract block sizes
7980   PetscCall(ISGetIndices(isrow, &rows));
7981   for (PetscInt b = 0, gr = rStart, i = 0; b < A->nblocks; ++b) {
7982     PetscBool occupied = PETSC_FALSE;
7983 
7984     for (PetscInt br = 0; br < A->bsizes[b]; ++br) {
7985       const PetscInt row = gr + br;
7986 
7987       if (i == n) break;
7988       if (rows[i] == row) {
7989         occupied = PETSC_TRUE;
7990         ++i;
7991       }
7992       while (i < n && rows[i] < row) ++i;
7993     }
7994     gr += A->bsizes[b];
7995     if (occupied) ++Nb;
7996   }
7997   subA->nblocks = Nb;
7998   PetscCall(PetscFree(subA->bsizes));
7999   PetscCall(PetscMalloc1(subA->nblocks, &subA->bsizes));
8000   PetscInt sb = 0;
8001   for (PetscInt b = 0, gr = rStart, i = 0; b < A->nblocks; ++b) {
8002     if (sb < subA->nblocks) subA->bsizes[sb] = 0;
8003     for (PetscInt br = 0; br < A->bsizes[b]; ++br) {
8004       const PetscInt row = gr + br;
8005 
8006       if (i == n) break;
8007       if (rows[i] == row) {
8008         ++subA->bsizes[sb];
8009         ++i;
8010       }
8011       while (i < n && rows[i] < row) ++i;
8012     }
8013     gr += A->bsizes[b];
8014     if (sb < subA->nblocks && subA->bsizes[sb]) ++sb;
8015   }
8016   PetscCheck(sb == subA->nblocks, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Invalid number of blocks %" PetscInt_FMT " != %" PetscInt_FMT, sb, subA->nblocks);
8017   PetscInt nlocal, ncnt = 0;
8018   PetscCall(MatGetLocalSize(subA, &nlocal, NULL));
8019   PetscCheck(subA->nblocks >= 0 && subA->nblocks <= nlocal, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Number of local blocks %" PetscInt_FMT " is not in [0, %" PetscInt_FMT "]", subA->nblocks, nlocal);
8020   for (PetscInt i = 0; i < subA->nblocks; i++) ncnt += subA->bsizes[i];
8021   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);
8022   PetscCall(ISRestoreIndices(isrow, &rows));
8023   PetscFunctionReturn(PETSC_SUCCESS);
8024 }
8025 
8026 /*@
8027   MatSetBlockSizes - Sets the matrix block row and column sizes.
8028 
8029   Logically Collective
8030 
8031   Input Parameters:
8032 + mat - the matrix
8033 . rbs - row block size
8034 - cbs - column block size
8035 
8036   Level: intermediate
8037 
8038   Notes:
8039   Block row formats are `MATBAIJ` and  `MATSBAIJ`. These formats ALWAYS have square block storage in the matrix.
8040   If you pass a different block size for the columns than the rows, the row block size determines the square block storage.
8041   This must be called before `MatSetUp()` or MatXXXSetPreallocation() (or will default to 1) and the block size cannot be changed later.
8042 
8043   For `MATAIJ` matrix this function can be called at a later stage, provided that the specified block sizes
8044   are compatible with the matrix local sizes.
8045 
8046   The row and column block size determine the blocksize of the "row" and "column" vectors returned by `MatCreateVecs()`.
8047 
8048 .seealso: [](ch_matrices), `Mat`, `MatCreateSeqBAIJ()`, `MatCreateBAIJ()`, `MatGetBlockSize()`, `MatSetBlockSize()`, `MatGetBlockSizes()`
8049 @*/
8050 PetscErrorCode MatSetBlockSizes(Mat mat, PetscInt rbs, PetscInt cbs)
8051 {
8052   PetscFunctionBegin;
8053   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
8054   PetscValidLogicalCollectiveInt(mat, rbs, 2);
8055   PetscValidLogicalCollectiveInt(mat, cbs, 3);
8056   PetscTryTypeMethod(mat, setblocksizes, rbs, cbs);
8057   if (mat->rmap->refcnt) {
8058     ISLocalToGlobalMapping l2g  = NULL;
8059     PetscLayout            nmap = NULL;
8060 
8061     PetscCall(PetscLayoutDuplicate(mat->rmap, &nmap));
8062     if (mat->rmap->mapping) PetscCall(ISLocalToGlobalMappingDuplicate(mat->rmap->mapping, &l2g));
8063     PetscCall(PetscLayoutDestroy(&mat->rmap));
8064     mat->rmap          = nmap;
8065     mat->rmap->mapping = l2g;
8066   }
8067   if (mat->cmap->refcnt) {
8068     ISLocalToGlobalMapping l2g  = NULL;
8069     PetscLayout            nmap = NULL;
8070 
8071     PetscCall(PetscLayoutDuplicate(mat->cmap, &nmap));
8072     if (mat->cmap->mapping) PetscCall(ISLocalToGlobalMappingDuplicate(mat->cmap->mapping, &l2g));
8073     PetscCall(PetscLayoutDestroy(&mat->cmap));
8074     mat->cmap          = nmap;
8075     mat->cmap->mapping = l2g;
8076   }
8077   PetscCall(PetscLayoutSetBlockSize(mat->rmap, rbs));
8078   PetscCall(PetscLayoutSetBlockSize(mat->cmap, cbs));
8079   PetscFunctionReturn(PETSC_SUCCESS);
8080 }
8081 
8082 /*@
8083   MatSetBlockSizesFromMats - Sets the matrix block row and column sizes to match a pair of matrices
8084 
8085   Logically Collective
8086 
8087   Input Parameters:
8088 + mat     - the matrix
8089 . fromRow - matrix from which to copy row block size
8090 - fromCol - matrix from which to copy column block size (can be same as fromRow)
8091 
8092   Level: developer
8093 
8094 .seealso: [](ch_matrices), `Mat`, `MatCreateSeqBAIJ()`, `MatCreateBAIJ()`, `MatGetBlockSize()`, `MatSetBlockSizes()`
8095 @*/
8096 PetscErrorCode MatSetBlockSizesFromMats(Mat mat, Mat fromRow, Mat fromCol)
8097 {
8098   PetscFunctionBegin;
8099   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
8100   PetscValidHeaderSpecific(fromRow, MAT_CLASSID, 2);
8101   PetscValidHeaderSpecific(fromCol, MAT_CLASSID, 3);
8102   PetscCall(PetscLayoutSetBlockSize(mat->rmap, fromRow->rmap->bs));
8103   PetscCall(PetscLayoutSetBlockSize(mat->cmap, fromCol->cmap->bs));
8104   PetscFunctionReturn(PETSC_SUCCESS);
8105 }
8106 
8107 /*@
8108   MatResidual - Default routine to calculate the residual r = b - Ax
8109 
8110   Collective
8111 
8112   Input Parameters:
8113 + mat - the matrix
8114 . b   - the right-hand-side
8115 - x   - the approximate solution
8116 
8117   Output Parameter:
8118 . r - location to store the residual
8119 
8120   Level: developer
8121 
8122 .seealso: [](ch_matrices), `Mat`, `MatMult()`, `MatMultAdd()`, `PCMGSetResidual()`
8123 @*/
8124 PetscErrorCode MatResidual(Mat mat, Vec b, Vec x, Vec r)
8125 {
8126   PetscFunctionBegin;
8127   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
8128   PetscValidHeaderSpecific(b, VEC_CLASSID, 2);
8129   PetscValidHeaderSpecific(x, VEC_CLASSID, 3);
8130   PetscValidHeaderSpecific(r, VEC_CLASSID, 4);
8131   PetscValidType(mat, 1);
8132   MatCheckPreallocated(mat, 1);
8133   PetscCall(PetscLogEventBegin(MAT_Residual, mat, 0, 0, 0));
8134   if (!mat->ops->residual) {
8135     PetscCall(MatMult(mat, x, r));
8136     PetscCall(VecAYPX(r, -1.0, b));
8137   } else {
8138     PetscUseTypeMethod(mat, residual, b, x, r);
8139   }
8140   PetscCall(PetscLogEventEnd(MAT_Residual, mat, 0, 0, 0));
8141   PetscFunctionReturn(PETSC_SUCCESS);
8142 }
8143 
8144 /*@C
8145   MatGetRowIJ - Returns the compressed row storage i and j indices for the local rows of a sparse matrix
8146 
8147   Collective
8148 
8149   Input Parameters:
8150 + mat             - the matrix
8151 . shift           - 0 or 1 indicating we want the indices starting at 0 or 1
8152 . symmetric       - `PETSC_TRUE` or `PETSC_FALSE` indicating the matrix data structure should be symmetrized
8153 - inodecompressed - `PETSC_TRUE` or `PETSC_FALSE`  indicating if the nonzero structure of the
8154                  inodes or the nonzero elements is wanted. For `MATBAIJ` matrices the compressed version is
8155                  always used.
8156 
8157   Output Parameters:
8158 + n    - number of local rows in the (possibly compressed) matrix, use `NULL` if not needed
8159 . 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
8160 . ja   - the column indices, use `NULL` if not needed
8161 - done - indicates if the routine actually worked and returned appropriate ia[] and ja[] arrays; callers
8162            are responsible for handling the case when done == `PETSC_FALSE` and ia and ja are not set
8163 
8164   Level: developer
8165 
8166   Notes:
8167   You CANNOT change any of the ia[] or ja[] values.
8168 
8169   Use `MatRestoreRowIJ()` when you are finished accessing the ia[] and ja[] values.
8170 
8171   Fortran Notes:
8172   Use
8173 .vb
8174     PetscInt, pointer :: ia(:),ja(:)
8175     call MatGetRowIJ(mat,shift,symmetric,inodecompressed,n,ia,ja,done,ierr)
8176     ! Access the ith and jth entries via ia(i) and ja(j)
8177 .ve
8178 
8179 .seealso: [](ch_matrices), `Mat`, `MATAIJ`, `MatGetColumnIJ()`, `MatRestoreRowIJ()`, `MatSeqAIJGetArray()`
8180 @*/
8181 PetscErrorCode MatGetRowIJ(Mat mat, PetscInt shift, PetscBool symmetric, PetscBool inodecompressed, PetscInt *n, const PetscInt *ia[], const PetscInt *ja[], PetscBool *done)
8182 {
8183   PetscFunctionBegin;
8184   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
8185   PetscValidType(mat, 1);
8186   if (n) PetscAssertPointer(n, 5);
8187   if (ia) PetscAssertPointer(ia, 6);
8188   if (ja) PetscAssertPointer(ja, 7);
8189   if (done) PetscAssertPointer(done, 8);
8190   MatCheckPreallocated(mat, 1);
8191   if (!mat->ops->getrowij && done) *done = PETSC_FALSE;
8192   else {
8193     if (done) *done = PETSC_TRUE;
8194     PetscCall(PetscLogEventBegin(MAT_GetRowIJ, mat, 0, 0, 0));
8195     PetscUseTypeMethod(mat, getrowij, shift, symmetric, inodecompressed, n, ia, ja, done);
8196     PetscCall(PetscLogEventEnd(MAT_GetRowIJ, mat, 0, 0, 0));
8197   }
8198   PetscFunctionReturn(PETSC_SUCCESS);
8199 }
8200 
8201 /*@C
8202   MatGetColumnIJ - Returns the compressed column storage i and j indices for sequential matrices.
8203 
8204   Collective
8205 
8206   Input Parameters:
8207 + mat             - the matrix
8208 . shift           - 1 or zero indicating we want the indices starting at 0 or 1
8209 . symmetric       - `PETSC_TRUE` or `PETSC_FALSE` indicating the matrix data structure should be
8210                 symmetrized
8211 - inodecompressed - `PETSC_TRUE` or `PETSC_FALSE` indicating if the nonzero structure of the
8212                  inodes or the nonzero elements is wanted. For `MATBAIJ` matrices the compressed version is
8213                  always used.
8214 
8215   Output Parameters:
8216 + n    - number of columns in the (possibly compressed) matrix
8217 . ia   - the column pointers; that is ia[0] = 0, ia[col] = i[col-1] + number of elements in that col of the matrix
8218 . ja   - the row indices
8219 - done - `PETSC_TRUE` or `PETSC_FALSE`, indicating whether the values have been returned
8220 
8221   Level: developer
8222 
8223 .seealso: [](ch_matrices), `Mat`, `MatGetRowIJ()`, `MatRestoreColumnIJ()`
8224 @*/
8225 PetscErrorCode MatGetColumnIJ(Mat mat, PetscInt shift, PetscBool symmetric, PetscBool inodecompressed, PetscInt *n, const PetscInt *ia[], const PetscInt *ja[], PetscBool *done)
8226 {
8227   PetscFunctionBegin;
8228   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
8229   PetscValidType(mat, 1);
8230   PetscAssertPointer(n, 5);
8231   if (ia) PetscAssertPointer(ia, 6);
8232   if (ja) PetscAssertPointer(ja, 7);
8233   PetscAssertPointer(done, 8);
8234   MatCheckPreallocated(mat, 1);
8235   if (!mat->ops->getcolumnij) *done = PETSC_FALSE;
8236   else {
8237     *done = PETSC_TRUE;
8238     PetscUseTypeMethod(mat, getcolumnij, shift, symmetric, inodecompressed, n, ia, ja, done);
8239   }
8240   PetscFunctionReturn(PETSC_SUCCESS);
8241 }
8242 
8243 /*@C
8244   MatRestoreRowIJ - Call after you are completed with the ia,ja indices obtained with `MatGetRowIJ()`.
8245 
8246   Collective
8247 
8248   Input Parameters:
8249 + mat             - the matrix
8250 . shift           - 1 or zero indicating we want the indices starting at 0 or 1
8251 . symmetric       - `PETSC_TRUE` or `PETSC_FALSE` indicating the matrix data structure should be symmetrized
8252 . inodecompressed - `PETSC_TRUE` or `PETSC_FALSE` indicating if the nonzero structure of the
8253                     inodes or the nonzero elements is wanted. For `MATBAIJ` matrices the compressed version is
8254                     always used.
8255 . n               - size of (possibly compressed) matrix
8256 . ia              - the row pointers
8257 - ja              - the column indices
8258 
8259   Output Parameter:
8260 . done - `PETSC_TRUE` or `PETSC_FALSE` indicated that the values have been returned
8261 
8262   Level: developer
8263 
8264   Note:
8265   This routine zeros out `n`, `ia`, and `ja`. This is to prevent accidental
8266   us of the array after it has been restored. If you pass `NULL`, it will
8267   not zero the pointers.  Use of ia or ja after `MatRestoreRowIJ()` is invalid.
8268 
8269 .seealso: [](ch_matrices), `Mat`, `MatGetRowIJ()`, `MatRestoreColumnIJ()`
8270 @*/
8271 PetscErrorCode MatRestoreRowIJ(Mat mat, PetscInt shift, PetscBool symmetric, PetscBool inodecompressed, PetscInt *n, const PetscInt *ia[], const PetscInt *ja[], PetscBool *done)
8272 {
8273   PetscFunctionBegin;
8274   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
8275   PetscValidType(mat, 1);
8276   if (ia) PetscAssertPointer(ia, 6);
8277   if (ja) PetscAssertPointer(ja, 7);
8278   if (done) PetscAssertPointer(done, 8);
8279   MatCheckPreallocated(mat, 1);
8280 
8281   if (!mat->ops->restorerowij && done) *done = PETSC_FALSE;
8282   else {
8283     if (done) *done = PETSC_TRUE;
8284     PetscUseTypeMethod(mat, restorerowij, shift, symmetric, inodecompressed, n, ia, ja, done);
8285     if (n) *n = 0;
8286     if (ia) *ia = NULL;
8287     if (ja) *ja = NULL;
8288   }
8289   PetscFunctionReturn(PETSC_SUCCESS);
8290 }
8291 
8292 /*@C
8293   MatRestoreColumnIJ - Call after you are completed with the ia,ja indices obtained with `MatGetColumnIJ()`.
8294 
8295   Collective
8296 
8297   Input Parameters:
8298 + mat             - the matrix
8299 . shift           - 1 or zero indicating we want the indices starting at 0 or 1
8300 . symmetric       - `PETSC_TRUE` or `PETSC_FALSE` indicating the matrix data structure should be symmetrized
8301 - inodecompressed - `PETSC_TRUE` or `PETSC_FALSE` indicating if the nonzero structure of the
8302                     inodes or the nonzero elements is wanted. For `MATBAIJ` matrices the compressed version is
8303                     always used.
8304 
8305   Output Parameters:
8306 + n    - size of (possibly compressed) matrix
8307 . ia   - the column pointers
8308 . ja   - the row indices
8309 - done - `PETSC_TRUE` or `PETSC_FALSE` indicated that the values have been returned
8310 
8311   Level: developer
8312 
8313 .seealso: [](ch_matrices), `Mat`, `MatGetColumnIJ()`, `MatRestoreRowIJ()`
8314 @*/
8315 PetscErrorCode MatRestoreColumnIJ(Mat mat, PetscInt shift, PetscBool symmetric, PetscBool inodecompressed, PetscInt *n, const PetscInt *ia[], const PetscInt *ja[], PetscBool *done)
8316 {
8317   PetscFunctionBegin;
8318   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
8319   PetscValidType(mat, 1);
8320   if (ia) PetscAssertPointer(ia, 6);
8321   if (ja) PetscAssertPointer(ja, 7);
8322   PetscAssertPointer(done, 8);
8323   MatCheckPreallocated(mat, 1);
8324 
8325   if (!mat->ops->restorecolumnij) *done = PETSC_FALSE;
8326   else {
8327     *done = PETSC_TRUE;
8328     PetscUseTypeMethod(mat, restorecolumnij, shift, symmetric, inodecompressed, n, ia, ja, done);
8329     if (n) *n = 0;
8330     if (ia) *ia = NULL;
8331     if (ja) *ja = NULL;
8332   }
8333   PetscFunctionReturn(PETSC_SUCCESS);
8334 }
8335 
8336 /*@
8337   MatColoringPatch - Used inside matrix coloring routines that use `MatGetRowIJ()` and/or
8338   `MatGetColumnIJ()`.
8339 
8340   Collective
8341 
8342   Input Parameters:
8343 + mat        - the matrix
8344 . ncolors    - maximum color value
8345 . n          - number of entries in colorarray
8346 - colorarray - array indicating color for each column
8347 
8348   Output Parameter:
8349 . iscoloring - coloring generated using colorarray information
8350 
8351   Level: developer
8352 
8353 .seealso: [](ch_matrices), `Mat`, `MatGetRowIJ()`, `MatGetColumnIJ()`
8354 @*/
8355 PetscErrorCode MatColoringPatch(Mat mat, PetscInt ncolors, PetscInt n, ISColoringValue colorarray[], ISColoring *iscoloring)
8356 {
8357   PetscFunctionBegin;
8358   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
8359   PetscValidType(mat, 1);
8360   PetscAssertPointer(colorarray, 4);
8361   PetscAssertPointer(iscoloring, 5);
8362   MatCheckPreallocated(mat, 1);
8363 
8364   if (!mat->ops->coloringpatch) {
8365     PetscCall(ISColoringCreate(PetscObjectComm((PetscObject)mat), ncolors, n, colorarray, PETSC_OWN_POINTER, iscoloring));
8366   } else {
8367     PetscUseTypeMethod(mat, coloringpatch, ncolors, n, colorarray, iscoloring);
8368   }
8369   PetscFunctionReturn(PETSC_SUCCESS);
8370 }
8371 
8372 /*@
8373   MatSetUnfactored - Resets a factored matrix to be treated as unfactored.
8374 
8375   Logically Collective
8376 
8377   Input Parameter:
8378 . mat - the factored matrix to be reset
8379 
8380   Level: developer
8381 
8382   Notes:
8383   This routine should be used only with factored matrices formed by in-place
8384   factorization via ILU(0) (or by in-place LU factorization for the `MATSEQDENSE`
8385   format).  This option can save memory, for example, when solving nonlinear
8386   systems with a matrix-free Newton-Krylov method and a matrix-based, in-place
8387   ILU(0) preconditioner.
8388 
8389   One can specify in-place ILU(0) factorization by calling
8390 .vb
8391      PCType(pc,PCILU);
8392      PCFactorSeUseInPlace(pc);
8393 .ve
8394   or by using the options -pc_type ilu -pc_factor_in_place
8395 
8396   In-place factorization ILU(0) can also be used as a local
8397   solver for the blocks within the block Jacobi or additive Schwarz
8398   methods (runtime option: -sub_pc_factor_in_place).  See Users-Manual: ch_pc
8399   for details on setting local solver options.
8400 
8401   Most users should employ the `KSP` interface for linear solvers
8402   instead of working directly with matrix algebra routines such as this.
8403   See, e.g., `KSPCreate()`.
8404 
8405 .seealso: [](ch_matrices), `Mat`, `PCFactorSetUseInPlace()`, `PCFactorGetUseInPlace()`
8406 @*/
8407 PetscErrorCode MatSetUnfactored(Mat mat)
8408 {
8409   PetscFunctionBegin;
8410   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
8411   PetscValidType(mat, 1);
8412   MatCheckPreallocated(mat, 1);
8413   mat->factortype = MAT_FACTOR_NONE;
8414   if (!mat->ops->setunfactored) PetscFunctionReturn(PETSC_SUCCESS);
8415   PetscUseTypeMethod(mat, setunfactored);
8416   PetscFunctionReturn(PETSC_SUCCESS);
8417 }
8418 
8419 /*@
8420   MatCreateSubMatrix - Gets a single submatrix on the same number of processors
8421   as the original matrix.
8422 
8423   Collective
8424 
8425   Input Parameters:
8426 + mat   - the original matrix
8427 . isrow - parallel `IS` containing the rows this processor should obtain
8428 . 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.
8429 - cll   - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`
8430 
8431   Output Parameter:
8432 . newmat - the new submatrix, of the same type as the original matrix
8433 
8434   Level: advanced
8435 
8436   Notes:
8437   The submatrix will be able to be multiplied with vectors using the same layout as `iscol`.
8438 
8439   Some matrix types place restrictions on the row and column indices, such
8440   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;
8441   for example, if the block size is 3 one cannot select the 0 and 2 rows without selecting the 1 row.
8442 
8443   The index sets may not have duplicate entries.
8444 
8445   The first time this is called you should use a cll of `MAT_INITIAL_MATRIX`,
8446   the `MatCreateSubMatrix()` routine will create the newmat for you. Any additional calls
8447   to this routine with a mat of the same nonzero structure and with a call of `MAT_REUSE_MATRIX`
8448   will reuse the matrix generated the first time.  You should call `MatDestroy()` on `newmat` when
8449   you are finished using it.
8450 
8451   The communicator of the newly obtained matrix is ALWAYS the same as the communicator of
8452   the input matrix.
8453 
8454   If `iscol` is `NULL` then all columns are obtained (not supported in Fortran).
8455 
8456   If `isrow` and `iscol` have a nontrivial block-size, then the resulting matrix has this block-size as well. This feature
8457   is used by `PCFIELDSPLIT` to allow easy nesting of its use.
8458 
8459   Example usage:
8460   Consider the following 8x8 matrix with 34 non-zero values, that is
8461   assembled across 3 processors. Let's assume that proc0 owns 3 rows,
8462   proc1 owns 3 rows, proc2 owns 2 rows. This division can be shown
8463   as follows
8464 .vb
8465             1  2  0  |  0  3  0  |  0  4
8466     Proc0   0  5  6  |  7  0  0  |  8  0
8467             9  0 10  | 11  0  0  | 12  0
8468     -------------------------------------
8469            13  0 14  | 15 16 17  |  0  0
8470     Proc1   0 18  0  | 19 20 21  |  0  0
8471             0  0  0  | 22 23  0  | 24  0
8472     -------------------------------------
8473     Proc2  25 26 27  |  0  0 28  | 29  0
8474            30  0  0  | 31 32 33  |  0 34
8475 .ve
8476 
8477   Suppose `isrow` = [0 1 | 4 | 6 7] and `iscol` = [1 2 | 3 4 5 | 6].  The resulting submatrix is
8478 
8479 .vb
8480             2  0  |  0  3  0  |  0
8481     Proc0   5  6  |  7  0  0  |  8
8482     -------------------------------
8483     Proc1  18  0  | 19 20 21  |  0
8484     -------------------------------
8485     Proc2  26 27  |  0  0 28  | 29
8486             0  0  | 31 32 33  |  0
8487 .ve
8488 
8489 .seealso: [](ch_matrices), `Mat`, `MatCreateSubMatrices()`, `MatCreateSubMatricesMPI()`, `MatCreateSubMatrixVirtual()`, `MatSubMatrixVirtualUpdate()`
8490 @*/
8491 PetscErrorCode MatCreateSubMatrix(Mat mat, IS isrow, IS iscol, MatReuse cll, Mat *newmat)
8492 {
8493   PetscMPIInt size;
8494   Mat        *local;
8495   IS          iscoltmp;
8496   PetscBool   flg;
8497 
8498   PetscFunctionBegin;
8499   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
8500   PetscValidHeaderSpecific(isrow, IS_CLASSID, 2);
8501   if (iscol) PetscValidHeaderSpecific(iscol, IS_CLASSID, 3);
8502   PetscAssertPointer(newmat, 5);
8503   if (cll == MAT_REUSE_MATRIX) PetscValidHeaderSpecific(*newmat, MAT_CLASSID, 5);
8504   PetscValidType(mat, 1);
8505   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
8506   PetscCheck(cll != MAT_IGNORE_MATRIX, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Cannot use MAT_IGNORE_MATRIX");
8507 
8508   MatCheckPreallocated(mat, 1);
8509   PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)mat), &size));
8510 
8511   if (!iscol || isrow == iscol) {
8512     PetscBool   stride;
8513     PetscMPIInt grabentirematrix = 0, grab;
8514     PetscCall(PetscObjectTypeCompare((PetscObject)isrow, ISSTRIDE, &stride));
8515     if (stride) {
8516       PetscInt first, step, n, rstart, rend;
8517       PetscCall(ISStrideGetInfo(isrow, &first, &step));
8518       if (step == 1) {
8519         PetscCall(MatGetOwnershipRange(mat, &rstart, &rend));
8520         if (rstart == first) {
8521           PetscCall(ISGetLocalSize(isrow, &n));
8522           if (n == rend - rstart) grabentirematrix = 1;
8523         }
8524       }
8525     }
8526     PetscCallMPI(MPIU_Allreduce(&grabentirematrix, &grab, 1, MPI_INT, MPI_MIN, PetscObjectComm((PetscObject)mat)));
8527     if (grab) {
8528       PetscCall(PetscInfo(mat, "Getting entire matrix as submatrix\n"));
8529       if (cll == MAT_INITIAL_MATRIX) {
8530         *newmat = mat;
8531         PetscCall(PetscObjectReference((PetscObject)mat));
8532       }
8533       PetscFunctionReturn(PETSC_SUCCESS);
8534     }
8535   }
8536 
8537   if (!iscol) {
8538     PetscCall(ISCreateStride(PetscObjectComm((PetscObject)mat), mat->cmap->n, mat->cmap->rstart, 1, &iscoltmp));
8539   } else {
8540     iscoltmp = iscol;
8541   }
8542 
8543   /* if original matrix is on just one processor then use submatrix generated */
8544   if (mat->ops->createsubmatrices && !mat->ops->createsubmatrix && size == 1 && cll == MAT_REUSE_MATRIX) {
8545     PetscCall(MatCreateSubMatrices(mat, 1, &isrow, &iscoltmp, MAT_REUSE_MATRIX, &newmat));
8546     goto setproperties;
8547   } else if (mat->ops->createsubmatrices && !mat->ops->createsubmatrix && size == 1) {
8548     PetscCall(MatCreateSubMatrices(mat, 1, &isrow, &iscoltmp, MAT_INITIAL_MATRIX, &local));
8549     *newmat = *local;
8550     PetscCall(PetscFree(local));
8551     goto setproperties;
8552   } else if (!mat->ops->createsubmatrix) {
8553     /* Create a new matrix type that implements the operation using the full matrix */
8554     PetscCall(PetscLogEventBegin(MAT_CreateSubMat, mat, 0, 0, 0));
8555     switch (cll) {
8556     case MAT_INITIAL_MATRIX:
8557       PetscCall(MatCreateSubMatrixVirtual(mat, isrow, iscoltmp, newmat));
8558       break;
8559     case MAT_REUSE_MATRIX:
8560       PetscCall(MatSubMatrixVirtualUpdate(*newmat, mat, isrow, iscoltmp));
8561       break;
8562     default:
8563       SETERRQ(PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_OUTOFRANGE, "Invalid MatReuse, must be either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX");
8564     }
8565     PetscCall(PetscLogEventEnd(MAT_CreateSubMat, mat, 0, 0, 0));
8566     goto setproperties;
8567   }
8568 
8569   PetscCall(PetscLogEventBegin(MAT_CreateSubMat, mat, 0, 0, 0));
8570   PetscUseTypeMethod(mat, createsubmatrix, isrow, iscoltmp, cll, newmat);
8571   PetscCall(PetscLogEventEnd(MAT_CreateSubMat, mat, 0, 0, 0));
8572 
8573 setproperties:
8574   if ((*newmat)->symmetric == PETSC_BOOL3_UNKNOWN && (*newmat)->structurally_symmetric == PETSC_BOOL3_UNKNOWN && (*newmat)->spd == PETSC_BOOL3_UNKNOWN && (*newmat)->hermitian == PETSC_BOOL3_UNKNOWN) {
8575     PetscCall(ISEqualUnsorted(isrow, iscoltmp, &flg));
8576     if (flg) PetscCall(MatPropagateSymmetryOptions(mat, *newmat));
8577   }
8578   if (!iscol) PetscCall(ISDestroy(&iscoltmp));
8579   if (*newmat && cll == MAT_INITIAL_MATRIX) PetscCall(PetscObjectStateIncrease((PetscObject)*newmat));
8580   if (!iscol || isrow == iscol) PetscCall(MatSelectVariableBlockSizes(*newmat, mat, isrow));
8581   PetscFunctionReturn(PETSC_SUCCESS);
8582 }
8583 
8584 /*@
8585   MatPropagateSymmetryOptions - Propagates symmetry options set on a matrix to another matrix
8586 
8587   Not Collective
8588 
8589   Input Parameters:
8590 + A - the matrix we wish to propagate options from
8591 - B - the matrix we wish to propagate options to
8592 
8593   Level: beginner
8594 
8595   Note:
8596   Propagates the options associated to `MAT_SYMMETRY_ETERNAL`, `MAT_STRUCTURALLY_SYMMETRIC`, `MAT_HERMITIAN`, `MAT_SPD`, `MAT_SYMMETRIC`, and `MAT_STRUCTURAL_SYMMETRY_ETERNAL`
8597 
8598 .seealso: [](ch_matrices), `Mat`, `MatSetOption()`, `MatIsSymmetricKnown()`, `MatIsSPDKnown()`, `MatIsHermitianKnown()`, `MatIsStructurallySymmetricKnown()`
8599 @*/
8600 PetscErrorCode MatPropagateSymmetryOptions(Mat A, Mat B)
8601 {
8602   PetscFunctionBegin;
8603   PetscValidHeaderSpecific(A, MAT_CLASSID, 1);
8604   PetscValidHeaderSpecific(B, MAT_CLASSID, 2);
8605   B->symmetry_eternal            = A->symmetry_eternal;
8606   B->structural_symmetry_eternal = A->structural_symmetry_eternal;
8607   B->symmetric                   = A->symmetric;
8608   B->structurally_symmetric      = A->structurally_symmetric;
8609   B->spd                         = A->spd;
8610   B->hermitian                   = A->hermitian;
8611   PetscFunctionReturn(PETSC_SUCCESS);
8612 }
8613 
8614 /*@
8615   MatStashSetInitialSize - sets the sizes of the matrix stash, that is
8616   used during the assembly process to store values that belong to
8617   other processors.
8618 
8619   Not Collective
8620 
8621   Input Parameters:
8622 + mat   - the matrix
8623 . size  - the initial size of the stash.
8624 - bsize - the initial size of the block-stash(if used).
8625 
8626   Options Database Keys:
8627 + -matstash_initial_size <size> or <size0,size1,...sizep-1>            - set initial size
8628 - -matstash_block_initial_size <bsize>  or <bsize0,bsize1,...bsizep-1> - set initial block size
8629 
8630   Level: intermediate
8631 
8632   Notes:
8633   The block-stash is used for values set with `MatSetValuesBlocked()` while
8634   the stash is used for values set with `MatSetValues()`
8635 
8636   Run with the option -info and look for output of the form
8637   MatAssemblyBegin_MPIXXX:Stash has MM entries, uses nn mallocs.
8638   to determine the appropriate value, MM, to use for size and
8639   MatAssemblyBegin_MPIXXX:Block-Stash has BMM entries, uses nn mallocs.
8640   to determine the value, BMM to use for bsize
8641 
8642 .seealso: [](ch_matrices), `MatAssemblyBegin()`, `MatAssemblyEnd()`, `Mat`, `MatStashGetInfo()`
8643 @*/
8644 PetscErrorCode MatStashSetInitialSize(Mat mat, PetscInt size, PetscInt bsize)
8645 {
8646   PetscFunctionBegin;
8647   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
8648   PetscValidType(mat, 1);
8649   PetscCall(MatStashSetInitialSize_Private(&mat->stash, size));
8650   PetscCall(MatStashSetInitialSize_Private(&mat->bstash, bsize));
8651   PetscFunctionReturn(PETSC_SUCCESS);
8652 }
8653 
8654 /*@
8655   MatInterpolateAdd - $w = y + A*x$ or $A^T*x$ depending on the shape of
8656   the matrix
8657 
8658   Neighbor-wise Collective
8659 
8660   Input Parameters:
8661 + A - the matrix
8662 . x - the vector to be multiplied by the interpolation operator
8663 - y - the vector to be added to the result
8664 
8665   Output Parameter:
8666 . w - the resulting vector
8667 
8668   Level: intermediate
8669 
8670   Notes:
8671   `w` may be the same vector as `y`.
8672 
8673   This allows one to use either the restriction or interpolation (its transpose)
8674   matrix to do the interpolation
8675 
8676 .seealso: [](ch_matrices), `Mat`, `MatMultAdd()`, `MatMultTransposeAdd()`, `MatRestrict()`, `PCMG`
8677 @*/
8678 PetscErrorCode MatInterpolateAdd(Mat A, Vec x, Vec y, Vec w)
8679 {
8680   PetscInt M, N, Ny;
8681 
8682   PetscFunctionBegin;
8683   PetscValidHeaderSpecific(A, MAT_CLASSID, 1);
8684   PetscValidHeaderSpecific(x, VEC_CLASSID, 2);
8685   PetscValidHeaderSpecific(y, VEC_CLASSID, 3);
8686   PetscValidHeaderSpecific(w, VEC_CLASSID, 4);
8687   PetscCall(MatGetSize(A, &M, &N));
8688   PetscCall(VecGetSize(y, &Ny));
8689   if (M == Ny) {
8690     PetscCall(MatMultAdd(A, x, y, w));
8691   } else {
8692     PetscCall(MatMultTransposeAdd(A, x, y, w));
8693   }
8694   PetscFunctionReturn(PETSC_SUCCESS);
8695 }
8696 
8697 /*@
8698   MatInterpolate - $y = A*x$ or $A^T*x$ depending on the shape of
8699   the matrix
8700 
8701   Neighbor-wise Collective
8702 
8703   Input Parameters:
8704 + A - the matrix
8705 - x - the vector to be interpolated
8706 
8707   Output Parameter:
8708 . y - the resulting vector
8709 
8710   Level: intermediate
8711 
8712   Note:
8713   This allows one to use either the restriction or interpolation (its transpose)
8714   matrix to do the interpolation
8715 
8716 .seealso: [](ch_matrices), `Mat`, `MatMultAdd()`, `MatMultTransposeAdd()`, `MatRestrict()`, `PCMG`
8717 @*/
8718 PetscErrorCode MatInterpolate(Mat A, Vec x, Vec y)
8719 {
8720   PetscInt M, N, Ny;
8721 
8722   PetscFunctionBegin;
8723   PetscValidHeaderSpecific(A, MAT_CLASSID, 1);
8724   PetscValidHeaderSpecific(x, VEC_CLASSID, 2);
8725   PetscValidHeaderSpecific(y, VEC_CLASSID, 3);
8726   PetscCall(MatGetSize(A, &M, &N));
8727   PetscCall(VecGetSize(y, &Ny));
8728   if (M == Ny) {
8729     PetscCall(MatMult(A, x, y));
8730   } else {
8731     PetscCall(MatMultTranspose(A, x, y));
8732   }
8733   PetscFunctionReturn(PETSC_SUCCESS);
8734 }
8735 
8736 /*@
8737   MatRestrict - $y = A*x$ or $A^T*x$
8738 
8739   Neighbor-wise Collective
8740 
8741   Input Parameters:
8742 + A - the matrix
8743 - x - the vector to be restricted
8744 
8745   Output Parameter:
8746 . y - the resulting vector
8747 
8748   Level: intermediate
8749 
8750   Note:
8751   This allows one to use either the restriction or interpolation (its transpose)
8752   matrix to do the restriction
8753 
8754 .seealso: [](ch_matrices), `Mat`, `MatMultAdd()`, `MatMultTransposeAdd()`, `MatInterpolate()`, `PCMG`
8755 @*/
8756 PetscErrorCode MatRestrict(Mat A, Vec x, Vec y)
8757 {
8758   PetscInt M, N, Nx;
8759 
8760   PetscFunctionBegin;
8761   PetscValidHeaderSpecific(A, MAT_CLASSID, 1);
8762   PetscValidHeaderSpecific(x, VEC_CLASSID, 2);
8763   PetscValidHeaderSpecific(y, VEC_CLASSID, 3);
8764   PetscCall(MatGetSize(A, &M, &N));
8765   PetscCall(VecGetSize(x, &Nx));
8766   if (M == Nx) {
8767     PetscCall(MatMultTranspose(A, x, y));
8768   } else {
8769     PetscCall(MatMult(A, x, y));
8770   }
8771   PetscFunctionReturn(PETSC_SUCCESS);
8772 }
8773 
8774 /*@
8775   MatMatInterpolateAdd - $Y = W + A*X$ or $W + A^T*X$ depending on the shape of `A`
8776 
8777   Neighbor-wise Collective
8778 
8779   Input Parameters:
8780 + A - the matrix
8781 . x - the input dense matrix to be multiplied
8782 - w - the input dense matrix to be added to the result
8783 
8784   Output Parameter:
8785 . y - the output dense matrix
8786 
8787   Level: intermediate
8788 
8789   Note:
8790   This allows one to use either the restriction or interpolation (its transpose)
8791   matrix to do the interpolation. `y` matrix can be reused if already created with the proper sizes,
8792   otherwise it will be recreated. `y` must be initialized to `NULL` if not supplied.
8793 
8794 .seealso: [](ch_matrices), `Mat`, `MatInterpolateAdd()`, `MatMatInterpolate()`, `MatMatRestrict()`, `PCMG`
8795 @*/
8796 PetscErrorCode MatMatInterpolateAdd(Mat A, Mat x, Mat w, Mat *y)
8797 {
8798   PetscInt  M, N, Mx, Nx, Mo, My = 0, Ny = 0;
8799   PetscBool trans = PETSC_TRUE;
8800   MatReuse  reuse = MAT_INITIAL_MATRIX;
8801 
8802   PetscFunctionBegin;
8803   PetscValidHeaderSpecific(A, MAT_CLASSID, 1);
8804   PetscValidHeaderSpecific(x, MAT_CLASSID, 2);
8805   PetscValidType(x, 2);
8806   if (w) PetscValidHeaderSpecific(w, MAT_CLASSID, 3);
8807   if (*y) PetscValidHeaderSpecific(*y, MAT_CLASSID, 4);
8808   PetscCall(MatGetSize(A, &M, &N));
8809   PetscCall(MatGetSize(x, &Mx, &Nx));
8810   if (N == Mx) trans = PETSC_FALSE;
8811   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);
8812   Mo = trans ? N : M;
8813   if (*y) {
8814     PetscCall(MatGetSize(*y, &My, &Ny));
8815     if (Mo == My && Nx == Ny) {
8816       reuse = MAT_REUSE_MATRIX;
8817     } else {
8818       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);
8819       PetscCall(MatDestroy(y));
8820     }
8821   }
8822 
8823   if (w && *y == w) { /* this is to minimize changes in PCMG */
8824     PetscBool flg;
8825 
8826     PetscCall(PetscObjectQuery((PetscObject)*y, "__MatMatIntAdd_w", (PetscObject *)&w));
8827     if (w) {
8828       PetscInt My, Ny, Mw, Nw;
8829 
8830       PetscCall(PetscObjectTypeCompare((PetscObject)*y, ((PetscObject)w)->type_name, &flg));
8831       PetscCall(MatGetSize(*y, &My, &Ny));
8832       PetscCall(MatGetSize(w, &Mw, &Nw));
8833       if (!flg || My != Mw || Ny != Nw) w = NULL;
8834     }
8835     if (!w) {
8836       PetscCall(MatDuplicate(*y, MAT_COPY_VALUES, &w));
8837       PetscCall(PetscObjectCompose((PetscObject)*y, "__MatMatIntAdd_w", (PetscObject)w));
8838       PetscCall(PetscObjectDereference((PetscObject)w));
8839     } else {
8840       PetscCall(MatCopy(*y, w, UNKNOWN_NONZERO_PATTERN));
8841     }
8842   }
8843   if (!trans) {
8844     PetscCall(MatMatMult(A, x, reuse, PETSC_DETERMINE, y));
8845   } else {
8846     PetscCall(MatTransposeMatMult(A, x, reuse, PETSC_DETERMINE, y));
8847   }
8848   if (w) PetscCall(MatAXPY(*y, 1.0, w, UNKNOWN_NONZERO_PATTERN));
8849   PetscFunctionReturn(PETSC_SUCCESS);
8850 }
8851 
8852 /*@
8853   MatMatInterpolate - $Y = A*X$ or $A^T*X$ depending on the shape of `A`
8854 
8855   Neighbor-wise Collective
8856 
8857   Input Parameters:
8858 + A - the matrix
8859 - x - the input dense matrix
8860 
8861   Output Parameter:
8862 . y - the output dense matrix
8863 
8864   Level: intermediate
8865 
8866   Note:
8867   This allows one to use either the restriction or interpolation (its transpose)
8868   matrix to do the interpolation. `y` matrix can be reused if already created with the proper sizes,
8869   otherwise it will be recreated. `y` must be initialized to `NULL` if not supplied.
8870 
8871 .seealso: [](ch_matrices), `Mat`, `MatInterpolate()`, `MatRestrict()`, `MatMatRestrict()`, `PCMG`
8872 @*/
8873 PetscErrorCode MatMatInterpolate(Mat A, Mat x, Mat *y)
8874 {
8875   PetscFunctionBegin;
8876   PetscCall(MatMatInterpolateAdd(A, x, NULL, y));
8877   PetscFunctionReturn(PETSC_SUCCESS);
8878 }
8879 
8880 /*@
8881   MatMatRestrict - $Y = A*X$ or $A^T*X$ depending on the shape of `A`
8882 
8883   Neighbor-wise Collective
8884 
8885   Input Parameters:
8886 + A - the matrix
8887 - x - the input dense matrix
8888 
8889   Output Parameter:
8890 . y - the output dense matrix
8891 
8892   Level: intermediate
8893 
8894   Note:
8895   This allows one to use either the restriction or interpolation (its transpose)
8896   matrix to do the restriction. `y` matrix can be reused if already created with the proper sizes,
8897   otherwise it will be recreated. `y` must be initialized to `NULL` if not supplied.
8898 
8899 .seealso: [](ch_matrices), `Mat`, `MatRestrict()`, `MatInterpolate()`, `MatMatInterpolate()`, `PCMG`
8900 @*/
8901 PetscErrorCode MatMatRestrict(Mat A, Mat x, Mat *y)
8902 {
8903   PetscFunctionBegin;
8904   PetscCall(MatMatInterpolateAdd(A, x, NULL, y));
8905   PetscFunctionReturn(PETSC_SUCCESS);
8906 }
8907 
8908 /*@
8909   MatGetNullSpace - retrieves the null space of a matrix.
8910 
8911   Logically Collective
8912 
8913   Input Parameters:
8914 + mat    - the matrix
8915 - nullsp - the null space object
8916 
8917   Level: developer
8918 
8919 .seealso: [](ch_matrices), `Mat`, `MatCreate()`, `MatNullSpaceCreate()`, `MatSetNearNullSpace()`, `MatSetNullSpace()`, `MatNullSpace`
8920 @*/
8921 PetscErrorCode MatGetNullSpace(Mat mat, MatNullSpace *nullsp)
8922 {
8923   PetscFunctionBegin;
8924   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
8925   PetscAssertPointer(nullsp, 2);
8926   *nullsp = (mat->symmetric == PETSC_BOOL3_TRUE && !mat->nullsp) ? mat->transnullsp : mat->nullsp;
8927   PetscFunctionReturn(PETSC_SUCCESS);
8928 }
8929 
8930 /*@C
8931   MatGetNullSpaces - gets the null spaces, transpose null spaces, and near null spaces from an array of matrices
8932 
8933   Logically Collective
8934 
8935   Input Parameters:
8936 + n   - the number of matrices
8937 - mat - the array of matrices
8938 
8939   Output Parameters:
8940 . nullsp - an array of null spaces, `NULL` for each matrix that does not have a null space, length 3 * `n`
8941 
8942   Level: developer
8943 
8944   Note:
8945   Call `MatRestoreNullspaces()` to provide these to another array of matrices
8946 
8947 .seealso: [](ch_matrices), `Mat`, `MatCreate()`, `MatNullSpaceCreate()`, `MatSetNearNullSpace()`, `MatGetNullSpace()`, `MatSetTransposeNullSpace()`, `MatGetTransposeNullSpace()`,
8948           `MatNullSpaceRemove()`, `MatRestoreNullSpaces()`
8949 @*/
8950 PetscErrorCode MatGetNullSpaces(PetscInt n, Mat mat[], MatNullSpace *nullsp[])
8951 {
8952   PetscFunctionBegin;
8953   PetscCheck(n >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Number of matrices %" PetscInt_FMT " must be non-negative", n);
8954   PetscAssertPointer(mat, 2);
8955   PetscAssertPointer(nullsp, 3);
8956 
8957   PetscCall(PetscCalloc1(3 * n, nullsp));
8958   for (PetscInt i = 0; i < n; i++) {
8959     PetscValidHeaderSpecific(mat[i], MAT_CLASSID, 2);
8960     (*nullsp)[i] = mat[i]->nullsp;
8961     PetscCall(PetscObjectReference((PetscObject)(*nullsp)[i]));
8962     (*nullsp)[n + i] = mat[i]->nearnullsp;
8963     PetscCall(PetscObjectReference((PetscObject)(*nullsp)[n + i]));
8964     (*nullsp)[2 * n + i] = mat[i]->transnullsp;
8965     PetscCall(PetscObjectReference((PetscObject)(*nullsp)[2 * n + i]));
8966   }
8967   PetscFunctionReturn(PETSC_SUCCESS);
8968 }
8969 
8970 /*@C
8971   MatRestoreNullSpaces - sets the null spaces, transpose null spaces, and near null spaces obtained with `MatGetNullSpaces()` for an array of matrices
8972 
8973   Logically Collective
8974 
8975   Input Parameters:
8976 + n      - the number of matrices
8977 . mat    - the array of matrices
8978 - nullsp - an array of null spaces
8979 
8980   Level: developer
8981 
8982   Note:
8983   Call `MatGetNullSpaces()` to create `nullsp`
8984 
8985 .seealso: [](ch_matrices), `Mat`, `MatCreate()`, `MatNullSpaceCreate()`, `MatSetNearNullSpace()`, `MatGetNullSpace()`, `MatSetTransposeNullSpace()`, `MatGetTransposeNullSpace()`,
8986           `MatNullSpaceRemove()`, `MatGetNullSpaces()`
8987 @*/
8988 PetscErrorCode MatRestoreNullSpaces(PetscInt n, Mat mat[], MatNullSpace *nullsp[])
8989 {
8990   PetscFunctionBegin;
8991   PetscCheck(n >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Number of matrices %" PetscInt_FMT " must be non-negative", n);
8992   PetscAssertPointer(mat, 2);
8993   PetscAssertPointer(nullsp, 3);
8994   PetscAssertPointer(*nullsp, 3);
8995 
8996   for (PetscInt i = 0; i < n; i++) {
8997     PetscValidHeaderSpecific(mat[i], MAT_CLASSID, 2);
8998     PetscCall(MatSetNullSpace(mat[i], (*nullsp)[i]));
8999     PetscCall(PetscObjectDereference((PetscObject)(*nullsp)[i]));
9000     PetscCall(MatSetNearNullSpace(mat[i], (*nullsp)[n + i]));
9001     PetscCall(PetscObjectDereference((PetscObject)(*nullsp)[n + i]));
9002     PetscCall(MatSetTransposeNullSpace(mat[i], (*nullsp)[2 * n + i]));
9003     PetscCall(PetscObjectDereference((PetscObject)(*nullsp)[2 * n + i]));
9004   }
9005   PetscCall(PetscFree(*nullsp));
9006   PetscFunctionReturn(PETSC_SUCCESS);
9007 }
9008 
9009 /*@
9010   MatSetNullSpace - attaches a null space to a matrix.
9011 
9012   Logically Collective
9013 
9014   Input Parameters:
9015 + mat    - the matrix
9016 - nullsp - the null space object
9017 
9018   Level: advanced
9019 
9020   Notes:
9021   This null space is used by the `KSP` linear solvers to solve singular systems.
9022 
9023   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`
9024 
9025   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
9026   to zero but the linear system will still be solved in a least squares sense.
9027 
9028   The fundamental theorem of linear algebra (Gilbert Strang, Introduction to Applied Mathematics, page 72) states that
9029   the domain of a matrix $A$ (from $R^n$ to $R^m$ ($m$ rows, $n$ columns) $R^n$ = the direct sum of the null space of $A$, $n(A)$, plus the range of $A^T$, $R(A^T)$.
9030   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
9031   $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
9032   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)$.
9033   This  $\hat{b}$ can be obtained by calling `MatNullSpaceRemove()` with the null space of the transpose of the matrix.
9034 
9035   If the matrix is known to be symmetric because it is an `MATSBAIJ` matrix or one has called
9036   `MatSetOption`(mat,`MAT_SYMMETRIC` or possibly `MAT_SYMMETRY_ETERNAL`,`PETSC_TRUE`); this
9037   routine also automatically calls `MatSetTransposeNullSpace()`.
9038 
9039   The user should call `MatNullSpaceDestroy()`.
9040 
9041 .seealso: [](ch_matrices), `Mat`, `MatCreate()`, `MatNullSpaceCreate()`, `MatSetNearNullSpace()`, `MatGetNullSpace()`, `MatSetTransposeNullSpace()`, `MatGetTransposeNullSpace()`, `MatNullSpaceRemove()`,
9042           `KSPSetPCSide()`
9043 @*/
9044 PetscErrorCode MatSetNullSpace(Mat mat, MatNullSpace nullsp)
9045 {
9046   PetscFunctionBegin;
9047   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
9048   if (nullsp) PetscValidHeaderSpecific(nullsp, MAT_NULLSPACE_CLASSID, 2);
9049   if (nullsp) PetscCall(PetscObjectReference((PetscObject)nullsp));
9050   PetscCall(MatNullSpaceDestroy(&mat->nullsp));
9051   mat->nullsp = nullsp;
9052   if (mat->symmetric == PETSC_BOOL3_TRUE) PetscCall(MatSetTransposeNullSpace(mat, nullsp));
9053   PetscFunctionReturn(PETSC_SUCCESS);
9054 }
9055 
9056 /*@
9057   MatGetTransposeNullSpace - retrieves the null space of the transpose of a matrix.
9058 
9059   Logically Collective
9060 
9061   Input Parameters:
9062 + mat    - the matrix
9063 - nullsp - the null space object
9064 
9065   Level: developer
9066 
9067 .seealso: [](ch_matrices), `Mat`, `MatNullSpace`, `MatCreate()`, `MatNullSpaceCreate()`, `MatSetNearNullSpace()`, `MatSetTransposeNullSpace()`, `MatSetNullSpace()`, `MatGetNullSpace()`
9068 @*/
9069 PetscErrorCode MatGetTransposeNullSpace(Mat mat, MatNullSpace *nullsp)
9070 {
9071   PetscFunctionBegin;
9072   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
9073   PetscValidType(mat, 1);
9074   PetscAssertPointer(nullsp, 2);
9075   *nullsp = (mat->symmetric == PETSC_BOOL3_TRUE && !mat->transnullsp) ? mat->nullsp : mat->transnullsp;
9076   PetscFunctionReturn(PETSC_SUCCESS);
9077 }
9078 
9079 /*@
9080   MatSetTransposeNullSpace - attaches the null space of a transpose of a matrix to the matrix
9081 
9082   Logically Collective
9083 
9084   Input Parameters:
9085 + mat    - the matrix
9086 - nullsp - the null space object
9087 
9088   Level: advanced
9089 
9090   Notes:
9091   This allows solving singular linear systems defined by the transpose of the matrix using `KSP` solvers with left preconditioning.
9092 
9093   See `MatSetNullSpace()`
9094 
9095 .seealso: [](ch_matrices), `Mat`, `MatNullSpace`, `MatCreate()`, `MatNullSpaceCreate()`, `MatSetNearNullSpace()`, `MatGetNullSpace()`, `MatSetNullSpace()`, `MatGetTransposeNullSpace()`, `MatNullSpaceRemove()`, `KSPSetPCSide()`
9096 @*/
9097 PetscErrorCode MatSetTransposeNullSpace(Mat mat, MatNullSpace nullsp)
9098 {
9099   PetscFunctionBegin;
9100   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
9101   if (nullsp) PetscValidHeaderSpecific(nullsp, MAT_NULLSPACE_CLASSID, 2);
9102   if (nullsp) PetscCall(PetscObjectReference((PetscObject)nullsp));
9103   PetscCall(MatNullSpaceDestroy(&mat->transnullsp));
9104   mat->transnullsp = nullsp;
9105   PetscFunctionReturn(PETSC_SUCCESS);
9106 }
9107 
9108 /*@
9109   MatSetNearNullSpace - attaches a null space to a matrix, which is often the null space (rigid body modes) of the operator without boundary conditions
9110   This null space will be used to provide near null space vectors to a multigrid preconditioner built from this matrix.
9111 
9112   Logically Collective
9113 
9114   Input Parameters:
9115 + mat    - the matrix
9116 - nullsp - the null space object
9117 
9118   Level: advanced
9119 
9120   Notes:
9121   Overwrites any previous near null space that may have been attached
9122 
9123   You can remove the null space by calling this routine with an `nullsp` of `NULL`
9124 
9125 .seealso: [](ch_matrices), `Mat`, `MatNullSpace`, `MatCreate()`, `MatNullSpaceCreate()`, `MatSetNullSpace()`, `MatNullSpaceCreateRigidBody()`, `MatGetNearNullSpace()`
9126 @*/
9127 PetscErrorCode MatSetNearNullSpace(Mat mat, MatNullSpace nullsp)
9128 {
9129   PetscFunctionBegin;
9130   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
9131   PetscValidType(mat, 1);
9132   if (nullsp) PetscValidHeaderSpecific(nullsp, MAT_NULLSPACE_CLASSID, 2);
9133   MatCheckPreallocated(mat, 1);
9134   if (nullsp) PetscCall(PetscObjectReference((PetscObject)nullsp));
9135   PetscCall(MatNullSpaceDestroy(&mat->nearnullsp));
9136   mat->nearnullsp = nullsp;
9137   PetscFunctionReturn(PETSC_SUCCESS);
9138 }
9139 
9140 /*@
9141   MatGetNearNullSpace - Get null space attached with `MatSetNearNullSpace()`
9142 
9143   Not Collective
9144 
9145   Input Parameter:
9146 . mat - the matrix
9147 
9148   Output Parameter:
9149 . nullsp - the null space object, `NULL` if not set
9150 
9151   Level: advanced
9152 
9153 .seealso: [](ch_matrices), `Mat`, `MatNullSpace`, `MatSetNearNullSpace()`, `MatGetNullSpace()`, `MatNullSpaceCreate()`
9154 @*/
9155 PetscErrorCode MatGetNearNullSpace(Mat mat, MatNullSpace *nullsp)
9156 {
9157   PetscFunctionBegin;
9158   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
9159   PetscValidType(mat, 1);
9160   PetscAssertPointer(nullsp, 2);
9161   MatCheckPreallocated(mat, 1);
9162   *nullsp = mat->nearnullsp;
9163   PetscFunctionReturn(PETSC_SUCCESS);
9164 }
9165 
9166 /*@
9167   MatICCFactor - Performs in-place incomplete Cholesky factorization of matrix.
9168 
9169   Collective
9170 
9171   Input Parameters:
9172 + mat  - the matrix
9173 . row  - row/column permutation
9174 - info - information on desired factorization process
9175 
9176   Level: developer
9177 
9178   Notes:
9179   Probably really in-place only when level of fill is zero, otherwise allocates
9180   new space to store factored matrix and deletes previous memory.
9181 
9182   Most users should employ the `KSP` interface for linear solvers
9183   instead of working directly with matrix algebra routines such as this.
9184   See, e.g., `KSPCreate()`.
9185 
9186   Fortran Note:
9187   A valid (non-null) `info` argument must be provided
9188 
9189 .seealso: [](ch_matrices), `Mat`, `MatFactorInfo`, `MatGetFactor()`, `MatICCFactorSymbolic()`, `MatLUFactorNumeric()`, `MatCholeskyFactor()`
9190 @*/
9191 PetscErrorCode MatICCFactor(Mat mat, IS row, const MatFactorInfo *info)
9192 {
9193   PetscFunctionBegin;
9194   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
9195   PetscValidType(mat, 1);
9196   if (row) PetscValidHeaderSpecific(row, IS_CLASSID, 2);
9197   PetscAssertPointer(info, 3);
9198   PetscCheck(mat->rmap->N == mat->cmap->N, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONG, "matrix must be square");
9199   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
9200   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
9201   MatCheckPreallocated(mat, 1);
9202   PetscUseTypeMethod(mat, iccfactor, row, info);
9203   PetscCall(PetscObjectStateIncrease((PetscObject)mat));
9204   PetscFunctionReturn(PETSC_SUCCESS);
9205 }
9206 
9207 /*@
9208   MatDiagonalScaleLocal - Scales columns of a matrix given the scaling values including the
9209   ghosted ones.
9210 
9211   Not Collective
9212 
9213   Input Parameters:
9214 + mat  - the matrix
9215 - diag - the diagonal values, including ghost ones
9216 
9217   Level: developer
9218 
9219   Notes:
9220   Works only for `MATMPIAIJ` and `MATMPIBAIJ` matrices
9221 
9222   This allows one to avoid during communication to perform the scaling that must be done with `MatDiagonalScale()`
9223 
9224 .seealso: [](ch_matrices), `Mat`, `MatDiagonalScale()`
9225 @*/
9226 PetscErrorCode MatDiagonalScaleLocal(Mat mat, Vec diag)
9227 {
9228   PetscMPIInt size;
9229 
9230   PetscFunctionBegin;
9231   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
9232   PetscValidHeaderSpecific(diag, VEC_CLASSID, 2);
9233   PetscValidType(mat, 1);
9234 
9235   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Matrix must be already assembled");
9236   PetscCall(PetscLogEventBegin(MAT_Scale, mat, 0, 0, 0));
9237   PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)mat), &size));
9238   if (size == 1) {
9239     PetscInt n, m;
9240     PetscCall(VecGetSize(diag, &n));
9241     PetscCall(MatGetSize(mat, NULL, &m));
9242     PetscCheck(m == n, PETSC_COMM_SELF, PETSC_ERR_SUP, "Only supported for sequential matrices when no ghost points/periodic conditions");
9243     PetscCall(MatDiagonalScale(mat, NULL, diag));
9244   } else {
9245     PetscUseMethod(mat, "MatDiagonalScaleLocal_C", (Mat, Vec), (mat, diag));
9246   }
9247   PetscCall(PetscLogEventEnd(MAT_Scale, mat, 0, 0, 0));
9248   PetscCall(PetscObjectStateIncrease((PetscObject)mat));
9249   PetscFunctionReturn(PETSC_SUCCESS);
9250 }
9251 
9252 /*@
9253   MatGetInertia - Gets the inertia from a factored matrix
9254 
9255   Collective
9256 
9257   Input Parameter:
9258 . mat - the matrix
9259 
9260   Output Parameters:
9261 + nneg  - number of negative eigenvalues
9262 . nzero - number of zero eigenvalues
9263 - npos  - number of positive eigenvalues
9264 
9265   Level: advanced
9266 
9267   Note:
9268   Matrix must have been factored by `MatCholeskyFactor()`
9269 
9270 .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatCholeskyFactor()`
9271 @*/
9272 PetscErrorCode MatGetInertia(Mat mat, PetscInt *nneg, PetscInt *nzero, PetscInt *npos)
9273 {
9274   PetscFunctionBegin;
9275   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
9276   PetscValidType(mat, 1);
9277   PetscCheck(mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Unfactored matrix");
9278   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Numeric factor mat is not assembled");
9279   PetscUseTypeMethod(mat, getinertia, nneg, nzero, npos);
9280   PetscFunctionReturn(PETSC_SUCCESS);
9281 }
9282 
9283 /*@C
9284   MatSolves - Solves $A x = b$, given a factored matrix, for a collection of vectors
9285 
9286   Neighbor-wise Collective
9287 
9288   Input Parameters:
9289 + mat - the factored matrix obtained with `MatGetFactor()`
9290 - b   - the right-hand-side vectors
9291 
9292   Output Parameter:
9293 . x - the result vectors
9294 
9295   Level: developer
9296 
9297   Note:
9298   The vectors `b` and `x` cannot be the same.  I.e., one cannot
9299   call `MatSolves`(A,x,x).
9300 
9301 .seealso: [](ch_matrices), `Mat`, `Vecs`, `MatSolveAdd()`, `MatSolveTranspose()`, `MatSolveTransposeAdd()`, `MatSolve()`
9302 @*/
9303 PetscErrorCode MatSolves(Mat mat, Vecs b, Vecs x)
9304 {
9305   PetscFunctionBegin;
9306   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
9307   PetscValidType(mat, 1);
9308   PetscCheck(x != b, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_IDN, "x and b must be different vectors");
9309   PetscCheck(mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Unfactored matrix");
9310   if (!mat->rmap->N && !mat->cmap->N) PetscFunctionReturn(PETSC_SUCCESS);
9311 
9312   MatCheckPreallocated(mat, 1);
9313   PetscCall(PetscLogEventBegin(MAT_Solves, mat, 0, 0, 0));
9314   PetscUseTypeMethod(mat, solves, b, x);
9315   PetscCall(PetscLogEventEnd(MAT_Solves, mat, 0, 0, 0));
9316   PetscFunctionReturn(PETSC_SUCCESS);
9317 }
9318 
9319 /*@
9320   MatIsSymmetric - Test whether a matrix is symmetric
9321 
9322   Collective
9323 
9324   Input Parameters:
9325 + A   - the matrix to test
9326 - tol - difference between value and its transpose less than this amount counts as equal (use 0.0 for exact transpose)
9327 
9328   Output Parameter:
9329 . flg - the result
9330 
9331   Level: intermediate
9332 
9333   Notes:
9334   For real numbers `MatIsSymmetric()` and `MatIsHermitian()` return identical results
9335 
9336   If the matrix does not yet know if it is symmetric or not this can be an expensive operation, also available `MatIsSymmetricKnown()`
9337 
9338   One can declare that a matrix is symmetric with `MatSetOption`(mat,`MAT_SYMMETRIC`,`PETSC_TRUE`) and if it is known to remain symmetric
9339   after changes to the matrices values one can call `MatSetOption`(mat,`MAT_SYMMETRY_ETERNAL`,`PETSC_TRUE`)
9340 
9341 .seealso: [](ch_matrices), `Mat`, `MatTranspose()`, `MatIsTranspose()`, `MatIsHermitian()`, `MatIsStructurallySymmetric()`, `MatSetOption()`, `MatIsSymmetricKnown()`,
9342           `MAT_SYMMETRIC`, `MAT_SYMMETRY_ETERNAL`
9343 @*/
9344 PetscErrorCode MatIsSymmetric(Mat A, PetscReal tol, PetscBool *flg)
9345 {
9346   PetscFunctionBegin;
9347   PetscValidHeaderSpecific(A, MAT_CLASSID, 1);
9348   PetscAssertPointer(flg, 3);
9349   if (A->symmetric != PETSC_BOOL3_UNKNOWN && !tol) *flg = PetscBool3ToBool(A->symmetric);
9350   else {
9351     if (A->ops->issymmetric) PetscUseTypeMethod(A, issymmetric, tol, flg);
9352     else PetscCall(MatIsTranspose(A, A, tol, flg));
9353     if (!tol) PetscCall(MatSetOption(A, MAT_SYMMETRIC, *flg));
9354   }
9355   PetscFunctionReturn(PETSC_SUCCESS);
9356 }
9357 
9358 /*@
9359   MatIsHermitian - Test whether a matrix is Hermitian
9360 
9361   Collective
9362 
9363   Input Parameters:
9364 + A   - the matrix to test
9365 - tol - difference between value and its transpose less than this amount counts as equal (use 0.0 for exact Hermitian)
9366 
9367   Output Parameter:
9368 . flg - the result
9369 
9370   Level: intermediate
9371 
9372   Notes:
9373   For real numbers `MatIsSymmetric()` and `MatIsHermitian()` return identical results
9374 
9375   If the matrix does not yet know if it is Hermitian or not this can be an expensive operation, also available `MatIsHermitianKnown()`
9376 
9377   One can declare that a matrix is Hermitian with `MatSetOption`(mat,`MAT_HERMITIAN`,`PETSC_TRUE`) and if it is known to remain Hermitian
9378   after changes to the matrices values one can call `MatSetOption`(mat,`MAT_SYMEMTRY_ETERNAL`,`PETSC_TRUE`)
9379 
9380 .seealso: [](ch_matrices), `Mat`, `MatTranspose()`, `MatIsTranspose()`, `MatIsHermitianKnown()`, `MatIsStructurallySymmetric()`, `MatSetOption()`,
9381           `MatIsSymmetricKnown()`, `MatIsSymmetric()`, `MAT_HERMITIAN`, `MAT_SYMMETRY_ETERNAL`
9382 @*/
9383 PetscErrorCode MatIsHermitian(Mat A, PetscReal tol, PetscBool *flg)
9384 {
9385   PetscFunctionBegin;
9386   PetscValidHeaderSpecific(A, MAT_CLASSID, 1);
9387   PetscAssertPointer(flg, 3);
9388   if (A->hermitian != PETSC_BOOL3_UNKNOWN && !tol) *flg = PetscBool3ToBool(A->hermitian);
9389   else {
9390     if (A->ops->ishermitian) PetscUseTypeMethod(A, ishermitian, tol, flg);
9391     else PetscCall(MatIsHermitianTranspose(A, A, tol, flg));
9392     if (!tol) PetscCall(MatSetOption(A, MAT_HERMITIAN, *flg));
9393   }
9394   PetscFunctionReturn(PETSC_SUCCESS);
9395 }
9396 
9397 /*@
9398   MatIsSymmetricKnown - Checks if a matrix knows if it is symmetric or not and its symmetric state
9399 
9400   Not Collective
9401 
9402   Input Parameter:
9403 . A - the matrix to check
9404 
9405   Output Parameters:
9406 + set - `PETSC_TRUE` if the matrix knows its symmetry state (this tells you if the next flag is valid)
9407 - flg - the result (only valid if set is `PETSC_TRUE`)
9408 
9409   Level: advanced
9410 
9411   Notes:
9412   Does not check the matrix values directly, so this may return unknown (set = `PETSC_FALSE`). Use `MatIsSymmetric()`
9413   if you want it explicitly checked
9414 
9415   One can declare that a matrix is symmetric with `MatSetOption`(mat,`MAT_SYMMETRIC`,`PETSC_TRUE`) and if it is known to remain symmetric
9416   after changes to the matrices values one can call `MatSetOption`(mat,`MAT_SYMMETRY_ETERNAL`,`PETSC_TRUE`)
9417 
9418 .seealso: [](ch_matrices), `Mat`, `MAT_SYMMETRY_ETERNAL`, `MatTranspose()`, `MatIsTranspose()`, `MatIsHermitian()`, `MatIsStructurallySymmetric()`, `MatSetOption()`, `MatIsSymmetric()`, `MatIsHermitianKnown()`
9419 @*/
9420 PetscErrorCode MatIsSymmetricKnown(Mat A, PetscBool *set, PetscBool *flg)
9421 {
9422   PetscFunctionBegin;
9423   PetscValidHeaderSpecific(A, MAT_CLASSID, 1);
9424   PetscAssertPointer(set, 2);
9425   PetscAssertPointer(flg, 3);
9426   if (A->symmetric != PETSC_BOOL3_UNKNOWN) {
9427     *set = PETSC_TRUE;
9428     *flg = PetscBool3ToBool(A->symmetric);
9429   } else {
9430     *set = PETSC_FALSE;
9431   }
9432   PetscFunctionReturn(PETSC_SUCCESS);
9433 }
9434 
9435 /*@
9436   MatIsSPDKnown - Checks if a matrix knows if it is symmetric positive definite or not and its symmetric positive definite state
9437 
9438   Not Collective
9439 
9440   Input Parameter:
9441 . A - the matrix to check
9442 
9443   Output Parameters:
9444 + set - `PETSC_TRUE` if the matrix knows its symmetric positive definite state (this tells you if the next flag is valid)
9445 - flg - the result (only valid if set is `PETSC_TRUE`)
9446 
9447   Level: advanced
9448 
9449   Notes:
9450   Does not check the matrix values directly, so this may return unknown (set = `PETSC_FALSE`).
9451 
9452   One can declare that a matrix is SPD with `MatSetOption`(mat,`MAT_SPD`,`PETSC_TRUE`) and if it is known to remain SPD
9453   after changes to the matrices values one can call `MatSetOption`(mat,`MAT_SPD_ETERNAL`,`PETSC_TRUE`)
9454 
9455 .seealso: [](ch_matrices), `Mat`, `MAT_SPD_ETERNAL`, `MAT_SPD`, `MatTranspose()`, `MatIsTranspose()`, `MatIsHermitian()`, `MatIsStructurallySymmetric()`, `MatSetOption()`, `MatIsSymmetric()`, `MatIsHermitianKnown()`
9456 @*/
9457 PetscErrorCode MatIsSPDKnown(Mat A, PetscBool *set, PetscBool *flg)
9458 {
9459   PetscFunctionBegin;
9460   PetscValidHeaderSpecific(A, MAT_CLASSID, 1);
9461   PetscAssertPointer(set, 2);
9462   PetscAssertPointer(flg, 3);
9463   if (A->spd != PETSC_BOOL3_UNKNOWN) {
9464     *set = PETSC_TRUE;
9465     *flg = PetscBool3ToBool(A->spd);
9466   } else {
9467     *set = PETSC_FALSE;
9468   }
9469   PetscFunctionReturn(PETSC_SUCCESS);
9470 }
9471 
9472 /*@
9473   MatIsHermitianKnown - Checks if a matrix knows if it is Hermitian or not and its Hermitian state
9474 
9475   Not Collective
9476 
9477   Input Parameter:
9478 . A - the matrix to check
9479 
9480   Output Parameters:
9481 + set - `PETSC_TRUE` if the matrix knows its Hermitian state (this tells you if the next flag is valid)
9482 - flg - the result (only valid if set is `PETSC_TRUE`)
9483 
9484   Level: advanced
9485 
9486   Notes:
9487   Does not check the matrix values directly, so this may return unknown (set = `PETSC_FALSE`). Use `MatIsHermitian()`
9488   if you want it explicitly checked
9489 
9490   One can declare that a matrix is Hermitian with `MatSetOption`(mat,`MAT_HERMITIAN`,`PETSC_TRUE`) and if it is known to remain Hermitian
9491   after changes to the matrices values one can call `MatSetOption`(mat,`MAT_SYMMETRY_ETERNAL`,`PETSC_TRUE`)
9492 
9493 .seealso: [](ch_matrices), `Mat`, `MAT_SYMMETRY_ETERNAL`, `MAT_HERMITIAN`, `MatTranspose()`, `MatIsTranspose()`, `MatIsHermitian()`, `MatIsStructurallySymmetric()`, `MatSetOption()`, `MatIsSymmetric()`
9494 @*/
9495 PetscErrorCode MatIsHermitianKnown(Mat A, PetscBool *set, PetscBool *flg)
9496 {
9497   PetscFunctionBegin;
9498   PetscValidHeaderSpecific(A, MAT_CLASSID, 1);
9499   PetscAssertPointer(set, 2);
9500   PetscAssertPointer(flg, 3);
9501   if (A->hermitian != PETSC_BOOL3_UNKNOWN) {
9502     *set = PETSC_TRUE;
9503     *flg = PetscBool3ToBool(A->hermitian);
9504   } else {
9505     *set = PETSC_FALSE;
9506   }
9507   PetscFunctionReturn(PETSC_SUCCESS);
9508 }
9509 
9510 /*@
9511   MatIsStructurallySymmetric - Test whether a matrix is structurally symmetric
9512 
9513   Collective
9514 
9515   Input Parameter:
9516 . A - the matrix to test
9517 
9518   Output Parameter:
9519 . flg - the result
9520 
9521   Level: intermediate
9522 
9523   Notes:
9524   If the matrix does yet know it is structurally symmetric this can be an expensive operation, also available `MatIsStructurallySymmetricKnown()`
9525 
9526   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
9527   symmetric after changes to the matrices values one can call `MatSetOption`(mat,`MAT_STRUCTURAL_SYMMETRY_ETERNAL`,`PETSC_TRUE`)
9528 
9529 .seealso: [](ch_matrices), `Mat`, `MAT_STRUCTURALLY_SYMMETRIC`, `MAT_STRUCTURAL_SYMMETRY_ETERNAL`, `MatTranspose()`, `MatIsTranspose()`, `MatIsHermitian()`, `MatIsSymmetric()`, `MatSetOption()`, `MatIsStructurallySymmetricKnown()`
9530 @*/
9531 PetscErrorCode MatIsStructurallySymmetric(Mat A, PetscBool *flg)
9532 {
9533   PetscFunctionBegin;
9534   PetscValidHeaderSpecific(A, MAT_CLASSID, 1);
9535   PetscAssertPointer(flg, 2);
9536   if (A->structurally_symmetric != PETSC_BOOL3_UNKNOWN) {
9537     *flg = PetscBool3ToBool(A->structurally_symmetric);
9538   } else {
9539     PetscUseTypeMethod(A, isstructurallysymmetric, flg);
9540     PetscCall(MatSetOption(A, MAT_STRUCTURALLY_SYMMETRIC, *flg));
9541   }
9542   PetscFunctionReturn(PETSC_SUCCESS);
9543 }
9544 
9545 /*@
9546   MatIsStructurallySymmetricKnown - Checks if a matrix knows if it is structurally symmetric or not and its structurally symmetric state
9547 
9548   Not Collective
9549 
9550   Input Parameter:
9551 . A - the matrix to check
9552 
9553   Output Parameters:
9554 + set - PETSC_TRUE if the matrix knows its structurally symmetric state (this tells you if the next flag is valid)
9555 - flg - the result (only valid if set is PETSC_TRUE)
9556 
9557   Level: advanced
9558 
9559   Notes:
9560   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
9561   symmetric after changes to the matrices values one can call `MatSetOption`(mat,`MAT_STRUCTURAL_SYMMETRY_ETERNAL`,`PETSC_TRUE`)
9562 
9563   Use `MatIsStructurallySymmetric()` to explicitly check if a matrix is structurally symmetric (this is an expensive operation)
9564 
9565 .seealso: [](ch_matrices), `Mat`, `MAT_STRUCTURALLY_SYMMETRIC`, `MatTranspose()`, `MatIsTranspose()`, `MatIsHermitian()`, `MatIsStructurallySymmetric()`, `MatSetOption()`, `MatIsSymmetric()`, `MatIsHermitianKnown()`
9566 @*/
9567 PetscErrorCode MatIsStructurallySymmetricKnown(Mat A, PetscBool *set, PetscBool *flg)
9568 {
9569   PetscFunctionBegin;
9570   PetscValidHeaderSpecific(A, MAT_CLASSID, 1);
9571   PetscAssertPointer(set, 2);
9572   PetscAssertPointer(flg, 3);
9573   if (A->structurally_symmetric != PETSC_BOOL3_UNKNOWN) {
9574     *set = PETSC_TRUE;
9575     *flg = PetscBool3ToBool(A->structurally_symmetric);
9576   } else {
9577     *set = PETSC_FALSE;
9578   }
9579   PetscFunctionReturn(PETSC_SUCCESS);
9580 }
9581 
9582 /*@
9583   MatStashGetInfo - Gets how many values are currently in the matrix stash, i.e. need
9584   to be communicated to other processors during the `MatAssemblyBegin()`/`MatAssemblyEnd()` process
9585 
9586   Not Collective
9587 
9588   Input Parameter:
9589 . mat - the matrix
9590 
9591   Output Parameters:
9592 + nstash    - the size of the stash
9593 . reallocs  - the number of additional mallocs incurred.
9594 . bnstash   - the size of the block stash
9595 - breallocs - the number of additional mallocs incurred.in the block stash
9596 
9597   Level: advanced
9598 
9599 .seealso: [](ch_matrices), `MatAssemblyBegin()`, `MatAssemblyEnd()`, `Mat`, `MatStashSetInitialSize()`
9600 @*/
9601 PetscErrorCode MatStashGetInfo(Mat mat, PetscInt *nstash, PetscInt *reallocs, PetscInt *bnstash, PetscInt *breallocs)
9602 {
9603   PetscFunctionBegin;
9604   PetscCall(MatStashGetInfo_Private(&mat->stash, nstash, reallocs));
9605   PetscCall(MatStashGetInfo_Private(&mat->bstash, bnstash, breallocs));
9606   PetscFunctionReturn(PETSC_SUCCESS);
9607 }
9608 
9609 /*@
9610   MatCreateVecs - Get vector(s) compatible with the matrix, i.e. with the same
9611   parallel layout, `PetscLayout` for rows and columns
9612 
9613   Collective
9614 
9615   Input Parameter:
9616 . mat - the matrix
9617 
9618   Output Parameters:
9619 + right - (optional) vector that the matrix can be multiplied against
9620 - left  - (optional) vector that the matrix vector product can be stored in
9621 
9622   Level: advanced
9623 
9624   Notes:
9625   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()`.
9626 
9627   These are new vectors which are not owned by the mat, they should be destroyed in `VecDestroy()` when no longer needed
9628 
9629 .seealso: [](ch_matrices), `Mat`, `Vec`, `VecCreate()`, `VecDestroy()`, `DMCreateGlobalVector()`
9630 @*/
9631 PetscErrorCode MatCreateVecs(Mat mat, Vec *right, Vec *left)
9632 {
9633   PetscFunctionBegin;
9634   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
9635   PetscValidType(mat, 1);
9636   if (mat->ops->getvecs) {
9637     PetscUseTypeMethod(mat, getvecs, right, left);
9638   } else {
9639     if (right) {
9640       PetscCheck(mat->cmap->n >= 0, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "PetscLayout for columns not yet setup");
9641       PetscCall(VecCreateWithLayout_Private(mat->cmap, right));
9642       PetscCall(VecSetType(*right, mat->defaultvectype));
9643 #if defined(PETSC_HAVE_VIENNACL) || defined(PETSC_HAVE_CUDA) || defined(PETSC_HAVE_HIP)
9644       if (mat->boundtocpu && mat->bindingpropagates) {
9645         PetscCall(VecSetBindingPropagates(*right, PETSC_TRUE));
9646         PetscCall(VecBindToCPU(*right, PETSC_TRUE));
9647       }
9648 #endif
9649     }
9650     if (left) {
9651       PetscCheck(mat->rmap->n >= 0, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "PetscLayout for rows not yet setup");
9652       PetscCall(VecCreateWithLayout_Private(mat->rmap, left));
9653       PetscCall(VecSetType(*left, mat->defaultvectype));
9654 #if defined(PETSC_HAVE_VIENNACL) || defined(PETSC_HAVE_CUDA) || defined(PETSC_HAVE_HIP)
9655       if (mat->boundtocpu && mat->bindingpropagates) {
9656         PetscCall(VecSetBindingPropagates(*left, PETSC_TRUE));
9657         PetscCall(VecBindToCPU(*left, PETSC_TRUE));
9658       }
9659 #endif
9660     }
9661   }
9662   PetscFunctionReturn(PETSC_SUCCESS);
9663 }
9664 
9665 /*@
9666   MatFactorInfoInitialize - Initializes a `MatFactorInfo` data structure
9667   with default values.
9668 
9669   Not Collective
9670 
9671   Input Parameter:
9672 . info - the `MatFactorInfo` data structure
9673 
9674   Level: developer
9675 
9676   Notes:
9677   The solvers are generally used through the `KSP` and `PC` objects, for example
9678   `PCLU`, `PCILU`, `PCCHOLESKY`, `PCICC`
9679 
9680   Once the data structure is initialized one may change certain entries as desired for the particular factorization to be performed
9681 
9682 .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatFactorInfo`
9683 @*/
9684 PetscErrorCode MatFactorInfoInitialize(MatFactorInfo *info)
9685 {
9686   PetscFunctionBegin;
9687   PetscCall(PetscMemzero(info, sizeof(MatFactorInfo)));
9688   PetscFunctionReturn(PETSC_SUCCESS);
9689 }
9690 
9691 /*@
9692   MatFactorSetSchurIS - Set indices corresponding to the Schur complement you wish to have computed
9693 
9694   Collective
9695 
9696   Input Parameters:
9697 + mat - the factored matrix
9698 - is  - the index set defining the Schur indices (0-based)
9699 
9700   Level: advanced
9701 
9702   Notes:
9703   Call `MatFactorSolveSchurComplement()` or `MatFactorSolveSchurComplementTranspose()` after this call to solve a Schur complement system.
9704 
9705   You can call `MatFactorGetSchurComplement()` or `MatFactorCreateSchurComplement()` after this call.
9706 
9707   This functionality is only supported for `MATSOLVERMUMPS` and `MATSOLVERMKL_PARDISO`
9708 
9709 .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatFactorGetSchurComplement()`, `MatFactorRestoreSchurComplement()`, `MatFactorCreateSchurComplement()`, `MatFactorSolveSchurComplement()`,
9710           `MatFactorSolveSchurComplementTranspose()`, `MATSOLVERMUMPS`, `MATSOLVERMKL_PARDISO`
9711 @*/
9712 PetscErrorCode MatFactorSetSchurIS(Mat mat, IS is)
9713 {
9714   PetscErrorCode (*f)(Mat, IS);
9715 
9716   PetscFunctionBegin;
9717   PetscValidType(mat, 1);
9718   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
9719   PetscValidType(is, 2);
9720   PetscValidHeaderSpecific(is, IS_CLASSID, 2);
9721   PetscCheckSameComm(mat, 1, is, 2);
9722   PetscCheck(mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Only for factored matrix");
9723   PetscCall(PetscObjectQueryFunction((PetscObject)mat, "MatFactorSetSchurIS_C", &f));
9724   PetscCheck(f, PetscObjectComm((PetscObject)mat), PETSC_ERR_SUP, "The selected MatSolverType does not support Schur complement computation. You should use MATSOLVERMUMPS or MATSOLVERMKL_PARDISO");
9725   PetscCall(MatDestroy(&mat->schur));
9726   PetscCall((*f)(mat, is));
9727   PetscCheck(mat->schur, PetscObjectComm((PetscObject)mat), PETSC_ERR_PLIB, "Schur complement has not been created");
9728   PetscFunctionReturn(PETSC_SUCCESS);
9729 }
9730 
9731 /*@
9732   MatFactorCreateSchurComplement - Create a Schur complement matrix object using Schur data computed during the factorization step
9733 
9734   Logically Collective
9735 
9736   Input Parameters:
9737 + F      - the factored matrix obtained by calling `MatGetFactor()`
9738 . S      - location where to return the Schur complement, can be `NULL`
9739 - status - the status of the Schur complement matrix, can be `NULL`
9740 
9741   Level: advanced
9742 
9743   Notes:
9744   You must call `MatFactorSetSchurIS()` before calling this routine.
9745 
9746   This functionality is only supported for `MATSOLVERMUMPS` and `MATSOLVERMKL_PARDISO`
9747 
9748   The routine provides a copy of the Schur matrix stored within the solver data structures.
9749   The caller must destroy the object when it is no longer needed.
9750   If `MatFactorInvertSchurComplement()` has been called, the routine gets back the inverse.
9751 
9752   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)
9753 
9754   See `MatCreateSchurComplement()` or `MatGetSchurComplement()` for ways to create virtual or approximate Schur complements.
9755 
9756   Developer Note:
9757   The reason this routine exists is because the representation of the Schur complement within the factor matrix may be different than a standard PETSc
9758   matrix representation and we normally do not want to use the time or memory to make a copy as a regular PETSc matrix.
9759 
9760 .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatFactorSetSchurIS()`, `MatFactorGetSchurComplement()`, `MatFactorSchurStatus`, `MATSOLVERMUMPS`, `MATSOLVERMKL_PARDISO`
9761 @*/
9762 PetscErrorCode MatFactorCreateSchurComplement(Mat F, Mat *S, MatFactorSchurStatus *status)
9763 {
9764   PetscFunctionBegin;
9765   PetscValidHeaderSpecific(F, MAT_CLASSID, 1);
9766   if (S) PetscAssertPointer(S, 2);
9767   if (status) PetscAssertPointer(status, 3);
9768   if (S) {
9769     PetscErrorCode (*f)(Mat, Mat *);
9770 
9771     PetscCall(PetscObjectQueryFunction((PetscObject)F, "MatFactorCreateSchurComplement_C", &f));
9772     if (f) {
9773       PetscCall((*f)(F, S));
9774     } else {
9775       PetscCall(MatDuplicate(F->schur, MAT_COPY_VALUES, S));
9776     }
9777   }
9778   if (status) *status = F->schur_status;
9779   PetscFunctionReturn(PETSC_SUCCESS);
9780 }
9781 
9782 /*@
9783   MatFactorGetSchurComplement - Gets access to a Schur complement matrix using the current Schur data within a factored matrix
9784 
9785   Logically Collective
9786 
9787   Input Parameters:
9788 + F      - the factored matrix obtained by calling `MatGetFactor()`
9789 . S      - location where to return the Schur complement, can be `NULL`
9790 - status - the status of the Schur complement matrix, can be `NULL`
9791 
9792   Level: advanced
9793 
9794   Notes:
9795   You must call `MatFactorSetSchurIS()` before calling this routine.
9796 
9797   Schur complement mode is currently implemented for sequential matrices with factor type of `MATSOLVERMUMPS`
9798 
9799   The routine returns a the Schur Complement stored within the data structures of the solver.
9800 
9801   If `MatFactorInvertSchurComplement()` has previously been called, the returned matrix is actually the inverse of the Schur complement.
9802 
9803   The returned matrix should not be destroyed; the caller should call `MatFactorRestoreSchurComplement()` when the object is no longer needed.
9804 
9805   Use `MatFactorCreateSchurComplement()` to create a copy of the Schur complement matrix that is within a factored matrix
9806 
9807   See `MatCreateSchurComplement()` or `MatGetSchurComplement()` for ways to create virtual or approximate Schur complements.
9808 
9809 .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatFactorSetSchurIS()`, `MatFactorRestoreSchurComplement()`, `MatFactorCreateSchurComplement()`, `MatFactorSchurStatus`
9810 @*/
9811 PetscErrorCode MatFactorGetSchurComplement(Mat F, Mat *S, MatFactorSchurStatus *status)
9812 {
9813   PetscFunctionBegin;
9814   PetscValidHeaderSpecific(F, MAT_CLASSID, 1);
9815   if (S) {
9816     PetscAssertPointer(S, 2);
9817     *S = F->schur;
9818   }
9819   if (status) {
9820     PetscAssertPointer(status, 3);
9821     *status = F->schur_status;
9822   }
9823   PetscFunctionReturn(PETSC_SUCCESS);
9824 }
9825 
9826 static PetscErrorCode MatFactorUpdateSchurStatus_Private(Mat F)
9827 {
9828   Mat S = F->schur;
9829 
9830   PetscFunctionBegin;
9831   switch (F->schur_status) {
9832   case MAT_FACTOR_SCHUR_UNFACTORED: // fall-through
9833   case MAT_FACTOR_SCHUR_INVERTED:
9834     if (S) {
9835       S->ops->solve             = NULL;
9836       S->ops->matsolve          = NULL;
9837       S->ops->solvetranspose    = NULL;
9838       S->ops->matsolvetranspose = NULL;
9839       S->ops->solveadd          = NULL;
9840       S->ops->solvetransposeadd = NULL;
9841       S->factortype             = MAT_FACTOR_NONE;
9842       PetscCall(PetscFree(S->solvertype));
9843     }
9844   case MAT_FACTOR_SCHUR_FACTORED: // fall-through
9845     break;
9846   default:
9847     SETERRQ(PetscObjectComm((PetscObject)F), PETSC_ERR_SUP, "Unhandled MatFactorSchurStatus %d", F->schur_status);
9848   }
9849   PetscFunctionReturn(PETSC_SUCCESS);
9850 }
9851 
9852 /*@
9853   MatFactorRestoreSchurComplement - Restore the Schur complement matrix object obtained from a call to `MatFactorGetSchurComplement()`
9854 
9855   Logically Collective
9856 
9857   Input Parameters:
9858 + F      - the factored matrix obtained by calling `MatGetFactor()`
9859 . S      - location where the Schur complement is stored
9860 - status - the status of the Schur complement matrix (see `MatFactorSchurStatus`)
9861 
9862   Level: advanced
9863 
9864 .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatFactorSetSchurIS()`, `MatFactorCreateSchurComplement()`, `MatFactorSchurStatus`
9865 @*/
9866 PetscErrorCode MatFactorRestoreSchurComplement(Mat F, Mat *S, MatFactorSchurStatus status)
9867 {
9868   PetscFunctionBegin;
9869   PetscValidHeaderSpecific(F, MAT_CLASSID, 1);
9870   if (S) {
9871     PetscValidHeaderSpecific(*S, MAT_CLASSID, 2);
9872     *S = NULL;
9873   }
9874   F->schur_status = status;
9875   PetscCall(MatFactorUpdateSchurStatus_Private(F));
9876   PetscFunctionReturn(PETSC_SUCCESS);
9877 }
9878 
9879 /*@
9880   MatFactorSolveSchurComplementTranspose - Solve the transpose of the Schur complement system computed during the factorization step
9881 
9882   Logically Collective
9883 
9884   Input Parameters:
9885 + F   - the factored matrix obtained by calling `MatGetFactor()`
9886 . rhs - location where the right-hand side of the Schur complement system is stored
9887 - sol - location where the solution of the Schur complement system has to be returned
9888 
9889   Level: advanced
9890 
9891   Notes:
9892   The sizes of the vectors should match the size of the Schur complement
9893 
9894   Must be called after `MatFactorSetSchurIS()`
9895 
9896 .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatFactorSetSchurIS()`, `MatFactorSolveSchurComplement()`
9897 @*/
9898 PetscErrorCode MatFactorSolveSchurComplementTranspose(Mat F, Vec rhs, Vec sol)
9899 {
9900   PetscFunctionBegin;
9901   PetscValidType(F, 1);
9902   PetscValidType(rhs, 2);
9903   PetscValidType(sol, 3);
9904   PetscValidHeaderSpecific(F, MAT_CLASSID, 1);
9905   PetscValidHeaderSpecific(rhs, VEC_CLASSID, 2);
9906   PetscValidHeaderSpecific(sol, VEC_CLASSID, 3);
9907   PetscCheckSameComm(F, 1, rhs, 2);
9908   PetscCheckSameComm(F, 1, sol, 3);
9909   PetscCall(MatFactorFactorizeSchurComplement(F));
9910   switch (F->schur_status) {
9911   case MAT_FACTOR_SCHUR_FACTORED:
9912     PetscCall(MatSolveTranspose(F->schur, rhs, sol));
9913     break;
9914   case MAT_FACTOR_SCHUR_INVERTED:
9915     PetscCall(MatMultTranspose(F->schur, rhs, sol));
9916     break;
9917   default:
9918     SETERRQ(PetscObjectComm((PetscObject)F), PETSC_ERR_SUP, "Unhandled MatFactorSchurStatus %d", F->schur_status);
9919   }
9920   PetscFunctionReturn(PETSC_SUCCESS);
9921 }
9922 
9923 /*@
9924   MatFactorSolveSchurComplement - Solve the Schur complement system computed during the factorization step
9925 
9926   Logically Collective
9927 
9928   Input Parameters:
9929 + F   - the factored matrix obtained by calling `MatGetFactor()`
9930 . rhs - location where the right-hand side of the Schur complement system is stored
9931 - sol - location where the solution of the Schur complement system has to be returned
9932 
9933   Level: advanced
9934 
9935   Notes:
9936   The sizes of the vectors should match the size of the Schur complement
9937 
9938   Must be called after `MatFactorSetSchurIS()`
9939 
9940 .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatFactorSetSchurIS()`, `MatFactorSolveSchurComplementTranspose()`
9941 @*/
9942 PetscErrorCode MatFactorSolveSchurComplement(Mat F, Vec rhs, Vec sol)
9943 {
9944   PetscFunctionBegin;
9945   PetscValidType(F, 1);
9946   PetscValidType(rhs, 2);
9947   PetscValidType(sol, 3);
9948   PetscValidHeaderSpecific(F, MAT_CLASSID, 1);
9949   PetscValidHeaderSpecific(rhs, VEC_CLASSID, 2);
9950   PetscValidHeaderSpecific(sol, VEC_CLASSID, 3);
9951   PetscCheckSameComm(F, 1, rhs, 2);
9952   PetscCheckSameComm(F, 1, sol, 3);
9953   PetscCall(MatFactorFactorizeSchurComplement(F));
9954   switch (F->schur_status) {
9955   case MAT_FACTOR_SCHUR_FACTORED:
9956     PetscCall(MatSolve(F->schur, rhs, sol));
9957     break;
9958   case MAT_FACTOR_SCHUR_INVERTED:
9959     PetscCall(MatMult(F->schur, rhs, sol));
9960     break;
9961   default:
9962     SETERRQ(PetscObjectComm((PetscObject)F), PETSC_ERR_SUP, "Unhandled MatFactorSchurStatus %d", F->schur_status);
9963   }
9964   PetscFunctionReturn(PETSC_SUCCESS);
9965 }
9966 
9967 PETSC_SINGLE_LIBRARY_INTERN PetscErrorCode MatSeqDenseInvertFactors_Private(Mat);
9968 #if PetscDefined(HAVE_CUDA)
9969 PETSC_SINGLE_LIBRARY_INTERN PetscErrorCode MatSeqDenseCUDAInvertFactors_Internal(Mat);
9970 #endif
9971 
9972 /* Schur status updated in the interface */
9973 static PetscErrorCode MatFactorInvertSchurComplement_Private(Mat F)
9974 {
9975   Mat S = F->schur;
9976 
9977   PetscFunctionBegin;
9978   if (S) {
9979     PetscMPIInt size;
9980     PetscBool   isdense, isdensecuda;
9981 
9982     PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)S), &size));
9983     PetscCheck(size <= 1, PetscObjectComm((PetscObject)S), PETSC_ERR_SUP, "Not yet implemented");
9984     PetscCall(PetscObjectTypeCompare((PetscObject)S, MATSEQDENSE, &isdense));
9985     PetscCall(PetscObjectTypeCompare((PetscObject)S, MATSEQDENSECUDA, &isdensecuda));
9986     PetscCheck(isdense || isdensecuda, PetscObjectComm((PetscObject)S), PETSC_ERR_SUP, "Not implemented for type %s", ((PetscObject)S)->type_name);
9987     PetscCall(PetscLogEventBegin(MAT_FactorInvS, F, 0, 0, 0));
9988     if (isdense) {
9989       PetscCall(MatSeqDenseInvertFactors_Private(S));
9990     } else if (isdensecuda) {
9991 #if defined(PETSC_HAVE_CUDA)
9992       PetscCall(MatSeqDenseCUDAInvertFactors_Internal(S));
9993 #endif
9994     }
9995     // HIP??????????????
9996     PetscCall(PetscLogEventEnd(MAT_FactorInvS, F, 0, 0, 0));
9997   }
9998   PetscFunctionReturn(PETSC_SUCCESS);
9999 }
10000 
10001 /*@
10002   MatFactorInvertSchurComplement - Invert the Schur complement matrix computed during the factorization step
10003 
10004   Logically Collective
10005 
10006   Input Parameter:
10007 . F - the factored matrix obtained by calling `MatGetFactor()`
10008 
10009   Level: advanced
10010 
10011   Notes:
10012   Must be called after `MatFactorSetSchurIS()`.
10013 
10014   Call `MatFactorGetSchurComplement()` or  `MatFactorCreateSchurComplement()` AFTER this call to actually compute the inverse and get access to it.
10015 
10016 .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatFactorSetSchurIS()`, `MatFactorGetSchurComplement()`, `MatFactorCreateSchurComplement()`
10017 @*/
10018 PetscErrorCode MatFactorInvertSchurComplement(Mat F)
10019 {
10020   PetscFunctionBegin;
10021   PetscValidType(F, 1);
10022   PetscValidHeaderSpecific(F, MAT_CLASSID, 1);
10023   if (F->schur_status == MAT_FACTOR_SCHUR_INVERTED) PetscFunctionReturn(PETSC_SUCCESS);
10024   PetscCall(MatFactorFactorizeSchurComplement(F));
10025   PetscCall(MatFactorInvertSchurComplement_Private(F));
10026   F->schur_status = MAT_FACTOR_SCHUR_INVERTED;
10027   PetscFunctionReturn(PETSC_SUCCESS);
10028 }
10029 
10030 /*@
10031   MatFactorFactorizeSchurComplement - Factorize the Schur complement matrix computed during the factorization step
10032 
10033   Logically Collective
10034 
10035   Input Parameter:
10036 . F - the factored matrix obtained by calling `MatGetFactor()`
10037 
10038   Level: advanced
10039 
10040   Note:
10041   Must be called after `MatFactorSetSchurIS()`
10042 
10043 .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatFactorSetSchurIS()`, `MatFactorInvertSchurComplement()`
10044 @*/
10045 PetscErrorCode MatFactorFactorizeSchurComplement(Mat F)
10046 {
10047   MatFactorInfo info;
10048 
10049   PetscFunctionBegin;
10050   PetscValidType(F, 1);
10051   PetscValidHeaderSpecific(F, MAT_CLASSID, 1);
10052   if (F->schur_status == MAT_FACTOR_SCHUR_INVERTED || F->schur_status == MAT_FACTOR_SCHUR_FACTORED) PetscFunctionReturn(PETSC_SUCCESS);
10053   PetscCall(PetscLogEventBegin(MAT_FactorFactS, F, 0, 0, 0));
10054   PetscCall(PetscMemzero(&info, sizeof(MatFactorInfo)));
10055   if (F->factortype == MAT_FACTOR_CHOLESKY) { /* LDL^t regarded as Cholesky */
10056     PetscCall(MatCholeskyFactor(F->schur, NULL, &info));
10057   } else {
10058     PetscCall(MatLUFactor(F->schur, NULL, NULL, &info));
10059   }
10060   PetscCall(PetscLogEventEnd(MAT_FactorFactS, F, 0, 0, 0));
10061   F->schur_status = MAT_FACTOR_SCHUR_FACTORED;
10062   PetscFunctionReturn(PETSC_SUCCESS);
10063 }
10064 
10065 /*@
10066   MatPtAP - Creates the matrix product $C = P^T * A * P$
10067 
10068   Neighbor-wise Collective
10069 
10070   Input Parameters:
10071 + A     - the matrix
10072 . P     - the projection matrix
10073 . scall - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`
10074 - fill  - expected fill as ratio of nnz(C)/(nnz(A) + nnz(P)), use `PETSC_DETERMINE` or `PETSC_CURRENT` if you do not have a good estimate
10075           if the result is a dense matrix this is irrelevant
10076 
10077   Output Parameter:
10078 . C - the product matrix
10079 
10080   Level: intermediate
10081 
10082   Notes:
10083   C will be created and must be destroyed by the user with `MatDestroy()`.
10084 
10085   An alternative approach to this function is to use `MatProductCreate()` and set the desired options before the computation is done
10086 
10087   The deprecated `PETSC_DEFAULT` in `fill` also means use the current value
10088 
10089   Developer Note:
10090   For matrix types without special implementation the function fallbacks to `MatMatMult()` followed by `MatTransposeMatMult()`.
10091 
10092 .seealso: [](ch_matrices), `Mat`, `MatProductCreate()`, `MatMatMult()`, `MatRARt()`
10093 @*/
10094 PetscErrorCode MatPtAP(Mat A, Mat P, MatReuse scall, PetscReal fill, Mat *C)
10095 {
10096   PetscFunctionBegin;
10097   if (scall == MAT_REUSE_MATRIX) MatCheckProduct(*C, 5);
10098   PetscCheck(scall != MAT_INPLACE_MATRIX, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "Inplace product not supported");
10099 
10100   if (scall == MAT_INITIAL_MATRIX) {
10101     PetscCall(MatProductCreate(A, P, NULL, C));
10102     PetscCall(MatProductSetType(*C, MATPRODUCT_PtAP));
10103     PetscCall(MatProductSetAlgorithm(*C, "default"));
10104     PetscCall(MatProductSetFill(*C, fill));
10105 
10106     (*C)->product->api_user = PETSC_TRUE;
10107     PetscCall(MatProductSetFromOptions(*C));
10108     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);
10109     PetscCall(MatProductSymbolic(*C));
10110   } else { /* scall == MAT_REUSE_MATRIX */
10111     PetscCall(MatProductReplaceMats(A, P, NULL, *C));
10112   }
10113 
10114   PetscCall(MatProductNumeric(*C));
10115   (*C)->symmetric = A->symmetric;
10116   (*C)->spd       = A->spd;
10117   PetscFunctionReturn(PETSC_SUCCESS);
10118 }
10119 
10120 /*@
10121   MatRARt - Creates the matrix product $C = R * A * R^T$
10122 
10123   Neighbor-wise Collective
10124 
10125   Input Parameters:
10126 + A     - the matrix
10127 . R     - the projection matrix
10128 . scall - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`
10129 - fill  - expected fill as ratio of nnz(C)/nnz(A), use `PETSC_DETERMINE` or `PETSC_CURRENT` if you do not have a good estimate
10130           if the result is a dense matrix this is irrelevant
10131 
10132   Output Parameter:
10133 . C - the product matrix
10134 
10135   Level: intermediate
10136 
10137   Notes:
10138   `C` will be created and must be destroyed by the user with `MatDestroy()`.
10139 
10140   An alternative approach to this function is to use `MatProductCreate()` and set the desired options before the computation is done
10141 
10142   This routine is currently only implemented for pairs of `MATAIJ` matrices and classes
10143   which inherit from `MATAIJ`. Due to PETSc sparse matrix block row distribution among processes,
10144   the parallel `MatRARt()` is implemented computing the explicit transpose of `R`, which can be very expensive.
10145   We recommend using `MatPtAP()` when possible.
10146 
10147   The deprecated `PETSC_DEFAULT` in `fill` also means use the current value
10148 
10149 .seealso: [](ch_matrices), `Mat`, `MatProductCreate()`, `MatMatMult()`, `MatPtAP()`
10150 @*/
10151 PetscErrorCode MatRARt(Mat A, Mat R, MatReuse scall, PetscReal fill, Mat *C)
10152 {
10153   PetscFunctionBegin;
10154   if (scall == MAT_REUSE_MATRIX) MatCheckProduct(*C, 5);
10155   PetscCheck(scall != MAT_INPLACE_MATRIX, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "Inplace product not supported");
10156 
10157   if (scall == MAT_INITIAL_MATRIX) {
10158     PetscCall(MatProductCreate(A, R, NULL, C));
10159     PetscCall(MatProductSetType(*C, MATPRODUCT_RARt));
10160     PetscCall(MatProductSetAlgorithm(*C, "default"));
10161     PetscCall(MatProductSetFill(*C, fill));
10162 
10163     (*C)->product->api_user = PETSC_TRUE;
10164     PetscCall(MatProductSetFromOptions(*C));
10165     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);
10166     PetscCall(MatProductSymbolic(*C));
10167   } else { /* scall == MAT_REUSE_MATRIX */
10168     PetscCall(MatProductReplaceMats(A, R, NULL, *C));
10169   }
10170 
10171   PetscCall(MatProductNumeric(*C));
10172   if (A->symmetric == PETSC_BOOL3_TRUE) PetscCall(MatSetOption(*C, MAT_SYMMETRIC, PETSC_TRUE));
10173   PetscFunctionReturn(PETSC_SUCCESS);
10174 }
10175 
10176 static PetscErrorCode MatProduct_Private(Mat A, Mat B, MatReuse scall, PetscReal fill, MatProductType ptype, Mat *C)
10177 {
10178   PetscBool flg = PETSC_TRUE;
10179 
10180   PetscFunctionBegin;
10181   PetscCheck(scall != MAT_INPLACE_MATRIX, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "MAT_INPLACE_MATRIX product not supported");
10182   if (scall == MAT_INITIAL_MATRIX) {
10183     PetscCall(PetscInfo(A, "Calling MatProduct API with MAT_INITIAL_MATRIX and product type %s\n", MatProductTypes[ptype]));
10184     PetscCall(MatProductCreate(A, B, NULL, C));
10185     PetscCall(MatProductSetAlgorithm(*C, MATPRODUCTALGORITHMDEFAULT));
10186     PetscCall(MatProductSetFill(*C, fill));
10187   } else { /* scall == MAT_REUSE_MATRIX */
10188     Mat_Product *product = (*C)->product;
10189 
10190     PetscCall(PetscObjectBaseTypeCompareAny((PetscObject)*C, &flg, MATSEQDENSE, MATMPIDENSE, ""));
10191     if (flg && product && product->type != ptype) {
10192       PetscCall(MatProductClear(*C));
10193       product = NULL;
10194     }
10195     PetscCall(PetscInfo(A, "Calling MatProduct API with MAT_REUSE_MATRIX %s product present and product type %s\n", product ? "with" : "without", MatProductTypes[ptype]));
10196     if (!product) { /* user provide the dense matrix *C without calling MatProductCreate() or reusing it from previous calls */
10197       PetscCheck(flg, PetscObjectComm((PetscObject)*C), PETSC_ERR_SUP, "Call MatProductCreate() first");
10198       PetscCall(MatProductCreate_Private(A, B, NULL, *C));
10199       product        = (*C)->product;
10200       product->fill  = fill;
10201       product->clear = PETSC_TRUE;
10202     } else { /* user may change input matrices A or B when MAT_REUSE_MATRIX */
10203       flg = PETSC_FALSE;
10204       PetscCall(MatProductReplaceMats(A, B, NULL, *C));
10205     }
10206   }
10207   if (flg) {
10208     (*C)->product->api_user = PETSC_TRUE;
10209     PetscCall(MatProductSetType(*C, ptype));
10210     PetscCall(MatProductSetFromOptions(*C));
10211     PetscCall(MatProductSymbolic(*C));
10212   }
10213   PetscCall(MatProductNumeric(*C));
10214   PetscFunctionReturn(PETSC_SUCCESS);
10215 }
10216 
10217 /*@
10218   MatMatMult - Performs matrix-matrix multiplication C=A*B.
10219 
10220   Neighbor-wise Collective
10221 
10222   Input Parameters:
10223 + A     - the left matrix
10224 . B     - the right matrix
10225 . scall - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`
10226 - fill  - expected fill as ratio of nnz(C)/(nnz(A) + nnz(B)), use `PETSC_DETERMINE` or `PETSC_CURRENT` if you do not have a good estimate
10227           if the result is a dense matrix this is irrelevant
10228 
10229   Output Parameter:
10230 . C - the product matrix
10231 
10232   Notes:
10233   Unless scall is `MAT_REUSE_MATRIX` C will be created.
10234 
10235   `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
10236   call to this function with `MAT_INITIAL_MATRIX`.
10237 
10238   To determine the correct fill value, run with `-info` and search for the string "Fill ratio" to see the value actually needed.
10239 
10240   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`,
10241   rather than first having `MatMatMult()` create it for you. You can NEVER do this if the matrix `C` is sparse.
10242 
10243   The deprecated `PETSC_DEFAULT` in `fill` also means use the current value
10244 
10245   Example of Usage:
10246 .vb
10247      MatProductCreate(A,B,NULL,&C);
10248      MatProductSetType(C,MATPRODUCT_AB);
10249      MatProductSymbolic(C);
10250      MatProductNumeric(C); // compute C=A * B
10251      MatProductReplaceMats(A1,B1,NULL,C); // compute C=A1 * B1
10252      MatProductNumeric(C);
10253      MatProductReplaceMats(A2,NULL,NULL,C); // compute C=A2 * B1
10254      MatProductNumeric(C);
10255 .ve
10256 
10257   Level: intermediate
10258 
10259 .seealso: [](ch_matrices), `Mat`, `MatProductType`, `MATPRODUCT_AB`, `MatTransposeMatMult()`, `MatMatTransposeMult()`, `MatPtAP()`, `MatProductCreate()`, `MatProductSymbolic()`, `MatProductReplaceMats()`, `MatProductNumeric()`
10260 @*/
10261 PetscErrorCode MatMatMult(Mat A, Mat B, MatReuse scall, PetscReal fill, Mat *C)
10262 {
10263   PetscFunctionBegin;
10264   PetscCall(MatProduct_Private(A, B, scall, fill, MATPRODUCT_AB, C));
10265   PetscFunctionReturn(PETSC_SUCCESS);
10266 }
10267 
10268 /*@
10269   MatMatTransposeMult - Performs matrix-matrix multiplication $C = A*B^T$.
10270 
10271   Neighbor-wise Collective
10272 
10273   Input Parameters:
10274 + A     - the left matrix
10275 . B     - the right matrix
10276 . scall - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`
10277 - fill  - expected fill as ratio of nnz(C)/(nnz(A) + nnz(B)), use `PETSC_DETERMINE` or `PETSC_CURRENT` if not known
10278 
10279   Output Parameter:
10280 . C - the product matrix
10281 
10282   Options Database Key:
10283 . -matmattransmult_mpidense_mpidense_via {allgatherv,cyclic} - Choose between algorithms for `MATMPIDENSE` matrices: the
10284               first redundantly copies the transposed `B` matrix on each process and requires O(log P) communication complexity;
10285               the second never stores more than one portion of the `B` matrix at a time but requires O(P) communication complexity.
10286 
10287   Level: intermediate
10288 
10289   Notes:
10290   C will be created if `MAT_INITIAL_MATRIX` and must be destroyed by the user with `MatDestroy()`.
10291 
10292   `MAT_REUSE_MATRIX` can only be used if the matrices A and B have the same nonzero pattern as in the previous call
10293 
10294   To determine the correct fill value, run with -info and search for the string "Fill ratio" to see the value
10295   actually needed.
10296 
10297   This routine is currently only implemented for pairs of `MATSEQAIJ` matrices, for the `MATSEQDENSE` class,
10298   and for pairs of `MATMPIDENSE` matrices.
10299 
10300   This routine is shorthand for using `MatProductCreate()` with the `MatProductType` of `MATPRODUCT_ABt`
10301 
10302   The deprecated `PETSC_DEFAULT` in `fill` also means use the current value
10303 
10304 .seealso: [](ch_matrices), `Mat`, `MatProductCreate()`, `MATPRODUCT_ABt`, `MatMatMult()`, `MatTransposeMatMult()` `MatPtAP()`, `MatProductAlgorithm`, `MatProductType`
10305 @*/
10306 PetscErrorCode MatMatTransposeMult(Mat A, Mat B, MatReuse scall, PetscReal fill, Mat *C)
10307 {
10308   PetscFunctionBegin;
10309   PetscCall(MatProduct_Private(A, B, scall, fill, MATPRODUCT_ABt, C));
10310   if (A == B) PetscCall(MatSetOption(*C, MAT_SYMMETRIC, PETSC_TRUE));
10311   PetscFunctionReturn(PETSC_SUCCESS);
10312 }
10313 
10314 /*@
10315   MatTransposeMatMult - Performs matrix-matrix multiplication $C = A^T*B$.
10316 
10317   Neighbor-wise Collective
10318 
10319   Input Parameters:
10320 + A     - the left matrix
10321 . B     - the right matrix
10322 . scall - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`
10323 - fill  - expected fill as ratio of nnz(C)/(nnz(A) + nnz(B)), use `PETSC_DETERMINE` or `PETSC_CURRENT` if not known
10324 
10325   Output Parameter:
10326 . C - the product matrix
10327 
10328   Level: intermediate
10329 
10330   Notes:
10331   `C` will be created if `MAT_INITIAL_MATRIX` and must be destroyed by the user with `MatDestroy()`.
10332 
10333   `MAT_REUSE_MATRIX` can only be used if the matrices A and B have the same nonzero pattern as in the previous call.
10334 
10335   This routine is shorthand for using `MatProductCreate()` with the `MatProductType` of `MATPRODUCT_AtB`
10336 
10337   To determine the correct fill value, run with -info and search for the string "Fill ratio" to see the value
10338   actually needed.
10339 
10340   This routine is currently implemented for pairs of `MATAIJ` matrices and pairs of `MATSEQDENSE` matrices and classes
10341   which inherit from `MATSEQAIJ`.  `C` will be of the same type as the input matrices.
10342 
10343   The deprecated `PETSC_DEFAULT` in `fill` also means use the current value
10344 
10345 .seealso: [](ch_matrices), `Mat`, `MatProductCreate()`, `MATPRODUCT_AtB`, `MatMatMult()`, `MatMatTransposeMult()`, `MatPtAP()`
10346 @*/
10347 PetscErrorCode MatTransposeMatMult(Mat A, Mat B, MatReuse scall, PetscReal fill, Mat *C)
10348 {
10349   PetscFunctionBegin;
10350   PetscCall(MatProduct_Private(A, B, scall, fill, MATPRODUCT_AtB, C));
10351   PetscFunctionReturn(PETSC_SUCCESS);
10352 }
10353 
10354 /*@
10355   MatMatMatMult - Performs matrix-matrix-matrix multiplication D=A*B*C.
10356 
10357   Neighbor-wise Collective
10358 
10359   Input Parameters:
10360 + A     - the left matrix
10361 . B     - the middle matrix
10362 . C     - the right matrix
10363 . scall - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`
10364 - fill  - expected fill as ratio of nnz(D)/(nnz(A) + nnz(B)+nnz(C)), use `PETSC_DETERMINE` or `PETSC_CURRENT` if you do not have a good estimate
10365           if the result is a dense matrix this is irrelevant
10366 
10367   Output Parameter:
10368 . D - the product matrix
10369 
10370   Level: intermediate
10371 
10372   Notes:
10373   Unless `scall` is `MAT_REUSE_MATRIX` `D` will be created.
10374 
10375   `MAT_REUSE_MATRIX` can only be used if the matrices `A`, `B`, and `C` have the same nonzero pattern as in the previous call
10376 
10377   This routine is shorthand for using `MatProductCreate()` with the `MatProductType` of `MATPRODUCT_ABC`
10378 
10379   To determine the correct fill value, run with `-info` and search for the string "Fill ratio" to see the value
10380   actually needed.
10381 
10382   If you have many matrices with the same non-zero structure to multiply, you
10383   should use `MAT_REUSE_MATRIX` in all calls but the first
10384 
10385   The deprecated `PETSC_DEFAULT` in `fill` also means use the current value
10386 
10387 .seealso: [](ch_matrices), `Mat`, `MatProductCreate()`, `MATPRODUCT_ABC`, `MatMatMult`, `MatPtAP()`, `MatMatTransposeMult()`, `MatTransposeMatMult()`
10388 @*/
10389 PetscErrorCode MatMatMatMult(Mat A, Mat B, Mat C, MatReuse scall, PetscReal fill, Mat *D)
10390 {
10391   PetscFunctionBegin;
10392   if (scall == MAT_REUSE_MATRIX) MatCheckProduct(*D, 6);
10393   PetscCheck(scall != MAT_INPLACE_MATRIX, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "Inplace product not supported");
10394 
10395   if (scall == MAT_INITIAL_MATRIX) {
10396     PetscCall(MatProductCreate(A, B, C, D));
10397     PetscCall(MatProductSetType(*D, MATPRODUCT_ABC));
10398     PetscCall(MatProductSetAlgorithm(*D, "default"));
10399     PetscCall(MatProductSetFill(*D, fill));
10400 
10401     (*D)->product->api_user = PETSC_TRUE;
10402     PetscCall(MatProductSetFromOptions(*D));
10403     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,
10404                ((PetscObject)C)->type_name);
10405     PetscCall(MatProductSymbolic(*D));
10406   } else { /* user may change input matrices when REUSE */
10407     PetscCall(MatProductReplaceMats(A, B, C, *D));
10408   }
10409   PetscCall(MatProductNumeric(*D));
10410   PetscFunctionReturn(PETSC_SUCCESS);
10411 }
10412 
10413 /*@
10414   MatCreateRedundantMatrix - Create redundant matrices and put them into processors of subcommunicators.
10415 
10416   Collective
10417 
10418   Input Parameters:
10419 + mat      - the matrix
10420 . nsubcomm - the number of subcommunicators (= number of redundant parallel or sequential matrices)
10421 . subcomm  - MPI communicator split from the communicator where mat resides in (or `MPI_COMM_NULL` if nsubcomm is used)
10422 - reuse    - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`
10423 
10424   Output Parameter:
10425 . matredundant - redundant matrix
10426 
10427   Level: advanced
10428 
10429   Notes:
10430   `MAT_REUSE_MATRIX` can only be used when the nonzero structure of the
10431   original matrix has not changed from that last call to `MatCreateRedundantMatrix()`.
10432 
10433   This routine creates the duplicated matrices in the subcommunicators; you should NOT create them before
10434   calling it.
10435 
10436   `PetscSubcommCreate()` can be used to manage the creation of the subcomm but need not be.
10437 
10438 .seealso: [](ch_matrices), `Mat`, `MatDestroy()`, `PetscSubcommCreate()`, `PetscSubcomm`
10439 @*/
10440 PetscErrorCode MatCreateRedundantMatrix(Mat mat, PetscInt nsubcomm, MPI_Comm subcomm, MatReuse reuse, Mat *matredundant)
10441 {
10442   MPI_Comm       comm;
10443   PetscMPIInt    size;
10444   PetscInt       mloc_sub, nloc_sub, rstart, rend, M = mat->rmap->N, N = mat->cmap->N, bs = mat->rmap->bs;
10445   Mat_Redundant *redund     = NULL;
10446   PetscSubcomm   psubcomm   = NULL;
10447   MPI_Comm       subcomm_in = subcomm;
10448   Mat           *matseq;
10449   IS             isrow, iscol;
10450   PetscBool      newsubcomm = PETSC_FALSE;
10451 
10452   PetscFunctionBegin;
10453   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
10454   if (nsubcomm && reuse == MAT_REUSE_MATRIX) {
10455     PetscAssertPointer(*matredundant, 5);
10456     PetscValidHeaderSpecific(*matredundant, MAT_CLASSID, 5);
10457   }
10458 
10459   PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)mat), &size));
10460   if (size == 1 || nsubcomm == 1) {
10461     if (reuse == MAT_INITIAL_MATRIX) {
10462       PetscCall(MatDuplicate(mat, MAT_COPY_VALUES, matredundant));
10463     } else {
10464       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");
10465       PetscCall(MatCopy(mat, *matredundant, SAME_NONZERO_PATTERN));
10466     }
10467     PetscFunctionReturn(PETSC_SUCCESS);
10468   }
10469 
10470   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
10471   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
10472   MatCheckPreallocated(mat, 1);
10473 
10474   PetscCall(PetscLogEventBegin(MAT_RedundantMat, mat, 0, 0, 0));
10475   if (subcomm_in == MPI_COMM_NULL && reuse == MAT_INITIAL_MATRIX) { /* get subcomm if user does not provide subcomm */
10476     /* create psubcomm, then get subcomm */
10477     PetscCall(PetscObjectGetComm((PetscObject)mat, &comm));
10478     PetscCallMPI(MPI_Comm_size(comm, &size));
10479     PetscCheck(nsubcomm >= 1 && nsubcomm <= size, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "nsubcomm must between 1 and %d", size);
10480 
10481     PetscCall(PetscSubcommCreate(comm, &psubcomm));
10482     PetscCall(PetscSubcommSetNumber(psubcomm, nsubcomm));
10483     PetscCall(PetscSubcommSetType(psubcomm, PETSC_SUBCOMM_CONTIGUOUS));
10484     PetscCall(PetscSubcommSetFromOptions(psubcomm));
10485     PetscCall(PetscCommDuplicate(PetscSubcommChild(psubcomm), &subcomm, NULL));
10486     newsubcomm = PETSC_TRUE;
10487     PetscCall(PetscSubcommDestroy(&psubcomm));
10488   }
10489 
10490   /* get isrow, iscol and a local sequential matrix matseq[0] */
10491   if (reuse == MAT_INITIAL_MATRIX) {
10492     mloc_sub = PETSC_DECIDE;
10493     nloc_sub = PETSC_DECIDE;
10494     if (bs < 1) {
10495       PetscCall(PetscSplitOwnership(subcomm, &mloc_sub, &M));
10496       PetscCall(PetscSplitOwnership(subcomm, &nloc_sub, &N));
10497     } else {
10498       PetscCall(PetscSplitOwnershipBlock(subcomm, bs, &mloc_sub, &M));
10499       PetscCall(PetscSplitOwnershipBlock(subcomm, bs, &nloc_sub, &N));
10500     }
10501     PetscCallMPI(MPI_Scan(&mloc_sub, &rend, 1, MPIU_INT, MPI_SUM, subcomm));
10502     rstart = rend - mloc_sub;
10503     PetscCall(ISCreateStride(PETSC_COMM_SELF, mloc_sub, rstart, 1, &isrow));
10504     PetscCall(ISCreateStride(PETSC_COMM_SELF, N, 0, 1, &iscol));
10505     PetscCall(ISSetIdentity(iscol));
10506   } else { /* reuse == MAT_REUSE_MATRIX */
10507     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");
10508     /* retrieve subcomm */
10509     PetscCall(PetscObjectGetComm((PetscObject)*matredundant, &subcomm));
10510     redund = (*matredundant)->redundant;
10511     isrow  = redund->isrow;
10512     iscol  = redund->iscol;
10513     matseq = redund->matseq;
10514   }
10515   PetscCall(MatCreateSubMatrices(mat, 1, &isrow, &iscol, reuse, &matseq));
10516 
10517   /* get matredundant over subcomm */
10518   if (reuse == MAT_INITIAL_MATRIX) {
10519     PetscCall(MatCreateMPIMatConcatenateSeqMat(subcomm, matseq[0], nloc_sub, reuse, matredundant));
10520 
10521     /* create a supporting struct and attach it to C for reuse */
10522     PetscCall(PetscNew(&redund));
10523     (*matredundant)->redundant = redund;
10524     redund->isrow              = isrow;
10525     redund->iscol              = iscol;
10526     redund->matseq             = matseq;
10527     if (newsubcomm) {
10528       redund->subcomm = subcomm;
10529     } else {
10530       redund->subcomm = MPI_COMM_NULL;
10531     }
10532   } else {
10533     PetscCall(MatCreateMPIMatConcatenateSeqMat(subcomm, matseq[0], PETSC_DECIDE, reuse, matredundant));
10534   }
10535 #if defined(PETSC_HAVE_VIENNACL) || defined(PETSC_HAVE_CUDA) || defined(PETSC_HAVE_HIP)
10536   if (matseq[0]->boundtocpu && matseq[0]->bindingpropagates) {
10537     PetscCall(MatBindToCPU(*matredundant, PETSC_TRUE));
10538     PetscCall(MatSetBindingPropagates(*matredundant, PETSC_TRUE));
10539   }
10540 #endif
10541   PetscCall(PetscLogEventEnd(MAT_RedundantMat, mat, 0, 0, 0));
10542   PetscFunctionReturn(PETSC_SUCCESS);
10543 }
10544 
10545 /*@C
10546   MatGetMultiProcBlock - Create multiple 'parallel submatrices' from
10547   a given `Mat`. Each submatrix can span multiple procs.
10548 
10549   Collective
10550 
10551   Input Parameters:
10552 + mat     - the matrix
10553 . subComm - the sub communicator obtained as if by `MPI_Comm_split(PetscObjectComm((PetscObject)mat))`
10554 - scall   - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`
10555 
10556   Output Parameter:
10557 . subMat - parallel sub-matrices each spanning a given `subcomm`
10558 
10559   Level: advanced
10560 
10561   Notes:
10562   The submatrix partition across processors is dictated by `subComm` a
10563   communicator obtained by `MPI_comm_split()` or via `PetscSubcommCreate()`. The `subComm`
10564   is not restricted to be grouped with consecutive original MPI processes.
10565 
10566   Due the `MPI_Comm_split()` usage, the parallel layout of the submatrices
10567   map directly to the layout of the original matrix [wrt the local
10568   row,col partitioning]. So the original 'DiagonalMat' naturally maps
10569   into the 'DiagonalMat' of the `subMat`, hence it is used directly from
10570   the `subMat`. However the offDiagMat looses some columns - and this is
10571   reconstructed with `MatSetValues()`
10572 
10573   This is used by `PCBJACOBI` when a single block spans multiple MPI processes.
10574 
10575 .seealso: [](ch_matrices), `Mat`, `MatCreateRedundantMatrix()`, `MatCreateSubMatrices()`, `PCBJACOBI`
10576 @*/
10577 PetscErrorCode MatGetMultiProcBlock(Mat mat, MPI_Comm subComm, MatReuse scall, Mat *subMat)
10578 {
10579   PetscMPIInt commsize, subCommSize;
10580 
10581   PetscFunctionBegin;
10582   PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)mat), &commsize));
10583   PetscCallMPI(MPI_Comm_size(subComm, &subCommSize));
10584   PetscCheck(subCommSize <= commsize, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_OUTOFRANGE, "CommSize %d < SubCommZize %d", commsize, subCommSize);
10585 
10586   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");
10587   PetscCall(PetscLogEventBegin(MAT_GetMultiProcBlock, mat, 0, 0, 0));
10588   PetscUseTypeMethod(mat, getmultiprocblock, subComm, scall, subMat);
10589   PetscCall(PetscLogEventEnd(MAT_GetMultiProcBlock, mat, 0, 0, 0));
10590   PetscFunctionReturn(PETSC_SUCCESS);
10591 }
10592 
10593 /*@
10594   MatGetLocalSubMatrix - Gets a reference to a submatrix specified in local numbering
10595 
10596   Not Collective
10597 
10598   Input Parameters:
10599 + mat   - matrix to extract local submatrix from
10600 . isrow - local row indices for submatrix
10601 - iscol - local column indices for submatrix
10602 
10603   Output Parameter:
10604 . submat - the submatrix
10605 
10606   Level: intermediate
10607 
10608   Notes:
10609   `submat` should be disposed of with `MatRestoreLocalSubMatrix()`.
10610 
10611   Depending on the format of `mat`, the returned `submat` may not implement `MatMult()`.  Its communicator may be
10612   the same as `mat`, it may be `PETSC_COMM_SELF`, or some other sub-communictor of `mat`'s.
10613 
10614   `submat` always implements `MatSetValuesLocal()`.  If `isrow` and `iscol` have the same block size, then
10615   `MatSetValuesBlockedLocal()` will also be implemented.
10616 
10617   `mat` must have had a `ISLocalToGlobalMapping` provided to it with `MatSetLocalToGlobalMapping()`.
10618   Matrices obtained with `DMCreateMatrix()` generally already have the local to global mapping provided.
10619 
10620 .seealso: [](ch_matrices), `Mat`, `MatRestoreLocalSubMatrix()`, `MatCreateLocalRef()`, `MatSetLocalToGlobalMapping()`
10621 @*/
10622 PetscErrorCode MatGetLocalSubMatrix(Mat mat, IS isrow, IS iscol, Mat *submat)
10623 {
10624   PetscFunctionBegin;
10625   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
10626   PetscValidHeaderSpecific(isrow, IS_CLASSID, 2);
10627   PetscValidHeaderSpecific(iscol, IS_CLASSID, 3);
10628   PetscCheckSameComm(isrow, 2, iscol, 3);
10629   PetscAssertPointer(submat, 4);
10630   PetscCheck(mat->rmap->mapping, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Matrix must have local to global mapping provided before this call");
10631 
10632   if (mat->ops->getlocalsubmatrix) {
10633     PetscUseTypeMethod(mat, getlocalsubmatrix, isrow, iscol, submat);
10634   } else {
10635     PetscCall(MatCreateLocalRef(mat, isrow, iscol, submat));
10636   }
10637   (*submat)->assembled = mat->assembled;
10638   PetscFunctionReturn(PETSC_SUCCESS);
10639 }
10640 
10641 /*@
10642   MatRestoreLocalSubMatrix - Restores a reference to a submatrix specified in local numbering obtained with `MatGetLocalSubMatrix()`
10643 
10644   Not Collective
10645 
10646   Input Parameters:
10647 + mat    - matrix to extract local submatrix from
10648 . isrow  - local row indices for submatrix
10649 . iscol  - local column indices for submatrix
10650 - submat - the submatrix
10651 
10652   Level: intermediate
10653 
10654 .seealso: [](ch_matrices), `Mat`, `MatGetLocalSubMatrix()`
10655 @*/
10656 PetscErrorCode MatRestoreLocalSubMatrix(Mat mat, IS isrow, IS iscol, Mat *submat)
10657 {
10658   PetscFunctionBegin;
10659   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
10660   PetscValidHeaderSpecific(isrow, IS_CLASSID, 2);
10661   PetscValidHeaderSpecific(iscol, IS_CLASSID, 3);
10662   PetscCheckSameComm(isrow, 2, iscol, 3);
10663   PetscAssertPointer(submat, 4);
10664   if (*submat) PetscValidHeaderSpecific(*submat, MAT_CLASSID, 4);
10665 
10666   if (mat->ops->restorelocalsubmatrix) {
10667     PetscUseTypeMethod(mat, restorelocalsubmatrix, isrow, iscol, submat);
10668   } else {
10669     PetscCall(MatDestroy(submat));
10670   }
10671   *submat = NULL;
10672   PetscFunctionReturn(PETSC_SUCCESS);
10673 }
10674 
10675 /*@
10676   MatFindZeroDiagonals - Finds all the rows of a matrix that have zero or no diagonal entry in the matrix
10677 
10678   Collective
10679 
10680   Input Parameter:
10681 . mat - the matrix
10682 
10683   Output Parameter:
10684 . is - if any rows have zero diagonals this contains the list of them
10685 
10686   Level: developer
10687 
10688 .seealso: [](ch_matrices), `Mat`, `MatMultTranspose()`, `MatMultAdd()`, `MatMultTransposeAdd()`
10689 @*/
10690 PetscErrorCode MatFindZeroDiagonals(Mat mat, IS *is)
10691 {
10692   PetscFunctionBegin;
10693   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
10694   PetscValidType(mat, 1);
10695   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
10696   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
10697 
10698   if (!mat->ops->findzerodiagonals) {
10699     Vec                diag;
10700     const PetscScalar *a;
10701     PetscInt          *rows;
10702     PetscInt           rStart, rEnd, r, nrow = 0;
10703 
10704     PetscCall(MatCreateVecs(mat, &diag, NULL));
10705     PetscCall(MatGetDiagonal(mat, diag));
10706     PetscCall(MatGetOwnershipRange(mat, &rStart, &rEnd));
10707     PetscCall(VecGetArrayRead(diag, &a));
10708     for (r = 0; r < rEnd - rStart; ++r)
10709       if (a[r] == 0.0) ++nrow;
10710     PetscCall(PetscMalloc1(nrow, &rows));
10711     nrow = 0;
10712     for (r = 0; r < rEnd - rStart; ++r)
10713       if (a[r] == 0.0) rows[nrow++] = r + rStart;
10714     PetscCall(VecRestoreArrayRead(diag, &a));
10715     PetscCall(VecDestroy(&diag));
10716     PetscCall(ISCreateGeneral(PetscObjectComm((PetscObject)mat), nrow, rows, PETSC_OWN_POINTER, is));
10717   } else {
10718     PetscUseTypeMethod(mat, findzerodiagonals, is);
10719   }
10720   PetscFunctionReturn(PETSC_SUCCESS);
10721 }
10722 
10723 /*@
10724   MatFindOffBlockDiagonalEntries - Finds all the rows of a matrix that have entries outside of the main diagonal block (defined by the matrix block size)
10725 
10726   Collective
10727 
10728   Input Parameter:
10729 . mat - the matrix
10730 
10731   Output Parameter:
10732 . is - contains the list of rows with off block diagonal entries
10733 
10734   Level: developer
10735 
10736 .seealso: [](ch_matrices), `Mat`, `MatMultTranspose()`, `MatMultAdd()`, `MatMultTransposeAdd()`
10737 @*/
10738 PetscErrorCode MatFindOffBlockDiagonalEntries(Mat mat, IS *is)
10739 {
10740   PetscFunctionBegin;
10741   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
10742   PetscValidType(mat, 1);
10743   PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
10744   PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
10745 
10746   PetscUseTypeMethod(mat, findoffblockdiagonalentries, is);
10747   PetscFunctionReturn(PETSC_SUCCESS);
10748 }
10749 
10750 /*@C
10751   MatInvertBlockDiagonal - Inverts the block diagonal entries.
10752 
10753   Collective; No Fortran Support
10754 
10755   Input Parameter:
10756 . mat - the matrix
10757 
10758   Output Parameter:
10759 . values - the block inverses in column major order (FORTRAN-like)
10760 
10761   Level: advanced
10762 
10763   Notes:
10764   The size of the blocks is determined by the block size of the matrix.
10765 
10766   The blocks never overlap between two MPI processes, use `MatInvertVariableBlockEnvelope()` for that case
10767 
10768   The blocks all have the same size, use `MatInvertVariableBlockDiagonal()` for variable block size
10769 
10770 .seealso: [](ch_matrices), `Mat`, `MatInvertVariableBlockEnvelope()`, `MatInvertBlockDiagonalMat()`
10771 @*/
10772 PetscErrorCode MatInvertBlockDiagonal(Mat mat, const PetscScalar *values[])
10773 {
10774   PetscFunctionBegin;
10775   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
10776   PetscCheck(mat->assembled, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
10777   PetscCheck(!mat->factortype, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
10778   PetscUseTypeMethod(mat, invertblockdiagonal, values);
10779   PetscFunctionReturn(PETSC_SUCCESS);
10780 }
10781 
10782 /*@
10783   MatInvertVariableBlockDiagonal - Inverts the point block diagonal entries.
10784 
10785   Collective; No Fortran Support
10786 
10787   Input Parameters:
10788 + mat     - the matrix
10789 . nblocks - the number of blocks on the process, set with `MatSetVariableBlockSizes()`
10790 - bsizes  - the size of each block on the process, set with `MatSetVariableBlockSizes()`
10791 
10792   Output Parameter:
10793 . values - the block inverses in column major order (FORTRAN-like)
10794 
10795   Level: advanced
10796 
10797   Notes:
10798   Use `MatInvertBlockDiagonal()` if all blocks have the same size
10799 
10800   The blocks never overlap between two MPI processes, use `MatInvertVariableBlockEnvelope()` for that case
10801 
10802 .seealso: [](ch_matrices), `Mat`, `MatInvertBlockDiagonal()`, `MatSetVariableBlockSizes()`, `MatInvertVariableBlockEnvelope()`
10803 @*/
10804 PetscErrorCode MatInvertVariableBlockDiagonal(Mat mat, PetscInt nblocks, const PetscInt bsizes[], PetscScalar values[])
10805 {
10806   PetscFunctionBegin;
10807   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
10808   PetscCheck(mat->assembled, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
10809   PetscCheck(!mat->factortype, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
10810   PetscUseTypeMethod(mat, invertvariableblockdiagonal, nblocks, bsizes, values);
10811   PetscFunctionReturn(PETSC_SUCCESS);
10812 }
10813 
10814 /*@
10815   MatInvertBlockDiagonalMat - set the values of matrix C to be the inverted block diagonal of matrix A
10816 
10817   Collective
10818 
10819   Input Parameters:
10820 + A - the matrix
10821 - C - matrix with inverted block diagonal of `A`.  This matrix should be created and may have its type set.
10822 
10823   Level: advanced
10824 
10825   Note:
10826   The blocksize of the matrix is used to determine the blocks on the diagonal of `C`
10827 
10828 .seealso: [](ch_matrices), `Mat`, `MatInvertBlockDiagonal()`
10829 @*/
10830 PetscErrorCode MatInvertBlockDiagonalMat(Mat A, Mat C)
10831 {
10832   const PetscScalar *vals;
10833   PetscInt          *dnnz;
10834   PetscInt           m, rstart, rend, bs, i, j;
10835 
10836   PetscFunctionBegin;
10837   PetscCall(MatInvertBlockDiagonal(A, &vals));
10838   PetscCall(MatGetBlockSize(A, &bs));
10839   PetscCall(MatGetLocalSize(A, &m, NULL));
10840   PetscCall(MatSetLayouts(C, A->rmap, A->cmap));
10841   PetscCall(MatSetBlockSizes(C, A->rmap->bs, A->cmap->bs));
10842   PetscCall(PetscMalloc1(m / bs, &dnnz));
10843   for (j = 0; j < m / bs; j++) dnnz[j] = 1;
10844   PetscCall(MatXAIJSetPreallocation(C, bs, dnnz, NULL, NULL, NULL));
10845   PetscCall(PetscFree(dnnz));
10846   PetscCall(MatGetOwnershipRange(C, &rstart, &rend));
10847   PetscCall(MatSetOption(C, MAT_ROW_ORIENTED, PETSC_FALSE));
10848   for (i = rstart / bs; i < rend / bs; i++) PetscCall(MatSetValuesBlocked(C, 1, &i, 1, &i, &vals[(i - rstart / bs) * bs * bs], INSERT_VALUES));
10849   PetscCall(MatAssemblyBegin(C, MAT_FINAL_ASSEMBLY));
10850   PetscCall(MatAssemblyEnd(C, MAT_FINAL_ASSEMBLY));
10851   PetscCall(MatSetOption(C, MAT_ROW_ORIENTED, PETSC_TRUE));
10852   PetscFunctionReturn(PETSC_SUCCESS);
10853 }
10854 
10855 /*@
10856   MatTransposeColoringDestroy - Destroys a coloring context for matrix product $C = A*B^T$ that was created
10857   via `MatTransposeColoringCreate()`.
10858 
10859   Collective
10860 
10861   Input Parameter:
10862 . c - coloring context
10863 
10864   Level: intermediate
10865 
10866 .seealso: [](ch_matrices), `Mat`, `MatTransposeColoringCreate()`
10867 @*/
10868 PetscErrorCode MatTransposeColoringDestroy(MatTransposeColoring *c)
10869 {
10870   MatTransposeColoring matcolor = *c;
10871 
10872   PetscFunctionBegin;
10873   if (!matcolor) PetscFunctionReturn(PETSC_SUCCESS);
10874   if (--((PetscObject)matcolor)->refct > 0) {
10875     matcolor = NULL;
10876     PetscFunctionReturn(PETSC_SUCCESS);
10877   }
10878 
10879   PetscCall(PetscFree3(matcolor->ncolumns, matcolor->nrows, matcolor->colorforrow));
10880   PetscCall(PetscFree(matcolor->rows));
10881   PetscCall(PetscFree(matcolor->den2sp));
10882   PetscCall(PetscFree(matcolor->colorforcol));
10883   PetscCall(PetscFree(matcolor->columns));
10884   if (matcolor->brows > 0) PetscCall(PetscFree(matcolor->lstart));
10885   PetscCall(PetscHeaderDestroy(c));
10886   PetscFunctionReturn(PETSC_SUCCESS);
10887 }
10888 
10889 /*@
10890   MatTransColoringApplySpToDen - Given a symbolic matrix product $C = A*B^T$ for which
10891   a `MatTransposeColoring` context has been created, computes a dense $B^T$ by applying
10892   `MatTransposeColoring` to sparse `B`.
10893 
10894   Collective
10895 
10896   Input Parameters:
10897 + coloring - coloring context created with `MatTransposeColoringCreate()`
10898 - B        - sparse matrix
10899 
10900   Output Parameter:
10901 . Btdense - dense matrix $B^T$
10902 
10903   Level: developer
10904 
10905   Note:
10906   These are used internally for some implementations of `MatRARt()`
10907 
10908 .seealso: [](ch_matrices), `Mat`, `MatTransposeColoringCreate()`, `MatTransposeColoringDestroy()`, `MatTransColoringApplyDenToSp()`
10909 @*/
10910 PetscErrorCode MatTransColoringApplySpToDen(MatTransposeColoring coloring, Mat B, Mat Btdense)
10911 {
10912   PetscFunctionBegin;
10913   PetscValidHeaderSpecific(coloring, MAT_TRANSPOSECOLORING_CLASSID, 1);
10914   PetscValidHeaderSpecific(B, MAT_CLASSID, 2);
10915   PetscValidHeaderSpecific(Btdense, MAT_CLASSID, 3);
10916 
10917   PetscCall((*B->ops->transcoloringapplysptoden)(coloring, B, Btdense));
10918   PetscFunctionReturn(PETSC_SUCCESS);
10919 }
10920 
10921 /*@
10922   MatTransColoringApplyDenToSp - Given a symbolic matrix product $C_{sp} = A*B^T$ for which
10923   a `MatTransposeColoring` context has been created and a dense matrix $C_{den} = A*B^T_{dense}$
10924   in which `B^T_{dens}` is obtained from `MatTransColoringApplySpToDen()`, recover sparse matrix
10925   $C_{sp}$ from $C_{den}$.
10926 
10927   Collective
10928 
10929   Input Parameters:
10930 + matcoloring - coloring context created with `MatTransposeColoringCreate()`
10931 - Cden        - matrix product of a sparse matrix and a dense matrix Btdense
10932 
10933   Output Parameter:
10934 . Csp - sparse matrix
10935 
10936   Level: developer
10937 
10938   Note:
10939   These are used internally for some implementations of `MatRARt()`
10940 
10941 .seealso: [](ch_matrices), `Mat`, `MatTransposeColoringCreate()`, `MatTransposeColoringDestroy()`, `MatTransColoringApplySpToDen()`
10942 @*/
10943 PetscErrorCode MatTransColoringApplyDenToSp(MatTransposeColoring matcoloring, Mat Cden, Mat Csp)
10944 {
10945   PetscFunctionBegin;
10946   PetscValidHeaderSpecific(matcoloring, MAT_TRANSPOSECOLORING_CLASSID, 1);
10947   PetscValidHeaderSpecific(Cden, MAT_CLASSID, 2);
10948   PetscValidHeaderSpecific(Csp, MAT_CLASSID, 3);
10949 
10950   PetscCall((*Csp->ops->transcoloringapplydentosp)(matcoloring, Cden, Csp));
10951   PetscCall(MatAssemblyBegin(Csp, MAT_FINAL_ASSEMBLY));
10952   PetscCall(MatAssemblyEnd(Csp, MAT_FINAL_ASSEMBLY));
10953   PetscFunctionReturn(PETSC_SUCCESS);
10954 }
10955 
10956 /*@
10957   MatTransposeColoringCreate - Creates a matrix coloring context for the matrix product $C = A*B^T$.
10958 
10959   Collective
10960 
10961   Input Parameters:
10962 + mat        - the matrix product C
10963 - iscoloring - the coloring of the matrix; usually obtained with `MatColoringCreate()` or `DMCreateColoring()`
10964 
10965   Output Parameter:
10966 . color - the new coloring context
10967 
10968   Level: intermediate
10969 
10970 .seealso: [](ch_matrices), `Mat`, `MatTransposeColoringDestroy()`, `MatTransColoringApplySpToDen()`,
10971           `MatTransColoringApplyDenToSp()`
10972 @*/
10973 PetscErrorCode MatTransposeColoringCreate(Mat mat, ISColoring iscoloring, MatTransposeColoring *color)
10974 {
10975   MatTransposeColoring c;
10976   MPI_Comm             comm;
10977 
10978   PetscFunctionBegin;
10979   PetscAssertPointer(color, 3);
10980 
10981   PetscCall(PetscLogEventBegin(MAT_TransposeColoringCreate, mat, 0, 0, 0));
10982   PetscCall(PetscObjectGetComm((PetscObject)mat, &comm));
10983   PetscCall(PetscHeaderCreate(c, MAT_TRANSPOSECOLORING_CLASSID, "MatTransposeColoring", "Matrix product C=A*B^T via coloring", "Mat", comm, MatTransposeColoringDestroy, NULL));
10984   c->ctype = iscoloring->ctype;
10985   PetscUseTypeMethod(mat, transposecoloringcreate, iscoloring, c);
10986   *color = c;
10987   PetscCall(PetscLogEventEnd(MAT_TransposeColoringCreate, mat, 0, 0, 0));
10988   PetscFunctionReturn(PETSC_SUCCESS);
10989 }
10990 
10991 /*@
10992   MatGetNonzeroState - Returns a 64-bit integer representing the current state of nonzeros in the matrix. If the
10993   matrix has had new nonzero locations added to (or removed from) the matrix since the previous call, the value will be larger.
10994 
10995   Not Collective
10996 
10997   Input Parameter:
10998 . mat - the matrix
10999 
11000   Output Parameter:
11001 . state - the current state
11002 
11003   Level: intermediate
11004 
11005   Notes:
11006   You can only compare states from two different calls to the SAME matrix, you cannot compare calls between
11007   different matrices
11008 
11009   Use `PetscObjectStateGet()` to check for changes to the numerical values in a matrix
11010 
11011   Use the result of `PetscObjectGetId()` to compare if a previously checked matrix is the same as the current matrix, do not compare object pointers.
11012 
11013 .seealso: [](ch_matrices), `Mat`, `PetscObjectStateGet()`, `PetscObjectGetId()`
11014 @*/
11015 PetscErrorCode MatGetNonzeroState(Mat mat, PetscObjectState *state)
11016 {
11017   PetscFunctionBegin;
11018   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
11019   *state = mat->nonzerostate;
11020   PetscFunctionReturn(PETSC_SUCCESS);
11021 }
11022 
11023 /*@
11024   MatCreateMPIMatConcatenateSeqMat - Creates a single large PETSc matrix by concatenating sequential
11025   matrices from each processor
11026 
11027   Collective
11028 
11029   Input Parameters:
11030 + comm   - the communicators the parallel matrix will live on
11031 . seqmat - the input sequential matrices
11032 . n      - number of local columns (or `PETSC_DECIDE`)
11033 - reuse  - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`
11034 
11035   Output Parameter:
11036 . mpimat - the parallel matrix generated
11037 
11038   Level: developer
11039 
11040   Note:
11041   The number of columns of the matrix in EACH processor MUST be the same.
11042 
11043 .seealso: [](ch_matrices), `Mat`
11044 @*/
11045 PetscErrorCode MatCreateMPIMatConcatenateSeqMat(MPI_Comm comm, Mat seqmat, PetscInt n, MatReuse reuse, Mat *mpimat)
11046 {
11047   PetscMPIInt size;
11048 
11049   PetscFunctionBegin;
11050   PetscCallMPI(MPI_Comm_size(comm, &size));
11051   if (size == 1) {
11052     if (reuse == MAT_INITIAL_MATRIX) {
11053       PetscCall(MatDuplicate(seqmat, MAT_COPY_VALUES, mpimat));
11054     } else {
11055       PetscCall(MatCopy(seqmat, *mpimat, SAME_NONZERO_PATTERN));
11056     }
11057     PetscFunctionReturn(PETSC_SUCCESS);
11058   }
11059 
11060   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");
11061 
11062   PetscCall(PetscLogEventBegin(MAT_Merge, seqmat, 0, 0, 0));
11063   PetscCall((*seqmat->ops->creatempimatconcatenateseqmat)(comm, seqmat, n, reuse, mpimat));
11064   PetscCall(PetscLogEventEnd(MAT_Merge, seqmat, 0, 0, 0));
11065   PetscFunctionReturn(PETSC_SUCCESS);
11066 }
11067 
11068 /*@
11069   MatSubdomainsCreateCoalesce - Creates index subdomains by coalescing adjacent MPI processes' ownership ranges.
11070 
11071   Collective
11072 
11073   Input Parameters:
11074 + A - the matrix to create subdomains from
11075 - N - requested number of subdomains
11076 
11077   Output Parameters:
11078 + n   - number of subdomains resulting on this MPI process
11079 - iss - `IS` list with indices of subdomains on this MPI process
11080 
11081   Level: advanced
11082 
11083   Note:
11084   The number of subdomains must be smaller than the communicator size
11085 
11086 .seealso: [](ch_matrices), `Mat`, `IS`
11087 @*/
11088 PetscErrorCode MatSubdomainsCreateCoalesce(Mat A, PetscInt N, PetscInt *n, IS *iss[])
11089 {
11090   MPI_Comm    comm, subcomm;
11091   PetscMPIInt size, rank, color;
11092   PetscInt    rstart, rend, k;
11093 
11094   PetscFunctionBegin;
11095   PetscCall(PetscObjectGetComm((PetscObject)A, &comm));
11096   PetscCallMPI(MPI_Comm_size(comm, &size));
11097   PetscCallMPI(MPI_Comm_rank(comm, &rank));
11098   PetscCheck(N >= 1 && N < size, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "number of subdomains must be > 0 and < %d, got N = %" PetscInt_FMT, size, N);
11099   *n    = 1;
11100   k     = size / N + (size % N > 0); /* There are up to k ranks to a color */
11101   color = rank / k;
11102   PetscCallMPI(MPI_Comm_split(comm, color, rank, &subcomm));
11103   PetscCall(PetscMalloc1(1, iss));
11104   PetscCall(MatGetOwnershipRange(A, &rstart, &rend));
11105   PetscCall(ISCreateStride(subcomm, rend - rstart, rstart, 1, iss[0]));
11106   PetscCallMPI(MPI_Comm_free(&subcomm));
11107   PetscFunctionReturn(PETSC_SUCCESS);
11108 }
11109 
11110 /*@
11111   MatGalerkin - Constructs the coarse grid problem matrix via Galerkin projection.
11112 
11113   If the interpolation and restriction operators are the same, uses `MatPtAP()`.
11114   If they are not the same, uses `MatMatMatMult()`.
11115 
11116   Once the coarse grid problem is constructed, correct for interpolation operators
11117   that are not of full rank, which can legitimately happen in the case of non-nested
11118   geometric multigrid.
11119 
11120   Input Parameters:
11121 + restrct     - restriction operator
11122 . dA          - fine grid matrix
11123 . interpolate - interpolation operator
11124 . reuse       - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`
11125 - fill        - expected fill, use `PETSC_DETERMINE` or `PETSC_DETERMINE` if you do not have a good estimate
11126 
11127   Output Parameter:
11128 . A - the Galerkin coarse matrix
11129 
11130   Options Database Key:
11131 . -pc_mg_galerkin <both,pmat,mat,none> - for what matrices the Galerkin process should be used
11132 
11133   Level: developer
11134 
11135   Note:
11136   The deprecated `PETSC_DEFAULT` in `fill` also means use the current value
11137 
11138 .seealso: [](ch_matrices), `Mat`, `MatPtAP()`, `MatMatMatMult()`
11139 @*/
11140 PetscErrorCode MatGalerkin(Mat restrct, Mat dA, Mat interpolate, MatReuse reuse, PetscReal fill, Mat *A)
11141 {
11142   IS  zerorows;
11143   Vec diag;
11144 
11145   PetscFunctionBegin;
11146   PetscCheck(reuse != MAT_INPLACE_MATRIX, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "Inplace product not supported");
11147   /* Construct the coarse grid matrix */
11148   if (interpolate == restrct) {
11149     PetscCall(MatPtAP(dA, interpolate, reuse, fill, A));
11150   } else {
11151     PetscCall(MatMatMatMult(restrct, dA, interpolate, reuse, fill, A));
11152   }
11153 
11154   /* If the interpolation matrix is not of full rank, A will have zero rows.
11155      This can legitimately happen in the case of non-nested geometric multigrid.
11156      In that event, we set the rows of the matrix to the rows of the identity,
11157      ignoring the equations (as the RHS will also be zero). */
11158 
11159   PetscCall(MatFindZeroRows(*A, &zerorows));
11160 
11161   if (zerorows != NULL) { /* if there are any zero rows */
11162     PetscCall(MatCreateVecs(*A, &diag, NULL));
11163     PetscCall(MatGetDiagonal(*A, diag));
11164     PetscCall(VecISSet(diag, zerorows, 1.0));
11165     PetscCall(MatDiagonalSet(*A, diag, INSERT_VALUES));
11166     PetscCall(VecDestroy(&diag));
11167     PetscCall(ISDestroy(&zerorows));
11168   }
11169   PetscFunctionReturn(PETSC_SUCCESS);
11170 }
11171 
11172 /*@C
11173   MatSetOperation - Allows user to set a matrix operation for any matrix type
11174 
11175   Logically Collective
11176 
11177   Input Parameters:
11178 + mat - the matrix
11179 . op  - the name of the operation
11180 - f   - the function that provides the operation
11181 
11182   Level: developer
11183 
11184   Example Usage:
11185 .vb
11186   extern PetscErrorCode usermult(Mat, Vec, Vec);
11187 
11188   PetscCall(MatCreateXXX(comm, ..., &A));
11189   PetscCall(MatSetOperation(A, MATOP_MULT, (PetscErrorCodeFn *)usermult));
11190 .ve
11191 
11192   Notes:
11193   See the file `include/petscmat.h` for a complete list of matrix
11194   operations, which all have the form MATOP_<OPERATION>, where
11195   <OPERATION> is the name (in all capital letters) of the
11196   user interface routine (e.g., `MatMult()` -> `MATOP_MULT`).
11197 
11198   All user-provided functions (except for `MATOP_DESTROY`) should have the same calling
11199   sequence as the usual matrix interface routines, since they
11200   are intended to be accessed via the usual matrix interface
11201   routines, e.g.,
11202 .vb
11203   MatMult(Mat, Vec, Vec) -> usermult(Mat, Vec, Vec)
11204 .ve
11205 
11206   In particular each function MUST return `PETSC_SUCCESS` on success and
11207   nonzero on failure.
11208 
11209   This routine is distinct from `MatShellSetOperation()` in that it can be called on any matrix type.
11210 
11211 .seealso: [](ch_matrices), `Mat`, `MatGetOperation()`, `MatCreateShell()`, `MatShellSetContext()`, `MatShellSetOperation()`
11212 @*/
11213 PetscErrorCode MatSetOperation(Mat mat, MatOperation op, PetscErrorCodeFn *f)
11214 {
11215   PetscFunctionBegin;
11216   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
11217   if (op == MATOP_VIEW && !mat->ops->viewnative && f != (PetscErrorCodeFn *)mat->ops->view) mat->ops->viewnative = mat->ops->view;
11218   (((PetscErrorCodeFn **)mat->ops)[op]) = f;
11219   PetscFunctionReturn(PETSC_SUCCESS);
11220 }
11221 
11222 /*@C
11223   MatGetOperation - Gets a matrix operation for any matrix type.
11224 
11225   Not Collective
11226 
11227   Input Parameters:
11228 + mat - the matrix
11229 - op  - the name of the operation
11230 
11231   Output Parameter:
11232 . f - the function that provides the operation
11233 
11234   Level: developer
11235 
11236   Example Usage:
11237 .vb
11238   PetscErrorCode (*usermult)(Mat, Vec, Vec);
11239 
11240   MatGetOperation(A, MATOP_MULT, (PetscErrorCodeFn **)&usermult);
11241 .ve
11242 
11243   Notes:
11244   See the file `include/petscmat.h` for a complete list of matrix
11245   operations, which all have the form MATOP_<OPERATION>, where
11246   <OPERATION> is the name (in all capital letters) of the
11247   user interface routine (e.g., `MatMult()` -> `MATOP_MULT`).
11248 
11249   This routine is distinct from `MatShellGetOperation()` in that it can be called on any matrix type.
11250 
11251 .seealso: [](ch_matrices), `Mat`, `MatSetOperation()`, `MatCreateShell()`, `MatShellGetContext()`, `MatShellGetOperation()`
11252 @*/
11253 PetscErrorCode MatGetOperation(Mat mat, MatOperation op, PetscErrorCodeFn **f)
11254 {
11255   PetscFunctionBegin;
11256   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
11257   *f = (((PetscErrorCodeFn **)mat->ops)[op]);
11258   PetscFunctionReturn(PETSC_SUCCESS);
11259 }
11260 
11261 /*@
11262   MatHasOperation - Determines whether the given matrix supports the particular operation.
11263 
11264   Not Collective
11265 
11266   Input Parameters:
11267 + mat - the matrix
11268 - op  - the operation, for example, `MATOP_GET_DIAGONAL`
11269 
11270   Output Parameter:
11271 . has - either `PETSC_TRUE` or `PETSC_FALSE`
11272 
11273   Level: advanced
11274 
11275   Note:
11276   See `MatSetOperation()` for additional discussion on naming convention and usage of `op`.
11277 
11278 .seealso: [](ch_matrices), `Mat`, `MatCreateShell()`, `MatGetOperation()`, `MatSetOperation()`
11279 @*/
11280 PetscErrorCode MatHasOperation(Mat mat, MatOperation op, PetscBool *has)
11281 {
11282   PetscFunctionBegin;
11283   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
11284   PetscAssertPointer(has, 3);
11285   if (mat->ops->hasoperation) {
11286     PetscUseTypeMethod(mat, hasoperation, op, has);
11287   } else {
11288     if (((void **)mat->ops)[op]) *has = PETSC_TRUE;
11289     else {
11290       *has = PETSC_FALSE;
11291       if (op == MATOP_CREATE_SUBMATRIX) {
11292         PetscMPIInt size;
11293 
11294         PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)mat), &size));
11295         if (size == 1) PetscCall(MatHasOperation(mat, MATOP_CREATE_SUBMATRICES, has));
11296       }
11297     }
11298   }
11299   PetscFunctionReturn(PETSC_SUCCESS);
11300 }
11301 
11302 /*@
11303   MatHasCongruentLayouts - Determines whether the rows and columns layouts of the matrix are congruent
11304 
11305   Collective
11306 
11307   Input Parameter:
11308 . mat - the matrix
11309 
11310   Output Parameter:
11311 . cong - either `PETSC_TRUE` or `PETSC_FALSE`
11312 
11313   Level: beginner
11314 
11315 .seealso: [](ch_matrices), `Mat`, `MatCreate()`, `MatSetSizes()`, `PetscLayout`
11316 @*/
11317 PetscErrorCode MatHasCongruentLayouts(Mat mat, PetscBool *cong)
11318 {
11319   PetscFunctionBegin;
11320   PetscValidHeaderSpecific(mat, MAT_CLASSID, 1);
11321   PetscValidType(mat, 1);
11322   PetscAssertPointer(cong, 2);
11323   if (!mat->rmap || !mat->cmap) {
11324     *cong = mat->rmap == mat->cmap ? PETSC_TRUE : PETSC_FALSE;
11325     PetscFunctionReturn(PETSC_SUCCESS);
11326   }
11327   if (mat->congruentlayouts == PETSC_DECIDE) { /* first time we compare rows and cols layouts */
11328     PetscCall(PetscLayoutSetUp(mat->rmap));
11329     PetscCall(PetscLayoutSetUp(mat->cmap));
11330     PetscCall(PetscLayoutCompare(mat->rmap, mat->cmap, cong));
11331     if (*cong) mat->congruentlayouts = 1;
11332     else mat->congruentlayouts = 0;
11333   } else *cong = mat->congruentlayouts ? PETSC_TRUE : PETSC_FALSE;
11334   PetscFunctionReturn(PETSC_SUCCESS);
11335 }
11336 
11337 PetscErrorCode MatSetInf(Mat A)
11338 {
11339   PetscFunctionBegin;
11340   PetscUseTypeMethod(A, setinf);
11341   PetscFunctionReturn(PETSC_SUCCESS);
11342 }
11343 
11344 /*@
11345   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
11346   and possibly removes small values from the graph structure.
11347 
11348   Collective
11349 
11350   Input Parameters:
11351 + A       - the matrix
11352 . sym     - `PETSC_TRUE` indicates that the graph should be symmetrized
11353 . scale   - `PETSC_TRUE` indicates that the graph edge weights should be symmetrically scaled with the diagonal entry
11354 . filter  - filter value - < 0: does nothing; == 0: removes only 0.0 entries; otherwise: removes entries with abs(entries) <= value
11355 . num_idx - size of 'index' array
11356 - index   - array of block indices to use for graph strength of connection weight
11357 
11358   Output Parameter:
11359 . graph - the resulting graph
11360 
11361   Level: advanced
11362 
11363 .seealso: [](ch_matrices), `Mat`, `MatCreate()`, `PCGAMG`
11364 @*/
11365 PetscErrorCode MatCreateGraph(Mat A, PetscBool sym, PetscBool scale, PetscReal filter, PetscInt num_idx, PetscInt index[], Mat *graph)
11366 {
11367   PetscFunctionBegin;
11368   PetscValidHeaderSpecific(A, MAT_CLASSID, 1);
11369   PetscValidType(A, 1);
11370   PetscValidLogicalCollectiveBool(A, scale, 3);
11371   PetscAssertPointer(graph, 7);
11372   PetscCall(PetscLogEventBegin(MAT_CreateGraph, A, 0, 0, 0));
11373   PetscUseTypeMethod(A, creategraph, sym, scale, filter, num_idx, index, graph);
11374   PetscCall(PetscLogEventEnd(MAT_CreateGraph, A, 0, 0, 0));
11375   PetscFunctionReturn(PETSC_SUCCESS);
11376 }
11377 
11378 /*@
11379   MatEliminateZeros - eliminate the nondiagonal zero entries in place from the nonzero structure of a sparse `Mat` in place,
11380   meaning the same memory is used for the matrix, and no new memory is allocated.
11381 
11382   Collective
11383 
11384   Input Parameters:
11385 + A    - the matrix
11386 - 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
11387 
11388   Level: intermediate
11389 
11390   Developer Note:
11391   The entries in the sparse matrix data structure are shifted to fill in the unneeded locations in the data. Thus the end
11392   of the arrays in the data structure are unneeded.
11393 
11394 .seealso: [](ch_matrices), `Mat`, `MatCreate()`, `MatCreateGraph()`, `MatFilter()`
11395 @*/
11396 PetscErrorCode MatEliminateZeros(Mat A, PetscBool keep)
11397 {
11398   PetscFunctionBegin;
11399   PetscValidHeaderSpecific(A, MAT_CLASSID, 1);
11400   PetscUseTypeMethod(A, eliminatezeros, keep);
11401   PetscFunctionReturn(PETSC_SUCCESS);
11402 }
11403 
11404 /*@C
11405   MatGetCurrentMemType - Get the memory location of the matrix
11406 
11407   Not Collective, but the result will be the same on all MPI processes
11408 
11409   Input Parameter:
11410 . A - the matrix whose memory type we are checking
11411 
11412   Output Parameter:
11413 . m - the memory type
11414 
11415   Level: intermediate
11416 
11417 .seealso: [](ch_matrices), `Mat`, `MatBoundToCPU()`, `PetscMemType`
11418 @*/
11419 PetscErrorCode MatGetCurrentMemType(Mat A, PetscMemType *m)
11420 {
11421   PetscFunctionBegin;
11422   PetscValidHeaderSpecific(A, MAT_CLASSID, 1);
11423   PetscAssertPointer(m, 2);
11424   if (A->ops->getcurrentmemtype) PetscUseTypeMethod(A, getcurrentmemtype, m);
11425   else *m = PETSC_MEMTYPE_HOST;
11426   PetscFunctionReturn(PETSC_SUCCESS);
11427 }
11428