Actual source code: matrix.c
1: /*
2: This is where the abstract matrix operations are defined
3: Portions of this code are under:
4: Copyright (c) 2022 Advanced Micro Devices, Inc. All rights reserved.
5: */
7: #include <petsc/private/matimpl.h>
8: #include <petsc/private/isimpl.h>
9: #include <petsc/private/vecimpl.h>
11: /* Logging support */
12: PetscClassId MAT_CLASSID;
13: PetscClassId MAT_COLORING_CLASSID;
14: PetscClassId MAT_FDCOLORING_CLASSID;
15: PetscClassId MAT_TRANSPOSECOLORING_CLASSID;
17: PetscLogEvent MAT_Mult, MAT_MultAdd, MAT_MultTranspose;
18: PetscLogEvent MAT_ADot, MAT_ANorm;
19: PetscLogEvent MAT_MultTransposeAdd, MAT_Solve, MAT_Solves, MAT_SolveAdd, MAT_SolveTranspose, MAT_MatSolve, MAT_MatTrSolve;
20: PetscLogEvent MAT_SolveTransposeAdd, MAT_SOR, MAT_ForwardSolve, MAT_BackwardSolve, MAT_LUFactor, MAT_LUFactorSymbolic;
21: PetscLogEvent MAT_LUFactorNumeric, MAT_CholeskyFactor, MAT_CholeskyFactorSymbolic, MAT_CholeskyFactorNumeric, MAT_ILUFactor;
22: PetscLogEvent MAT_ILUFactorSymbolic, MAT_ICCFactorSymbolic, MAT_Copy, MAT_Convert, MAT_Scale, MAT_AssemblyBegin;
23: PetscLogEvent MAT_QRFactorNumeric, MAT_QRFactorSymbolic, MAT_QRFactor;
24: PetscLogEvent MAT_AssemblyEnd, MAT_SetValues, MAT_GetValues, MAT_GetRow, MAT_GetRowIJ, MAT_CreateSubMats, MAT_GetOrdering, MAT_RedundantMat, MAT_GetSeqNonzeroStructure;
25: PetscLogEvent MAT_IncreaseOverlap, MAT_Partitioning, MAT_PartitioningND, MAT_Coarsen, MAT_ZeroEntries, MAT_Load, MAT_View, MAT_AXPY, MAT_FDColoringCreate;
26: PetscLogEvent MAT_FDColoringSetUp, MAT_FDColoringApply, MAT_Transpose, MAT_FDColoringFunction, MAT_CreateSubMat;
27: PetscLogEvent MAT_TransposeColoringCreate;
28: PetscLogEvent MAT_MatMult, MAT_MatMultSymbolic, MAT_MatMultNumeric;
29: PetscLogEvent MAT_PtAP, MAT_PtAPSymbolic, MAT_PtAPNumeric, MAT_RARt, MAT_RARtSymbolic, MAT_RARtNumeric;
30: PetscLogEvent MAT_MatTransposeMult, MAT_MatTransposeMultSymbolic, MAT_MatTransposeMultNumeric;
31: PetscLogEvent MAT_TransposeMatMult, MAT_TransposeMatMultSymbolic, MAT_TransposeMatMultNumeric;
32: PetscLogEvent MAT_MatMatMult, MAT_MatMatMultSymbolic, MAT_MatMatMultNumeric;
33: PetscLogEvent MAT_MultHermitianTranspose, MAT_MultHermitianTransposeAdd;
34: PetscLogEvent MAT_Getsymtransreduced, MAT_GetBrowsOfAcols;
35: PetscLogEvent MAT_GetBrowsOfAocols, MAT_Getlocalmat, MAT_Getlocalmatcondensed, MAT_Seqstompi, MAT_Seqstompinum, MAT_Seqstompisym;
36: PetscLogEvent MAT_GetMultiProcBlock;
37: PetscLogEvent MAT_CUSPARSECopyToGPU, MAT_CUSPARSECopyFromGPU, MAT_CUSPARSEGenerateTranspose, MAT_CUSPARSESolveAnalysis;
38: PetscLogEvent MAT_HIPSPARSECopyToGPU, MAT_HIPSPARSECopyFromGPU, MAT_HIPSPARSEGenerateTranspose, MAT_HIPSPARSESolveAnalysis;
39: PetscLogEvent MAT_PreallCOO, MAT_SetVCOO;
40: PetscLogEvent MAT_CreateGraph;
41: PetscLogEvent MAT_SetValuesBatch;
42: PetscLogEvent MAT_ViennaCLCopyToGPU;
43: PetscLogEvent MAT_CUDACopyToGPU, MAT_HIPCopyToGPU;
44: PetscLogEvent MAT_DenseCopyToGPU, MAT_DenseCopyFromGPU;
45: PetscLogEvent MAT_Merge, MAT_Residual, MAT_SetRandom;
46: PetscLogEvent MAT_FactorFactS, MAT_FactorInvS;
47: PetscLogEvent MATCOLORING_Apply, MATCOLORING_Comm, MATCOLORING_Local, MATCOLORING_ISCreate, MATCOLORING_SetUp, MATCOLORING_Weights;
48: PetscLogEvent MAT_H2Opus_Build, MAT_H2Opus_Compress, MAT_H2Opus_Orthog, MAT_H2Opus_LR;
50: const char *const MatFactorTypes[] = {"NONE", "LU", "CHOLESKY", "ILU", "ICC", "ILUDT", "QR", "MatFactorType", "MAT_FACTOR_", NULL};
52: /*@
53: MatSetRandom - Sets all components of a matrix to random numbers.
55: Logically Collective
57: Input Parameters:
58: + x - the matrix
59: - rctx - the `PetscRandom` object, formed by `PetscRandomCreate()`, or `NULL` and
60: it will create one internally.
62: Example:
63: .vb
64: PetscRandomCreate(PETSC_COMM_WORLD,&rctx);
65: MatSetRandom(x,rctx);
66: PetscRandomDestroy(rctx);
67: .ve
69: Level: intermediate
71: Notes:
72: For sparse matrices that have been preallocated but not been assembled, it randomly selects appropriate locations,
74: for sparse matrices that already have nonzero locations, it fills the locations with random numbers.
76: It generates an error if used on unassembled sparse matrices that have not been preallocated.
78: .seealso: [](ch_matrices), `Mat`, `PetscRandom`, `PetscRandomCreate()`, `MatZeroEntries()`, `MatSetValues()`, `PetscRandomDestroy()`
79: @*/
80: PetscErrorCode MatSetRandom(Mat x, PetscRandom rctx)
81: {
82: PetscRandom randObj = NULL;
84: PetscFunctionBegin;
88: MatCheckPreallocated(x, 1);
90: if (!rctx) {
91: MPI_Comm comm;
92: PetscCall(PetscObjectGetComm((PetscObject)x, &comm));
93: PetscCall(PetscRandomCreate(comm, &randObj));
94: PetscCall(PetscRandomSetType(randObj, x->defaultrandtype));
95: PetscCall(PetscRandomSetFromOptions(randObj));
96: rctx = randObj;
97: }
98: PetscCall(PetscLogEventBegin(MAT_SetRandom, x, rctx, 0, 0));
99: PetscUseTypeMethod(x, setrandom, rctx);
100: PetscCall(PetscLogEventEnd(MAT_SetRandom, x, rctx, 0, 0));
102: PetscCall(MatAssemblyBegin(x, MAT_FINAL_ASSEMBLY));
103: PetscCall(MatAssemblyEnd(x, MAT_FINAL_ASSEMBLY));
104: PetscCall(PetscRandomDestroy(&randObj));
105: PetscFunctionReturn(PETSC_SUCCESS);
106: }
108: /*@
109: MatCopyHashToXAIJ - copy hash table entries into an XAIJ matrix type
111: Logically Collective
113: Input Parameter:
114: . A - A matrix in unassembled, hash table form
116: Output Parameter:
117: . B - The XAIJ matrix. This can either be `A` or some matrix of equivalent size, e.g. obtained from `A` via `MatDuplicate()`
119: Example:
120: .vb
121: PetscCall(MatDuplicate(A, MAT_DO_NOT_COPY_VALUES, &B));
122: PetscCall(MatCopyHashToXAIJ(A, B));
123: .ve
125: Level: advanced
127: Notes:
128: If `B` is `A`, then the hash table data structure will be destroyed. `B` is assembled
130: .seealso: [](ch_matrices), `Mat`, `MAT_USE_HASH_TABLE`
131: @*/
132: PetscErrorCode MatCopyHashToXAIJ(Mat A, Mat B)
133: {
134: PetscFunctionBegin;
136: PetscUseTypeMethod(A, copyhashtoxaij, B);
137: PetscFunctionReturn(PETSC_SUCCESS);
138: }
140: /*@
141: MatFactorGetErrorZeroPivot - returns the pivot value that was determined to be zero and the row it occurred in
143: Logically Collective
145: Input Parameter:
146: . mat - the factored matrix
148: Output Parameters:
149: + pivot - the pivot value computed
150: - row - the row that the zero pivot occurred. This row value must be interpreted carefully due to row reorderings and which processes
151: the share the matrix
153: Level: advanced
155: Notes:
156: This routine does not work for factorizations done with external packages.
158: This routine should only be called if `MatGetFactorError()` returns a value of `MAT_FACTOR_NUMERIC_ZEROPIVOT`
160: This can also be called on non-factored matrices that come from, for example, matrices used in SOR.
162: .seealso: [](ch_matrices), `Mat`, `MatZeroEntries()`, `MatFactor()`, `MatGetFactor()`,
163: `MatLUFactorSymbolic()`, `MatCholeskyFactorSymbolic()`, `MatFactorClearError()`,
164: `MAT_FACTOR_NUMERIC_ZEROPIVOT`
165: @*/
166: PetscErrorCode MatFactorGetErrorZeroPivot(Mat mat, PetscReal *pivot, PetscInt *row)
167: {
168: PetscFunctionBegin;
170: PetscAssertPointer(pivot, 2);
171: PetscAssertPointer(row, 3);
172: *pivot = mat->factorerror_zeropivot_value;
173: *row = mat->factorerror_zeropivot_row;
174: PetscFunctionReturn(PETSC_SUCCESS);
175: }
177: /*@
178: MatFactorGetError - gets the error code from a factorization
180: Logically Collective
182: Input Parameter:
183: . mat - the factored matrix
185: Output Parameter:
186: . err - the error code
188: Level: advanced
190: Note:
191: This can also be called on non-factored matrices that come from, for example, matrices used in SOR.
193: .seealso: [](ch_matrices), `Mat`, `MatZeroEntries()`, `MatFactor()`, `MatGetFactor()`, `MatLUFactorSymbolic()`, `MatCholeskyFactorSymbolic()`,
194: `MatFactorClearError()`, `MatFactorGetErrorZeroPivot()`, `MatFactorError`
195: @*/
196: PetscErrorCode MatFactorGetError(Mat mat, MatFactorError *err)
197: {
198: PetscFunctionBegin;
200: PetscAssertPointer(err, 2);
201: *err = mat->factorerrortype;
202: PetscFunctionReturn(PETSC_SUCCESS);
203: }
205: /*@
206: MatFactorClearError - clears the error code in a factorization
208: Logically Collective
210: Input Parameter:
211: . mat - the factored matrix
213: Level: developer
215: Note:
216: This can also be called on non-factored matrices that come from, for example, matrices used in SOR.
218: .seealso: [](ch_matrices), `Mat`, `MatZeroEntries()`, `MatFactor()`, `MatGetFactor()`, `MatLUFactorSymbolic()`, `MatCholeskyFactorSymbolic()`, `MatFactorGetError()`, `MatFactorGetErrorZeroPivot()`,
219: `MatGetErrorCode()`, `MatFactorError`
220: @*/
221: PetscErrorCode MatFactorClearError(Mat mat)
222: {
223: PetscFunctionBegin;
225: mat->factorerrortype = MAT_FACTOR_NOERROR;
226: mat->factorerror_zeropivot_value = 0.0;
227: mat->factorerror_zeropivot_row = 0;
228: PetscFunctionReturn(PETSC_SUCCESS);
229: }
231: PetscErrorCode MatFindNonzeroRowsOrCols_Basic(Mat mat, PetscBool cols, PetscReal tol, IS *nonzero)
232: {
233: Vec r, l;
234: const PetscScalar *al;
235: PetscInt i, nz, gnz, N, n, st;
237: PetscFunctionBegin;
238: PetscCall(MatCreateVecs(mat, &r, &l));
239: if (!cols) { /* nonzero rows */
240: PetscCall(MatGetOwnershipRange(mat, &st, NULL));
241: PetscCall(MatGetSize(mat, &N, NULL));
242: PetscCall(MatGetLocalSize(mat, &n, NULL));
243: PetscCall(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: }
287: /*@
288: MatFindNonzeroRows - Locate all rows that are not completely zero in the matrix
290: Input Parameter:
291: . mat - the matrix
293: Output Parameter:
294: . keptrows - the rows that are not completely zero
296: Level: intermediate
298: Note:
299: `keptrows` is set to `NULL` if all rows are nonzero.
301: Developer Note:
302: If `keptrows` is not `NULL`, it must be sorted.
304: .seealso: [](ch_matrices), `Mat`, `MatFindZeroRows()`
305: @*/
306: PetscErrorCode MatFindNonzeroRows(Mat mat, IS *keptrows)
307: {
308: PetscFunctionBegin;
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: }
320: /*@
321: MatFindZeroRows - Locate all rows that are completely zero in the matrix
323: Input Parameter:
324: . mat - the matrix
326: Output Parameter:
327: . zerorows - the rows that are completely zero
329: Level: intermediate
331: Note:
332: `zerorows` is set to `NULL` if no rows are zero.
334: .seealso: [](ch_matrices), `Mat`, `MatFindNonzeroRows()`
335: @*/
336: PetscErrorCode MatFindZeroRows(Mat mat, IS *zerorows)
337: {
338: IS keptrows;
339: PetscInt m, n;
341: PetscFunctionBegin;
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: }
359: /*@
360: MatGetDiagonalBlock - Returns the part of the matrix associated with the on-process coupling
362: Not Collective
364: Input Parameter:
365: . A - the matrix
367: Output Parameter:
368: . a - the diagonal part (which is a SEQUENTIAL matrix)
370: Level: advanced
372: Notes:
373: See `MatCreateAIJ()` for more information on the "diagonal part" of the matrix.
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.
377: .seealso: [](ch_matrices), `Mat`, `MatCreateAIJ()`, `MATAIJ`, `MATBAIJ`, `MATSBAIJ`
378: @*/
379: PetscErrorCode MatGetDiagonalBlock(Mat A, Mat *a)
380: {
381: PetscFunctionBegin;
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;
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: }
397: /*@
398: MatGetTrace - Gets the trace of a matrix. The sum of the diagonal entries.
400: Collective
402: Input Parameter:
403: . mat - the matrix
405: Output Parameter:
406: . trace - the sum of the diagonal entries
408: Level: advanced
410: .seealso: [](ch_matrices), `Mat`
411: @*/
412: PetscErrorCode MatGetTrace(Mat mat, PetscScalar *trace)
413: {
414: Vec diag;
416: PetscFunctionBegin;
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: }
426: /*@
427: MatRealPart - Zeros out the imaginary part of the matrix
429: Logically Collective
431: Input Parameter:
432: . mat - the matrix
434: Level: advanced
436: .seealso: [](ch_matrices), `Mat`, `MatImaginaryPart()`
437: @*/
438: PetscErrorCode MatRealPart(Mat mat)
439: {
440: PetscFunctionBegin;
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: }
450: /*@C
451: MatGetGhosts - Get the global indices of all ghost nodes defined by the sparse matrix
453: Collective
455: Input Parameter:
456: . mat - the matrix
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
462: Level: advanced
464: Note:
465: `nghosts` and `ghosts` are suitable to pass into `VecCreateGhost()` or `VecCreateGhostBlock()`
467: .seealso: [](ch_matrices), `Mat`, `VecCreateGhost()`, `VecCreateGhostBlock()`
468: @*/
469: PetscErrorCode MatGetGhosts(Mat mat, PetscInt *nghosts, const PetscInt *ghosts[])
470: {
471: PetscFunctionBegin;
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: }
484: /*@
485: MatImaginaryPart - Moves the imaginary part of the matrix to the real part and zeros the imaginary part
487: Logically Collective
489: Input Parameter:
490: . mat - the matrix
492: Level: advanced
494: .seealso: [](ch_matrices), `Mat`, `MatRealPart()`
495: @*/
496: PetscErrorCode MatImaginaryPart(Mat mat)
497: {
498: PetscFunctionBegin;
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: }
508: // PetscClangLinter pragma disable: -fdoc-section-header-unknown
509: /*@C
510: MatGetRow - Gets a row of a matrix. You MUST call `MatRestoreRow()`
511: for each row that you get to ensure that your application does
512: not bleed memory.
514: Not Collective
516: Input Parameters:
517: + mat - the matrix
518: - row - the row to get
520: Output Parameters:
521: + ncols - if not `NULL`, the number of nonzeros in `row`
522: . cols - if not `NULL`, the column numbers
523: - vals - if not `NULL`, the numerical values
525: Level: advanced
527: Notes:
528: This routine is provided for people who need to have direct access
529: to the structure of a matrix. We hope that we provide enough
530: high-level matrix routines that few users will need it.
532: `MatGetRow()` always returns 0-based column indices, regardless of
533: whether the internal representation is 0-based (default) or 1-based.
535: For better efficiency, set `cols` and/or `vals` to `NULL` if you do
536: not wish to extract these quantities.
538: The user can only examine the values extracted with `MatGetRow()`;
539: the values CANNOT be altered. To change the matrix entries, one
540: must use `MatSetValues()`.
542: You can only have one call to `MatGetRow()` outstanding for a particular
543: matrix at a time, per processor. `MatGetRow()` can only obtain rows
544: associated with the given processor, it cannot get rows from the
545: other processors; for that we suggest using `MatCreateSubMatrices()`, then
546: `MatGetRow()` on the submatrix. The row index passed to `MatGetRow()`
547: is in the global number of rows.
549: Use `MatGetRowIJ()` and `MatRestoreRowIJ()` to access all the local indices of the sparse matrix.
551: Use `MatSeqAIJGetArray()` and similar functions to access the numerical values for certain matrix types directly.
553: Fortran Note:
554: .vb
555: PetscInt, pointer :: cols(:)
556: PetscScalar, pointer :: vals(:)
557: .ve
559: .seealso: [](ch_matrices), `Mat`, `MatRestoreRow()`, `MatSetValues()`, `MatGetValues()`, `MatCreateSubMatrices()`, `MatGetDiagonal()`, `MatGetRowIJ()`, `MatRestoreRowIJ()`
560: @*/
561: PetscErrorCode MatGetRow(Mat mat, PetscInt row, PetscInt *ncols, const PetscInt *cols[], const PetscScalar *vals[])
562: {
563: PetscInt incols;
565: PetscFunctionBegin;
568: PetscCheck(mat->assembled, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
569: PetscCheck(!mat->factortype, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
570: MatCheckPreallocated(mat, 1);
571: 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);
572: PetscCall(PetscLogEventBegin(MAT_GetRow, mat, 0, 0, 0));
573: PetscUseTypeMethod(mat, getrow, row, &incols, (PetscInt **)cols, (PetscScalar **)vals);
574: if (ncols) *ncols = incols;
575: PetscCall(PetscLogEventEnd(MAT_GetRow, mat, 0, 0, 0));
576: PetscFunctionReturn(PETSC_SUCCESS);
577: }
579: /*@
580: MatConjugate - replaces the matrix values with their complex conjugates
582: Logically Collective
584: Input Parameter:
585: . mat - the matrix
587: Level: advanced
589: .seealso: [](ch_matrices), `Mat`, `MatRealPart()`, `MatImaginaryPart()`, `VecConjugate()`, `MatTranspose()`
590: @*/
591: PetscErrorCode MatConjugate(Mat mat)
592: {
593: PetscFunctionBegin;
595: PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
596: if (PetscDefined(USE_COMPLEX) && !(mat->symmetric == PETSC_BOOL3_TRUE && mat->hermitian == PETSC_BOOL3_TRUE)) {
597: PetscUseTypeMethod(mat, conjugate);
598: PetscCall(PetscObjectStateIncrease((PetscObject)mat));
599: }
600: PetscFunctionReturn(PETSC_SUCCESS);
601: }
603: /*@C
604: MatRestoreRow - Frees any temporary space allocated by `MatGetRow()`.
606: Not Collective
608: Input Parameters:
609: + mat - the matrix
610: . row - the row to get
611: . ncols - the number of nonzeros
612: . cols - the columns of the nonzeros
613: - vals - if nonzero the column values
615: Level: advanced
617: Notes:
618: This routine should be called after you have finished examining the entries.
620: This routine zeros out `ncols`, `cols`, and `vals`. This is to prevent accidental
621: us of the array after it has been restored. If you pass `NULL`, it will
622: not zero the pointers. Use of `cols` or `vals` after `MatRestoreRow()` is invalid.
624: Fortran Note:
625: .vb
626: PetscInt, pointer :: cols(:)
627: PetscScalar, pointer :: vals(:)
628: .ve
630: .seealso: [](ch_matrices), `Mat`, `MatGetRow()`
631: @*/
632: PetscErrorCode MatRestoreRow(Mat mat, PetscInt row, PetscInt *ncols, const PetscInt *cols[], const PetscScalar *vals[])
633: {
634: PetscFunctionBegin;
636: if (ncols) PetscAssertPointer(ncols, 3);
637: PetscCheck(mat->assembled, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
638: PetscTryTypeMethod(mat, restorerow, row, ncols, (PetscInt **)cols, (PetscScalar **)vals);
639: if (ncols) *ncols = 0;
640: if (cols) *cols = NULL;
641: if (vals) *vals = NULL;
642: PetscFunctionReturn(PETSC_SUCCESS);
643: }
645: /*@
646: MatGetRowUpperTriangular - Sets a flag to enable calls to `MatGetRow()` for matrix in `MATSBAIJ` format.
647: You should call `MatRestoreRowUpperTriangular()` after calling` MatGetRow()` and `MatRestoreRow()` to disable the flag.
649: Not Collective
651: Input Parameter:
652: . mat - the matrix
654: Level: advanced
656: Note:
657: 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.
659: .seealso: [](ch_matrices), `Mat`, `MATSBAIJ`, `MatRestoreRowUpperTriangular()`
660: @*/
661: PetscErrorCode MatGetRowUpperTriangular(Mat mat)
662: {
663: PetscFunctionBegin;
666: PetscCheck(mat->assembled, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
667: PetscCheck(!mat->factortype, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
668: MatCheckPreallocated(mat, 1);
669: PetscTryTypeMethod(mat, getrowuppertriangular);
670: PetscFunctionReturn(PETSC_SUCCESS);
671: }
673: /*@
674: MatRestoreRowUpperTriangular - Disable calls to `MatGetRow()` for matrix in `MATSBAIJ` format.
676: Not Collective
678: Input Parameter:
679: . mat - the matrix
681: Level: advanced
683: Note:
684: This routine should be called after you have finished calls to `MatGetRow()` and `MatRestoreRow()`.
686: .seealso: [](ch_matrices), `Mat`, `MATSBAIJ`, `MatGetRowUpperTriangular()`
687: @*/
688: PetscErrorCode MatRestoreRowUpperTriangular(Mat mat)
689: {
690: PetscFunctionBegin;
693: PetscCheck(mat->assembled, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
694: PetscCheck(!mat->factortype, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
695: MatCheckPreallocated(mat, 1);
696: PetscTryTypeMethod(mat, restorerowuppertriangular);
697: PetscFunctionReturn(PETSC_SUCCESS);
698: }
700: /*@
701: MatSetOptionsPrefix - Sets the prefix used for searching for all
702: `Mat` options in the database.
704: Logically Collective
706: Input Parameters:
707: + A - the matrix
708: - prefix - the prefix to prepend to all option names
710: Level: advanced
712: Notes:
713: A hyphen (-) must NOT be given at the beginning of the prefix name.
714: The first character of all runtime options is AUTOMATICALLY the hyphen.
716: This is NOT used for options for the factorization of the matrix. Normally the
717: prefix is automatically passed in from the PC calling the factorization. To set
718: it directly use `MatSetOptionsPrefixFactor()`
720: .seealso: [](ch_matrices), `Mat`, `MatSetFromOptions()`, `MatSetOptionsPrefixFactor()`
721: @*/
722: PetscErrorCode MatSetOptionsPrefix(Mat A, const char prefix[])
723: {
724: PetscFunctionBegin;
726: PetscCall(PetscObjectSetOptionsPrefix((PetscObject)A, prefix));
727: PetscTryMethod(A, "MatSetOptionsPrefix_C", (Mat, const char[]), (A, prefix));
728: PetscFunctionReturn(PETSC_SUCCESS);
729: }
731: /*@
732: MatSetOptionsPrefixFactor - Sets the prefix used for searching for all matrix factor options in the database for
733: for matrices created with `MatGetFactor()`
735: Logically Collective
737: Input Parameters:
738: + A - the matrix
739: - prefix - the prefix to prepend to all option names for the factored matrix
741: Level: developer
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.
747: Normally the prefix is automatically passed in from the `PC` calling the factorization. To set
748: it directly when not using `KSP`/`PC` use `MatSetOptionsPrefixFactor()`
750: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatGetFactor()`, `MatSetFromOptions()`, `MatSetOptionsPrefix()`, `MatAppendOptionsPrefixFactor()`
751: @*/
752: PetscErrorCode MatSetOptionsPrefixFactor(Mat A, const char prefix[])
753: {
754: PetscFunctionBegin;
756: if (prefix) {
757: PetscAssertPointer(prefix, 2);
758: PetscCheck(prefix[0] != '-', PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_WRONG, "Options prefix should not begin with a hyphen");
759: if (prefix != A->factorprefix) {
760: PetscCall(PetscFree(A->factorprefix));
761: PetscCall(PetscStrallocpy(prefix, &A->factorprefix));
762: }
763: } else PetscCall(PetscFree(A->factorprefix));
764: PetscFunctionReturn(PETSC_SUCCESS);
765: }
767: /*@
768: MatAppendOptionsPrefixFactor - Appends to the prefix used for searching for all matrix factor options in the database for
769: for matrices created with `MatGetFactor()`
771: Logically Collective
773: Input Parameters:
774: + A - the matrix
775: - prefix - the prefix to prepend to all option names for the factored matrix
777: Level: developer
779: Notes:
780: A hyphen (-) must NOT be given at the beginning of the prefix name.
781: The first character of all runtime options is AUTOMATICALLY the hyphen.
783: Normally the prefix is automatically passed in from the `PC` calling the factorization. To set
784: it directly when not using `KSP`/`PC` use `MatAppendOptionsPrefixFactor()`
786: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatGetFactor()`, `PetscOptionsCreate()`, `PetscOptionsDestroy()`, `PetscObjectSetOptionsPrefix()`, `PetscObjectPrependOptionsPrefix()`,
787: `PetscObjectGetOptionsPrefix()`, `TSAppendOptionsPrefix()`, `SNESAppendOptionsPrefix()`, `KSPAppendOptionsPrefix()`, `MatSetOptionsPrefixFactor()`,
788: `MatSetOptionsPrefix()`
789: @*/
790: PetscErrorCode MatAppendOptionsPrefixFactor(Mat A, const char prefix[])
791: {
792: size_t len1, len2, new_len;
794: PetscFunctionBegin;
796: if (!prefix) PetscFunctionReturn(PETSC_SUCCESS);
797: if (!A->factorprefix) {
798: PetscCall(MatSetOptionsPrefixFactor(A, prefix));
799: PetscFunctionReturn(PETSC_SUCCESS);
800: }
801: PetscCheck(prefix[0] != '-', PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_WRONG, "Options prefix should not begin with a hyphen");
803: PetscCall(PetscStrlen(A->factorprefix, &len1));
804: PetscCall(PetscStrlen(prefix, &len2));
805: new_len = len1 + len2 + 1;
806: PetscCall(PetscRealloc(new_len * sizeof(*A->factorprefix), &A->factorprefix));
807: PetscCall(PetscStrncpy(A->factorprefix + len1, prefix, len2 + 1));
808: PetscFunctionReturn(PETSC_SUCCESS);
809: }
811: /*@
812: MatAppendOptionsPrefix - Appends to the prefix used for searching for all
813: matrix options in the database.
815: Logically Collective
817: Input Parameters:
818: + A - the matrix
819: - prefix - the prefix to prepend to all option names
821: Level: advanced
823: Note:
824: A hyphen (-) must NOT be given at the beginning of the prefix name.
825: The first character of all runtime options is AUTOMATICALLY the hyphen.
827: .seealso: [](ch_matrices), `Mat`, `MatGetOptionsPrefix()`, `MatAppendOptionsPrefixFactor()`, `MatSetOptionsPrefix()`
828: @*/
829: PetscErrorCode MatAppendOptionsPrefix(Mat A, const char prefix[])
830: {
831: PetscFunctionBegin;
833: PetscCall(PetscObjectAppendOptionsPrefix((PetscObject)A, prefix));
834: PetscTryMethod(A, "MatAppendOptionsPrefix_C", (Mat, const char[]), (A, prefix));
835: PetscFunctionReturn(PETSC_SUCCESS);
836: }
838: /*@
839: MatGetOptionsPrefix - Gets the prefix used for searching for all
840: matrix options in the database.
842: Not Collective
844: Input Parameter:
845: . A - the matrix
847: Output Parameter:
848: . prefix - pointer to the prefix string used
850: Level: advanced
852: .seealso: [](ch_matrices), `Mat`, `MatAppendOptionsPrefix()`, `MatSetOptionsPrefix()`, `MatAppendOptionsPrefixFactor()`, `MatSetOptionsPrefixFactor()`
853: @*/
854: PetscErrorCode MatGetOptionsPrefix(Mat A, const char *prefix[])
855: {
856: PetscFunctionBegin;
858: PetscAssertPointer(prefix, 2);
859: PetscCall(PetscObjectGetOptionsPrefix((PetscObject)A, prefix));
860: PetscFunctionReturn(PETSC_SUCCESS);
861: }
863: /*@
864: MatGetState - Gets the state of a `Mat`. Same value as returned by `PetscObjectStateGet()`
866: Not Collective
868: Input Parameter:
869: . A - the matrix
871: Output Parameter:
872: . state - the object state
874: Level: advanced
876: Note:
877: Object state is an integer which gets increased every time
878: the object is changed. By saving and later querying the object state
879: one can determine whether information about the object is still current.
881: See `MatGetNonzeroState()` to determine if the nonzero structure of the matrix has changed.
883: .seealso: [](ch_matrices), `Mat`, `MatCreate()`, `PetscObjectStateGet()`, `MatGetNonzeroState()`
884: @*/
885: PetscErrorCode MatGetState(Mat A, PetscObjectState *state)
886: {
887: PetscFunctionBegin;
889: PetscAssertPointer(state, 2);
890: PetscCall(PetscObjectStateGet((PetscObject)A, state));
891: PetscFunctionReturn(PETSC_SUCCESS);
892: }
894: /*@
895: MatResetPreallocation - Reset matrix to use the original preallocation values provided by the user, for example with `MatXAIJSetPreallocation()`
897: Collective
899: Input Parameter:
900: . A - the matrix
902: Level: beginner
904: Notes:
905: After calling `MatAssemblyBegin()` and `MatAssemblyEnd()` with `MAT_FINAL_ASSEMBLY` the matrix data structures represent the nonzeros assigned to the
906: matrix. If that space is less than the preallocated space that extra preallocated space is no longer available to take on new values. `MatResetPreallocation()`
907: makes all of the preallocation space available
909: Current values in the matrix are lost in this call
911: Currently only supported for `MATAIJ` matrices.
913: .seealso: [](ch_matrices), `Mat`, `MatSeqAIJSetPreallocation()`, `MatMPIAIJSetPreallocation()`, `MatXAIJSetPreallocation()`
914: @*/
915: PetscErrorCode MatResetPreallocation(Mat A)
916: {
917: PetscFunctionBegin;
920: PetscUseMethod(A, "MatResetPreallocation_C", (Mat), (A));
921: PetscFunctionReturn(PETSC_SUCCESS);
922: }
924: /*@
925: MatResetHash - Reset the matrix so that it will use a hash table for the next round of `MatSetValues()` and `MatAssemblyBegin()`/`MatAssemblyEnd()`.
927: Collective
929: Input Parameter:
930: . A - the matrix
932: Level: intermediate
934: Notes:
935: The matrix will again delete the hash table data structures after following calls to `MatAssemblyBegin()`/`MatAssemblyEnd()` with `MAT_FINAL_ASSEMBLY`.
937: Currently only supported for `MATAIJ` matrices.
939: .seealso: [](ch_matrices), `Mat`, `MatResetPreallocation()`
940: @*/
941: PetscErrorCode MatResetHash(Mat A)
942: {
943: PetscFunctionBegin;
946: 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()");
947: if (A->num_ass == 0) PetscFunctionReturn(PETSC_SUCCESS);
948: PetscUseMethod(A, "MatResetHash_C", (Mat), (A));
949: /* These flags are used to determine whether certain setups occur */
950: A->was_assembled = PETSC_FALSE;
951: A->assembled = PETSC_FALSE;
952: /* Log that the state of this object has changed; this will help guarantee that preconditioners get re-setup */
953: PetscCall(PetscObjectStateIncrease((PetscObject)A));
954: PetscFunctionReturn(PETSC_SUCCESS);
955: }
957: /*@
958: MatSetUp - Sets up the internal matrix data structures for later use by the matrix
960: Collective
962: Input Parameter:
963: . A - the matrix
965: Level: advanced
967: Notes:
968: If the user has not set preallocation for this matrix then an efficient algorithm will be used for the first round of
969: setting values in the matrix.
971: This routine is called internally by other `Mat` functions when needed so rarely needs to be called by users
973: .seealso: [](ch_matrices), `Mat`, `MatMult()`, `MatCreate()`, `MatDestroy()`, `MatXAIJSetPreallocation()`
974: @*/
975: PetscErrorCode MatSetUp(Mat A)
976: {
977: PetscFunctionBegin;
979: if (!((PetscObject)A)->type_name) {
980: PetscMPIInt size;
982: PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)A), &size));
983: PetscCall(MatSetType(A, size == 1 ? MATSEQAIJ : MATMPIAIJ));
984: }
985: if (!A->preallocated) PetscTryTypeMethod(A, setup);
986: PetscCall(PetscLayoutSetUp(A->rmap));
987: PetscCall(PetscLayoutSetUp(A->cmap));
988: A->preallocated = PETSC_TRUE;
989: PetscFunctionReturn(PETSC_SUCCESS);
990: }
992: #if defined(PETSC_HAVE_SAWS)
993: #include <petscviewersaws.h>
994: #endif
996: /*
997: If threadsafety is on extraneous matrices may be printed
999: This flag cannot be stored in the matrix because the original matrix in MatView() may assemble a new matrix which is passed into MatViewFromOptions()
1000: */
1001: #if !defined(PETSC_HAVE_THREADSAFETY)
1002: static PetscInt insidematview = 0;
1003: #endif
1005: /*@
1006: MatViewFromOptions - View properties of the matrix based on options set in the options database
1008: Collective
1010: Input Parameters:
1011: + A - the matrix
1012: . obj - optional additional object that provides the options prefix to use
1013: - name - command line option
1015: Options Database Key:
1016: . -name [viewertype][:...] - option name and values. See `PetscObjectViewFromOptions()` for the possible arguments
1018: Level: intermediate
1020: .seealso: [](ch_matrices), `Mat`, `MatView()`, `PetscObjectViewFromOptions()`, `MatCreate()`
1021: @*/
1022: PetscErrorCode MatViewFromOptions(Mat A, PetscObject obj, const char name[])
1023: {
1024: PetscFunctionBegin;
1026: #if !defined(PETSC_HAVE_THREADSAFETY)
1027: if (insidematview) PetscFunctionReturn(PETSC_SUCCESS);
1028: #endif
1029: PetscCall(PetscObjectViewFromOptions((PetscObject)A, obj, name));
1030: PetscFunctionReturn(PETSC_SUCCESS);
1031: }
1033: /*@
1034: MatView - display information about a matrix in a variety ways
1036: Collective on viewer
1038: Input Parameters:
1039: + mat - the matrix
1040: - viewer - visualization context
1042: Options Database Keys:
1043: + -mat_view ::ascii_info - Prints info on matrix at conclusion of `MatAssemblyEnd()`
1044: . -mat_view ::ascii_info_detail - Prints more detailed info
1045: . -mat_view - Prints matrix in ASCII format
1046: . -mat_view ::ascii_matlab - Prints matrix in MATLAB format
1047: . -mat_view draw - PetscDraws nonzero structure of matrix, using `MatView()` and `PetscDrawOpenX()`.
1048: . -display name - Sets display name (default is host)
1049: . -draw_pause sec - Sets number of seconds to pause after display
1050: . -mat_view socket - Sends matrix to socket, can be accessed from MATLAB (see Users-Manual: ch_matlab for details)
1051: . -viewer_socket_machine machine - -
1052: . -viewer_socket_port port - -
1053: . -mat_view binary - save matrix to file in binary format
1054: - -viewer_binary_filename name - -
1056: Level: beginner
1058: Notes:
1059: The available visualization contexts include
1060: + `PETSC_VIEWER_STDOUT_SELF` - for sequential matrices
1061: . `PETSC_VIEWER_STDOUT_WORLD` - for parallel matrices created on `PETSC_COMM_WORLD`
1062: . `PETSC_VIEWER_STDOUT_`(comm) - for matrices created on MPI communicator comm
1063: - `PETSC_VIEWER_DRAW_WORLD` - graphical display of nonzero structure
1065: The user can open alternative visualization contexts with
1066: + `PetscViewerASCIIOpen()` - Outputs matrix to a specified file
1067: . `PetscViewerBinaryOpen()` - Outputs matrix in binary to a specified file; corresponding input uses `MatLoad()`
1068: . `PetscViewerDrawOpen()` - Outputs nonzero matrix nonzero structure to an X window display
1069: - `PetscViewerSocketOpen()` - Outputs matrix to Socket viewer, `PETSCVIEWERSOCKET`. Only the `MATSEQDENSE` and `MATAIJ` types support this viewer.
1071: The user can call `PetscViewerPushFormat()` to specify the output
1072: format of ASCII printed objects (when using `PETSC_VIEWER_STDOUT_SELF`,
1073: `PETSC_VIEWER_STDOUT_WORLD` and `PetscViewerASCIIOpen()`). Available formats include
1074: + `PETSC_VIEWER_DEFAULT` - default, prints matrix contents
1075: . `PETSC_VIEWER_ASCII_MATLAB` - prints matrix contents in MATLAB format
1076: . `PETSC_VIEWER_ASCII_DENSE` - prints entire matrix including zeros
1077: . `PETSC_VIEWER_ASCII_COMMON` - prints matrix contents, using a sparse format common among all matrix types
1078: . `PETSC_VIEWER_ASCII_IMPL` - prints matrix contents, using an implementation-specific format (which is in many cases the same as the default)
1079: . `PETSC_VIEWER_ASCII_INFO` - prints basic information about the matrix size and structure (not the matrix entries)
1080: - `PETSC_VIEWER_ASCII_INFO_DETAIL` - prints more detailed information about the matrix nonzero structure (still not vector or matrix entries)
1082: The ASCII viewers are only recommended for small matrices on at most a moderate number of processes,
1083: the program will seemingly hang and take hours for larger matrices, for larger matrices one should use the binary format.
1085: In the debugger you can do "call MatView(mat,0)" to display the matrix. (The same holds for any PETSc object viewer).
1087: See the manual page for `MatLoad()` for the exact format of the binary file when the binary
1088: viewer is used.
1090: See share/petsc/matlab/PetscBinaryRead.m for a MATLAB code that can read in the binary file when the binary
1091: viewer is used and lib/petsc/bin/PetscBinaryIO.py for loading them into Python.
1093: One can use `-mat_view draw -draw_pause -1` to pause the graphical display of matrix nonzero structure,
1094: and then use the following mouse functions.
1095: .vb
1096: left mouse: zoom in
1097: middle mouse: zoom out
1098: right mouse: continue with the simulation
1099: .ve
1101: .seealso: [](ch_matrices), `Mat`, `PetscViewerPushFormat()`, `PetscViewerASCIIOpen()`, `PetscViewerDrawOpen()`, `PetscViewer`,
1102: `PetscViewerSocketOpen()`, `PetscViewerBinaryOpen()`, `MatLoad()`, `MatViewFromOptions()`
1103: @*/
1104: PetscErrorCode MatView(Mat mat, PetscViewer viewer)
1105: {
1106: PetscInt rows, cols, rbs, cbs;
1107: PetscBool isascii, isstring, issaws;
1108: PetscViewerFormat format;
1109: PetscMPIInt size;
1111: PetscFunctionBegin;
1114: if (!viewer) PetscCall(PetscViewerASCIIGetStdout(PetscObjectComm((PetscObject)mat), &viewer));
1117: PetscCall(PetscViewerGetFormat(viewer, &format));
1118: PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)viewer), &size));
1119: if (size == 1 && format == PETSC_VIEWER_LOAD_BALANCE) PetscFunctionReturn(PETSC_SUCCESS);
1121: #if !defined(PETSC_HAVE_THREADSAFETY)
1122: insidematview++;
1123: #endif
1124: PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERSTRING, &isstring));
1125: PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERASCII, &isascii));
1126: PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERSAWS, &issaws));
1127: 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");
1129: PetscCall(PetscLogEventBegin(MAT_View, mat, viewer, 0, 0));
1130: if (isascii) {
1131: if (!mat->preallocated) {
1132: PetscCall(PetscViewerASCIIPrintf(viewer, "Matrix has not been preallocated yet\n"));
1133: #if !defined(PETSC_HAVE_THREADSAFETY)
1134: insidematview--;
1135: #endif
1136: PetscCall(PetscLogEventEnd(MAT_View, mat, viewer, 0, 0));
1137: PetscFunctionReturn(PETSC_SUCCESS);
1138: }
1139: if (!mat->assembled) {
1140: PetscCall(PetscViewerASCIIPrintf(viewer, "Matrix has not been assembled yet\n"));
1141: #if !defined(PETSC_HAVE_THREADSAFETY)
1142: insidematview--;
1143: #endif
1144: PetscCall(PetscLogEventEnd(MAT_View, mat, viewer, 0, 0));
1145: PetscFunctionReturn(PETSC_SUCCESS);
1146: }
1147: PetscCall(PetscObjectPrintClassNamePrefixType((PetscObject)mat, viewer));
1148: if (format == PETSC_VIEWER_ASCII_INFO || format == PETSC_VIEWER_ASCII_INFO_DETAIL) {
1149: MatNullSpace nullsp, transnullsp;
1150: PetscBool nz_factor = PETSC_TRUE;
1152: PetscCall(PetscViewerASCIIPushTab(viewer));
1153: PetscCall(MatGetSize(mat, &rows, &cols));
1154: PetscCall(MatGetBlockSizes(mat, &rbs, &cbs));
1155: if (rbs != 1 || cbs != 1) {
1156: if (rbs != cbs) PetscCall(PetscViewerASCIIPrintf(viewer, "rows=%" PetscInt_FMT ", cols=%" PetscInt_FMT ", rbs=%" PetscInt_FMT ", cbs=%" PetscInt_FMT "%s\n", rows, cols, rbs, cbs, mat->bsizes ? " variable blocks set" : ""));
1157: else PetscCall(PetscViewerASCIIPrintf(viewer, "rows=%" PetscInt_FMT ", cols=%" PetscInt_FMT ", bs=%" PetscInt_FMT "%s\n", rows, cols, rbs, mat->bsizes ? " variable blocks set" : ""));
1158: } else PetscCall(PetscViewerASCIIPrintf(viewer, "rows=%" PetscInt_FMT ", cols=%" PetscInt_FMT "\n", rows, cols));
1159: if (mat->factortype) {
1160: MatSolverType solver;
1162: PetscCall(MatFactorGetSolverType(mat, &solver));
1163: PetscCall(PetscViewerASCIIPrintf(viewer, "package used to perform factorization: %s\n", solver));
1164: PetscCall(PetscStrcmpAny(solver, &nz_factor, MATSOLVERUMFPACK, MATSOLVERCHOLMOD, MATSOLVERSUPERLU, MATSOLVERSUPERLU_DIST, MATSOLVERSTRUMPACK, MATSOLVERHTOOL, ""));
1165: nz_factor = !nz_factor;
1166: }
1167: if (mat->ops->getinfo) {
1168: PetscBool is_constant_or_diagonal;
1170: // Don't print nonzero information for constant or diagonal matrices, it just adds noise to the output
1171: PetscCall(PetscObjectTypeCompareAny((PetscObject)mat, &is_constant_or_diagonal, MATCONSTANTDIAGONAL, MATDIAGONAL, ""));
1172: if (!is_constant_or_diagonal && nz_factor) {
1173: MatInfo info;
1175: PetscCall(MatGetInfo(mat, MAT_GLOBAL_SUM, &info));
1176: PetscCall(PetscViewerASCIIPrintf(viewer, "total: nonzeros=%.f, allocated nonzeros=%.f\n", info.nz_used, info.nz_allocated));
1177: if (!mat->factortype) PetscCall(PetscViewerASCIIPrintf(viewer, "total number of mallocs used during MatSetValues calls=%" PetscInt_FMT "\n", (PetscInt)info.mallocs));
1178: }
1179: }
1180: PetscCall(MatGetNullSpace(mat, &nullsp));
1181: PetscCall(MatGetTransposeNullSpace(mat, &transnullsp));
1182: if (nullsp) PetscCall(PetscViewerASCIIPrintf(viewer, " has attached null space\n"));
1183: if (transnullsp && transnullsp != nullsp) PetscCall(PetscViewerASCIIPrintf(viewer, " has attached transposed null space\n"));
1184: PetscCall(MatGetNearNullSpace(mat, &nullsp));
1185: if (nullsp) PetscCall(PetscViewerASCIIPrintf(viewer, " has attached near null space\n"));
1186: PetscCall(PetscViewerASCIIPushTab(viewer));
1187: PetscCall(MatProductView(mat, viewer));
1188: PetscCall(PetscViewerASCIIPopTab(viewer));
1189: if (mat->bsizes && format == PETSC_VIEWER_ASCII_INFO_DETAIL) {
1190: IS tmp;
1192: PetscCall(ISCreateGeneral(PetscObjectComm((PetscObject)viewer), mat->nblocks, mat->bsizes, PETSC_USE_POINTER, &tmp));
1193: PetscCall(PetscObjectSetName((PetscObject)tmp, "Block Sizes"));
1194: PetscCall(PetscViewerASCIIPushTab(viewer));
1195: PetscCall(ISView(tmp, viewer));
1196: PetscCall(PetscViewerASCIIPopTab(viewer));
1197: PetscCall(ISDestroy(&tmp));
1198: }
1199: }
1200: } else if (issaws) {
1201: #if defined(PETSC_HAVE_SAWS)
1202: PetscMPIInt rank;
1204: PetscCall(PetscObjectName((PetscObject)mat));
1205: PetscCallMPI(MPI_Comm_rank(PETSC_COMM_WORLD, &rank));
1206: if (!((PetscObject)mat)->amsmem && rank == 0) PetscCall(PetscObjectViewSAWs((PetscObject)mat, viewer));
1207: #endif
1208: } else if (isstring) {
1209: const char *type;
1210: PetscCall(MatGetType(mat, &type));
1211: PetscCall(PetscViewerStringSPrintf(viewer, " MatType: %-7.7s", type));
1212: PetscTryTypeMethod(mat, view, viewer);
1213: }
1214: if ((format == PETSC_VIEWER_NATIVE || format == PETSC_VIEWER_LOAD_BALANCE) && mat->ops->viewnative) {
1215: PetscCall(PetscViewerASCIIPushTab(viewer));
1216: PetscUseTypeMethod(mat, viewnative, viewer);
1217: PetscCall(PetscViewerASCIIPopTab(viewer));
1218: } else if (mat->ops->view) {
1219: PetscCall(PetscViewerASCIIPushTab(viewer));
1220: PetscUseTypeMethod(mat, view, viewer);
1221: PetscCall(PetscViewerASCIIPopTab(viewer));
1222: }
1223: if (isascii) {
1224: PetscCall(PetscViewerGetFormat(viewer, &format));
1225: if (format == PETSC_VIEWER_ASCII_INFO || format == PETSC_VIEWER_ASCII_INFO_DETAIL) PetscCall(PetscViewerASCIIPopTab(viewer));
1226: }
1227: PetscCall(PetscLogEventEnd(MAT_View, mat, viewer, 0, 0));
1228: #if !defined(PETSC_HAVE_THREADSAFETY)
1229: insidematview--;
1230: #endif
1231: PetscFunctionReturn(PETSC_SUCCESS);
1232: }
1234: #if defined(PETSC_USE_DEBUG)
1235: #include <../src/sys/totalview/tv_data_display.h>
1236: PETSC_UNUSED static int TV_display_type(const struct _p_Mat *mat)
1237: {
1238: TV_add_row("Local rows", "int", &mat->rmap->n);
1239: TV_add_row("Local columns", "int", &mat->cmap->n);
1240: TV_add_row("Global rows", "int", &mat->rmap->N);
1241: TV_add_row("Global columns", "int", &mat->cmap->N);
1242: TV_add_row("Typename", TV_ascii_string_type, ((PetscObject)mat)->type_name);
1243: return TV_format_OK;
1244: }
1245: #endif
1247: /*@
1248: MatLoad - Loads a matrix that has been stored in binary/HDF5 format
1249: with `MatView()`. The matrix format is determined from the options database.
1250: Generates a parallel MPI matrix if the communicator has more than one
1251: processor. The default matrix type is `MATAIJ`.
1253: Collective
1255: Input Parameters:
1256: + mat - the newly loaded matrix, this needs to have been created with `MatCreate()`
1257: or some related function before a call to `MatLoad()`
1258: - viewer - `PETSCVIEWERBINARY`/`PETSCVIEWERHDF5` file viewer
1260: Options Database Key:
1261: . -matload_block_size bs - set block size
1263: Level: beginner
1265: Notes:
1266: If the `Mat` type has not yet been given then `MATAIJ` is used, call `MatSetFromOptions()` on the
1267: `Mat` before calling this routine if you wish to set it from the options database.
1269: `MatLoad()` automatically loads into the options database any options
1270: given in the file filename.info where filename is the name of the file
1271: that was passed to the `PetscViewerBinaryOpen()`. The options in the info
1272: file will be ignored if you use the -viewer_binary_skip_info option.
1274: If the type or size of mat is not set before a call to `MatLoad()`, PETSc
1275: sets the default matrix type AIJ and sets the local and global sizes.
1276: If type and/or size is already set, then the same are used.
1278: In parallel, each processor can load a subset of rows (or the
1279: entire matrix). This routine is especially useful when a large
1280: matrix is stored on disk and only part of it is desired on each
1281: processor. For example, a parallel solver may access only some of
1282: the rows from each processor. The algorithm used here reads
1283: relatively small blocks of data rather than reading the entire
1284: matrix and then subsetting it.
1286: Viewer's `PetscViewerType` must be either `PETSCVIEWERBINARY` or `PETSCVIEWERHDF5`.
1287: Such viewer can be created using `PetscViewerBinaryOpen()` or `PetscViewerHDF5Open()`,
1288: or the sequence like
1289: .vb
1290: `PetscViewer` v;
1291: `PetscViewerCreate`(`PETSC_COMM_WORLD`,&v);
1292: `PetscViewerSetType`(v,`PETSCVIEWERBINARY`);
1293: `PetscViewerSetFromOptions`(v);
1294: `PetscViewerFileSetMode`(v,`FILE_MODE_READ`);
1295: `PetscViewerFileSetName`(v,"datafile");
1296: .ve
1297: The optional `PetscViewerSetFromOptions()` call allows overriding `PetscViewerSetType()` using the option
1298: .vb
1299: -viewer_type {binary, hdf5}
1300: .ve
1302: See the example src/ksp/ksp/tutorials/ex27.c with the first approach,
1303: and src/mat/tutorials/ex10.c with the second approach.
1305: In case of `PETSCVIEWERBINARY`, a native PETSc binary format is used. Each of the blocks
1306: is read onto MPI rank 0 and then shipped to its destination MPI rank, one after another.
1307: Multiple objects, both matrices and vectors, can be stored within the same file.
1308: Their `PetscObject` name is ignored; they are loaded in the order of their storage.
1310: Most users should not need to know the details of the binary storage
1311: format, since `MatLoad()` and `MatView()` completely hide these details.
1312: But for anyone who is interested, the standard binary matrix storage
1313: format is
1315: .vb
1316: PetscInt MAT_FILE_CLASSID
1317: PetscInt number of rows
1318: PetscInt number of columns
1319: PetscInt total number of nonzeros
1320: PetscInt *number nonzeros in each row
1321: PetscInt *column indices of all nonzeros (starting index is zero)
1322: PetscScalar *values of all nonzeros
1323: .ve
1324: If PETSc was not configured with `--with-64-bit-indices` then only `MATMPIAIJ` matrices with more than `PETSC_INT_MAX` non-zeros can be
1325: 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
1326: case will not fit in a (32-bit) `PetscInt` the value `PETSC_INT_MAX` is used for the header entry `total number of nonzeros`.
1328: PETSc automatically does the byte swapping for
1329: machines that store the bytes reversed. Thus if you write your own binary
1330: read/write routines you have to swap the bytes; see `PetscBinaryRead()`
1331: and `PetscBinaryWrite()` to see how this may be done.
1333: In case of `PETSCVIEWERHDF5`, a parallel HDF5 reader is used.
1334: Each processor's chunk is loaded independently by its owning MPI process.
1335: Multiple objects, both matrices and vectors, can be stored within the same file.
1336: They are looked up by their PetscObject name.
1338: As the MATLAB MAT-File Version 7.3 format is also a HDF5 flavor, we decided to use
1339: by default the same structure and naming of the AIJ arrays and column count
1340: within the HDF5 file. This means that a MAT file saved with -v7.3 flag, e.g.
1341: .vb
1342: save example.mat A b -v7.3
1343: .ve
1344: can be directly read by this routine (see Reference 1 for details).
1346: Depending on your MATLAB version, this format might be a default,
1347: otherwise you can set it as default in Preferences.
1349: Unless -nocompression flag is used to save the file in MATLAB,
1350: PETSc must be configured with ZLIB package.
1352: See also examples src/mat/tutorials/ex10.c and src/ksp/ksp/tutorials/ex27.c
1354: This reader currently supports only real `MATSEQAIJ`, `MATMPIAIJ`, `MATSEQDENSE` and `MATMPIDENSE` matrices for `PETSCVIEWERHDF5`
1356: Corresponding `MatView()` is not yet implemented.
1358: The loaded matrix is actually a transpose of the original one in MATLAB,
1359: unless you push `PETSC_VIEWER_HDF5_MAT` format (see examples above).
1360: With this format, matrix is automatically transposed by PETSc,
1361: unless the matrix is marked as SPD or symmetric
1362: (see `MatSetOption()`, `MAT_SPD`, `MAT_SYMMETRIC`).
1364: See MATLAB Documentation on `save()`, <https://www.mathworks.com/help/matlab/ref/save.html#btox10b-1-version>
1366: .seealso: [](ch_matrices), `Mat`, `PetscViewerBinaryOpen()`, `PetscViewerSetType()`, `MatView()`, `VecLoad()`
1367: @*/
1368: PetscErrorCode MatLoad(Mat mat, PetscViewer viewer)
1369: {
1370: PetscBool flg;
1372: PetscFunctionBegin;
1376: if (!((PetscObject)mat)->type_name) PetscCall(MatSetType(mat, MATAIJ));
1378: flg = PETSC_FALSE;
1379: PetscCall(PetscOptionsGetBool(((PetscObject)mat)->options, ((PetscObject)mat)->prefix, "-matload_symmetric", &flg, NULL));
1380: if (flg) {
1381: PetscCall(MatSetOption(mat, MAT_SYMMETRIC, PETSC_TRUE));
1382: PetscCall(MatSetOption(mat, MAT_SYMMETRY_ETERNAL, PETSC_TRUE));
1383: }
1384: flg = PETSC_FALSE;
1385: PetscCall(PetscOptionsGetBool(((PetscObject)mat)->options, ((PetscObject)mat)->prefix, "-matload_spd", &flg, NULL));
1386: if (flg) PetscCall(MatSetOption(mat, MAT_SPD, PETSC_TRUE));
1388: PetscCall(PetscLogEventBegin(MAT_Load, mat, viewer, 0, 0));
1389: PetscUseTypeMethod(mat, load, viewer);
1390: PetscCall(PetscLogEventEnd(MAT_Load, mat, viewer, 0, 0));
1391: PetscFunctionReturn(PETSC_SUCCESS);
1392: }
1394: static PetscErrorCode MatDestroy_Redundant(Mat_Redundant **redundant)
1395: {
1396: Mat_Redundant *redund = *redundant;
1398: PetscFunctionBegin;
1399: if (redund) {
1400: if (redund->matseq) { /* via MatCreateSubMatrices() */
1401: PetscCall(ISDestroy(&redund->isrow));
1402: PetscCall(ISDestroy(&redund->iscol));
1403: PetscCall(MatDestroySubMatrices(1, &redund->matseq));
1404: } else {
1405: PetscCall(PetscFree2(redund->send_rank, redund->recv_rank));
1406: PetscCall(PetscFree(redund->sbuf_j));
1407: PetscCall(PetscFree(redund->sbuf_a));
1408: for (PetscInt i = 0; i < redund->nrecvs; i++) {
1409: PetscCall(PetscFree(redund->rbuf_j[i]));
1410: PetscCall(PetscFree(redund->rbuf_a[i]));
1411: }
1412: PetscCall(PetscFree4(redund->sbuf_nz, redund->rbuf_nz, redund->rbuf_j, redund->rbuf_a));
1413: }
1415: PetscCall(PetscCommDestroy(&redund->subcomm));
1416: PetscCall(PetscFree(redund));
1417: }
1418: PetscFunctionReturn(PETSC_SUCCESS);
1419: }
1421: /*@
1422: MatDestroy - Frees space taken by a matrix.
1424: Collective
1426: Input Parameter:
1427: . A - the matrix
1429: Level: beginner
1431: Developer Note:
1432: Some special arrays of matrices are not destroyed in this routine but instead by the routines called by
1433: `MatDestroySubMatrices()`. Thus one must be sure that any changes here must also be made in those routines.
1434: `MatHeaderMerge()` and `MatHeaderReplace()` also manipulate the data in the `Mat` object and likely need changes
1435: if changes are needed here.
1437: .seealso: [](ch_matrices), `Mat`, `MatCreate()`
1438: @*/
1439: PetscErrorCode MatDestroy(Mat *A)
1440: {
1441: PetscFunctionBegin;
1442: if (!*A) PetscFunctionReturn(PETSC_SUCCESS);
1444: if (--((PetscObject)*A)->refct > 0) {
1445: *A = NULL;
1446: PetscFunctionReturn(PETSC_SUCCESS);
1447: }
1449: /* if memory was published with SAWs then destroy it */
1450: PetscCall(PetscObjectSAWsViewOff((PetscObject)*A));
1451: PetscTryTypeMethod(*A, destroy);
1453: PetscCall(PetscFree((*A)->factorprefix));
1454: PetscCall(PetscFree((*A)->defaultvectype));
1455: PetscCall(PetscFree((*A)->defaultrandtype));
1456: PetscCall(PetscFree((*A)->bsizes));
1457: PetscCall(PetscFree((*A)->solvertype));
1458: for (PetscInt i = 0; i < MAT_FACTOR_NUM_TYPES; i++) PetscCall(PetscFree((*A)->preferredordering[i]));
1459: if ((*A)->redundant && (*A)->redundant->matseq[0] == *A) (*A)->redundant->matseq[0] = NULL;
1460: PetscCall(MatDestroy_Redundant(&(*A)->redundant));
1461: PetscCall(MatProductClear(*A));
1462: PetscCall(MatNullSpaceDestroy(&(*A)->nullsp));
1463: PetscCall(MatNullSpaceDestroy(&(*A)->transnullsp));
1464: PetscCall(MatNullSpaceDestroy(&(*A)->nearnullsp));
1465: PetscCall(MatDestroy(&(*A)->schur));
1466: PetscCall(VecDestroy(&(*A)->dot_vec));
1467: PetscCall(PetscLayoutDestroy(&(*A)->rmap));
1468: PetscCall(PetscLayoutDestroy(&(*A)->cmap));
1469: PetscCall(PetscHeaderDestroy(A));
1470: PetscFunctionReturn(PETSC_SUCCESS);
1471: }
1473: // PetscClangLinter pragma disable: -fdoc-section-header-unknown
1474: /*@
1475: MatSetValues - Inserts or adds a block of values into a matrix.
1476: These values may be cached, so `MatAssemblyBegin()` and `MatAssemblyEnd()`
1477: MUST be called after all calls to `MatSetValues()` have been completed.
1479: Not Collective
1481: Input Parameters:
1482: + mat - the matrix
1483: . m - the number of rows
1484: . idxm - the global indices of the rows
1485: . n - the number of columns
1486: . idxn - the global indices of the columns
1487: . v - a one-dimensional array that contains the values implicitly stored as a two-dimensional array, by default in row-major order.
1488: See `MAT_ROW_ORIENTED` in `MatSetOption()` for how to use column-major order.
1489: - addv - either `ADD_VALUES` to add values to any existing entries, or `INSERT_VALUES` to replace existing entries with new values
1491: Level: beginner
1493: Notes:
1494: Calls to `MatSetValues()` with the `INSERT_VALUES` and `ADD_VALUES`
1495: options cannot be mixed without intervening calls to the assembly
1496: routines.
1498: `MatSetValues()` uses 0-based row and column numbers in Fortran
1499: as well as in C.
1501: Negative indices may be passed in `idxm` and `idxn`, these rows and columns are simply ignored. This allows easily inserting element stiffness matrices
1502: with homogeneous Dirichlet boundary conditions that you don't want represented
1503: in the matrix.
1505: Efficiency Alert:
1506: The routine `MatSetValuesBlocked()` may offer much better efficiency
1507: for users of block sparse formats (`MATSEQBAIJ` and `MATMPIBAIJ`).
1509: Fortran Notes:
1510: If any of `idxm`, `idxn`, and `v` are scalars pass them using, for example,
1511: .vb
1512: call MatSetValues(mat, one, [idxm], one, [idxn], [v], INSERT_VALUES, ierr)
1513: .ve
1515: If `v` is a two-dimensional array make sure to first call `MatSetOption(mat, MAT_ROW_ORIENTED, PETSC_FALSE, ierr)` before using this function,
1516: otherwise the transpose of `v` will seemingly be inserted in the matrix, since Fortran passes two-dimensional arrays with column orientation.
1518: .seealso: [](ch_matrices), `Mat`, `MatSetOption()`, `MatAssemblyBegin()`, `MatAssemblyEnd()`, `MatSetValuesBlocked()`, `MatSetValuesLocal()`,
1519: `InsertMode`, `INSERT_VALUES`, `ADD_VALUES`
1520: @*/
1521: PetscErrorCode MatSetValues(Mat mat, PetscInt m, const PetscInt idxm[], PetscInt n, const PetscInt idxn[], const PetscScalar v[], InsertMode addv)
1522: {
1523: PetscFunctionBeginHot;
1526: if (!m || !n) PetscFunctionReturn(PETSC_SUCCESS); /* no values to insert */
1527: PetscAssertPointer(idxm, 3);
1528: PetscAssertPointer(idxn, 5);
1529: MatCheckPreallocated(mat, 1);
1531: if (mat->insertmode == NOT_SET_VALUES) mat->insertmode = addv;
1532: else PetscCheck(mat->insertmode == addv, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Cannot mix add values and insert values");
1534: if (PetscDefined(USE_DEBUG)) {
1535: PetscInt i, j;
1537: PetscCheck(!mat->factortype, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
1538: if (v) {
1539: for (i = 0; i < m; i++) {
1540: for (j = 0; j < n; j++) {
1541: if (mat->erroriffailure && PetscIsInfOrNanScalar(v[i * n + j]))
1542: #if defined(PETSC_USE_COMPLEX)
1543: 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]);
1544: #else
1545: 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]);
1546: #endif
1547: }
1548: }
1549: }
1550: 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);
1551: 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);
1552: }
1554: if (mat->assembled) {
1555: mat->was_assembled = PETSC_TRUE;
1556: mat->assembled = PETSC_FALSE;
1557: }
1558: PetscCall(PetscLogEventBegin(MAT_SetValues, mat, 0, 0, 0));
1559: PetscUseTypeMethod(mat, setvalues, m, idxm, n, idxn, v, addv);
1560: PetscCall(PetscLogEventEnd(MAT_SetValues, mat, 0, 0, 0));
1561: PetscFunctionReturn(PETSC_SUCCESS);
1562: }
1564: // PetscClangLinter pragma disable: -fdoc-section-header-unknown
1565: /*@
1566: MatSetValuesIS - Inserts or adds a block of values into a matrix using an `IS` to indicate the rows and columns
1567: These values may be cached, so `MatAssemblyBegin()` and `MatAssemblyEnd()`
1568: MUST be called after all calls to `MatSetValues()` have been completed.
1570: Not Collective
1572: Input Parameters:
1573: + mat - the matrix
1574: . ism - the rows to provide
1575: . isn - the columns to provide
1576: . v - a one-dimensional array that contains the values implicitly stored as a two-dimensional array, by default in row-major order.
1577: See `MAT_ROW_ORIENTED` in `MatSetOption()` for how to use column-major order.
1578: - addv - either `ADD_VALUES` to add values to any existing entries, or `INSERT_VALUES` to replace existing entries with new values
1580: Level: beginner
1582: Notes:
1583: By default, the values, `v`, are stored in row-major order. See `MAT_ROW_ORIENTED` in `MatSetOption()` for how to use column-major order.
1585: Calls to `MatSetValues()` with the `INSERT_VALUES` and `ADD_VALUES`
1586: options cannot be mixed without intervening calls to the assembly
1587: routines.
1589: `MatSetValues()` uses 0-based row and column numbers in Fortran
1590: as well as in C.
1592: Negative indices may be passed in `ism` and `isn`, these rows and columns are
1593: simply ignored. This allows easily inserting element stiffness matrices
1594: with homogeneous Dirichlet boundary conditions that you don't want represented
1595: in the matrix.
1597: Fortran Note:
1598: If `v` is a two-dimensional array make sure to first call `MatSetOption(mat, MAT_ROW_ORIENTED, PETSC_FALSE, ierr)` before using this function,
1599: otherwise the transpose of `v` will seemingly be inserted in the matrix, since Fortran passes two-dimensional arrays with column orientation.
1601: Efficiency Alert:
1602: The routine `MatSetValuesBlocked()` may offer much better efficiency
1603: for users of block sparse formats (`MATSEQBAIJ` and `MATMPIBAIJ`).
1605: This is currently not optimized for any particular `ISType`
1607: .seealso: [](ch_matrices), `Mat`, `MatSetOption()`, `MatSetValues()`, `MatAssemblyBegin()`, `MatAssemblyEnd()`, `MatSetValuesBlocked()`, `MatSetValuesLocal()`,
1608: `InsertMode`, `INSERT_VALUES`, `ADD_VALUES`
1609: @*/
1610: PetscErrorCode MatSetValuesIS(Mat mat, IS ism, IS isn, const PetscScalar v[], InsertMode addv)
1611: {
1612: PetscInt m, n;
1613: const PetscInt *rows, *cols;
1615: PetscFunctionBeginHot;
1617: PetscCall(ISGetIndices(ism, &rows));
1618: PetscCall(ISGetIndices(isn, &cols));
1619: PetscCall(ISGetLocalSize(ism, &m));
1620: PetscCall(ISGetLocalSize(isn, &n));
1621: PetscCall(MatSetValues(mat, m, rows, n, cols, v, addv));
1622: PetscCall(ISRestoreIndices(ism, &rows));
1623: PetscCall(ISRestoreIndices(isn, &cols));
1624: PetscFunctionReturn(PETSC_SUCCESS);
1625: }
1627: /*@
1628: MatSetValuesRowLocal - Inserts a row of nonzero values into a matrix
1630: Not Collective
1632: Input Parameters:
1633: + mat - the matrix
1634: . row - the row to set
1635: - v - a one-dimensional array that contains the values
1637: Level: intermediate
1639: Notes:
1640: Currently only supported for `MATAIJ`.
1642: All the nonzero values in `row` must be provided
1644: The matrix must have previously had its column indices set, likely by having been assembled.
1646: `row` must belong to this MPI process
1648: .seealso: [](ch_matrices), `Mat`, `MatSetOption()`, `MatAssemblyBegin()`, `MatAssemblyEnd()`, `MatSetValuesBlocked()`, `MatSetValuesLocal()`,
1649: `InsertMode`, `INSERT_VALUES`, `ADD_VALUES`, `MatSetValues()`, `MatSetValuesRow()`, `MatSetLocalToGlobalMapping()`, `MATAIJ`
1650: @*/
1651: PetscErrorCode MatSetValuesRowLocal(Mat mat, PetscInt row, const PetscScalar v[])
1652: {
1653: PetscInt globalrow;
1655: PetscFunctionBegin;
1658: PetscAssertPointer(v, 3);
1659: PetscCall(ISLocalToGlobalMappingApply(mat->rmap->mapping, 1, &row, &globalrow));
1660: PetscCall(MatSetValuesRow(mat, globalrow, v));
1661: PetscFunctionReturn(PETSC_SUCCESS);
1662: }
1664: /*@
1665: MatSetValuesRow - Inserts a row of nonzero values into a matrix
1667: Not Collective
1669: Input Parameters:
1670: + mat - the matrix
1671: . row - the row to set
1672: - v - a one dimensional array of values
1674: Level: advanced
1676: Notes:
1677: Currently only supported for `MATAIJ`.
1679: All the nonzeros in `row` must be provided
1681: The matrix must have previously had its column indices set, likely by having been assembled.
1683: `row` must belong to this process
1685: .seealso: [](ch_matrices), `Mat`, `MatSetValues()`, `MatSetOption()`, `MatAssemblyBegin()`, `MatAssemblyEnd()`, `MatSetValuesBlocked()`, `MatSetValuesLocal()`,
1686: `InsertMode`, `INSERT_VALUES`, `ADD_VALUES`, `MATAIJ`
1687: @*/
1688: PetscErrorCode MatSetValuesRow(Mat mat, PetscInt row, const PetscScalar v[])
1689: {
1690: PetscFunctionBeginHot;
1693: MatCheckPreallocated(mat, 1);
1694: PetscAssertPointer(v, 3);
1695: PetscCheck(mat->insertmode != ADD_VALUES, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Cannot mix add and insert values");
1696: PetscCheck(!mat->factortype, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
1697: mat->insertmode = INSERT_VALUES;
1699: if (mat->assembled) {
1700: mat->was_assembled = PETSC_TRUE;
1701: mat->assembled = PETSC_FALSE;
1702: }
1703: PetscCall(PetscLogEventBegin(MAT_SetValues, mat, 0, 0, 0));
1704: PetscUseTypeMethod(mat, setvaluesrow, row, v);
1705: PetscCall(PetscLogEventEnd(MAT_SetValues, mat, 0, 0, 0));
1706: PetscFunctionReturn(PETSC_SUCCESS);
1707: }
1709: // PetscClangLinter pragma disable: -fdoc-section-header-unknown
1710: /*@
1711: MatSetValuesStencil - Inserts or adds a block of values into a matrix.
1712: Using structured grid indexing
1714: Not Collective
1716: Input Parameters:
1717: + mat - the matrix
1718: . m - number of rows being entered
1719: . idxm - grid coordinates (and component number when dof > 1) for matrix rows being entered
1720: . n - number of columns being entered
1721: . idxn - grid coordinates (and component number when dof > 1) for matrix columns being entered
1722: . v - a one-dimensional array that contains the values implicitly stored as a two-dimensional array, by default in row-major order.
1723: See `MAT_ROW_ORIENTED` in `MatSetOption()` for how to use column-major order.
1724: - addv - either `ADD_VALUES` to add to existing entries at that location or `INSERT_VALUES` to replace existing entries with new values
1726: Level: beginner
1728: Notes:
1729: By default the values, `v`, are row-oriented. See `MatSetOption()` for other options.
1731: Calls to `MatSetValuesStencil()` with the `INSERT_VALUES` and `ADD_VALUES`
1732: options cannot be mixed without intervening calls to the assembly
1733: routines.
1735: The grid coordinates are across the entire grid, not just the local portion
1737: `MatSetValuesStencil()` uses 0-based row and column numbers in Fortran
1738: as well as in C.
1740: For setting/accessing vector values via array coordinates you can use the `DMDAVecGetArray()` routine
1742: In order to use this routine you must either obtain the matrix with `DMCreateMatrix()`
1743: or call `MatSetLocalToGlobalMapping()` and `MatSetStencil()` first.
1745: The columns and rows in the stencil passed in MUST be contained within the
1746: ghost region of the given process as set with DMDACreateXXX() or `MatSetStencil()`. For example,
1747: if you create a `DMDA` with an overlap of one grid level and on a particular process its first
1748: local nonghost x logical coordinate is 6 (so its first ghost x logical coordinate is 5) the
1749: first i index you can use in your column and row indices in `MatSetStencil()` is 5.
1751: For periodic boundary conditions use negative indices for values to the left (below 0; that are to be
1752: obtained by wrapping values from right edge). For values to the right of the last entry using that index plus one
1753: etc to obtain values that obtained by wrapping the values from the left edge. This does not work for anything but the
1754: `DM_BOUNDARY_PERIODIC` boundary type.
1756: 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
1757: a single value per point) you can skip filling those indices.
1759: Inspired by the structured grid interface to the HYPRE package
1760: (https://computation.llnl.gov/projects/hypre-scalable-linear-solvers-multigrid-methods)
1762: Fortran Notes:
1763: If any of `idxm`, `idxn`, and `v` are scalars pass them using, for example,
1764: .vb
1765: call MatSetValuesStencil(mat, one, [idxm], one, [idxn], [v], INSERT_VALUES, ierr)
1766: .ve
1768: If `v` is a two-dimensional array make sure to first call `MatSetOption(mat, MAT_ROW_ORIENTED, PETSC_FALSE, ierr)` before using this function,
1769: otherwise the transpose of `v` will seemingly be inserted in the matrix, since Fortran passes two-dimensional arrays with column orientation.
1771: Efficiency Alert:
1772: The routine `MatSetValuesBlockedStencil()` may offer much better efficiency
1773: for users of block sparse formats (`MATSEQBAIJ` and `MATMPIBAIJ`).
1775: .seealso: [](ch_matrices), `Mat`, `DMDA`, `MatSetOption()`, `MatAssemblyBegin()`, `MatAssemblyEnd()`, `MatSetValuesBlocked()`, `MatSetValuesLocal()`,
1776: `MatSetValues()`, `MatSetValuesBlockedStencil()`, `MatSetStencil()`, `DMCreateMatrix()`, `DMDAVecGetArray()`, `MatStencil`
1777: @*/
1778: PetscErrorCode MatSetValuesStencil(Mat mat, PetscInt m, const MatStencil idxm[], PetscInt n, const MatStencil idxn[], const PetscScalar v[], InsertMode addv)
1779: {
1780: PetscInt buf[8192], *bufm = NULL, *bufn = NULL, *jdxm, *jdxn;
1781: PetscInt j, i, dim = mat->stencil.dim, *dims = mat->stencil.dims + 1, tmp;
1782: PetscInt *starts = mat->stencil.starts, *dxm = (PetscInt *)idxm, *dxn = (PetscInt *)idxn, sdim = dim - (1 - (PetscInt)mat->stencil.noc);
1784: PetscFunctionBegin;
1785: if (!m || !n) PetscFunctionReturn(PETSC_SUCCESS); /* no values to insert */
1788: PetscAssertPointer(idxm, 3);
1789: PetscAssertPointer(idxn, 5);
1791: if ((m + n) <= (PetscInt)PETSC_STATIC_ARRAY_LENGTH(buf)) {
1792: jdxm = buf;
1793: jdxn = buf + m;
1794: } else {
1795: PetscCall(PetscMalloc2(m, &bufm, n, &bufn));
1796: jdxm = bufm;
1797: jdxn = bufn;
1798: }
1799: for (i = 0; i < m; i++) {
1800: for (j = 0; j < 3 - sdim; j++) dxm++;
1801: tmp = *dxm++ - starts[0];
1802: for (j = 0; j < dim - 1; j++) {
1803: if ((*dxm++ - starts[j + 1]) < 0 || tmp < 0) tmp = -1;
1804: else tmp = tmp * dims[j] + *(dxm - 1) - starts[j + 1];
1805: }
1806: if (mat->stencil.noc) dxm++;
1807: jdxm[i] = tmp;
1808: }
1809: for (i = 0; i < n; i++) {
1810: for (j = 0; j < 3 - sdim; j++) dxn++;
1811: tmp = *dxn++ - starts[0];
1812: for (j = 0; j < dim - 1; j++) {
1813: if ((*dxn++ - starts[j + 1]) < 0 || tmp < 0) tmp = -1;
1814: else tmp = tmp * dims[j] + *(dxn - 1) - starts[j + 1];
1815: }
1816: if (mat->stencil.noc) dxn++;
1817: jdxn[i] = tmp;
1818: }
1819: PetscCall(MatSetValuesLocal(mat, m, jdxm, n, jdxn, v, addv));
1820: PetscCall(PetscFree2(bufm, bufn));
1821: PetscFunctionReturn(PETSC_SUCCESS);
1822: }
1824: /*@
1825: MatSetValuesBlockedStencil - Inserts or adds a block of values into a matrix.
1826: Using structured grid indexing
1828: Not Collective
1830: Input Parameters:
1831: + mat - the matrix
1832: . m - number of rows being entered
1833: . idxm - grid coordinates for matrix rows being entered
1834: . n - number of columns being entered
1835: . idxn - grid coordinates for matrix columns being entered
1836: . v - a one-dimensional array that contains the values implicitly stored as a two-dimensional array, by default in row-major order.
1837: See `MAT_ROW_ORIENTED` in `MatSetOption()` for how to use column-major order.
1838: - addv - either `ADD_VALUES` to add to existing entries or `INSERT_VALUES` to replace existing entries with new values
1840: Level: beginner
1842: Notes:
1843: By default the values, `v`, are row-oriented and unsorted.
1844: See `MatSetOption()` for other options.
1846: Calls to `MatSetValuesBlockedStencil()` with the `INSERT_VALUES` and `ADD_VALUES`
1847: options cannot be mixed without intervening calls to the assembly
1848: routines.
1850: The grid coordinates are across the entire grid, not just the local portion
1852: `MatSetValuesBlockedStencil()` uses 0-based row and column numbers in Fortran
1853: as well as in C.
1855: For setting/accessing vector values via array coordinates you can use the `DMDAVecGetArray()` routine
1857: In order to use this routine you must either obtain the matrix with `DMCreateMatrix()`
1858: or call `MatSetBlockSize()`, `MatSetLocalToGlobalMapping()` and `MatSetStencil()` first.
1860: The columns and rows in the stencil passed in MUST be contained within the
1861: ghost region of the given process as set with DMDACreateXXX() or `MatSetStencil()`. For example,
1862: if you create a `DMDA` with an overlap of one grid level and on a particular process its first
1863: local nonghost x logical coordinate is 6 (so its first ghost x logical coordinate is 5) the
1864: first i index you can use in your column and row indices in `MatSetStencil()` is 5.
1866: Negative indices may be passed in `idxm` and `idxn`, these rows and columns are
1867: simply ignored. This allows easily inserting element stiffness matrices
1868: with homogeneous Dirichlet boundary conditions that you don't want represented
1869: in the matrix.
1871: Inspired by the structured grid interface to the HYPRE package
1872: (https://computation.llnl.gov/projects/hypre-scalable-linear-solvers-multigrid-methods)
1874: Fortran Notes:
1875: If any of `idxm`, `idxn`, and `v` are scalars pass them using, for example,
1876: .vb
1877: call MatSetValuesBlockedStencil(mat, one, [idxm], one, [idxn], [v], INSERT_VALUES, ierr)
1878: .ve
1880: If `v` is a two-dimensional array make sure to first call `MatSetOption(mat, MAT_ROW_ORIENTED, PETSC_FALSE, ierr)` before using this function,
1881: otherwise the transpose of `v` will seemingly be inserted in the matrix, since Fortran passes two-dimensional arrays with column orientation.
1883: .seealso: [](ch_matrices), `Mat`, `DMDA`, `MatSetOption()`, `MatAssemblyBegin()`, `MatAssemblyEnd()`, `MatSetValuesBlocked()`, `MatSetValuesLocal()`,
1884: `MatSetValues()`, `MatSetValuesStencil()`, `MatSetStencil()`, `DMCreateMatrix()`, `DMDAVecGetArray()`, `MatStencil`,
1885: `MatSetBlockSize()`, `MatSetLocalToGlobalMapping()`
1886: @*/
1887: PetscErrorCode MatSetValuesBlockedStencil(Mat mat, PetscInt m, const MatStencil idxm[], PetscInt n, const MatStencil idxn[], const PetscScalar v[], InsertMode addv)
1888: {
1889: PetscInt buf[8192], *bufm = NULL, *bufn = NULL, *jdxm, *jdxn;
1890: PetscInt j, i, dim = mat->stencil.dim, *dims = mat->stencil.dims + 1, tmp;
1891: PetscInt *starts = mat->stencil.starts, *dxm = (PetscInt *)idxm, *dxn = (PetscInt *)idxn, sdim = dim - (1 - (PetscInt)mat->stencil.noc);
1893: PetscFunctionBegin;
1894: if (!m || !n) PetscFunctionReturn(PETSC_SUCCESS); /* no values to insert */
1897: PetscAssertPointer(idxm, 3);
1898: PetscAssertPointer(idxn, 5);
1899: PetscAssertPointer(v, 6);
1901: if ((m + n) <= (PetscInt)PETSC_STATIC_ARRAY_LENGTH(buf)) {
1902: jdxm = buf;
1903: jdxn = buf + m;
1904: } else {
1905: PetscCall(PetscMalloc2(m, &bufm, n, &bufn));
1906: jdxm = bufm;
1907: jdxn = bufn;
1908: }
1909: for (i = 0; i < m; i++) {
1910: for (j = 0; j < 3 - sdim; j++) dxm++;
1911: tmp = *dxm++ - starts[0];
1912: for (j = 0; j < sdim - 1; j++) {
1913: if ((*dxm++ - starts[j + 1]) < 0 || tmp < 0) tmp = -1;
1914: else tmp = tmp * dims[j] + *(dxm - 1) - starts[j + 1];
1915: }
1916: dxm++;
1917: jdxm[i] = tmp;
1918: }
1919: for (i = 0; i < n; i++) {
1920: for (j = 0; j < 3 - sdim; j++) dxn++;
1921: tmp = *dxn++ - starts[0];
1922: for (j = 0; j < sdim - 1; j++) {
1923: if ((*dxn++ - starts[j + 1]) < 0 || tmp < 0) tmp = -1;
1924: else tmp = tmp * dims[j] + *(dxn - 1) - starts[j + 1];
1925: }
1926: dxn++;
1927: jdxn[i] = tmp;
1928: }
1929: PetscCall(MatSetValuesBlockedLocal(mat, m, jdxm, n, jdxn, v, addv));
1930: PetscCall(PetscFree2(bufm, bufn));
1931: PetscFunctionReturn(PETSC_SUCCESS);
1932: }
1934: /*@
1935: MatSetStencil - Sets the grid information for setting values into a matrix via
1936: `MatSetValuesStencil()`
1938: Not Collective
1940: Input Parameters:
1941: + mat - the matrix
1942: . dim - dimension of the grid 1, 2, or 3
1943: . dims - number of grid points in x, y, and z direction, including ghost points on your processor
1944: . starts - starting point of ghost nodes on your processor in x, y, and z direction
1945: - dof - number of degrees of freedom per node
1947: Level: beginner
1949: Notes:
1950: Inspired by the structured grid interface to the HYPRE package
1951: (www.llnl.gov/CASC/hyper)
1953: For matrices generated with `DMCreateMatrix()` this routine is automatically called and so not needed by the
1954: user.
1956: .seealso: [](ch_matrices), `Mat`, `MatStencil`, `MatSetOption()`, `MatAssemblyBegin()`, `MatAssemblyEnd()`, `MatSetValuesBlocked()`, `MatSetValuesLocal()`,
1957: `MatSetValues()`, `MatSetValuesBlockedStencil()`, `MatSetValuesStencil()`
1958: @*/
1959: PetscErrorCode MatSetStencil(Mat mat, PetscInt dim, const PetscInt dims[], const PetscInt starts[], PetscInt dof)
1960: {
1961: PetscFunctionBegin;
1963: PetscAssertPointer(dims, 3);
1964: PetscAssertPointer(starts, 4);
1966: mat->stencil.dim = dim + (dof > 1);
1967: for (PetscInt i = 0; i < dim; i++) {
1968: mat->stencil.dims[i] = dims[dim - i - 1]; /* copy the values in backwards */
1969: mat->stencil.starts[i] = starts[dim - i - 1];
1970: }
1971: mat->stencil.dims[dim] = dof;
1972: mat->stencil.starts[dim] = 0;
1973: mat->stencil.noc = (PetscBool)(dof == 1);
1974: PetscFunctionReturn(PETSC_SUCCESS);
1975: }
1977: /*@
1978: MatSetValuesBlocked - Inserts or adds a block of values into a matrix.
1980: Not Collective
1982: Input Parameters:
1983: + mat - the matrix
1984: . m - the number of block rows
1985: . idxm - the global block indices
1986: . n - the number of block columns
1987: . idxn - the global block indices
1988: . v - a one-dimensional array that contains the values implicitly stored as a two-dimensional array, by default in row-major order.
1989: See `MAT_ROW_ORIENTED` in `MatSetOption()` for how to use column-major order.
1990: - addv - either `ADD_VALUES` to add values to any existing entries, or `INSERT_VALUES` replaces existing entries with new values
1992: Level: intermediate
1994: Notes:
1995: If you create the matrix yourself (that is not with a call to `DMCreateMatrix()`) then you MUST call
1996: MatXXXXSetPreallocation() or `MatSetUp()` before using this routine.
1998: The `m` and `n` count the NUMBER of blocks in the row direction and column direction,
1999: NOT the total number of rows/columns; for example, if the block size is 2 and
2000: you are passing in values for rows 2,3,4,5 then `m` would be 2 (not 4).
2001: The values in `idxm` would be 1 2; that is the first index for each block divided by
2002: the block size.
2004: You must call `MatSetBlockSize()` when constructing this matrix (before
2005: preallocating it).
2007: By default, the values, `v`, are stored in row-major order. See `MAT_ROW_ORIENTED` in `MatSetOption()` for how to use column-major order.
2009: Calls to `MatSetValuesBlocked()` with the `INSERT_VALUES` and `ADD_VALUES`
2010: options cannot be mixed without intervening calls to the assembly
2011: routines.
2013: `MatSetValuesBlocked()` uses 0-based row and column numbers in Fortran
2014: as well as in C.
2016: Negative indices may be passed in `idxm` and `idxn`, these rows and columns are
2017: simply ignored. This allows easily inserting element stiffness matrices
2018: with homogeneous Dirichlet boundary conditions that you don't want represented
2019: in the matrix.
2021: Each time an entry is set within a sparse matrix via `MatSetValues()`,
2022: internal searching must be done to determine where to place the
2023: data in the matrix storage space. By instead inserting blocks of
2024: entries via `MatSetValuesBlocked()`, the overhead of matrix assembly is
2025: reduced.
2027: Example:
2028: .vb
2029: Suppose m=n=2 and block size(bs) = 2 The array is
2031: 1 2 | 3 4
2032: 5 6 | 7 8
2033: - - - | - - -
2034: 9 10 | 11 12
2035: 13 14 | 15 16
2037: v[] should be passed in like
2038: v[] = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]
2040: If you are not using row-oriented storage of v (that is you called MatSetOption(mat,MAT_ROW_ORIENTED,PETSC_FALSE)) then
2041: v[] = [1,5,9,13,2,6,10,14,3,7,11,15,4,8,12,16]
2042: .ve
2044: Fortran Notes:
2045: If any of `idmx`, `idxn`, and `v` are scalars pass them using, for example,
2046: .vb
2047: call MatSetValuesBlocked(mat, one, [idxm], one, [idxn], [v], INSERT_VALUES, ierr)
2048: .ve
2050: If `v` is a two-dimensional array make sure to first call `MatSetOption(mat, MAT_ROW_ORIENTED, PETSC_FALSE, ierr)` before using this function,
2051: otherwise the transpose of `v` will seemingly be inserted in the matrix, since Fortran passes two-dimensional arrays with column orientation.
2053: .seealso: [](ch_matrices), `Mat`, `MatSetBlockSize()`, `MatSetOption()`, `MatAssemblyBegin()`, `MatAssemblyEnd()`, `MatSetValues()`, `MatSetValuesBlockedLocal()`
2054: @*/
2055: PetscErrorCode MatSetValuesBlocked(Mat mat, PetscInt m, const PetscInt idxm[], PetscInt n, const PetscInt idxn[], const PetscScalar v[], InsertMode addv)
2056: {
2057: PetscFunctionBeginHot;
2060: if (!m || !n) PetscFunctionReturn(PETSC_SUCCESS); /* no values to insert */
2061: PetscAssertPointer(idxm, 3);
2062: PetscAssertPointer(idxn, 5);
2063: MatCheckPreallocated(mat, 1);
2064: if (mat->insertmode == NOT_SET_VALUES) mat->insertmode = addv;
2065: else PetscCheck(mat->insertmode == addv, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Cannot mix add values and insert values");
2066: if (PetscDefined(USE_DEBUG)) {
2067: PetscCheck(!mat->factortype, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
2068: PetscCheck(mat->ops->setvaluesblocked || mat->ops->setvalues, PETSC_COMM_SELF, PETSC_ERR_SUP, "Mat type %s", ((PetscObject)mat)->type_name);
2069: }
2070: if (PetscDefined(USE_DEBUG)) {
2071: PetscInt rbs, cbs, M, N, i;
2072: PetscCall(MatGetBlockSizes(mat, &rbs, &cbs));
2073: PetscCall(MatGetSize(mat, &M, &N));
2074: 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);
2075: for (i = 0; i < n; i++)
2076: 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);
2077: }
2078: if (mat->assembled) {
2079: mat->was_assembled = PETSC_TRUE;
2080: mat->assembled = PETSC_FALSE;
2081: }
2082: PetscCall(PetscLogEventBegin(MAT_SetValues, mat, 0, 0, 0));
2083: if (mat->ops->setvaluesblocked) PetscUseTypeMethod(mat, setvaluesblocked, m, idxm, n, idxn, v, addv);
2084: else {
2085: PetscInt buf[8192], *bufr = NULL, *bufc = NULL, *iidxm, *iidxn;
2086: PetscInt i, j, bs, cbs;
2088: PetscCall(MatGetBlockSizes(mat, &bs, &cbs));
2089: if ((m * bs + n * cbs) <= (PetscInt)PETSC_STATIC_ARRAY_LENGTH(buf)) {
2090: iidxm = buf;
2091: iidxn = buf + m * bs;
2092: } else {
2093: PetscCall(PetscMalloc2(m * bs, &bufr, n * cbs, &bufc));
2094: iidxm = bufr;
2095: iidxn = bufc;
2096: }
2097: for (i = 0; i < m; i++) {
2098: for (j = 0; j < bs; j++) iidxm[i * bs + j] = bs * idxm[i] + j;
2099: }
2100: if (m != n || bs != cbs || idxm != idxn) {
2101: for (i = 0; i < n; i++) {
2102: for (j = 0; j < cbs; j++) iidxn[i * cbs + j] = cbs * idxn[i] + j;
2103: }
2104: } else iidxn = iidxm;
2105: PetscCall(MatSetValues(mat, m * bs, iidxm, n * cbs, iidxn, v, addv));
2106: PetscCall(PetscFree2(bufr, bufc));
2107: }
2108: PetscCall(PetscLogEventEnd(MAT_SetValues, mat, 0, 0, 0));
2109: PetscFunctionReturn(PETSC_SUCCESS);
2110: }
2112: /*@
2113: MatGetValues - Gets a block of local values from a matrix.
2115: Not Collective; can only return values that are owned by the give process
2117: Input Parameters:
2118: + mat - the matrix
2119: . v - a logically two-dimensional array for storing the values
2120: . m - the number of rows
2121: . idxm - the global indices of the rows
2122: . n - the number of columns
2123: - idxn - the global indices of the columns
2125: Level: advanced
2127: Notes:
2128: The user must allocate space (m*n `PetscScalar`s) for the values, `v`.
2129: The values, `v`, are then returned in a row-oriented format,
2130: analogous to that used by default in `MatSetValues()`.
2132: `MatGetValues()` uses 0-based row and column numbers in
2133: Fortran as well as in C.
2135: `MatGetValues()` requires that the matrix has been assembled
2136: with `MatAssemblyBegin()`/`MatAssemblyEnd()`. Thus, calls to
2137: `MatSetValues()` and `MatGetValues()` CANNOT be made in succession
2138: without intermediate matrix assembly.
2140: Negative row or column indices will be ignored and those locations in `v` will be
2141: left unchanged.
2143: For the standard row-based matrix formats, `idxm` can only contain rows owned by the requesting MPI process.
2144: That is, rows with global index greater than or equal to rstart and less than rend where rstart and rend are obtainable
2145: from `MatGetOwnershipRange`(mat,&rstart,&rend).
2147: .seealso: [](ch_matrices), `Mat`, `MatGetRow()`, `MatCreateSubMatrices()`, `MatSetValues()`, `MatGetOwnershipRange()`, `MatGetValuesLocal()`, `MatGetValue()`
2148: @*/
2149: PetscErrorCode MatGetValues(Mat mat, PetscInt m, const PetscInt idxm[], PetscInt n, const PetscInt idxn[], PetscScalar v[])
2150: {
2151: PetscFunctionBegin;
2154: if (!m || !n) PetscFunctionReturn(PETSC_SUCCESS);
2155: PetscAssertPointer(idxm, 3);
2156: PetscAssertPointer(idxn, 5);
2157: PetscAssertPointer(v, 6);
2158: PetscCheck(mat->assembled, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
2159: PetscCheck(!mat->factortype, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
2160: MatCheckPreallocated(mat, 1);
2162: PetscCall(PetscLogEventBegin(MAT_GetValues, mat, 0, 0, 0));
2163: PetscUseTypeMethod(mat, getvalues, m, idxm, n, idxn, v);
2164: PetscCall(PetscLogEventEnd(MAT_GetValues, mat, 0, 0, 0));
2165: PetscFunctionReturn(PETSC_SUCCESS);
2166: }
2168: /*@
2169: MatGetValuesLocal - retrieves values from certain locations in a matrix using the local numbering of the indices
2170: defined previously by `MatSetLocalToGlobalMapping()`
2172: Not Collective
2174: Input Parameters:
2175: + mat - the matrix
2176: . nrow - number of rows
2177: . irow - the row local indices
2178: . ncol - number of columns
2179: - icol - the column local indices
2181: Output Parameter:
2182: . y - a one-dimensional array that contains the values implicitly stored as a two-dimensional array, by default in row-major order.
2183: See `MAT_ROW_ORIENTED` in `MatSetOption()` for how to use column-major order.
2185: Level: advanced
2187: Notes:
2188: If you create the matrix yourself (that is not with a call to `DMCreateMatrix()`) then you MUST call `MatSetLocalToGlobalMapping()` before using this routine.
2190: 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,
2191: are greater than or equal to rstart and less than rend where rstart and rend are obtainable from `MatGetOwnershipRange`(mat,&rstart,&rend). One can
2192: determine if the resulting global row associated with the local row r is owned by the requesting MPI process by applying the `ISLocalToGlobalMapping` set
2193: with `MatSetLocalToGlobalMapping()`.
2195: .seealso: [](ch_matrices), `Mat`, `MatAssemblyBegin()`, `MatAssemblyEnd()`, `MatSetValues()`, `MatSetLocalToGlobalMapping()`,
2196: `MatSetValuesLocal()`, `MatGetValues()`
2197: @*/
2198: PetscErrorCode MatGetValuesLocal(Mat mat, PetscInt nrow, const PetscInt irow[], PetscInt ncol, const PetscInt icol[], PetscScalar y[])
2199: {
2200: PetscFunctionBeginHot;
2203: MatCheckPreallocated(mat, 1);
2204: if (!nrow || !ncol) PetscFunctionReturn(PETSC_SUCCESS); /* no values to retrieve */
2205: PetscAssertPointer(irow, 3);
2206: PetscAssertPointer(icol, 5);
2207: if (PetscDefined(USE_DEBUG)) {
2208: PetscCheck(!mat->factortype, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
2209: PetscCheck(mat->ops->getvalueslocal || mat->ops->getvalues, PETSC_COMM_SELF, PETSC_ERR_SUP, "Mat type %s", ((PetscObject)mat)->type_name);
2210: }
2211: PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
2212: PetscCall(PetscLogEventBegin(MAT_GetValues, mat, 0, 0, 0));
2213: if (mat->ops->getvalueslocal) PetscUseTypeMethod(mat, getvalueslocal, nrow, irow, ncol, icol, y);
2214: else {
2215: PetscInt buf[8192], *bufr = NULL, *bufc = NULL, *irowm, *icolm;
2216: if ((nrow + ncol) <= (PetscInt)PETSC_STATIC_ARRAY_LENGTH(buf)) {
2217: irowm = buf;
2218: icolm = buf + nrow;
2219: } else {
2220: PetscCall(PetscMalloc2(nrow, &bufr, ncol, &bufc));
2221: irowm = bufr;
2222: icolm = bufc;
2223: }
2224: PetscCheck(mat->rmap->mapping, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "MatGetValuesLocal() cannot proceed without local-to-global row mapping (See MatSetLocalToGlobalMapping()).");
2225: PetscCheck(mat->cmap->mapping, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "MatGetValuesLocal() cannot proceed without local-to-global column mapping (See MatSetLocalToGlobalMapping()).");
2226: PetscCall(ISLocalToGlobalMappingApply(mat->rmap->mapping, nrow, irow, irowm));
2227: PetscCall(ISLocalToGlobalMappingApply(mat->cmap->mapping, ncol, icol, icolm));
2228: PetscCall(MatGetValues(mat, nrow, irowm, ncol, icolm, y));
2229: PetscCall(PetscFree2(bufr, bufc));
2230: }
2231: PetscCall(PetscLogEventEnd(MAT_GetValues, mat, 0, 0, 0));
2232: PetscFunctionReturn(PETSC_SUCCESS);
2233: }
2235: /*@
2236: MatSetValuesBatch - Adds (`ADD_VALUES`) many blocks of values into a matrix at once. The blocks must all be square and
2237: the same size. Currently, this can only be called once and creates the given matrix.
2239: Not Collective
2241: Input Parameters:
2242: + mat - the matrix
2243: . nb - the number of blocks
2244: . bs - the number of rows (and columns) in each block
2245: . rows - a concatenation of the rows for each block
2246: - v - a concatenation of logically two-dimensional arrays of values
2248: Level: advanced
2250: Notes:
2251: `MatSetPreallocationCOO()` and `MatSetValuesCOO()` may be a better way to provide the values
2253: In the future, we will extend this routine to handle rectangular blocks, and to allow multiple calls for a given matrix.
2255: .seealso: [](ch_matrices), `Mat`, `MatSetOption()`, `MatAssemblyBegin()`, `MatAssemblyEnd()`, `MatSetValuesBlocked()`, `MatSetValuesLocal()`,
2256: `InsertMode`, `INSERT_VALUES`, `ADD_VALUES`, `MatSetValues()`, `MatSetPreallocationCOO()`, `MatSetValuesCOO()`
2257: @*/
2258: PetscErrorCode MatSetValuesBatch(Mat mat, PetscInt nb, PetscInt bs, PetscInt rows[], const PetscScalar v[])
2259: {
2260: PetscFunctionBegin;
2263: PetscAssertPointer(rows, 4);
2264: PetscAssertPointer(v, 5);
2265: PetscAssert(!mat->factortype, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
2267: PetscCall(PetscLogEventBegin(MAT_SetValuesBatch, mat, 0, 0, 0));
2268: for (PetscInt b = 0; b < nb; ++b) PetscCall(MatSetValues(mat, bs, &rows[b * bs], bs, &rows[b * bs], &v[b * bs * bs], ADD_VALUES));
2269: PetscCall(PetscLogEventEnd(MAT_SetValuesBatch, mat, 0, 0, 0));
2270: PetscFunctionReturn(PETSC_SUCCESS);
2271: }
2273: /*@
2274: MatSetLocalToGlobalMapping - Sets a local-to-global numbering for use by
2275: the routine `MatSetValuesLocal()` to allow users to insert matrix entries
2276: using a local (per-processor) numbering.
2278: Not Collective
2280: Input Parameters:
2281: + x - the matrix
2282: . rmapping - row mapping created with `ISLocalToGlobalMappingCreate()` or `ISLocalToGlobalMappingCreateIS()`
2283: - cmapping - column mapping
2285: Level: intermediate
2287: Note:
2288: If the matrix is obtained with `DMCreateMatrix()` then this may already have been called on the matrix
2290: .seealso: [](ch_matrices), `Mat`, `DM`, `DMCreateMatrix()`, `MatGetLocalToGlobalMapping()`, `MatAssemblyBegin()`, `MatAssemblyEnd()`, `MatSetValues()`, `MatSetValuesLocal()`, `MatGetValuesLocal()`
2291: @*/
2292: PetscErrorCode MatSetLocalToGlobalMapping(Mat x, ISLocalToGlobalMapping rmapping, ISLocalToGlobalMapping cmapping)
2293: {
2294: PetscFunctionBegin;
2299: if (x->ops->setlocaltoglobalmapping) PetscUseTypeMethod(x, setlocaltoglobalmapping, rmapping, cmapping);
2300: else {
2301: PetscCall(PetscLayoutSetISLocalToGlobalMapping(x->rmap, rmapping));
2302: PetscCall(PetscLayoutSetISLocalToGlobalMapping(x->cmap, cmapping));
2303: }
2304: PetscFunctionReturn(PETSC_SUCCESS);
2305: }
2307: /*@
2308: MatGetLocalToGlobalMapping - Gets the local-to-global numbering set by `MatSetLocalToGlobalMapping()`
2310: Not Collective
2312: Input Parameter:
2313: . A - the matrix
2315: Output Parameters:
2316: + rmapping - row mapping
2317: - cmapping - column mapping
2319: Level: advanced
2321: .seealso: [](ch_matrices), `Mat`, `MatSetLocalToGlobalMapping()`, `MatSetValuesLocal()`
2322: @*/
2323: PetscErrorCode MatGetLocalToGlobalMapping(Mat A, ISLocalToGlobalMapping *rmapping, ISLocalToGlobalMapping *cmapping)
2324: {
2325: PetscFunctionBegin;
2328: if (rmapping) {
2329: PetscAssertPointer(rmapping, 2);
2330: *rmapping = A->rmap->mapping;
2331: }
2332: if (cmapping) {
2333: PetscAssertPointer(cmapping, 3);
2334: *cmapping = A->cmap->mapping;
2335: }
2336: PetscFunctionReturn(PETSC_SUCCESS);
2337: }
2339: /*@
2340: MatSetLayouts - Sets the `PetscLayout` objects for rows and columns of a matrix
2342: Logically Collective
2344: Input Parameters:
2345: + A - the matrix
2346: . rmap - row layout
2347: - cmap - column layout
2349: Level: advanced
2351: Note:
2352: The `PetscLayout` objects are usually created automatically for the matrix so this routine rarely needs to be called.
2354: .seealso: [](ch_matrices), `Mat`, `PetscLayout`, `MatCreateVecs()`, `MatGetLocalToGlobalMapping()`, `MatGetLayouts()`
2355: @*/
2356: PetscErrorCode MatSetLayouts(Mat A, PetscLayout rmap, PetscLayout cmap)
2357: {
2358: PetscFunctionBegin;
2360: PetscCall(PetscLayoutReference(rmap, &A->rmap));
2361: PetscCall(PetscLayoutReference(cmap, &A->cmap));
2362: PetscFunctionReturn(PETSC_SUCCESS);
2363: }
2365: /*@
2366: MatGetLayouts - Gets the `PetscLayout` objects for rows and columns
2368: Not Collective
2370: Input Parameter:
2371: . A - the matrix
2373: Output Parameters:
2374: + rmap - row layout
2375: - cmap - column layout
2377: Level: advanced
2379: .seealso: [](ch_matrices), `Mat`, [Matrix Layouts](sec_matlayout), `PetscLayout`, `MatCreateVecs()`, `MatGetLocalToGlobalMapping()`, `MatSetLayouts()`
2380: @*/
2381: PetscErrorCode MatGetLayouts(Mat A, PetscLayout *rmap, PetscLayout *cmap)
2382: {
2383: PetscFunctionBegin;
2386: if (rmap) {
2387: PetscAssertPointer(rmap, 2);
2388: *rmap = A->rmap;
2389: }
2390: if (cmap) {
2391: PetscAssertPointer(cmap, 3);
2392: *cmap = A->cmap;
2393: }
2394: PetscFunctionReturn(PETSC_SUCCESS);
2395: }
2397: /*@
2398: MatSetValuesLocal - Inserts or adds values into certain locations of a matrix,
2399: using a local numbering of the rows and columns.
2401: Not Collective
2403: Input Parameters:
2404: + mat - the matrix
2405: . nrow - number of rows
2406: . irow - the row local indices
2407: . ncol - number of columns
2408: . icol - the column local indices
2409: . v - a one-dimensional array that contains the values implicitly stored as a two-dimensional array, by default in row-major order.
2410: See `MAT_ROW_ORIENTED` in `MatSetOption()` for how to use column-major order.
2411: - addv - either `ADD_VALUES` to add values to any existing entries, or `INSERT_VALUES` to replace existing entries with new values
2413: Level: intermediate
2415: Notes:
2416: If you create the matrix yourself (that is not with a call to `DMCreateMatrix()`) then you MUST call `MatSetLocalToGlobalMapping()` before using this routine
2418: Calls to `MatSetValuesLocal()` with the `INSERT_VALUES` and `ADD_VALUES`
2419: options cannot be mixed without intervening calls to the assembly
2420: routines.
2422: These values may be cached, so `MatAssemblyBegin()` and `MatAssemblyEnd()`
2423: MUST be called after all calls to `MatSetValuesLocal()` have been completed.
2425: Fortran Notes:
2426: If any of `irow`, `icol`, and `v` are scalars pass them using, for example,
2427: .vb
2428: call MatSetValuesLocal(mat, one, [irow], one, [icol], [v], INSERT_VALUES, ierr)
2429: .ve
2431: If `v` is a two-dimensional array make sure to first call `MatSetOption(mat, MAT_ROW_ORIENTED, PETSC_FALSE, ierr)` before using this function,
2432: otherwise the transpose of `v` will seemingly be inserted in the matrix, since Fortran passes two-dimensional arrays with column orientation.
2434: .seealso: [](ch_matrices), `Mat`, `MatAssemblyBegin()`, `MatAssemblyEnd()`, `MatSetValues()`, `MatSetLocalToGlobalMapping()`,
2435: `MatGetValuesLocal()`
2436: @*/
2437: PetscErrorCode MatSetValuesLocal(Mat mat, PetscInt nrow, const PetscInt irow[], PetscInt ncol, const PetscInt icol[], const PetscScalar v[], InsertMode addv)
2438: {
2439: PetscFunctionBeginHot;
2442: MatCheckPreallocated(mat, 1);
2443: if (!nrow || !ncol) PetscFunctionReturn(PETSC_SUCCESS); /* no values to insert */
2444: PetscAssertPointer(irow, 3);
2445: PetscAssertPointer(icol, 5);
2446: if (mat->insertmode == NOT_SET_VALUES) mat->insertmode = addv;
2447: else PetscCheck(mat->insertmode == addv, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Cannot mix add values and insert values");
2448: if (PetscDefined(USE_DEBUG)) {
2449: PetscCheck(!mat->factortype, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
2450: PetscCheck(mat->ops->setvalueslocal || mat->ops->setvalues, PETSC_COMM_SELF, PETSC_ERR_SUP, "Mat type %s", ((PetscObject)mat)->type_name);
2451: }
2453: if (mat->assembled) {
2454: mat->was_assembled = PETSC_TRUE;
2455: mat->assembled = PETSC_FALSE;
2456: }
2457: PetscCall(PetscLogEventBegin(MAT_SetValues, mat, 0, 0, 0));
2458: if (mat->ops->setvalueslocal) PetscUseTypeMethod(mat, setvalueslocal, nrow, irow, ncol, icol, v, addv);
2459: else {
2460: PetscInt buf[8192], *bufr = NULL, *bufc = NULL;
2461: const PetscInt *irowm, *icolm;
2463: if ((!mat->rmap->mapping && !mat->cmap->mapping) || (nrow + ncol) <= (PetscInt)PETSC_STATIC_ARRAY_LENGTH(buf)) {
2464: bufr = buf;
2465: bufc = buf + nrow;
2466: irowm = bufr;
2467: icolm = bufc;
2468: } else {
2469: PetscCall(PetscMalloc2(nrow, &bufr, ncol, &bufc));
2470: irowm = bufr;
2471: icolm = bufc;
2472: }
2473: if (mat->rmap->mapping) PetscCall(ISLocalToGlobalMappingApply(mat->rmap->mapping, nrow, irow, bufr));
2474: else irowm = irow;
2475: if (mat->cmap->mapping) {
2476: if (mat->cmap->mapping != mat->rmap->mapping || ncol != nrow || icol != irow) PetscCall(ISLocalToGlobalMappingApply(mat->cmap->mapping, ncol, icol, bufc));
2477: else icolm = irowm;
2478: } else icolm = icol;
2479: PetscCall(MatSetValues(mat, nrow, irowm, ncol, icolm, v, addv));
2480: if (bufr != buf) PetscCall(PetscFree2(bufr, bufc));
2481: }
2482: PetscCall(PetscLogEventEnd(MAT_SetValues, mat, 0, 0, 0));
2483: PetscFunctionReturn(PETSC_SUCCESS);
2484: }
2486: /*@
2487: MatSetValuesBlockedLocal - Inserts or adds values into certain locations of a matrix,
2488: using a local ordering of the nodes a block at a time.
2490: Not Collective
2492: Input Parameters:
2493: + mat - the matrix
2494: . nrow - number of rows
2495: . irow - the row local indices
2496: . ncol - number of columns
2497: . icol - the column local indices
2498: . v - a one-dimensional array that contains the values implicitly stored as a two-dimensional array, by default in row-major order.
2499: See `MAT_ROW_ORIENTED` in `MatSetOption()` for how to use column-major order.
2500: - addv - either `ADD_VALUES` to add values to any existing entries, or `INSERT_VALUES` to replace existing entries with new values
2502: Level: intermediate
2504: Notes:
2505: If you create the matrix yourself (that is not with a call to `DMCreateMatrix()`) then you MUST call `MatSetBlockSize()` and `MatSetLocalToGlobalMapping()`
2506: before using this routineBefore calling `MatSetValuesLocal()`, the user must first set the
2508: Calls to `MatSetValuesBlockedLocal()` with the `INSERT_VALUES` and `ADD_VALUES`
2509: options cannot be mixed without intervening calls to the assembly
2510: routines.
2512: These values may be cached, so `MatAssemblyBegin()` and `MatAssemblyEnd()`
2513: MUST be called after all calls to `MatSetValuesBlockedLocal()` have been completed.
2515: Fortran Notes:
2516: If any of `irow`, `icol`, and `v` are scalars pass them using, for example,
2517: .vb
2518: call MatSetValuesBlockedLocal(mat, one, [irow], one, [icol], [v], INSERT_VALUES, ierr)
2519: .ve
2521: If `v` is a two-dimensional array make sure to first call `MatSetOption(mat, MAT_ROW_ORIENTED, PETSC_FALSE, ierr)` before using this function,
2522: otherwise the transpose of `v` will seemingly be inserted in the matrix, since Fortran passes two-dimensional arrays with column orientation.
2524: .seealso: [](ch_matrices), `Mat`, `MatSetBlockSize()`, `MatSetLocalToGlobalMapping()`, `MatAssemblyBegin()`, `MatAssemblyEnd()`,
2525: `MatSetValuesLocal()`, `MatSetValuesBlocked()`
2526: @*/
2527: PetscErrorCode MatSetValuesBlockedLocal(Mat mat, PetscInt nrow, const PetscInt irow[], PetscInt ncol, const PetscInt icol[], const PetscScalar v[], InsertMode addv)
2528: {
2529: PetscFunctionBeginHot;
2532: MatCheckPreallocated(mat, 1);
2533: if (!nrow || !ncol) PetscFunctionReturn(PETSC_SUCCESS); /* no values to insert */
2534: PetscAssertPointer(irow, 3);
2535: PetscAssertPointer(icol, 5);
2536: if (mat->insertmode == NOT_SET_VALUES) mat->insertmode = addv;
2537: else PetscCheck(mat->insertmode == addv, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Cannot mix add values and insert values");
2538: if (PetscDefined(USE_DEBUG)) {
2539: PetscCheck(!mat->factortype, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
2540: PetscCheck(mat->ops->setvaluesblockedlocal || mat->ops->setvaluesblocked || mat->ops->setvalueslocal || mat->ops->setvalues, PETSC_COMM_SELF, PETSC_ERR_SUP, "Mat type %s", ((PetscObject)mat)->type_name);
2541: }
2543: if (mat->assembled) {
2544: mat->was_assembled = PETSC_TRUE;
2545: mat->assembled = PETSC_FALSE;
2546: }
2547: if (PetscUnlikelyDebug(mat->rmap->mapping)) { /* Condition on the mapping existing, because MatSetValuesBlockedLocal_IS does not require it to be set. */
2548: PetscInt irbs, rbs;
2549: PetscCall(MatGetBlockSizes(mat, &rbs, NULL));
2550: PetscCall(ISLocalToGlobalMappingGetBlockSize(mat->rmap->mapping, &irbs));
2551: PetscCheck(rbs == irbs, PetscObjectComm((PetscObject)mat), PETSC_ERR_SUP, "Different row block sizes! mat %" PetscInt_FMT ", row l2g map %" PetscInt_FMT, rbs, irbs);
2552: }
2553: if (PetscUnlikelyDebug(mat->cmap->mapping)) {
2554: PetscInt icbs, cbs;
2555: PetscCall(MatGetBlockSizes(mat, NULL, &cbs));
2556: PetscCall(ISLocalToGlobalMappingGetBlockSize(mat->cmap->mapping, &icbs));
2557: PetscCheck(cbs == icbs, PetscObjectComm((PetscObject)mat), PETSC_ERR_SUP, "Different col block sizes! mat %" PetscInt_FMT ", col l2g map %" PetscInt_FMT, cbs, icbs);
2558: }
2559: PetscCall(PetscLogEventBegin(MAT_SetValues, mat, 0, 0, 0));
2560: if (mat->ops->setvaluesblockedlocal) PetscUseTypeMethod(mat, setvaluesblockedlocal, nrow, irow, ncol, icol, v, addv);
2561: else {
2562: PetscInt buf[8192], *bufr = NULL, *bufc = NULL;
2563: const PetscInt *irowm, *icolm;
2565: if ((!mat->rmap->mapping && !mat->cmap->mapping) || (nrow + ncol) <= ((PetscInt)PETSC_STATIC_ARRAY_LENGTH(buf))) {
2566: bufr = buf;
2567: bufc = buf + nrow;
2568: irowm = bufr;
2569: icolm = bufc;
2570: } else {
2571: PetscCall(PetscMalloc2(nrow, &bufr, ncol, &bufc));
2572: irowm = bufr;
2573: icolm = bufc;
2574: }
2575: if (mat->rmap->mapping) PetscCall(ISLocalToGlobalMappingApplyBlock(mat->rmap->mapping, nrow, irow, bufr));
2576: else irowm = irow;
2577: if (mat->cmap->mapping) {
2578: if (mat->cmap->mapping != mat->rmap->mapping || ncol != nrow || icol != irow) PetscCall(ISLocalToGlobalMappingApplyBlock(mat->cmap->mapping, ncol, icol, bufc));
2579: else icolm = irowm;
2580: } else icolm = icol;
2581: PetscCall(MatSetValuesBlocked(mat, nrow, irowm, ncol, icolm, v, addv));
2582: if (bufr != buf) PetscCall(PetscFree2(bufr, bufc));
2583: }
2584: PetscCall(PetscLogEventEnd(MAT_SetValues, mat, 0, 0, 0));
2585: PetscFunctionReturn(PETSC_SUCCESS);
2586: }
2588: /*@
2589: MatMultDiagonalBlock - Computes the matrix-vector product, $y = Dx$. Where `D` is defined by the inode or block structure of the diagonal
2591: Collective
2593: Input Parameters:
2594: + mat - the matrix
2595: - x - the vector to be multiplied
2597: Output Parameter:
2598: . y - the result
2600: Level: developer
2602: Note:
2603: The vectors `x` and `y` cannot be the same. I.e., one cannot
2604: call `MatMultDiagonalBlock`(A,y,y).
2606: .seealso: [](ch_matrices), `Mat`, `MatMult()`, `MatMultTranspose()`, `MatMultAdd()`, `MatMultTransposeAdd()`
2607: @*/
2608: PetscErrorCode MatMultDiagonalBlock(Mat mat, Vec x, Vec y)
2609: {
2610: PetscFunctionBegin;
2616: PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
2617: PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
2618: PetscCheck(x != y, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "x and y must be different vectors");
2619: MatCheckPreallocated(mat, 1);
2621: PetscUseTypeMethod(mat, multdiagonalblock, x, y);
2622: PetscCall(PetscObjectStateIncrease((PetscObject)y));
2623: PetscFunctionReturn(PETSC_SUCCESS);
2624: }
2626: /*@
2627: MatMult - Computes the matrix-vector product, $y = Ax$.
2629: Neighbor-wise Collective
2631: Input Parameters:
2632: + mat - the matrix
2633: - x - the vector to be multiplied
2635: Output Parameter:
2636: . y - the result
2638: Level: beginner
2640: Note:
2641: The vectors `x` and `y` cannot be the same. I.e., one cannot
2642: call `MatMult`(A,y,y).
2644: .seealso: [](ch_matrices), `Mat`, `MatMultTranspose()`, `MatMultAdd()`, `MatMultTransposeAdd()`
2645: @*/
2646: PetscErrorCode MatMult(Mat mat, Vec x, Vec y)
2647: {
2648: PetscFunctionBegin;
2652: VecCheckAssembled(x);
2654: PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
2655: PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
2656: PetscCheck(x != y, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "x and y must be different vectors");
2657: PetscCheck(mat->cmap->N == x->map->N, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_SIZ, "Mat mat,Vec x: global dim %" PetscInt_FMT " %" PetscInt_FMT, mat->cmap->N, x->map->N);
2658: PetscCheck(mat->rmap->N == y->map->N, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_SIZ, "Mat mat,Vec y: global dim %" PetscInt_FMT " %" PetscInt_FMT, mat->rmap->N, y->map->N);
2659: PetscCheck(mat->cmap->n == x->map->n, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Mat mat,Vec x: local dim %" PetscInt_FMT " %" PetscInt_FMT, mat->cmap->n, x->map->n);
2660: PetscCheck(mat->rmap->n == y->map->n, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Mat mat,Vec y: local dim %" PetscInt_FMT " %" PetscInt_FMT, mat->rmap->n, y->map->n);
2661: PetscCall(VecSetErrorIfLocked(y, 3));
2662: if (mat->erroriffailure) PetscCall(VecValidValues_Internal(x, 2, PETSC_TRUE));
2663: MatCheckPreallocated(mat, 1);
2665: PetscCall(VecLockReadPush(x));
2666: PetscCall(PetscLogEventBegin(MAT_Mult, mat, x, y, 0));
2667: PetscUseTypeMethod(mat, mult, x, y);
2668: PetscCall(PetscLogEventEnd(MAT_Mult, mat, x, y, 0));
2669: if (mat->erroriffailure) PetscCall(VecValidValues_Internal(y, 3, PETSC_FALSE));
2670: PetscCall(VecLockReadPop(x));
2671: PetscFunctionReturn(PETSC_SUCCESS);
2672: }
2674: /*@
2675: MatMultTranspose - Computes matrix transpose times a vector $y = A^T * x$.
2677: Neighbor-wise Collective
2679: Input Parameters:
2680: + mat - the matrix
2681: - x - the vector to be multiplied
2683: Output Parameter:
2684: . y - the result
2686: Level: beginner
2688: Notes:
2689: The vectors `x` and `y` cannot be the same. I.e., one cannot
2690: call `MatMultTranspose`(A,y,y).
2692: For complex numbers this does NOT compute the Hermitian (complex conjugate) transpose multiple,
2693: use `MatMultHermitianTranspose()`
2695: .seealso: [](ch_matrices), `Mat`, `MatMult()`, `MatMultAdd()`, `MatMultTransposeAdd()`, `MatMultHermitianTranspose()`, `MatTranspose()`
2696: @*/
2697: PetscErrorCode MatMultTranspose(Mat mat, Vec x, Vec y)
2698: {
2699: PetscErrorCode (*op)(Mat, Vec, Vec) = NULL;
2701: PetscFunctionBegin;
2705: VecCheckAssembled(x);
2708: PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
2709: PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
2710: PetscCheck(x != y, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "x and y must be different vectors");
2711: PetscCheck(mat->cmap->N == y->map->N, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_SIZ, "Mat mat,Vec y: global dim %" PetscInt_FMT " %" PetscInt_FMT, mat->cmap->N, y->map->N);
2712: PetscCheck(mat->rmap->N == x->map->N, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_SIZ, "Mat mat,Vec x: global dim %" PetscInt_FMT " %" PetscInt_FMT, mat->rmap->N, x->map->N);
2713: PetscCheck(mat->cmap->n == y->map->n, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Mat mat,Vec y: local dim %" PetscInt_FMT " %" PetscInt_FMT, mat->cmap->n, y->map->n);
2714: PetscCheck(mat->rmap->n == x->map->n, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Mat mat,Vec x: local dim %" PetscInt_FMT " %" PetscInt_FMT, mat->rmap->n, x->map->n);
2715: if (mat->erroriffailure) PetscCall(VecValidValues_Internal(x, 2, PETSC_TRUE));
2716: MatCheckPreallocated(mat, 1);
2718: if (!mat->ops->multtranspose) {
2719: if (mat->symmetric == PETSC_BOOL3_TRUE && mat->ops->mult) op = mat->ops->mult;
2720: PetscCheck(op, PetscObjectComm((PetscObject)mat), PETSC_ERR_SUP, "Matrix type %s does not have a multiply transpose defined or is symmetric and does not have a multiply defined", ((PetscObject)mat)->type_name);
2721: } else op = mat->ops->multtranspose;
2722: PetscCall(PetscLogEventBegin(MAT_MultTranspose, mat, x, y, 0));
2723: PetscCall(VecLockReadPush(x));
2724: PetscCall((*op)(mat, x, y));
2725: PetscCall(VecLockReadPop(x));
2726: PetscCall(PetscLogEventEnd(MAT_MultTranspose, mat, x, y, 0));
2727: PetscCall(PetscObjectStateIncrease((PetscObject)y));
2728: if (mat->erroriffailure) PetscCall(VecValidValues_Internal(y, 3, PETSC_FALSE));
2729: PetscFunctionReturn(PETSC_SUCCESS);
2730: }
2732: /*@
2733: MatMultHermitianTranspose - Computes matrix Hermitian-transpose times a vector $y = A^H * x$.
2735: Neighbor-wise Collective
2737: Input Parameters:
2738: + mat - the matrix
2739: - x - the vector to be multiplied
2741: Output Parameter:
2742: . y - the result
2744: Level: beginner
2746: Notes:
2747: The vectors `x` and `y` cannot be the same. I.e., one cannot
2748: call `MatMultHermitianTranspose`(A,y,y).
2750: Also called the conjugate transpose, complex conjugate transpose, or adjoint.
2752: For real numbers `MatMultTranspose()` and `MatMultHermitianTranspose()` are identical.
2754: .seealso: [](ch_matrices), `Mat`, `MatMult()`, `MatMultAdd()`, `MatMultHermitianTransposeAdd()`, `MatMultTranspose()`
2755: @*/
2756: PetscErrorCode MatMultHermitianTranspose(Mat mat, Vec x, Vec y)
2757: {
2758: PetscFunctionBegin;
2764: PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
2765: PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
2766: PetscCheck(x != y, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "x and y must be different vectors");
2767: PetscCheck(mat->cmap->N == y->map->N, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_SIZ, "Mat mat,Vec y: global dim %" PetscInt_FMT " %" PetscInt_FMT, mat->cmap->N, y->map->N);
2768: PetscCheck(mat->rmap->N == x->map->N, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_SIZ, "Mat mat,Vec x: global dim %" PetscInt_FMT " %" PetscInt_FMT, mat->rmap->N, x->map->N);
2769: PetscCheck(mat->cmap->n == y->map->n, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Mat mat,Vec y: local dim %" PetscInt_FMT " %" PetscInt_FMT, mat->cmap->n, y->map->n);
2770: PetscCheck(mat->rmap->n == x->map->n, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Mat mat,Vec x: local dim %" PetscInt_FMT " %" PetscInt_FMT, mat->rmap->n, x->map->n);
2771: MatCheckPreallocated(mat, 1);
2773: PetscCall(PetscLogEventBegin(MAT_MultHermitianTranspose, mat, x, y, 0));
2774: #if defined(PETSC_USE_COMPLEX)
2775: if (mat->ops->multhermitiantranspose || (mat->hermitian == PETSC_BOOL3_TRUE && mat->ops->mult)) {
2776: PetscCall(VecLockReadPush(x));
2777: if (mat->ops->multhermitiantranspose) PetscUseTypeMethod(mat, multhermitiantranspose, x, y);
2778: else PetscUseTypeMethod(mat, mult, x, y);
2779: PetscCall(VecLockReadPop(x));
2780: } else {
2781: Vec w;
2782: PetscCall(VecDuplicate(x, &w));
2783: PetscCall(VecCopy(x, w));
2784: PetscCall(VecConjugate(w));
2785: PetscCall(MatMultTranspose(mat, w, y));
2786: PetscCall(VecDestroy(&w));
2787: PetscCall(VecConjugate(y));
2788: }
2789: PetscCall(PetscObjectStateIncrease((PetscObject)y));
2790: #else
2791: PetscCall(MatMultTranspose(mat, x, y));
2792: #endif
2793: PetscCall(PetscLogEventEnd(MAT_MultHermitianTranspose, mat, x, y, 0));
2794: PetscFunctionReturn(PETSC_SUCCESS);
2795: }
2797: /*@
2798: MatMultAdd - Computes $v3 = v2 + A * v1$.
2800: Neighbor-wise Collective
2802: Input Parameters:
2803: + mat - the matrix
2804: . v1 - the vector to be multiplied by `mat`
2805: - v2 - the vector to be added to the result
2807: Output Parameter:
2808: . v3 - the result
2810: Level: beginner
2812: Note:
2813: The vectors `v1` and `v3` cannot be the same. I.e., one cannot
2814: call `MatMultAdd`(A,v1,v2,v1).
2816: .seealso: [](ch_matrices), `Mat`, `MatMultTranspose()`, `MatMult()`, `MatMultTransposeAdd()`
2817: @*/
2818: PetscErrorCode MatMultAdd(Mat mat, Vec v1, Vec v2, Vec v3)
2819: {
2820: PetscFunctionBegin;
2827: PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
2828: PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
2829: PetscCheck(mat->cmap->N == v1->map->N, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_SIZ, "Mat mat,Vec v1: global dim %" PetscInt_FMT " %" PetscInt_FMT, mat->cmap->N, v1->map->N);
2830: /* PetscCheck(mat->rmap->N == v2->map->N,PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Mat mat,Vec v2: global dim %" PetscInt_FMT " %" PetscInt_FMT,mat->rmap->N,v2->map->N);
2831: PetscCheck(mat->rmap->N == v3->map->N,PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Mat mat,Vec v3: global dim %" PetscInt_FMT " %" PetscInt_FMT,mat->rmap->N,v3->map->N); */
2832: PetscCheck(mat->rmap->n == v3->map->n, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Mat mat,Vec v3: local dim %" PetscInt_FMT " %" PetscInt_FMT, mat->rmap->n, v3->map->n);
2833: PetscCheck(mat->rmap->n == v2->map->n, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Mat mat,Vec v2: local dim %" PetscInt_FMT " %" PetscInt_FMT, mat->rmap->n, v2->map->n);
2834: PetscCheck(v1 != v3, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_IDN, "v1 and v3 must be different vectors");
2835: MatCheckPreallocated(mat, 1);
2837: PetscCall(PetscLogEventBegin(MAT_MultAdd, mat, v1, v2, v3));
2838: PetscCall(VecLockReadPush(v1));
2839: PetscUseTypeMethod(mat, multadd, v1, v2, v3);
2840: PetscCall(VecLockReadPop(v1));
2841: PetscCall(PetscLogEventEnd(MAT_MultAdd, mat, v1, v2, v3));
2842: PetscCall(PetscObjectStateIncrease((PetscObject)v3));
2843: PetscFunctionReturn(PETSC_SUCCESS);
2844: }
2846: /*@
2847: MatMultTransposeAdd - Computes $v3 = v2 + A^T * v1$.
2849: Neighbor-wise Collective
2851: Input Parameters:
2852: + mat - the matrix
2853: . v1 - the vector to be multiplied by the transpose of the matrix
2854: - v2 - the vector to be added to the result
2856: Output Parameter:
2857: . v3 - the result
2859: Level: beginner
2861: Note:
2862: The vectors `v1` and `v3` cannot be the same. I.e., one cannot
2863: call `MatMultTransposeAdd`(A,v1,v2,v1).
2865: .seealso: [](ch_matrices), `Mat`, `MatMultTranspose()`, `MatMultAdd()`, `MatMult()`
2866: @*/
2867: PetscErrorCode MatMultTransposeAdd(Mat mat, Vec v1, Vec v2, Vec v3)
2868: {
2869: PetscErrorCode (*op)(Mat, Vec, Vec, Vec) = (!mat->ops->multtransposeadd && mat->symmetric) ? mat->ops->multadd : mat->ops->multtransposeadd;
2871: PetscFunctionBegin;
2878: PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
2879: PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
2880: PetscCheck(mat->rmap->N == v1->map->N, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_SIZ, "Mat mat,Vec v1: global dim %" PetscInt_FMT " %" PetscInt_FMT, mat->rmap->N, v1->map->N);
2881: PetscCheck(mat->cmap->N == v2->map->N, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_SIZ, "Mat mat,Vec v2: global dim %" PetscInt_FMT " %" PetscInt_FMT, mat->cmap->N, v2->map->N);
2882: PetscCheck(mat->cmap->N == v3->map->N, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_SIZ, "Mat mat,Vec v3: global dim %" PetscInt_FMT " %" PetscInt_FMT, mat->cmap->N, v3->map->N);
2883: PetscCheck(v1 != v3, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_IDN, "v1 and v3 must be different vectors");
2884: PetscCheck(op, PetscObjectComm((PetscObject)mat), PETSC_ERR_SUP, "Mat type %s", ((PetscObject)mat)->type_name);
2885: MatCheckPreallocated(mat, 1);
2887: PetscCall(PetscLogEventBegin(MAT_MultTransposeAdd, mat, v1, v2, v3));
2888: PetscCall(VecLockReadPush(v1));
2889: PetscCall((*op)(mat, v1, v2, v3));
2890: PetscCall(VecLockReadPop(v1));
2891: PetscCall(PetscLogEventEnd(MAT_MultTransposeAdd, mat, v1, v2, v3));
2892: PetscCall(PetscObjectStateIncrease((PetscObject)v3));
2893: PetscFunctionReturn(PETSC_SUCCESS);
2894: }
2896: /*@
2897: MatMultHermitianTransposeAdd - Computes $v3 = v2 + A^H * v1$.
2899: Neighbor-wise Collective
2901: Input Parameters:
2902: + mat - the matrix
2903: . v1 - the vector to be multiplied by the Hermitian transpose
2904: - v2 - the vector to be added to the result
2906: Output Parameter:
2907: . v3 - the result
2909: Level: beginner
2911: Note:
2912: The vectors `v1` and `v3` cannot be the same. I.e., one cannot
2913: call `MatMultHermitianTransposeAdd`(A,v1,v2,v1).
2915: .seealso: [](ch_matrices), `Mat`, `MatMultHermitianTranspose()`, `MatMultTranspose()`, `MatMultAdd()`, `MatMult()`
2916: @*/
2917: PetscErrorCode MatMultHermitianTransposeAdd(Mat mat, Vec v1, Vec v2, Vec v3)
2918: {
2919: PetscFunctionBegin;
2926: PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
2927: PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
2928: PetscCheck(v1 != v3, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_IDN, "v1 and v3 must be different vectors");
2929: PetscCheck(mat->rmap->N == v1->map->N, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_SIZ, "Mat mat,Vec v1: global dim %" PetscInt_FMT " %" PetscInt_FMT, mat->rmap->N, v1->map->N);
2930: PetscCheck(mat->cmap->N == v2->map->N, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_SIZ, "Mat mat,Vec v2: global dim %" PetscInt_FMT " %" PetscInt_FMT, mat->cmap->N, v2->map->N);
2931: PetscCheck(mat->cmap->N == v3->map->N, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_SIZ, "Mat mat,Vec v3: global dim %" PetscInt_FMT " %" PetscInt_FMT, mat->cmap->N, v3->map->N);
2932: MatCheckPreallocated(mat, 1);
2934: PetscCall(PetscLogEventBegin(MAT_MultHermitianTransposeAdd, mat, v1, v2, v3));
2935: PetscCall(VecLockReadPush(v1));
2936: if (mat->ops->multhermitiantransposeadd) PetscUseTypeMethod(mat, multhermitiantransposeadd, v1, v2, v3);
2937: else {
2938: Vec w, z;
2939: PetscCall(VecDuplicate(v1, &w));
2940: PetscCall(VecCopy(v1, w));
2941: PetscCall(VecConjugate(w));
2942: PetscCall(VecDuplicate(v3, &z));
2943: PetscCall(MatMultTranspose(mat, w, z));
2944: PetscCall(VecDestroy(&w));
2945: PetscCall(VecConjugate(z));
2946: if (v2 != v3) PetscCall(VecWAXPY(v3, 1.0, v2, z));
2947: else PetscCall(VecAXPY(v3, 1.0, z));
2948: PetscCall(VecDestroy(&z));
2949: }
2950: PetscCall(VecLockReadPop(v1));
2951: PetscCall(PetscLogEventEnd(MAT_MultHermitianTransposeAdd, mat, v1, v2, v3));
2952: PetscCall(PetscObjectStateIncrease((PetscObject)v3));
2953: PetscFunctionReturn(PETSC_SUCCESS);
2954: }
2956: PetscErrorCode MatADot_Default(Mat mat, Vec x, Vec y, PetscScalar *val)
2957: {
2958: PetscFunctionBegin;
2959: if (!mat->dot_vec) PetscCall(MatCreateVecs(mat, &mat->dot_vec, NULL));
2960: PetscCall(MatMult(mat, x, mat->dot_vec));
2961: PetscCall(VecDot(mat->dot_vec, y, val));
2962: PetscFunctionReturn(PETSC_SUCCESS);
2963: }
2965: PetscErrorCode MatANorm_Default(Mat mat, Vec x, PetscReal *val)
2966: {
2967: PetscScalar sval;
2969: PetscFunctionBegin;
2970: PetscCall(MatADot_Default(mat, x, x, &sval));
2971: PetscCheck(PetscRealPart(sval) >= 0.0, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONG, "Matrix argument is not positive definite");
2972: PetscCheck(PetscAbsReal(PetscImaginaryPart(sval)) < 100 * PETSC_MACHINE_EPSILON, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONG, "Matrix argument is not Hermitian");
2973: *val = PetscSqrtReal(PetscRealPart(sval));
2974: PetscFunctionReturn(PETSC_SUCCESS);
2975: }
2977: /*@
2978: MatADot - Computes the inner product with respect to a matrix, i.e., $(x, y)_A = y^H A x$ where $A$ is symmetric (Hermitian when using complex)
2979: positive definite.
2981: Collective
2983: Input Parameters:
2984: + mat - matrix used to define the inner product
2985: . x - first vector
2986: - y - second vector
2988: Output Parameter:
2989: . val - the dot product with respect to `A`
2991: Level: intermediate
2993: Note:
2994: For complex vectors, `MatADot()` computes
2995: $$
2996: val = (x,y)_A = y^H A x,
2997: $$
2998: where $y^H$ denotes the conjugate transpose of `y`. Note that this corresponds to the "mathematicians" complex
2999: inner product where the SECOND argument gets the complex conjugate.
3001: .seealso: [](ch_matrices), `Mat`, `MatANorm()`, `VecDot()`, `VecNorm()`, `MatMult()`, `MatMultAdd()`, `MatMultTransposeAdd()`
3002: @*/
3003: PetscErrorCode MatADot(Mat mat, Vec x, Vec y, PetscScalar *val)
3004: {
3005: PetscFunctionBegin;
3009: VecCheckAssembled(x);
3011: VecCheckAssembled(y);
3014: PetscAssertPointer(val, 4);
3015: PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
3016: PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
3017: PetscCheck(mat->cmap->N == x->map->N, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_SIZ, "Mat mat,Vec x: global dim %" PetscInt_FMT " %" PetscInt_FMT, mat->cmap->N, x->map->N);
3018: PetscCheck(mat->rmap->N == y->map->N, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_SIZ, "Mat mat,Vec y: global dim %" PetscInt_FMT " %" PetscInt_FMT, mat->rmap->N, y->map->N);
3019: PetscCheck(mat->cmap->n == x->map->n, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Mat mat,Vec x: local dim %" PetscInt_FMT " %" PetscInt_FMT, mat->cmap->n, x->map->n);
3020: PetscCheck(mat->rmap->n == y->map->n, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Mat mat,Vec y: local dim %" PetscInt_FMT " %" PetscInt_FMT, mat->rmap->n, y->map->n);
3021: if (mat->erroriffailure) PetscCall(VecValidValues_Internal(x, 2, PETSC_TRUE));
3022: if (mat->erroriffailure) PetscCall(VecValidValues_Internal(y, 3, PETSC_TRUE));
3023: MatCheckPreallocated(mat, 1);
3025: PetscCall(VecLockReadPush(x));
3026: PetscCall(VecLockReadPush(y));
3027: PetscCall(PetscLogEventBegin(MAT_ADot, mat, x, y, 0));
3028: PetscUseTypeMethod(mat, adot, x, y, val);
3029: PetscCall(PetscLogEventEnd(MAT_ADot, mat, x, y, 0));
3030: PetscCall(VecLockReadPop(y));
3031: PetscCall(VecLockReadPop(x));
3032: PetscFunctionReturn(PETSC_SUCCESS);
3033: }
3035: /*@
3036: MatANorm - Computes the norm with respect to a matrix, i.e., $(x, x)_A^{1/2} = (x^H A x)^{1/2}$ where $A$ is symmetric (Hermitian when using complex)
3037: positive definite.
3039: Collective
3041: Input Parameters:
3042: + mat - matrix used to define norm
3043: - x - the vector to compute the norm of
3045: Output Parameter:
3046: . val - the norm with respect to `A`
3048: Level: intermediate
3050: Note:
3051: For complex vectors, `MatANorm()` computes
3052: $$
3053: val = (x,x)_A^{1/2} = (x^H A x)^{1/2},
3054: $$
3055: where $x^H$ denotes the conjugate transpose of `x`.
3057: .seealso: [](ch_matrices), `Mat`, `MatADot()`, `VecDot()`, `VecNorm()`, `MatMult()`, `MatMultAdd()`, `MatMultTransposeAdd()`
3058: @*/
3059: PetscErrorCode MatANorm(Mat mat, Vec x, PetscReal *val)
3060: {
3061: PetscFunctionBegin;
3065: VecCheckAssembled(x);
3067: PetscAssertPointer(val, 3);
3068: PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
3069: PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
3070: PetscCheck(mat->cmap->N == x->map->N, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_SIZ, "Mat mat,Vec x: global dim %" PetscInt_FMT " %" PetscInt_FMT, mat->cmap->N, x->map->N);
3071: PetscCheck(mat->rmap->N == x->map->N, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_SIZ, "Mat mat,Vec x: global dim %" PetscInt_FMT " %" PetscInt_FMT, mat->rmap->N, x->map->N);
3072: PetscCheck(mat->cmap->n == x->map->n, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Mat mat,Vec x: local dim %" PetscInt_FMT " %" PetscInt_FMT, mat->cmap->n, x->map->n);
3073: PetscCheck(mat->rmap->n == x->map->n, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Mat mat,Vec x: local dim %" PetscInt_FMT " %" PetscInt_FMT, mat->rmap->n, x->map->n);
3074: if (mat->erroriffailure) PetscCall(VecValidValues_Internal(x, 2, PETSC_TRUE));
3075: MatCheckPreallocated(mat, 1);
3077: PetscCall(VecLockReadPush(x));
3078: PetscCall(PetscLogEventBegin(MAT_ANorm, mat, x, 0, 0));
3079: PetscUseTypeMethod(mat, anorm, x, val);
3080: PetscCall(PetscLogEventEnd(MAT_ANorm, mat, x, 0, 0));
3081: PetscCall(VecLockReadPop(x));
3082: PetscFunctionReturn(PETSC_SUCCESS);
3083: }
3085: /*@
3086: MatGetFactorType - gets the type of factorization a matrix is
3088: Not Collective
3090: Input Parameter:
3091: . mat - the matrix
3093: Output Parameter:
3094: . t - the type, one of `MAT_FACTOR_NONE`, `MAT_FACTOR_LU`, `MAT_FACTOR_CHOLESKY`, `MAT_FACTOR_ILU`, `MAT_FACTOR_ICC,MAT_FACTOR_ILUDT`, `MAT_FACTOR_QR`
3096: Level: intermediate
3098: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatFactorType`, `MatGetFactor()`, `MatSetFactorType()`, `MAT_FACTOR_NONE`, `MAT_FACTOR_LU`, `MAT_FACTOR_CHOLESKY`, `MAT_FACTOR_ILU`,
3099: `MAT_FACTOR_ICC`, `MAT_FACTOR_ILUDT`, `MAT_FACTOR_QR`
3100: @*/
3101: PetscErrorCode MatGetFactorType(Mat mat, MatFactorType *t)
3102: {
3103: PetscFunctionBegin;
3106: PetscAssertPointer(t, 2);
3107: *t = mat->factortype;
3108: PetscFunctionReturn(PETSC_SUCCESS);
3109: }
3111: /*@
3112: MatSetFactorType - sets the type of factorization a matrix is
3114: Logically Collective
3116: Input Parameters:
3117: + mat - the matrix
3118: - t - the type, one of `MAT_FACTOR_NONE`, `MAT_FACTOR_LU`, `MAT_FACTOR_CHOLESKY`, `MAT_FACTOR_ILU`, `MAT_FACTOR_ICC,MAT_FACTOR_ILUDT`, `MAT_FACTOR_QR`
3120: Level: intermediate
3122: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatFactorType`, `MatGetFactor()`, `MatGetFactorType()`, `MAT_FACTOR_NONE`, `MAT_FACTOR_LU`, `MAT_FACTOR_CHOLESKY`, `MAT_FACTOR_ILU`,
3123: `MAT_FACTOR_ICC`, `MAT_FACTOR_ILUDT`, `MAT_FACTOR_QR`
3124: @*/
3125: PetscErrorCode MatSetFactorType(Mat mat, MatFactorType t)
3126: {
3127: PetscFunctionBegin;
3130: mat->factortype = t;
3131: PetscFunctionReturn(PETSC_SUCCESS);
3132: }
3134: /*@
3135: MatGetInfo - Returns information about matrix storage (number of
3136: nonzeros, memory, etc.).
3138: Collective if `MAT_GLOBAL_MAX` or `MAT_GLOBAL_SUM` is used as the flag
3140: Input Parameters:
3141: + mat - the matrix
3142: - flag - flag indicating the type of parameters to be returned (`MAT_LOCAL` - local matrix, `MAT_GLOBAL_MAX` - maximum over all processors, `MAT_GLOBAL_SUM` - sum over all processors)
3144: Output Parameter:
3145: . info - matrix information context
3147: Options Database Key:
3148: . -mat_view ::ascii_info - print matrix info to `PETSC_STDOUT`
3150: Level: intermediate
3152: Notes:
3153: The `MatInfo` context contains a variety of matrix data, including
3154: number of nonzeros allocated and used, number of mallocs during
3155: matrix assembly, etc. Additional information for factored matrices
3156: is provided (such as the fill ratio, number of mallocs during
3157: factorization, etc.).
3159: Example:
3160: See the file ${PETSC_DIR}/include/petscmat.h for a complete list of
3161: data within the `MatInfo` context. For example,
3162: .vb
3163: MatInfo info;
3164: Mat A;
3165: double mal, nz_a, nz_u;
3167: MatGetInfo(A, MAT_LOCAL, &info);
3168: mal = info.mallocs;
3169: nz_a = info.nz_allocated;
3170: .ve
3172: .seealso: [](ch_matrices), `Mat`, `MatInfo`, `MatStashGetInfo()`
3173: @*/
3174: PetscErrorCode MatGetInfo(Mat mat, MatInfoType flag, MatInfo *info)
3175: {
3176: PetscFunctionBegin;
3179: PetscAssertPointer(info, 3);
3180: MatCheckPreallocated(mat, 1);
3181: PetscUseTypeMethod(mat, getinfo, flag, info);
3182: PetscFunctionReturn(PETSC_SUCCESS);
3183: }
3185: /*
3186: This is used by external packages where it is not easy to get the info from the actual
3187: matrix factorization.
3188: */
3189: PetscErrorCode MatGetInfo_External(Mat A, MatInfoType flag, MatInfo *info)
3190: {
3191: PetscFunctionBegin;
3192: PetscCall(PetscMemzero(info, sizeof(MatInfo)));
3193: PetscFunctionReturn(PETSC_SUCCESS);
3194: }
3196: /*@
3197: MatLUFactor - Performs in-place LU factorization of matrix.
3199: Collective
3201: Input Parameters:
3202: + mat - the matrix
3203: . row - row permutation
3204: . col - column permutation
3205: - info - options for factorization, includes
3206: .vb
3207: fill - expected fill as ratio of original fill.
3208: dtcol - pivot tolerance (0 no pivot, 1 full column pivoting)
3209: Run with the option -info to determine an optimal value to use
3210: .ve
3212: Level: developer
3214: Notes:
3215: Most users should employ the `KSP` interface for linear solvers
3216: instead of working directly with matrix algebra routines such as this.
3217: See, e.g., `KSPCreate()`.
3219: This changes the state of the matrix to a factored matrix; it cannot be used
3220: for example with `MatSetValues()` unless one first calls `MatSetUnfactored()`.
3222: This is really in-place only for dense matrices, the preferred approach is to use `MatGetFactor()`, `MatLUFactorSymbolic()`, and `MatLUFactorNumeric()`
3223: when not using `KSP`.
3225: Fortran Note:
3226: A valid (non-null) `info` argument must be provided
3228: .seealso: [](ch_matrices), [Matrix Factorization](sec_matfactor), `Mat`, `MatFactorType`, `MatLUFactorSymbolic()`, `MatLUFactorNumeric()`, `MatCholeskyFactor()`,
3229: `MatGetOrdering()`, `MatSetUnfactored()`, `MatFactorInfo`, `MatGetFactor()`
3230: @*/
3231: PetscErrorCode MatLUFactor(Mat mat, IS row, IS col, const MatFactorInfo *info)
3232: {
3233: MatFactorInfo tinfo;
3235: PetscFunctionBegin;
3239: if (info) PetscAssertPointer(info, 4);
3241: PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
3242: PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
3243: MatCheckPreallocated(mat, 1);
3244: if (!info) {
3245: PetscCall(MatFactorInfoInitialize(&tinfo));
3246: info = &tinfo;
3247: }
3249: PetscCall(PetscLogEventBegin(MAT_LUFactor, mat, row, col, 0));
3250: PetscUseTypeMethod(mat, lufactor, row, col, info);
3251: PetscCall(PetscLogEventEnd(MAT_LUFactor, mat, row, col, 0));
3252: PetscCall(PetscObjectStateIncrease((PetscObject)mat));
3253: PetscFunctionReturn(PETSC_SUCCESS);
3254: }
3256: /*@
3257: MatILUFactor - Performs in-place ILU factorization of matrix.
3259: Collective
3261: Input Parameters:
3262: + mat - the matrix
3263: . row - row permutation
3264: . col - column permutation
3265: - info - structure containing
3266: .vb
3267: levels - number of levels of fill.
3268: expected fill - as ratio of original fill.
3269: 1 or 0 - indicating force fill on diagonal (improves robustness for matrices
3270: missing diagonal entries)
3271: .ve
3273: Level: developer
3275: Notes:
3276: Most users should employ the `KSP` interface for linear solvers
3277: instead of working directly with matrix algebra routines such as this.
3278: See, e.g., `KSPCreate()`.
3280: Probably really in-place only when level of fill is zero, otherwise allocates
3281: new space to store factored matrix and deletes previous memory. The preferred approach is to use `MatGetFactor()`, `MatILUFactorSymbolic()`, and `MatLUFactorNumeric()`
3282: when not using `KSP`.
3284: Fortran Note:
3285: A valid (non-null) `info` argument must be provided
3287: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatILUFactorSymbolic()`, `MatLUFactorNumeric()`, `MatCholeskyFactor()`, `MatFactorInfo`
3288: @*/
3289: PetscErrorCode MatILUFactor(Mat mat, IS row, IS col, const MatFactorInfo *info)
3290: {
3291: PetscFunctionBegin;
3295: PetscAssertPointer(info, 4);
3297: PetscCheck(mat->rmap->N == mat->cmap->N, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONG, "matrix must be square");
3298: PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
3299: PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
3300: MatCheckPreallocated(mat, 1);
3302: PetscCall(PetscLogEventBegin(MAT_ILUFactor, mat, row, col, 0));
3303: PetscUseTypeMethod(mat, ilufactor, row, col, info);
3304: PetscCall(PetscLogEventEnd(MAT_ILUFactor, mat, row, col, 0));
3305: PetscCall(PetscObjectStateIncrease((PetscObject)mat));
3306: PetscFunctionReturn(PETSC_SUCCESS);
3307: }
3309: /*@
3310: MatLUFactorSymbolic - Performs symbolic LU factorization of matrix.
3311: Call this routine before calling `MatLUFactorNumeric()` and after `MatGetFactor()`.
3313: Collective
3315: Input Parameters:
3316: + fact - the factor matrix obtained with `MatGetFactor()`
3317: . mat - the matrix
3318: . row - the row permutation
3319: . col - the column permutation
3320: - info - options for factorization, includes
3321: .vb
3322: fill - expected fill as ratio of original fill. Run with the option -info to determine an optimal value to use
3323: dtcol - pivot tolerance (0 no pivot, 1 full column pivoting)
3324: .ve
3326: Level: developer
3328: Notes:
3329: See [Matrix Factorization](sec_matfactor) for additional information about factorizations
3331: Most users should employ the simplified `KSP` interface for linear solvers
3332: instead of working directly with matrix algebra routines such as this.
3333: See, e.g., `KSPCreate()`.
3335: Fortran Note:
3336: A valid (non-null) `info` argument must be provided
3338: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatGetFactor()`, `MatLUFactor()`, `MatLUFactorNumeric()`, `MatCholeskyFactor()`, `MatFactorInfo`, `MatFactorInfoInitialize()`
3339: @*/
3340: PetscErrorCode MatLUFactorSymbolic(Mat fact, Mat mat, IS row, IS col, const MatFactorInfo *info)
3341: {
3342: MatFactorInfo tinfo;
3344: PetscFunctionBegin;
3349: if (info) PetscAssertPointer(info, 5);
3352: PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
3353: PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
3354: MatCheckPreallocated(mat, 2);
3355: if (!info) {
3356: PetscCall(MatFactorInfoInitialize(&tinfo));
3357: info = &tinfo;
3358: }
3360: if (!fact->trivialsymbolic) PetscCall(PetscLogEventBegin(MAT_LUFactorSymbolic, mat, row, col, 0));
3361: PetscUseTypeMethod(fact, lufactorsymbolic, mat, row, col, info);
3362: if (!fact->trivialsymbolic) PetscCall(PetscLogEventEnd(MAT_LUFactorSymbolic, mat, row, col, 0));
3363: PetscCall(PetscObjectStateIncrease((PetscObject)fact));
3364: PetscFunctionReturn(PETSC_SUCCESS);
3365: }
3367: /*@
3368: MatLUFactorNumeric - Performs numeric LU factorization of a matrix.
3369: Call this routine after first calling `MatLUFactorSymbolic()` and `MatGetFactor()`.
3371: Collective
3373: Input Parameters:
3374: + fact - the factor matrix obtained with `MatGetFactor()`
3375: . mat - the matrix
3376: - info - options for factorization
3378: Level: developer
3380: Notes:
3381: See `MatLUFactor()` for in-place factorization. See
3382: `MatCholeskyFactorNumeric()` for the symmetric, positive definite case.
3384: Most users should employ the `KSP` interface for linear solvers
3385: instead of working directly with matrix algebra routines such as this.
3386: See, e.g., `KSPCreate()`.
3388: Fortran Note:
3389: A valid (non-null) `info` argument must be provided
3391: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatGetFactor()`, `MatFactorInfo`, `MatLUFactorSymbolic()`, `MatLUFactor()`, `MatCholeskyFactor()`
3392: @*/
3393: PetscErrorCode MatLUFactorNumeric(Mat fact, Mat mat, const MatFactorInfo *info)
3394: {
3395: MatFactorInfo tinfo;
3397: PetscFunctionBegin;
3402: PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
3403: PetscCheck(mat->rmap->N == (fact)->rmap->N && mat->cmap->N == (fact)->cmap->N, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_SIZ, "Mat mat,Mat fact: global dimensions are different %" PetscInt_FMT " should = %" PetscInt_FMT " %" PetscInt_FMT " should = %" PetscInt_FMT,
3404: mat->rmap->N, (fact)->rmap->N, mat->cmap->N, (fact)->cmap->N);
3406: MatCheckPreallocated(mat, 2);
3407: if (!info) {
3408: PetscCall(MatFactorInfoInitialize(&tinfo));
3409: info = &tinfo;
3410: }
3412: if (!fact->trivialsymbolic) PetscCall(PetscLogEventBegin(MAT_LUFactorNumeric, mat, fact, 0, 0));
3413: else PetscCall(PetscLogEventBegin(MAT_LUFactor, mat, fact, 0, 0));
3414: PetscUseTypeMethod(fact, lufactornumeric, mat, info);
3415: if (!fact->trivialsymbolic) PetscCall(PetscLogEventEnd(MAT_LUFactorNumeric, mat, fact, 0, 0));
3416: else PetscCall(PetscLogEventEnd(MAT_LUFactor, mat, fact, 0, 0));
3417: PetscCall(MatViewFromOptions(fact, NULL, "-mat_factor_view"));
3418: PetscCall(PetscObjectStateIncrease((PetscObject)fact));
3419: PetscFunctionReturn(PETSC_SUCCESS);
3420: }
3422: /*@
3423: MatCholeskyFactor - Performs in-place Cholesky factorization of a
3424: symmetric matrix.
3426: Collective
3428: Input Parameters:
3429: + mat - the matrix
3430: . perm - row and column permutations
3431: - info - expected fill as ratio of original fill
3433: Level: developer
3435: Notes:
3436: See `MatLUFactor()` for the nonsymmetric case. See also `MatGetFactor()`,
3437: `MatCholeskyFactorSymbolic()`, and `MatCholeskyFactorNumeric()`.
3439: Most users should employ the `KSP` interface for linear solvers
3440: instead of working directly with matrix algebra routines such as this.
3441: See, e.g., `KSPCreate()`.
3443: Fortran Note:
3444: A valid (non-null) `info` argument must be provided
3446: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatGetFactor()`, `MatFactorInfo`, `MatLUFactor()`, `MatCholeskyFactorSymbolic()`, `MatCholeskyFactorNumeric()`,
3447: `MatGetOrdering()`
3448: @*/
3449: PetscErrorCode MatCholeskyFactor(Mat mat, IS perm, const MatFactorInfo *info)
3450: {
3451: MatFactorInfo tinfo;
3453: PetscFunctionBegin;
3456: if (info) PetscAssertPointer(info, 3);
3458: PetscCheck(mat->rmap->N == mat->cmap->N, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONG, "Matrix must be square");
3459: PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
3460: PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
3461: MatCheckPreallocated(mat, 1);
3462: if (!info) {
3463: PetscCall(MatFactorInfoInitialize(&tinfo));
3464: info = &tinfo;
3465: }
3467: PetscCall(PetscLogEventBegin(MAT_CholeskyFactor, mat, perm, 0, 0));
3468: PetscUseTypeMethod(mat, choleskyfactor, perm, info);
3469: PetscCall(PetscLogEventEnd(MAT_CholeskyFactor, mat, perm, 0, 0));
3470: PetscCall(PetscObjectStateIncrease((PetscObject)mat));
3471: PetscFunctionReturn(PETSC_SUCCESS);
3472: }
3474: /*@
3475: MatCholeskyFactorSymbolic - Performs symbolic Cholesky factorization
3476: of a symmetric matrix.
3478: Collective
3480: Input Parameters:
3481: + fact - the factor matrix obtained with `MatGetFactor()`
3482: . mat - the matrix
3483: . perm - row and column permutations
3484: - info - options for factorization, includes
3485: .vb
3486: fill - expected fill as ratio of original fill.
3487: dtcol - pivot tolerance (0 no pivot, 1 full column pivoting)
3488: Run with the option -info to determine an optimal value to use
3489: .ve
3491: Level: developer
3493: Notes:
3494: See `MatLUFactorSymbolic()` for the nonsymmetric case. See also
3495: `MatCholeskyFactor()` and `MatCholeskyFactorNumeric()`.
3497: Most users should employ the `KSP` interface for linear solvers
3498: instead of working directly with matrix algebra routines such as this.
3499: See, e.g., `KSPCreate()`.
3501: Fortran Note:
3502: A valid (non-null) `info` argument must be provided
3504: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatFactorInfo`, `MatGetFactor()`, `MatLUFactorSymbolic()`, `MatCholeskyFactor()`, `MatCholeskyFactorNumeric()`,
3505: `MatGetOrdering()`
3506: @*/
3507: PetscErrorCode MatCholeskyFactorSymbolic(Mat fact, Mat mat, IS perm, const MatFactorInfo *info)
3508: {
3509: MatFactorInfo tinfo;
3511: PetscFunctionBegin;
3515: if (info) PetscAssertPointer(info, 4);
3518: PetscCheck(mat->rmap->N == mat->cmap->N, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONG, "Matrix must be square");
3519: PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
3520: PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
3521: MatCheckPreallocated(mat, 2);
3522: if (!info) {
3523: PetscCall(MatFactorInfoInitialize(&tinfo));
3524: info = &tinfo;
3525: }
3527: if (!fact->trivialsymbolic) PetscCall(PetscLogEventBegin(MAT_CholeskyFactorSymbolic, mat, perm, 0, 0));
3528: PetscUseTypeMethod(fact, choleskyfactorsymbolic, mat, perm, info);
3529: if (!fact->trivialsymbolic) PetscCall(PetscLogEventEnd(MAT_CholeskyFactorSymbolic, mat, perm, 0, 0));
3530: PetscCall(PetscObjectStateIncrease((PetscObject)fact));
3531: PetscFunctionReturn(PETSC_SUCCESS);
3532: }
3534: /*@
3535: MatCholeskyFactorNumeric - Performs numeric Cholesky factorization
3536: of a symmetric matrix. Call this routine after first calling `MatGetFactor()` and
3537: `MatCholeskyFactorSymbolic()`.
3539: Collective
3541: Input Parameters:
3542: + fact - the factor matrix obtained with `MatGetFactor()`, where the factored values are stored
3543: . mat - the initial matrix that is to be factored
3544: - info - options for factorization
3546: Level: developer
3548: Note:
3549: Most users should employ the `KSP` interface for linear solvers
3550: instead of working directly with matrix algebra routines such as this.
3551: See, e.g., `KSPCreate()`.
3553: Fortran Note:
3554: A valid (non-null) `info` argument must be provided
3556: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatFactorInfo`, `MatGetFactor()`, `MatCholeskyFactorSymbolic()`, `MatCholeskyFactor()`, `MatLUFactorNumeric()`
3557: @*/
3558: PetscErrorCode MatCholeskyFactorNumeric(Mat fact, Mat mat, const MatFactorInfo *info)
3559: {
3560: MatFactorInfo tinfo;
3562: PetscFunctionBegin;
3567: PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
3568: PetscCheck(mat->rmap->N == (fact)->rmap->N && mat->cmap->N == (fact)->cmap->N, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_SIZ, "Mat mat,Mat fact: global dim %" PetscInt_FMT " should = %" PetscInt_FMT " %" PetscInt_FMT " should = %" PetscInt_FMT,
3569: mat->rmap->N, (fact)->rmap->N, mat->cmap->N, (fact)->cmap->N);
3570: MatCheckPreallocated(mat, 2);
3571: if (!info) {
3572: PetscCall(MatFactorInfoInitialize(&tinfo));
3573: info = &tinfo;
3574: }
3576: if (!fact->trivialsymbolic) PetscCall(PetscLogEventBegin(MAT_CholeskyFactorNumeric, mat, fact, 0, 0));
3577: else PetscCall(PetscLogEventBegin(MAT_CholeskyFactor, mat, fact, 0, 0));
3578: PetscUseTypeMethod(fact, choleskyfactornumeric, mat, info);
3579: if (!fact->trivialsymbolic) PetscCall(PetscLogEventEnd(MAT_CholeskyFactorNumeric, mat, fact, 0, 0));
3580: else PetscCall(PetscLogEventEnd(MAT_CholeskyFactor, mat, fact, 0, 0));
3581: PetscCall(MatViewFromOptions(fact, NULL, "-mat_factor_view"));
3582: PetscCall(PetscObjectStateIncrease((PetscObject)fact));
3583: PetscFunctionReturn(PETSC_SUCCESS);
3584: }
3586: /*@
3587: MatQRFactor - Performs in-place QR factorization of matrix.
3589: Collective
3591: Input Parameters:
3592: + mat - the matrix
3593: . col - column permutation
3594: - info - options for factorization, includes
3595: .vb
3596: fill - expected fill as ratio of original fill.
3597: dtcol - pivot tolerance (0 no pivot, 1 full column pivoting)
3598: Run with the option -info to determine an optimal value to use
3599: .ve
3601: Level: developer
3603: Notes:
3604: Most users should employ the `KSP` interface for linear solvers
3605: instead of working directly with matrix algebra routines such as this.
3606: See, e.g., `KSPCreate()`.
3608: This changes the state of the matrix to a factored matrix; it cannot be used
3609: for example with `MatSetValues()` unless one first calls `MatSetUnfactored()`.
3611: Fortran Note:
3612: A valid (non-null) `info` argument must be provided
3614: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatFactorInfo`, `MatGetFactor()`, `MatQRFactorSymbolic()`, `MatQRFactorNumeric()`, `MatLUFactor()`,
3615: `MatSetUnfactored()`
3616: @*/
3617: PetscErrorCode MatQRFactor(Mat mat, IS col, const MatFactorInfo *info)
3618: {
3619: PetscFunctionBegin;
3622: if (info) PetscAssertPointer(info, 3);
3624: PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
3625: PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
3626: MatCheckPreallocated(mat, 1);
3627: PetscCall(PetscLogEventBegin(MAT_QRFactor, mat, col, 0, 0));
3628: PetscUseMethod(mat, "MatQRFactor_C", (Mat, IS, const MatFactorInfo *), (mat, col, info));
3629: PetscCall(PetscLogEventEnd(MAT_QRFactor, mat, col, 0, 0));
3630: PetscCall(PetscObjectStateIncrease((PetscObject)mat));
3631: PetscFunctionReturn(PETSC_SUCCESS);
3632: }
3634: /*@
3635: MatQRFactorSymbolic - Performs symbolic QR factorization of matrix.
3636: Call this routine after `MatGetFactor()` but before calling `MatQRFactorNumeric()`.
3638: Collective
3640: Input Parameters:
3641: + fact - the factor matrix obtained with `MatGetFactor()`
3642: . mat - the matrix
3643: . col - column permutation
3644: - info - options for factorization, includes
3645: .vb
3646: fill - expected fill as ratio of original fill.
3647: dtcol - pivot tolerance (0 no pivot, 1 full column pivoting)
3648: Run with the option -info to determine an optimal value to use
3649: .ve
3651: Level: developer
3653: Note:
3654: Most users should employ the `KSP` interface for linear solvers
3655: instead of working directly with matrix algebra routines such as this.
3656: See, e.g., `KSPCreate()`.
3658: Fortran Note:
3659: A valid (non-null) `info` argument must be provided
3661: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatGetFactor()`, `MatFactorInfo`, `MatQRFactor()`, `MatQRFactorNumeric()`, `MatLUFactor()`, `MatFactorInfoInitialize()`
3662: @*/
3663: PetscErrorCode MatQRFactorSymbolic(Mat fact, Mat mat, IS col, const MatFactorInfo *info)
3664: {
3665: MatFactorInfo tinfo;
3667: PetscFunctionBegin;
3671: if (info) PetscAssertPointer(info, 4);
3674: PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
3675: PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
3676: MatCheckPreallocated(mat, 2);
3677: if (!info) {
3678: PetscCall(MatFactorInfoInitialize(&tinfo));
3679: info = &tinfo;
3680: }
3682: if (!fact->trivialsymbolic) PetscCall(PetscLogEventBegin(MAT_QRFactorSymbolic, fact, mat, col, 0));
3683: PetscUseMethod(fact, "MatQRFactorSymbolic_C", (Mat, Mat, IS, const MatFactorInfo *), (fact, mat, col, info));
3684: if (!fact->trivialsymbolic) PetscCall(PetscLogEventEnd(MAT_QRFactorSymbolic, fact, mat, col, 0));
3685: PetscCall(PetscObjectStateIncrease((PetscObject)fact));
3686: PetscFunctionReturn(PETSC_SUCCESS);
3687: }
3689: /*@
3690: MatQRFactorNumeric - Performs numeric QR factorization of a matrix.
3691: Call this routine after first calling `MatGetFactor()`, and `MatQRFactorSymbolic()`.
3693: Collective
3695: Input Parameters:
3696: + fact - the factor matrix obtained with `MatGetFactor()`
3697: . mat - the matrix
3698: - info - options for factorization
3700: Level: developer
3702: Notes:
3703: See `MatQRFactor()` for in-place factorization.
3705: Most users should employ the `KSP` interface for linear solvers
3706: instead of working directly with matrix algebra routines such as this.
3707: See, e.g., `KSPCreate()`.
3709: Fortran Note:
3710: A valid (non-null) `info` argument must be provided
3712: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatFactorInfo`, `MatGetFactor()`, `MatQRFactor()`, `MatQRFactorSymbolic()`, `MatLUFactor()`
3713: @*/
3714: PetscErrorCode MatQRFactorNumeric(Mat fact, Mat mat, const MatFactorInfo *info)
3715: {
3716: MatFactorInfo tinfo;
3718: PetscFunctionBegin;
3723: PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
3724: PetscCheck(mat->rmap->N == fact->rmap->N && mat->cmap->N == fact->cmap->N, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_SIZ, "Mat mat,Mat fact: global dimensions are different %" PetscInt_FMT " should = %" PetscInt_FMT " %" PetscInt_FMT " should = %" PetscInt_FMT,
3725: mat->rmap->N, (fact)->rmap->N, mat->cmap->N, (fact)->cmap->N);
3727: MatCheckPreallocated(mat, 2);
3728: if (!info) {
3729: PetscCall(MatFactorInfoInitialize(&tinfo));
3730: info = &tinfo;
3731: }
3733: if (!fact->trivialsymbolic) PetscCall(PetscLogEventBegin(MAT_QRFactorNumeric, mat, fact, 0, 0));
3734: else PetscCall(PetscLogEventBegin(MAT_QRFactor, mat, fact, 0, 0));
3735: PetscUseMethod(fact, "MatQRFactorNumeric_C", (Mat, Mat, const MatFactorInfo *), (fact, mat, info));
3736: if (!fact->trivialsymbolic) PetscCall(PetscLogEventEnd(MAT_QRFactorNumeric, mat, fact, 0, 0));
3737: else PetscCall(PetscLogEventEnd(MAT_QRFactor, mat, fact, 0, 0));
3738: PetscCall(MatViewFromOptions(fact, NULL, "-mat_factor_view"));
3739: PetscCall(PetscObjectStateIncrease((PetscObject)fact));
3740: PetscFunctionReturn(PETSC_SUCCESS);
3741: }
3743: /*@
3744: MatSolve - Solves $A x = b$, given a factored matrix.
3746: Neighbor-wise Collective
3748: Input Parameters:
3749: + mat - the factored matrix
3750: - b - the right-hand-side vector
3752: Output Parameter:
3753: . x - the result vector
3755: Level: developer
3757: Notes:
3758: The vectors `b` and `x` cannot be the same. I.e., one cannot
3759: call `MatSolve`(A,x,x).
3761: Most users should employ the `KSP` interface for linear solvers
3762: instead of working directly with matrix algebra routines such as this.
3763: See, e.g., `KSPCreate()`.
3765: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatGetFactor()`, `MatLUFactor()`, `MatSolveAdd()`, `MatSolveTranspose()`, `MatSolveTransposeAdd()`
3766: @*/
3767: PetscErrorCode MatSolve(Mat mat, Vec b, Vec x)
3768: {
3769: PetscFunctionBegin;
3774: PetscCheckSameComm(mat, 1, b, 2);
3775: PetscCheckSameComm(mat, 1, x, 3);
3776: PetscCheck(x != b, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_IDN, "x and b must be different vectors");
3777: PetscCheck(mat->cmap->N == x->map->N, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_SIZ, "Mat mat,Vec x: global dim %" PetscInt_FMT " %" PetscInt_FMT, mat->cmap->N, x->map->N);
3778: PetscCheck(mat->rmap->N == b->map->N, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_SIZ, "Mat mat,Vec b: global dim %" PetscInt_FMT " %" PetscInt_FMT, mat->rmap->N, b->map->N);
3779: PetscCheck(mat->rmap->n == b->map->n, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Mat mat,Vec b: local dim %" PetscInt_FMT " %" PetscInt_FMT, mat->rmap->n, b->map->n);
3780: if (!mat->rmap->N && !mat->cmap->N) PetscFunctionReturn(PETSC_SUCCESS);
3781: MatCheckPreallocated(mat, 1);
3783: PetscCall(PetscLogEventBegin(MAT_Solve, mat, b, x, 0));
3784: PetscCall(VecFlag(x, mat->factorerrortype));
3785: if (mat->factorerrortype) PetscCall(PetscInfo(mat, "MatFactorError %d\n", mat->factorerrortype));
3786: else PetscUseTypeMethod(mat, solve, b, x);
3787: PetscCall(PetscLogEventEnd(MAT_Solve, mat, b, x, 0));
3788: PetscCall(PetscObjectStateIncrease((PetscObject)x));
3789: PetscFunctionReturn(PETSC_SUCCESS);
3790: }
3792: static PetscErrorCode MatMatSolve_Basic(Mat A, Mat B, Mat X, PetscBool trans)
3793: {
3794: Vec b, x;
3795: PetscInt N;
3796: PetscErrorCode (*f)(Mat, Vec, Vec);
3797: PetscBool Abound, Bneedconv = PETSC_FALSE, Xneedconv = PETSC_FALSE;
3799: PetscFunctionBegin;
3800: if (A->factorerrortype) {
3801: PetscCall(PetscInfo(A, "MatFactorError %d\n", A->factorerrortype));
3802: PetscCall(MatSetInf(X));
3803: PetscFunctionReturn(PETSC_SUCCESS);
3804: }
3805: f = (!trans || (!A->ops->solvetranspose && A->symmetric)) ? A->ops->solve : A->ops->solvetranspose;
3806: PetscCheck(f, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "Mat type %s", ((PetscObject)A)->type_name);
3807: PetscCall(MatBoundToCPU(A, &Abound));
3808: if (!Abound) {
3809: PetscCall(PetscObjectTypeCompareAny((PetscObject)B, &Bneedconv, MATSEQDENSE, MATMPIDENSE, ""));
3810: PetscCall(PetscObjectTypeCompareAny((PetscObject)X, &Xneedconv, MATSEQDENSE, MATMPIDENSE, ""));
3811: }
3812: #if PetscDefined(HAVE_CUDA)
3813: if (Bneedconv) PetscCall(MatConvert(B, MATDENSECUDA, MAT_INPLACE_MATRIX, &B));
3814: if (Xneedconv) PetscCall(MatConvert(X, MATDENSECUDA, MAT_INPLACE_MATRIX, &X));
3815: #elif PetscDefined(HAVE_HIP)
3816: if (Bneedconv) PetscCall(MatConvert(B, MATDENSEHIP, MAT_INPLACE_MATRIX, &B));
3817: if (Xneedconv) PetscCall(MatConvert(X, MATDENSEHIP, MAT_INPLACE_MATRIX, &X));
3818: #endif
3819: PetscCall(MatGetSize(B, NULL, &N));
3820: for (PetscInt i = 0; i < N; i++) {
3821: PetscCall(MatDenseGetColumnVecRead(B, i, &b));
3822: PetscCall(MatDenseGetColumnVecWrite(X, i, &x));
3823: PetscCall((*f)(A, b, x));
3824: PetscCall(MatDenseRestoreColumnVecWrite(X, i, &x));
3825: PetscCall(MatDenseRestoreColumnVecRead(B, i, &b));
3826: }
3827: if (Bneedconv) PetscCall(MatConvert(B, MATDENSE, MAT_INPLACE_MATRIX, &B));
3828: if (Xneedconv) PetscCall(MatConvert(X, MATDENSE, MAT_INPLACE_MATRIX, &X));
3829: PetscFunctionReturn(PETSC_SUCCESS);
3830: }
3832: /*@
3833: MatMatSolve - Solves $A X = B$, given a factored matrix.
3835: Neighbor-wise Collective
3837: Input Parameters:
3838: + A - the factored matrix
3839: - B - the right-hand-side matrix `MATDENSE` (or sparse `MATAIJ`-- when using MUMPS)
3841: Output Parameter:
3842: . X - the result matrix (dense matrix)
3844: Level: developer
3846: Note:
3847: If `B` is a `MATDENSE` matrix then one can call `MatMatSolve`(A,B,B) except with `MATSOLVERMKL_CPARDISO`;
3848: otherwise, `B` and `X` cannot be the same.
3850: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatGetFactor()`, `MatSolve()`, `MatMatSolveTranspose()`, `MatLUFactor()`, `MatCholeskyFactor()`
3851: @*/
3852: PetscErrorCode MatMatSolve(Mat A, Mat B, Mat X)
3853: {
3854: PetscFunctionBegin;
3859: PetscCheckSameComm(A, 1, B, 2);
3860: PetscCheckSameComm(A, 1, X, 3);
3861: PetscCheck(A->cmap->N == X->rmap->N, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_SIZ, "Mat A,Mat X: global dim %" PetscInt_FMT " %" PetscInt_FMT, A->cmap->N, X->rmap->N);
3862: PetscCheck(A->rmap->N == B->rmap->N, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_SIZ, "Mat A,Mat B: global dim %" PetscInt_FMT " %" PetscInt_FMT, A->rmap->N, B->rmap->N);
3863: PetscCheck(X->cmap->N == B->cmap->N, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_SIZ, "Solution matrix must have same number of columns as rhs matrix");
3864: if (!A->rmap->N && !A->cmap->N) PetscFunctionReturn(PETSC_SUCCESS);
3865: MatCheckPreallocated(A, 1);
3867: PetscCall(PetscLogEventBegin(MAT_MatSolve, A, B, X, 0));
3868: if (!A->ops->matsolve) {
3869: PetscCall(PetscInfo(A, "Mat type %s using basic MatMatSolve\n", ((PetscObject)A)->type_name));
3870: PetscCall(MatMatSolve_Basic(A, B, X, PETSC_FALSE));
3871: } else PetscUseTypeMethod(A, matsolve, B, X);
3872: PetscCall(PetscLogEventEnd(MAT_MatSolve, A, B, X, 0));
3873: PetscCall(PetscObjectStateIncrease((PetscObject)X));
3874: PetscFunctionReturn(PETSC_SUCCESS);
3875: }
3877: /*@
3878: MatMatSolveTranspose - Solves $A^T X = B $, given a factored matrix.
3880: Neighbor-wise Collective
3882: Input Parameters:
3883: + A - the factored matrix
3884: - B - the right-hand-side matrix (`MATDENSE` matrix)
3886: Output Parameter:
3887: . X - the result matrix (dense matrix)
3889: Level: developer
3891: Note:
3892: The matrices `B` and `X` cannot be the same. I.e., one cannot
3893: call `MatMatSolveTranspose`(A,X,X).
3895: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatGetFactor()`, `MatSolveTranspose()`, `MatMatSolve()`, `MatLUFactor()`, `MatCholeskyFactor()`
3896: @*/
3897: PetscErrorCode MatMatSolveTranspose(Mat A, Mat B, Mat X)
3898: {
3899: PetscFunctionBegin;
3904: PetscCheckSameComm(A, 1, B, 2);
3905: PetscCheckSameComm(A, 1, X, 3);
3906: PetscCheck(X != B, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_IDN, "X and B must be different matrices");
3907: PetscCheck(A->cmap->N == X->rmap->N, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_SIZ, "Mat A,Mat X: global dim %" PetscInt_FMT " %" PetscInt_FMT, A->cmap->N, X->rmap->N);
3908: PetscCheck(A->rmap->N == B->rmap->N, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_SIZ, "Mat A,Mat B: global dim %" PetscInt_FMT " %" PetscInt_FMT, A->rmap->N, B->rmap->N);
3909: PetscCheck(A->rmap->n == B->rmap->n, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Mat A,Mat B: local dim %" PetscInt_FMT " %" PetscInt_FMT, A->rmap->n, B->rmap->n);
3910: PetscCheck(X->cmap->N >= B->cmap->N, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Solution matrix must have same number of columns as rhs matrix");
3911: if (!A->rmap->N && !A->cmap->N) PetscFunctionReturn(PETSC_SUCCESS);
3912: MatCheckPreallocated(A, 1);
3914: PetscCall(PetscLogEventBegin(MAT_MatSolve, A, B, X, 0));
3915: if (!A->ops->matsolvetranspose) {
3916: PetscCall(PetscInfo(A, "Mat type %s using basic MatMatSolveTranspose\n", ((PetscObject)A)->type_name));
3917: PetscCall(MatMatSolve_Basic(A, B, X, PETSC_TRUE));
3918: } else PetscUseTypeMethod(A, matsolvetranspose, B, X);
3919: PetscCall(PetscLogEventEnd(MAT_MatSolve, A, B, X, 0));
3920: PetscCall(PetscObjectStateIncrease((PetscObject)X));
3921: PetscFunctionReturn(PETSC_SUCCESS);
3922: }
3924: /*@
3925: MatMatTransposeSolve - Solves $A X = B^T$, given a factored matrix.
3927: Neighbor-wise Collective
3929: Input Parameters:
3930: + A - the factored matrix
3931: - Bt - the transpose of right-hand-side matrix as a `MATDENSE`
3933: Output Parameter:
3934: . X - the result matrix (dense matrix)
3936: Level: developer
3938: Note:
3939: For MUMPS, it only supports centralized sparse compressed column format on the host processor for right-hand side matrix. User must create `Bt` in sparse compressed row
3940: format on the host processor and call `MatMatTransposeSolve()` to implement MUMPS' `MatMatSolve()`.
3942: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatMatSolve()`, `MatMatSolveTranspose()`, `MatLUFactor()`, `MatCholeskyFactor()`
3943: @*/
3944: PetscErrorCode MatMatTransposeSolve(Mat A, Mat Bt, Mat X)
3945: {
3946: PetscFunctionBegin;
3951: PetscCheckSameComm(A, 1, Bt, 2);
3952: PetscCheckSameComm(A, 1, X, 3);
3954: PetscCheck(X != Bt, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_IDN, "X and B must be different matrices");
3955: PetscCheck(A->cmap->N == X->rmap->N, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_SIZ, "Mat A,Mat X: global dim %" PetscInt_FMT " %" PetscInt_FMT, A->cmap->N, X->rmap->N);
3956: PetscCheck(A->rmap->N == Bt->cmap->N, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_SIZ, "Mat A,Mat Bt: global dim %" PetscInt_FMT " %" PetscInt_FMT, A->rmap->N, Bt->cmap->N);
3957: PetscCheck(X->cmap->N >= Bt->rmap->N, PetscObjectComm((PetscObject)X), PETSC_ERR_ARG_SIZ, "Solution matrix must have same number of columns as row number of the rhs matrix");
3958: if (!A->rmap->N && !A->cmap->N) PetscFunctionReturn(PETSC_SUCCESS);
3959: PetscCheck(A->factortype, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_WRONGSTATE, "Unfactored matrix");
3960: MatCheckPreallocated(A, 1);
3962: PetscCall(PetscLogEventBegin(MAT_MatTrSolve, A, Bt, X, 0));
3963: PetscUseTypeMethod(A, mattransposesolve, Bt, X);
3964: PetscCall(PetscLogEventEnd(MAT_MatTrSolve, A, Bt, X, 0));
3965: PetscCall(PetscObjectStateIncrease((PetscObject)X));
3966: PetscFunctionReturn(PETSC_SUCCESS);
3967: }
3969: /*@
3970: MatForwardSolve - Solves $ L x = b $, given a factored matrix, $A = LU $, or
3971: $U^T*D^(1/2) x = b$, given a factored symmetric matrix, $A = U^T*D*U$,
3973: Neighbor-wise Collective
3975: Input Parameters:
3976: + mat - the factored matrix
3977: - b - the right-hand-side vector
3979: Output Parameter:
3980: . x - the result vector
3982: Level: developer
3984: Notes:
3985: `MatSolve()` should be used for most applications, as it performs
3986: a forward solve followed by a backward solve.
3988: The vectors `b` and `x` cannot be the same, i.e., one cannot
3989: call `MatForwardSolve`(A,x,x).
3991: For matrix in `MATSEQBAIJ` format with block size larger than 1,
3992: the diagonal blocks are not implemented as $D = D^(1/2) * D^(1/2)$ yet.
3993: `MatForwardSolve()` solves $U^T*D y = b$, and
3994: `MatBackwardSolve()` solves $U x = y$.
3995: Thus they do not provide a symmetric preconditioner.
3997: .seealso: [](ch_matrices), `Mat`, `MatBackwardSolve()`, `MatGetFactor()`, `MatSolve()`
3998: @*/
3999: PetscErrorCode MatForwardSolve(Mat mat, Vec b, Vec x)
4000: {
4001: PetscFunctionBegin;
4006: PetscCheckSameComm(mat, 1, b, 2);
4007: PetscCheckSameComm(mat, 1, x, 3);
4008: PetscCheck(x != b, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_IDN, "x and b must be different vectors");
4009: PetscCheck(mat->cmap->N == x->map->N, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_SIZ, "Mat mat,Vec x: global dim %" PetscInt_FMT " %" PetscInt_FMT, mat->cmap->N, x->map->N);
4010: PetscCheck(mat->rmap->N == b->map->N, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_SIZ, "Mat mat,Vec b: global dim %" PetscInt_FMT " %" PetscInt_FMT, mat->rmap->N, b->map->N);
4011: PetscCheck(mat->rmap->n == b->map->n, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Mat mat,Vec b: local dim %" PetscInt_FMT " %" PetscInt_FMT, mat->rmap->n, b->map->n);
4012: if (!mat->rmap->N && !mat->cmap->N) PetscFunctionReturn(PETSC_SUCCESS);
4013: MatCheckPreallocated(mat, 1);
4015: PetscCall(PetscLogEventBegin(MAT_ForwardSolve, mat, b, x, 0));
4016: PetscUseTypeMethod(mat, forwardsolve, b, x);
4017: PetscCall(PetscLogEventEnd(MAT_ForwardSolve, mat, b, x, 0));
4018: PetscCall(PetscObjectStateIncrease((PetscObject)x));
4019: PetscFunctionReturn(PETSC_SUCCESS);
4020: }
4022: /*@
4023: MatBackwardSolve - Solves $U x = b$, given a factored matrix, $A = LU$.
4024: $D^(1/2) U x = b$, given a factored symmetric matrix, $A = U^T*D*U$,
4026: Neighbor-wise Collective
4028: Input Parameters:
4029: + mat - the factored matrix
4030: - b - the right-hand-side vector
4032: Output Parameter:
4033: . x - the result vector
4035: Level: developer
4037: Notes:
4038: `MatSolve()` should be used for most applications, as it performs
4039: a forward solve followed by a backward solve.
4041: The vectors `b` and `x` cannot be the same. I.e., one cannot
4042: call `MatBackwardSolve`(A,x,x).
4044: For matrix in `MATSEQBAIJ` format with block size larger than 1,
4045: the diagonal blocks are not implemented as $D = D^(1/2) * D^(1/2)$ yet.
4046: `MatForwardSolve()` solves $U^T*D y = b$, and
4047: `MatBackwardSolve()` solves $U x = y$.
4048: Thus they do not provide a symmetric preconditioner.
4050: .seealso: [](ch_matrices), `Mat`, `MatForwardSolve()`, `MatGetFactor()`, `MatSolve()`
4051: @*/
4052: PetscErrorCode MatBackwardSolve(Mat mat, Vec b, Vec x)
4053: {
4054: PetscFunctionBegin;
4059: PetscCheckSameComm(mat, 1, b, 2);
4060: PetscCheckSameComm(mat, 1, x, 3);
4061: PetscCheck(x != b, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_IDN, "x and b must be different vectors");
4062: PetscCheck(mat->cmap->N == x->map->N, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_SIZ, "Mat mat,Vec x: global dim %" PetscInt_FMT " %" PetscInt_FMT, mat->cmap->N, x->map->N);
4063: PetscCheck(mat->rmap->N == b->map->N, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_SIZ, "Mat mat,Vec b: global dim %" PetscInt_FMT " %" PetscInt_FMT, mat->rmap->N, b->map->N);
4064: PetscCheck(mat->rmap->n == b->map->n, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Mat mat,Vec b: local dim %" PetscInt_FMT " %" PetscInt_FMT, mat->rmap->n, b->map->n);
4065: if (!mat->rmap->N && !mat->cmap->N) PetscFunctionReturn(PETSC_SUCCESS);
4066: MatCheckPreallocated(mat, 1);
4068: PetscCall(PetscLogEventBegin(MAT_BackwardSolve, mat, b, x, 0));
4069: PetscUseTypeMethod(mat, backwardsolve, b, x);
4070: PetscCall(PetscLogEventEnd(MAT_BackwardSolve, mat, b, x, 0));
4071: PetscCall(PetscObjectStateIncrease((PetscObject)x));
4072: PetscFunctionReturn(PETSC_SUCCESS);
4073: }
4075: /*@
4076: MatSolveAdd - Computes $x = y + A^{-1}*b$, given a factored matrix.
4078: Neighbor-wise Collective
4080: Input Parameters:
4081: + mat - the factored matrix
4082: . b - the right-hand-side vector
4083: - y - the vector to be added to
4085: Output Parameter:
4086: . x - the result vector
4088: Level: developer
4090: Note:
4091: The vectors `b` and `x` cannot be the same. I.e., one cannot
4092: call `MatSolveAdd`(A,x,y,x).
4094: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatSolve()`, `MatGetFactor()`, `MatSolveTranspose()`, `MatSolveTransposeAdd()`
4095: @*/
4096: PetscErrorCode MatSolveAdd(Mat mat, Vec b, Vec y, Vec x)
4097: {
4098: PetscScalar one = 1.0;
4099: Vec tmp;
4101: PetscFunctionBegin;
4107: PetscCheckSameComm(mat, 1, b, 2);
4108: PetscCheckSameComm(mat, 1, y, 3);
4109: PetscCheckSameComm(mat, 1, x, 4);
4110: PetscCheck(x != b, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_IDN, "x and b must be different vectors");
4111: PetscCheck(mat->cmap->N == x->map->N, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_SIZ, "Mat mat,Vec x: global dim %" PetscInt_FMT " %" PetscInt_FMT, mat->cmap->N, x->map->N);
4112: PetscCheck(mat->rmap->N == b->map->N, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_SIZ, "Mat mat,Vec b: global dim %" PetscInt_FMT " %" PetscInt_FMT, mat->rmap->N, b->map->N);
4113: PetscCheck(mat->rmap->N == y->map->N, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_SIZ, "Mat mat,Vec y: global dim %" PetscInt_FMT " %" PetscInt_FMT, mat->rmap->N, y->map->N);
4114: PetscCheck(mat->rmap->n == b->map->n, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Mat mat,Vec b: local dim %" PetscInt_FMT " %" PetscInt_FMT, mat->rmap->n, b->map->n);
4115: PetscCheck(x->map->n == y->map->n, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Vec x,Vec y: local dim %" PetscInt_FMT " %" PetscInt_FMT, x->map->n, y->map->n);
4116: if (!mat->rmap->N && !mat->cmap->N) PetscFunctionReturn(PETSC_SUCCESS);
4117: MatCheckPreallocated(mat, 1);
4119: PetscCall(PetscLogEventBegin(MAT_SolveAdd, mat, b, x, y));
4120: PetscCall(VecFlag(x, mat->factorerrortype));
4121: if (mat->factorerrortype) {
4122: PetscCall(PetscInfo(mat, "MatFactorError %d\n", mat->factorerrortype));
4123: } else if (mat->ops->solveadd) {
4124: PetscUseTypeMethod(mat, solveadd, b, y, x);
4125: } else {
4126: /* do the solve then the add manually */
4127: if (x != y) {
4128: PetscCall(MatSolve(mat, b, x));
4129: PetscCall(VecAXPY(x, one, y));
4130: } else {
4131: PetscCall(VecDuplicate(x, &tmp));
4132: PetscCall(VecCopy(x, tmp));
4133: PetscCall(MatSolve(mat, b, x));
4134: PetscCall(VecAXPY(x, one, tmp));
4135: PetscCall(VecDestroy(&tmp));
4136: }
4137: }
4138: PetscCall(PetscLogEventEnd(MAT_SolveAdd, mat, b, x, y));
4139: PetscCall(PetscObjectStateIncrease((PetscObject)x));
4140: PetscFunctionReturn(PETSC_SUCCESS);
4141: }
4143: /*@
4144: MatSolveTranspose - Solves $A^T x = b$, given a factored matrix.
4146: Neighbor-wise Collective
4148: Input Parameters:
4149: + mat - the factored matrix
4150: - b - the right-hand-side vector
4152: Output Parameter:
4153: . x - the result vector
4155: Level: developer
4157: Notes:
4158: The vectors `b` and `x` cannot be the same. I.e., one cannot
4159: call `MatSolveTranspose`(A,x,x).
4161: Most users should employ the `KSP` interface for linear solvers
4162: instead of working directly with matrix algebra routines such as this.
4163: See, e.g., `KSPCreate()`.
4165: .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `KSP`, `MatSolve()`, `MatSolveAdd()`, `MatSolveTransposeAdd()`
4166: @*/
4167: PetscErrorCode MatSolveTranspose(Mat mat, Vec b, Vec x)
4168: {
4169: PetscErrorCode (*f)(Mat, Vec, Vec) = (!mat->ops->solvetranspose && mat->symmetric) ? mat->ops->solve : mat->ops->solvetranspose;
4171: PetscFunctionBegin;
4176: PetscCheckSameComm(mat, 1, b, 2);
4177: PetscCheckSameComm(mat, 1, x, 3);
4178: PetscCheck(x != b, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_IDN, "x and b must be different vectors");
4179: PetscCheck(mat->rmap->N == x->map->N, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_SIZ, "Mat mat,Vec x: global dim %" PetscInt_FMT " %" PetscInt_FMT, mat->rmap->N, x->map->N);
4180: PetscCheck(mat->cmap->N == b->map->N, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_SIZ, "Mat mat,Vec b: global dim %" PetscInt_FMT " %" PetscInt_FMT, mat->cmap->N, b->map->N);
4181: if (!mat->rmap->N && !mat->cmap->N) PetscFunctionReturn(PETSC_SUCCESS);
4182: MatCheckPreallocated(mat, 1);
4183: PetscCall(PetscLogEventBegin(MAT_SolveTranspose, mat, b, x, 0));
4184: PetscCall(VecFlag(x, mat->factorerrortype));
4185: if (mat->factorerrortype) {
4186: PetscCall(PetscInfo(mat, "MatFactorError %d\n", mat->factorerrortype));
4187: } else {
4188: PetscCheck(f, PetscObjectComm((PetscObject)mat), PETSC_ERR_SUP, "Matrix type %s", ((PetscObject)mat)->type_name);
4189: PetscCall((*f)(mat, b, x));
4190: }
4191: PetscCall(PetscLogEventEnd(MAT_SolveTranspose, mat, b, x, 0));
4192: PetscCall(PetscObjectStateIncrease((PetscObject)x));
4193: PetscFunctionReturn(PETSC_SUCCESS);
4194: }
4196: /*@
4197: MatSolveTransposeAdd - Computes $x = y + A^{-T} b$
4198: factored matrix.
4200: Neighbor-wise Collective
4202: Input Parameters:
4203: + mat - the factored matrix
4204: . b - the right-hand-side vector
4205: - y - the vector to be added to
4207: Output Parameter:
4208: . x - the result vector
4210: Level: developer
4212: Note:
4213: The vectors `b` and `x` cannot be the same. I.e., one cannot
4214: call `MatSolveTransposeAdd`(A,x,y,x).
4216: .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatSolve()`, `MatSolveAdd()`, `MatSolveTranspose()`
4217: @*/
4218: PetscErrorCode MatSolveTransposeAdd(Mat mat, Vec b, Vec y, Vec x)
4219: {
4220: PetscScalar one = 1.0;
4221: Vec tmp;
4222: PetscErrorCode (*f)(Mat, Vec, Vec, Vec) = (!mat->ops->solvetransposeadd && mat->symmetric) ? mat->ops->solveadd : mat->ops->solvetransposeadd;
4224: PetscFunctionBegin;
4230: PetscCheckSameComm(mat, 1, b, 2);
4231: PetscCheckSameComm(mat, 1, y, 3);
4232: PetscCheckSameComm(mat, 1, x, 4);
4233: PetscCheck(x != b, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_IDN, "x and b must be different vectors");
4234: PetscCheck(mat->rmap->N == x->map->N, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_SIZ, "Mat mat,Vec x: global dim %" PetscInt_FMT " %" PetscInt_FMT, mat->rmap->N, x->map->N);
4235: PetscCheck(mat->cmap->N == b->map->N, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_SIZ, "Mat mat,Vec b: global dim %" PetscInt_FMT " %" PetscInt_FMT, mat->cmap->N, b->map->N);
4236: PetscCheck(mat->cmap->N == y->map->N, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_SIZ, "Mat mat,Vec y: global dim %" PetscInt_FMT " %" PetscInt_FMT, mat->cmap->N, y->map->N);
4237: PetscCheck(x->map->n == y->map->n, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Vec x,Vec y: local dim %" PetscInt_FMT " %" PetscInt_FMT, x->map->n, y->map->n);
4238: if (!mat->rmap->N && !mat->cmap->N) PetscFunctionReturn(PETSC_SUCCESS);
4239: MatCheckPreallocated(mat, 1);
4241: PetscCall(PetscLogEventBegin(MAT_SolveTransposeAdd, mat, b, x, y));
4242: PetscCall(VecFlag(x, mat->factorerrortype));
4243: if (mat->factorerrortype) {
4244: PetscCall(PetscInfo(mat, "MatFactorError %d\n", mat->factorerrortype));
4245: } else if (f) {
4246: PetscCall((*f)(mat, b, y, x));
4247: } else {
4248: /* do the solve then the add manually */
4249: if (x != y) {
4250: PetscCall(MatSolveTranspose(mat, b, x));
4251: PetscCall(VecAXPY(x, one, y));
4252: } else {
4253: PetscCall(VecDuplicate(x, &tmp));
4254: PetscCall(VecCopy(x, tmp));
4255: PetscCall(MatSolveTranspose(mat, b, x));
4256: PetscCall(VecAXPY(x, one, tmp));
4257: PetscCall(VecDestroy(&tmp));
4258: }
4259: }
4260: PetscCall(PetscLogEventEnd(MAT_SolveTransposeAdd, mat, b, x, y));
4261: PetscCall(PetscObjectStateIncrease((PetscObject)x));
4262: PetscFunctionReturn(PETSC_SUCCESS);
4263: }
4265: // PetscClangLinter pragma disable: -fdoc-section-header-unknown
4266: /*@
4267: MatSOR - Computes relaxation (SOR, Gauss-Seidel) sweeps.
4269: Neighbor-wise Collective
4271: Input Parameters:
4272: + mat - the matrix
4273: . b - the right-hand side
4274: . omega - the relaxation factor
4275: . flag - flag indicating the type of SOR (see below)
4276: . shift - diagonal shift
4277: . its - the number of iterations
4278: - lits - the number of local iterations
4280: Output Parameter:
4281: . x - the solution (can contain an initial guess, use option `SOR_ZERO_INITIAL_GUESS` to indicate no guess)
4283: SOR Flags:
4284: + `SOR_FORWARD_SWEEP` - forward SOR
4285: . `SOR_BACKWARD_SWEEP` - backward SOR
4286: . `SOR_SYMMETRIC_SWEEP` - SSOR (symmetric SOR)
4287: . `SOR_LOCAL_FORWARD_SWEEP` - local forward SOR
4288: . `SOR_LOCAL_BACKWARD_SWEEP` - local forward SOR
4289: . `SOR_LOCAL_SYMMETRIC_SWEEP` - local SSOR
4290: . `SOR_EISENSTAT` - SOR with Eisenstat trick
4291: . `SOR_APPLY_UPPER`, `SOR_APPLY_LOWER` - applies upper/lower triangular part of matrix to vector (with `omega`)
4292: - `SOR_ZERO_INITIAL_GUESS` - zero initial guess
4294: Level: developer
4296: Notes:
4297: `SOR_LOCAL_FORWARD_SWEEP`, `SOR_LOCAL_BACKWARD_SWEEP`, and
4298: `SOR_LOCAL_SYMMETRIC_SWEEP` perform separate independent smoothings
4299: on each processor.
4301: Application programmers will not generally use `MatSOR()` directly,
4302: but instead will employ `PCSOR` or `PCEISENSTAT`
4304: For `MATBAIJ`, `MATSBAIJ`, and `MATAIJ` matrices with inodes, this does a block SOR smoothing, otherwise it does a pointwise smoothing.
4305: For `MATAIJ` matrices with inodes, the block sizes are determined by the inode sizes, not the block size set with `MatSetBlockSize()`
4307: Vectors `x` and `b` CANNOT be the same
4309: The flags are implemented as bitwise inclusive or operations.
4310: For example, use (`SOR_ZERO_INITIAL_GUESS` | `SOR_SYMMETRIC_SWEEP`)
4311: to specify a zero initial guess for SSOR.
4313: Developer Note:
4314: We should add block SOR support for `MATAIJ` matrices with block size set to greater than one and no inodes
4316: .seealso: [](ch_matrices), `Mat`, `MatMult()`, `KSP`, `PC`, `MatGetFactor()`
4317: @*/
4318: PetscErrorCode MatSOR(Mat mat, Vec b, PetscReal omega, MatSORType flag, PetscReal shift, PetscInt its, PetscInt lits, Vec x)
4319: {
4320: PetscFunctionBegin;
4325: PetscCheckSameComm(mat, 1, b, 2);
4326: PetscCheckSameComm(mat, 1, x, 8);
4327: PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
4328: PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
4329: PetscCheck(mat->cmap->N == x->map->N, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_SIZ, "Mat mat,Vec x: global dim %" PetscInt_FMT " %" PetscInt_FMT, mat->cmap->N, x->map->N);
4330: PetscCheck(mat->rmap->N == b->map->N, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_SIZ, "Mat mat,Vec b: global dim %" PetscInt_FMT " %" PetscInt_FMT, mat->rmap->N, b->map->N);
4331: PetscCheck(mat->rmap->n == b->map->n, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Mat mat,Vec b: local dim %" PetscInt_FMT " %" PetscInt_FMT, mat->rmap->n, b->map->n);
4332: PetscCheck(its > 0, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Relaxation requires global its %" PetscInt_FMT " positive", its);
4333: PetscCheck(lits > 0, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Relaxation requires local its %" PetscInt_FMT " positive", lits);
4334: PetscCheck(b != x, PETSC_COMM_SELF, PETSC_ERR_ARG_IDN, "b and x vector cannot be the same");
4336: MatCheckPreallocated(mat, 1);
4337: PetscCall(PetscLogEventBegin(MAT_SOR, mat, b, x, 0));
4338: PetscUseTypeMethod(mat, sor, b, omega, flag, shift, its, lits, x);
4339: PetscCall(PetscLogEventEnd(MAT_SOR, mat, b, x, 0));
4340: PetscCall(PetscObjectStateIncrease((PetscObject)x));
4341: PetscFunctionReturn(PETSC_SUCCESS);
4342: }
4344: /*
4345: Default matrix copy routine.
4346: */
4347: PetscErrorCode MatCopy_Basic(Mat A, Mat B, MatStructure str)
4348: {
4349: PetscInt i, rstart = 0, rend = 0, nz;
4350: const PetscInt *cwork;
4351: const PetscScalar *vwork;
4353: PetscFunctionBegin;
4354: if (B->assembled) PetscCall(MatZeroEntries(B));
4355: if (str == SAME_NONZERO_PATTERN) {
4356: PetscCall(MatGetOwnershipRange(A, &rstart, &rend));
4357: for (i = rstart; i < rend; i++) {
4358: PetscCall(MatGetRow(A, i, &nz, &cwork, &vwork));
4359: PetscCall(MatSetValues(B, 1, &i, nz, cwork, vwork, INSERT_VALUES));
4360: PetscCall(MatRestoreRow(A, i, &nz, &cwork, &vwork));
4361: }
4362: } else {
4363: PetscCall(MatAYPX(B, 0.0, A, str));
4364: }
4365: PetscCall(MatAssemblyBegin(B, MAT_FINAL_ASSEMBLY));
4366: PetscCall(MatAssemblyEnd(B, MAT_FINAL_ASSEMBLY));
4367: PetscFunctionReturn(PETSC_SUCCESS);
4368: }
4370: /*@
4371: MatCopy - Copies a matrix to another matrix.
4373: Collective
4375: Input Parameters:
4376: + A - the matrix
4377: - str - `SAME_NONZERO_PATTERN` or `DIFFERENT_NONZERO_PATTERN`
4379: Output Parameter:
4380: . B - where the copy is put
4382: Level: intermediate
4384: Notes:
4385: If you use `SAME_NONZERO_PATTERN`, then the two matrices must have the same nonzero pattern or the routine will crash.
4387: `MatCopy()` copies the matrix entries of a matrix to another existing
4388: matrix (after first zeroing the second matrix). A related routine is
4389: `MatConvert()`, which first creates a new matrix and then copies the data.
4391: .seealso: [](ch_matrices), `Mat`, `MatConvert()`, `MatDuplicate()`
4392: @*/
4393: PetscErrorCode MatCopy(Mat A, Mat B, MatStructure str)
4394: {
4395: PetscInt i;
4397: PetscFunctionBegin;
4402: PetscCheckSameComm(A, 1, B, 2);
4403: MatCheckPreallocated(B, 2);
4404: PetscCheck(A->assembled, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
4405: PetscCheck(!A->factortype, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
4406: PetscCheck(A->rmap->N == B->rmap->N && A->cmap->N == B->cmap->N, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_SIZ, "Mat A,Mat B: global dim (%" PetscInt_FMT ",%" PetscInt_FMT ") (%" PetscInt_FMT ",%" PetscInt_FMT ")", A->rmap->N, B->rmap->N,
4407: A->cmap->N, B->cmap->N);
4408: MatCheckPreallocated(A, 1);
4409: if (A == B) PetscFunctionReturn(PETSC_SUCCESS);
4411: PetscCall(PetscLogEventBegin(MAT_Copy, A, B, 0, 0));
4412: if (A->ops->copy) PetscUseTypeMethod(A, copy, B, str);
4413: else PetscCall(MatCopy_Basic(A, B, str));
4415: B->stencil.dim = A->stencil.dim;
4416: B->stencil.noc = A->stencil.noc;
4417: for (i = 0; i <= A->stencil.dim + (A->stencil.noc ? 0 : -1); i++) {
4418: B->stencil.dims[i] = A->stencil.dims[i];
4419: B->stencil.starts[i] = A->stencil.starts[i];
4420: }
4422: PetscCall(PetscLogEventEnd(MAT_Copy, A, B, 0, 0));
4423: PetscCall(PetscObjectStateIncrease((PetscObject)B));
4424: PetscFunctionReturn(PETSC_SUCCESS);
4425: }
4427: /*@
4428: MatConvert - Converts a matrix to another matrix, either of the same
4429: or different type.
4431: Collective
4433: Input Parameters:
4434: + mat - the matrix
4435: . newtype - new matrix type. Use `MATSAME` to create a new matrix of the
4436: same type as the original matrix.
4437: - reuse - denotes if the destination matrix is to be created or reused.
4438: Use `MAT_INPLACE_MATRIX` for inplace conversion (that is when you want the input `Mat` to be changed to contain the matrix in the new format), otherwise use
4439: `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX` (can only be used after the first call was made with `MAT_INITIAL_MATRIX`, causes the matrix space in M to be reused).
4441: Output Parameter:
4442: . M - pointer to place new matrix
4444: Level: intermediate
4446: Notes:
4447: `MatConvert()` first creates a new matrix and then copies the data from
4448: the first matrix. A related routine is `MatCopy()`, which copies the matrix
4449: entries of one matrix to another already existing matrix context.
4451: Cannot be used to convert a sequential matrix to parallel or parallel to sequential,
4452: the MPI communicator of the generated matrix is always the same as the communicator
4453: of the input matrix.
4455: .seealso: [](ch_matrices), `Mat`, `MatCopy()`, `MatDuplicate()`, `MAT_INITIAL_MATRIX`, `MAT_REUSE_MATRIX`, `MAT_INPLACE_MATRIX`
4456: @*/
4457: PetscErrorCode MatConvert(Mat mat, MatType newtype, MatReuse reuse, Mat *M)
4458: {
4459: PetscBool sametype, issame, flg;
4460: PetscBool3 issymmetric, ishermitian, isspd;
4461: char convname[256], mtype[256];
4462: Mat B;
4464: PetscFunctionBegin;
4467: PetscAssertPointer(M, 4);
4468: PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
4469: PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
4470: MatCheckPreallocated(mat, 1);
4472: PetscCall(PetscOptionsGetString(((PetscObject)mat)->options, ((PetscObject)mat)->prefix, "-matconvert_type", mtype, sizeof(mtype), &flg));
4473: if (flg) newtype = mtype;
4475: PetscCall(PetscObjectTypeCompare((PetscObject)mat, newtype, &sametype));
4476: PetscCall(PetscStrcmp(newtype, "same", &issame));
4477: PetscCheck(!(reuse == MAT_INPLACE_MATRIX) || !(mat != *M), PetscObjectComm((PetscObject)mat), PETSC_ERR_SUP, "MAT_INPLACE_MATRIX requires same input and output matrix");
4478: if (reuse == MAT_REUSE_MATRIX) {
4480: PetscCheck(mat != *M, PetscObjectComm((PetscObject)mat), PETSC_ERR_SUP, "MAT_REUSE_MATRIX means reuse matrix in final argument, perhaps you mean MAT_INPLACE_MATRIX");
4481: }
4483: if ((reuse == MAT_INPLACE_MATRIX) && (issame || sametype)) {
4484: PetscCall(PetscInfo(mat, "Early return for inplace %s %d %d\n", ((PetscObject)mat)->type_name, sametype, issame));
4485: PetscFunctionReturn(PETSC_SUCCESS);
4486: }
4488: /* Cache Mat options because some converters use MatHeaderReplace() */
4489: issymmetric = mat->symmetric;
4490: ishermitian = mat->hermitian;
4491: isspd = mat->spd;
4493: if ((sametype || issame) && (reuse == MAT_INITIAL_MATRIX) && mat->ops->duplicate) {
4494: PetscCall(PetscInfo(mat, "Calling duplicate for initial matrix %s %d %d\n", ((PetscObject)mat)->type_name, sametype, issame));
4495: PetscUseTypeMethod(mat, duplicate, MAT_COPY_VALUES, M);
4496: } else {
4497: PetscErrorCode (*conv)(Mat, MatType, MatReuse, Mat *) = NULL;
4498: const char *prefix[3] = {"seq", "mpi", ""};
4499: PetscInt i;
4500: /*
4501: Order of precedence:
4502: 0) See if newtype is a superclass of the current matrix.
4503: 1) See if a specialized converter is known to the current matrix.
4504: 2) See if a specialized converter is known to the desired matrix class.
4505: 3) See if a good general converter is registered for the desired class
4506: (as of 6/27/03 only MATMPIADJ falls into this category).
4507: 4) See if a good general converter is known for the current matrix.
4508: 5) Use a really basic converter.
4509: */
4511: /* 0) See if newtype is a superclass of the current matrix.
4512: i.e mat is mpiaij and newtype is aij */
4513: for (i = 0; i < (PetscInt)PETSC_STATIC_ARRAY_LENGTH(prefix); i++) {
4514: PetscCall(PetscStrncpy(convname, prefix[i], sizeof(convname)));
4515: PetscCall(PetscStrlcat(convname, newtype, sizeof(convname)));
4516: PetscCall(PetscStrcmp(convname, ((PetscObject)mat)->type_name, &flg));
4517: PetscCall(PetscInfo(mat, "Check superclass %s %s -> %d\n", convname, ((PetscObject)mat)->type_name, flg));
4518: if (flg) {
4519: if (reuse == MAT_INPLACE_MATRIX) {
4520: PetscCall(PetscInfo(mat, "Early return\n"));
4521: PetscFunctionReturn(PETSC_SUCCESS);
4522: } else if (reuse == MAT_INITIAL_MATRIX && mat->ops->duplicate) {
4523: PetscCall(PetscInfo(mat, "Calling MatDuplicate\n"));
4524: PetscUseTypeMethod(mat, duplicate, MAT_COPY_VALUES, M);
4525: PetscFunctionReturn(PETSC_SUCCESS);
4526: } else if (reuse == MAT_REUSE_MATRIX && mat->ops->copy) {
4527: PetscCall(PetscInfo(mat, "Calling MatCopy\n"));
4528: PetscCall(MatCopy(mat, *M, SAME_NONZERO_PATTERN));
4529: PetscFunctionReturn(PETSC_SUCCESS);
4530: }
4531: }
4532: }
4533: /* 1) See if a specialized converter is known to the current matrix and the desired class */
4534: for (i = 0; i < (PetscInt)PETSC_STATIC_ARRAY_LENGTH(prefix); i++) {
4535: PetscCall(PetscStrncpy(convname, "MatConvert_", sizeof(convname)));
4536: PetscCall(PetscStrlcat(convname, ((PetscObject)mat)->type_name, sizeof(convname)));
4537: PetscCall(PetscStrlcat(convname, "_", sizeof(convname)));
4538: PetscCall(PetscStrlcat(convname, prefix[i], sizeof(convname)));
4539: PetscCall(PetscStrlcat(convname, issame ? ((PetscObject)mat)->type_name : newtype, sizeof(convname)));
4540: PetscCall(PetscStrlcat(convname, "_C", sizeof(convname)));
4541: PetscCall(PetscObjectQueryFunction((PetscObject)mat, convname, &conv));
4542: PetscCall(PetscInfo(mat, "Check specialized (1) %s (%s) -> %d\n", convname, ((PetscObject)mat)->type_name, !!conv));
4543: if (conv) goto foundconv;
4544: }
4546: /* 2) See if a specialized converter is known to the desired matrix class. */
4547: PetscCall(MatCreate(PetscObjectComm((PetscObject)mat), &B));
4548: PetscCall(MatSetSizes(B, mat->rmap->n, mat->cmap->n, mat->rmap->N, mat->cmap->N));
4549: PetscCall(MatSetType(B, newtype));
4550: for (i = 0; i < (PetscInt)PETSC_STATIC_ARRAY_LENGTH(prefix); i++) {
4551: PetscCall(PetscStrncpy(convname, "MatConvert_", sizeof(convname)));
4552: PetscCall(PetscStrlcat(convname, ((PetscObject)mat)->type_name, sizeof(convname)));
4553: PetscCall(PetscStrlcat(convname, "_", sizeof(convname)));
4554: PetscCall(PetscStrlcat(convname, prefix[i], sizeof(convname)));
4555: PetscCall(PetscStrlcat(convname, newtype, sizeof(convname)));
4556: PetscCall(PetscStrlcat(convname, "_C", sizeof(convname)));
4557: PetscCall(PetscObjectQueryFunction((PetscObject)B, convname, &conv));
4558: PetscCall(PetscInfo(mat, "Check specialized (2) %s (%s) -> %d\n", convname, ((PetscObject)B)->type_name, !!conv));
4559: if (conv) {
4560: PetscCall(MatDestroy(&B));
4561: goto foundconv;
4562: }
4563: }
4565: /* 3) See if a good general converter is registered for the desired class */
4566: conv = B->ops->convertfrom;
4567: PetscCall(PetscInfo(mat, "Check convertfrom (%s) -> %d\n", ((PetscObject)B)->type_name, !!conv));
4568: PetscCall(MatDestroy(&B));
4569: if (conv) goto foundconv;
4571: /* 4) See if a good general converter is known for the current matrix */
4572: if (mat->ops->convert) conv = mat->ops->convert;
4573: PetscCall(PetscInfo(mat, "Check general convert (%s) -> %d\n", ((PetscObject)mat)->type_name, !!conv));
4574: if (conv) goto foundconv;
4576: /* 5) Use a really basic converter. */
4577: PetscCall(PetscInfo(mat, "Using MatConvert_Basic\n"));
4578: conv = MatConvert_Basic;
4580: foundconv:
4581: PetscCall(PetscLogEventBegin(MAT_Convert, mat, 0, 0, 0));
4582: PetscCall((*conv)(mat, newtype, reuse, M));
4583: if (mat->rmap->mapping && mat->cmap->mapping && !(*M)->rmap->mapping && !(*M)->cmap->mapping) {
4584: /* the block sizes must be same if the mappings are copied over */
4585: (*M)->rmap->bs = mat->rmap->bs;
4586: (*M)->cmap->bs = mat->cmap->bs;
4587: PetscCall(PetscObjectReference((PetscObject)mat->rmap->mapping));
4588: PetscCall(PetscObjectReference((PetscObject)mat->cmap->mapping));
4589: (*M)->rmap->mapping = mat->rmap->mapping;
4590: (*M)->cmap->mapping = mat->cmap->mapping;
4591: }
4592: (*M)->stencil.dim = mat->stencil.dim;
4593: (*M)->stencil.noc = mat->stencil.noc;
4594: for (i = 0; i <= mat->stencil.dim + (mat->stencil.noc ? 0 : -1); i++) {
4595: (*M)->stencil.dims[i] = mat->stencil.dims[i];
4596: (*M)->stencil.starts[i] = mat->stencil.starts[i];
4597: }
4598: PetscCall(PetscLogEventEnd(MAT_Convert, mat, 0, 0, 0));
4599: }
4600: PetscCall(PetscObjectStateIncrease((PetscObject)*M));
4602: /* Reset Mat options */
4603: if (issymmetric != PETSC_BOOL3_UNKNOWN) PetscCall(MatSetOption(*M, MAT_SYMMETRIC, PetscBool3ToBool(issymmetric)));
4604: if (ishermitian != PETSC_BOOL3_UNKNOWN) PetscCall(MatSetOption(*M, MAT_HERMITIAN, PetscBool3ToBool(ishermitian)));
4605: if (isspd != PETSC_BOOL3_UNKNOWN) PetscCall(MatSetOption(*M, MAT_SPD, PetscBool3ToBool(isspd)));
4606: PetscFunctionReturn(PETSC_SUCCESS);
4607: }
4609: /*@
4610: MatFactorGetSolverType - Returns name of the package providing the factorization routines
4612: Not Collective
4614: Input Parameter:
4615: . mat - the matrix, must be a factored matrix
4617: Output Parameter:
4618: . type - the string name of the package (do not free this string)
4620: Level: intermediate
4622: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatGetFactor()`, `MatSolverType`, `MatCopy()`, `MatDuplicate()`, `MatGetFactorAvailable()`
4623: @*/
4624: PetscErrorCode MatFactorGetSolverType(Mat mat, MatSolverType *type)
4625: {
4626: PetscErrorCode (*conv)(Mat, MatSolverType *);
4628: PetscFunctionBegin;
4631: PetscAssertPointer(type, 2);
4632: PetscCheck(mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Only for factored matrix");
4633: PetscCall(PetscObjectQueryFunction((PetscObject)mat, "MatFactorGetSolverType_C", &conv));
4634: if (conv) PetscCall((*conv)(mat, type));
4635: else *type = MATSOLVERPETSC;
4636: PetscFunctionReturn(PETSC_SUCCESS);
4637: }
4639: typedef struct _MatSolverTypeForSpecifcType *MatSolverTypeForSpecifcType;
4640: struct _MatSolverTypeForSpecifcType {
4641: MatType mtype;
4642: /* no entry for MAT_FACTOR_NONE */
4643: PetscErrorCode (*createfactor[MAT_FACTOR_NUM_TYPES - 1])(Mat, MatFactorType, Mat *);
4644: MatSolverTypeForSpecifcType next;
4645: };
4647: typedef struct _MatSolverTypeHolder *MatSolverTypeHolder;
4648: struct _MatSolverTypeHolder {
4649: char *name;
4650: MatSolverTypeForSpecifcType handlers;
4651: MatSolverTypeHolder next;
4652: };
4654: static MatSolverTypeHolder MatSolverTypeHolders = NULL;
4656: /*@C
4657: MatSolverTypeRegister - Registers a `MatSolverType` that works for a particular matrix type
4659: Logically Collective, No Fortran Support
4661: Input Parameters:
4662: + package - name of the package, for example `petsc` or `superlu`
4663: . mtype - the matrix type that works with this package
4664: . ftype - the type of factorization supported by the package
4665: - createfactor - routine that will create the factored matrix ready to be used
4667: Level: developer
4669: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatFactorGetSolverType()`, `MatCopy()`, `MatDuplicate()`, `MatGetFactorAvailable()`,
4670: `MatGetFactor()`
4671: @*/
4672: PetscErrorCode MatSolverTypeRegister(MatSolverType package, MatType mtype, MatFactorType ftype, PetscErrorCode (*createfactor)(Mat, MatFactorType, Mat *))
4673: {
4674: MatSolverTypeHolder next = MatSolverTypeHolders, prev = NULL;
4675: PetscBool flg;
4676: MatSolverTypeForSpecifcType inext, iprev = NULL;
4678: PetscFunctionBegin;
4679: PetscCall(MatInitializePackage());
4680: if (!next) {
4681: PetscCall(PetscNew(&MatSolverTypeHolders));
4682: PetscCall(PetscStrallocpy(package, &MatSolverTypeHolders->name));
4683: PetscCall(PetscNew(&MatSolverTypeHolders->handlers));
4684: PetscCall(PetscStrallocpy(mtype, (char **)&MatSolverTypeHolders->handlers->mtype));
4685: MatSolverTypeHolders->handlers->createfactor[(int)ftype - 1] = createfactor;
4686: PetscFunctionReturn(PETSC_SUCCESS);
4687: }
4688: while (next) {
4689: PetscCall(PetscStrcasecmp(package, next->name, &flg));
4690: if (flg) {
4691: PetscCheck(next->handlers, PETSC_COMM_SELF, PETSC_ERR_PLIB, "MatSolverTypeHolder is missing handlers");
4692: inext = next->handlers;
4693: while (inext) {
4694: PetscCall(PetscStrcasecmp(mtype, inext->mtype, &flg));
4695: if (flg) {
4696: inext->createfactor[(int)ftype - 1] = createfactor;
4697: PetscFunctionReturn(PETSC_SUCCESS);
4698: }
4699: iprev = inext;
4700: inext = inext->next;
4701: }
4702: PetscCall(PetscNew(&iprev->next));
4703: PetscCall(PetscStrallocpy(mtype, (char **)&iprev->next->mtype));
4704: iprev->next->createfactor[(int)ftype - 1] = createfactor;
4705: PetscFunctionReturn(PETSC_SUCCESS);
4706: }
4707: prev = next;
4708: next = next->next;
4709: }
4710: PetscCall(PetscNew(&prev->next));
4711: PetscCall(PetscStrallocpy(package, &prev->next->name));
4712: PetscCall(PetscNew(&prev->next->handlers));
4713: PetscCall(PetscStrallocpy(mtype, (char **)&prev->next->handlers->mtype));
4714: prev->next->handlers->createfactor[(int)ftype - 1] = createfactor;
4715: PetscFunctionReturn(PETSC_SUCCESS);
4716: }
4718: /*@C
4719: MatSolverTypeGet - Gets the function that creates the factor matrix if it exist
4721: Input Parameters:
4722: + type - name of the package, for example `petsc` or `superlu`, if this is `NULL`, then the first result that satisfies the other criteria is returned
4723: . ftype - the type of factorization supported by the type
4724: - mtype - the matrix type that works with this type
4726: Output Parameters:
4727: + foundtype - `PETSC_TRUE` if the type was registered
4728: . foundmtype - `PETSC_TRUE` if the type supports the requested mtype
4729: - createfactor - routine that will create the factored matrix ready to be used or `NULL` if not found
4731: Calling sequence of `createfactor`:
4732: + A - the matrix providing the factor matrix
4733: . ftype - the `MatFactorType` of the factor requested
4734: - B - the new factor matrix that responds to MatXXFactorSymbolic,Numeric() functions, such as `MatLUFactorSymbolic()`
4736: Level: developer
4738: Note:
4739: When `type` is `NULL` the available functions are searched for based on the order of the calls to `MatSolverTypeRegister()` in `MatInitializePackage()`.
4740: Since different PETSc configurations may have different external solvers, seemingly identical runs with different PETSc configurations may use a different solver.
4741: For example if one configuration had `--download-mumps` while a different one had `--download-superlu_dist`.
4743: .seealso: [](ch_matrices), `Mat`, `MatFactorType`, `MatType`, `MatCopy()`, `MatDuplicate()`, `MatGetFactorAvailable()`, `MatSolverTypeRegister()`, `MatGetFactor()`,
4744: `MatInitializePackage()`
4745: @*/
4746: PetscErrorCode MatSolverTypeGet(MatSolverType type, MatType mtype, MatFactorType ftype, PetscBool *foundtype, PetscBool *foundmtype, PetscErrorCode (**createfactor)(Mat A, MatFactorType ftype, Mat *B))
4747: {
4748: MatSolverTypeHolder next = MatSolverTypeHolders;
4749: PetscBool flg;
4750: MatSolverTypeForSpecifcType inext;
4752: PetscFunctionBegin;
4753: if (foundtype) *foundtype = PETSC_FALSE;
4754: if (foundmtype) *foundmtype = PETSC_FALSE;
4755: if (createfactor) *createfactor = NULL;
4757: if (type) {
4758: while (next) {
4759: PetscCall(PetscStrcasecmp(type, next->name, &flg));
4760: if (flg) {
4761: if (foundtype) *foundtype = PETSC_TRUE;
4762: inext = next->handlers;
4763: while (inext) {
4764: PetscCall(PetscStrbeginswith(mtype, inext->mtype, &flg));
4765: if (flg) {
4766: if (foundmtype) *foundmtype = PETSC_TRUE;
4767: if (createfactor) *createfactor = inext->createfactor[(int)ftype - 1];
4768: PetscFunctionReturn(PETSC_SUCCESS);
4769: }
4770: inext = inext->next;
4771: }
4772: }
4773: next = next->next;
4774: }
4775: } else {
4776: while (next) {
4777: inext = next->handlers;
4778: while (inext) {
4779: PetscCall(PetscStrcmp(mtype, inext->mtype, &flg));
4780: if (flg && inext->createfactor[(int)ftype - 1]) {
4781: if (foundtype) *foundtype = PETSC_TRUE;
4782: if (foundmtype) *foundmtype = PETSC_TRUE;
4783: if (createfactor) *createfactor = inext->createfactor[(int)ftype - 1];
4784: PetscFunctionReturn(PETSC_SUCCESS);
4785: }
4786: inext = inext->next;
4787: }
4788: next = next->next;
4789: }
4790: /* try with base classes inext->mtype */
4791: next = MatSolverTypeHolders;
4792: while (next) {
4793: inext = next->handlers;
4794: while (inext) {
4795: PetscCall(PetscStrbeginswith(mtype, inext->mtype, &flg));
4796: if (flg && inext->createfactor[(int)ftype - 1]) {
4797: if (foundtype) *foundtype = PETSC_TRUE;
4798: if (foundmtype) *foundmtype = PETSC_TRUE;
4799: if (createfactor) *createfactor = inext->createfactor[(int)ftype - 1];
4800: PetscFunctionReturn(PETSC_SUCCESS);
4801: }
4802: inext = inext->next;
4803: }
4804: next = next->next;
4805: }
4806: }
4807: PetscFunctionReturn(PETSC_SUCCESS);
4808: }
4810: PetscErrorCode MatSolverTypeDestroy(void)
4811: {
4812: MatSolverTypeHolder next = MatSolverTypeHolders, prev;
4813: MatSolverTypeForSpecifcType inext, iprev;
4815: PetscFunctionBegin;
4816: while (next) {
4817: PetscCall(PetscFree(next->name));
4818: inext = next->handlers;
4819: while (inext) {
4820: PetscCall(PetscFree(inext->mtype));
4821: iprev = inext;
4822: inext = inext->next;
4823: PetscCall(PetscFree(iprev));
4824: }
4825: prev = next;
4826: next = next->next;
4827: PetscCall(PetscFree(prev));
4828: }
4829: MatSolverTypeHolders = NULL;
4830: PetscFunctionReturn(PETSC_SUCCESS);
4831: }
4833: static PetscErrorCode MatGetFactor_Private(Mat mat, MatFactorType ftype, PetscBool exact, PetscBool *found, Mat *f)
4834: {
4835: MatSolverTypeHolder next = MatSolverTypeHolders;
4836: MatSolverTypeForSpecifcType inext;
4837: PetscBool flg, same;
4839: PetscFunctionBegin;
4840: *found = PETSC_FALSE;
4841: *f = NULL;
4842: /* When no solver type is requested, MatGetFactor() must honor registration order, but a registered
4843: MatSolverType may only be able to reject a particular MatType at runtime by returning NULL in *f.
4844: Keep walking the registry until a matching backend actually creates a factor. */
4845: while (next) {
4846: inext = next->handlers;
4847: while (inext) {
4848: PetscCall(PetscStrcmp(((PetscObject)mat)->type_name, inext->mtype, &same));
4849: if (exact) flg = same;
4850: else {
4851: /* Do the base-type pass separately from the exact pass so exact registrations for the MatType
4852: are all tried before broader registrations such as implementation base classes. */
4853: PetscCall(PetscStrbeginswith(((PetscObject)mat)->type_name, inext->mtype, &flg));
4854: flg = (PetscBool)(flg && !same);
4855: }
4856: if (flg && inext->createfactor[(int)ftype - 1]) {
4857: *found = PETSC_TRUE;
4858: PetscCall((*inext->createfactor[(int)ftype - 1])(mat, ftype, f));
4859: if (*f) PetscFunctionReturn(PETSC_SUCCESS);
4860: }
4861: inext = inext->next;
4862: }
4863: next = next->next;
4864: }
4865: PetscFunctionReturn(PETSC_SUCCESS);
4866: }
4868: /*@
4869: MatFactorGetCanUseOrdering - Indicates if the factorization can use the ordering provided in `MatLUFactorSymbolic()`, `MatCholeskyFactorSymbolic()`
4871: Logically Collective
4873: Input Parameter:
4874: . mat - the matrix
4876: Output Parameter:
4877: . flg - `PETSC_TRUE` if uses the ordering
4879: Level: developer
4881: Note:
4882: Most internal PETSc factorizations use the ordering passed to the factorization routine but external
4883: packages do not, thus we want to skip generating the ordering when it is not needed or used.
4885: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatCopy()`, `MatDuplicate()`, `MatGetFactorAvailable()`, `MatGetFactor()`, `MatLUFactorSymbolic()`, `MatCholeskyFactorSymbolic()`
4886: @*/
4887: PetscErrorCode MatFactorGetCanUseOrdering(Mat mat, PetscBool *flg)
4888: {
4889: PetscFunctionBegin;
4890: *flg = mat->canuseordering;
4891: PetscFunctionReturn(PETSC_SUCCESS);
4892: }
4894: /*@
4895: MatFactorGetPreferredOrdering - The preferred ordering for a particular matrix factor object
4897: Logically Collective
4899: Input Parameters:
4900: + mat - the matrix obtained with `MatGetFactor()`
4901: - ftype - the factorization type to be used
4903: Output Parameter:
4904: . otype - the preferred ordering type
4906: Level: developer
4908: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatFactorType`, `MatOrderingType`, `MatCopy()`, `MatDuplicate()`, `MatGetFactorAvailable()`, `MatGetFactor()`, `MatLUFactorSymbolic()`, `MatCholeskyFactorSymbolic()`
4909: @*/
4910: PetscErrorCode MatFactorGetPreferredOrdering(Mat mat, MatFactorType ftype, MatOrderingType *otype)
4911: {
4912: PetscFunctionBegin;
4913: *otype = mat->preferredordering[ftype];
4914: PetscCheck(*otype, PETSC_COMM_SELF, PETSC_ERR_PLIB, "MatFactor did not have a preferred ordering");
4915: PetscFunctionReturn(PETSC_SUCCESS);
4916: }
4918: /*@
4919: MatGetFactor - Returns a matrix suitable to calls to routines such as `MatLUFactorSymbolic()`, `MatCholeskyFactorSymbolic()`, `MatILUFactorSymbolic()`,
4920: `MatICCFactorSymbolic()`, `MatLUFactorNumeric()`, and `MatCholeskyFactorNumeric()`
4922: Collective
4924: Input Parameters:
4925: + mat - the matrix
4926: . type - name of solver type, for example, `superlu_dist`, `petsc` (to use PETSc's solver if it is available), if this is `NULL`, then the first result that satisfies
4927: the other criteria is returned
4928: - ftype - factor type, `MAT_FACTOR_LU`, `MAT_FACTOR_CHOLESKY`, `MAT_FACTOR_ICC`, `MAT_FACTOR_ILU`, `MAT_FACTOR_QR`
4930: Output Parameter:
4931: . f - the factor matrix used with MatXXFactorSymbolic,Numeric() calls. Can be `NULL` in some cases, see notes below.
4933: Options Database Keys:
4934: + -pc_factor_mat_solver_type type - choose the type at run time. When using `KSP` solvers
4935: . -pc_factor_mat_factor_on_host (true|false) - do matrix factorization on host (with device matrices). Default is doing it on device
4936: - -pc_factor_mat_solve_on_host (true|false) - do matrix solve on host (with device matrices). Default is doing it on device
4938: Level: intermediate
4940: Notes:
4941: Some of the packages, such as MUMPS, have options for controlling the factorization, these are in the form `-prefix_mat_packagename_packageoption`
4942: (for example, `-mat_mumps_icntl_6 1`) where `prefix` is normally set automatically from the calling `KSP`/`PC`. If `MatGetFactor()` is called directly,
4943: without using a `PC`, one can set the prefix by
4944: calling `MatSetOptionsPrefixFactor()` on the originating matrix or `MatSetOptionsPrefix()` on the resulting factor matrix.
4946: Some PETSc matrix formats have alternative solvers available that are provided by alternative packages
4947: such as PaStiX, SuperLU_DIST, MUMPS etc. PETSc must have been configured to use the external solver,
4948: using the corresponding `./configure` option such as `--download-package` or `--with-package-dir`.
4950: When `type` is `NULL` the available results are searched for based on the order of the calls to `MatSolverTypeRegister()` in `MatInitializePackage()`.
4951: Since different PETSc configurations may have different external solvers, seemingly identical runs with different PETSc configurations may use a different solver.
4952: For example if one configuration had `--download-mumps` while a different one had `--download-superlu_dist`.
4954: The return matrix can be `NULL` if the requested factorization is not available, since some combinations of matrix types and factorization
4955: types registered with `MatSolverTypeRegister()` cannot be fully tested if not at runtime.
4957: Developer Note:
4958: This should actually be called `MatCreateFactor()` since it creates a new factor object
4960: The `MatGetFactor()` implementations should not be accessing the PETSc options database or making other decisions about solver options,
4961: that should be delayed until the later operations. This is to ensure the correct options prefix has been set in the factor matrix.
4963: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `KSP`, `MatSolverType`, `MatFactorType`, `MatCopy()`, `MatDuplicate()`,
4964: `MatGetFactorAvailable()`, `MatFactorGetCanUseOrdering()`, `MatSolverTypeRegister()`, `MatSolverTypeGet()`,
4965: `MAT_FACTOR_LU`, `MAT_FACTOR_CHOLESKY`, `MAT_FACTOR_ICC`, `MAT_FACTOR_ILU`, `MAT_FACTOR_QR`, `MatInitializePackage()`,
4966: `MatLUFactorSymbolic()`, `MatCholeskyFactorSymbolic()`, `MatILUFactorSymbolic()`,
4967: `MatICCFactorSymbolic()`, `MatLUFactorNumeric()`, `MatCholeskyFactorNumeric()`
4968: @*/
4969: PetscErrorCode MatGetFactor(Mat mat, MatSolverType type, MatFactorType ftype, Mat *f)
4970: {
4971: PetscBool foundtype, foundmtype, shell, hasop = PETSC_FALSE;
4972: PetscErrorCode (*conv)(Mat, MatFactorType, Mat *);
4974: PetscFunctionBegin;
4978: PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
4979: MatCheckPreallocated(mat, 1);
4981: PetscCall(MatIsShell(mat, &shell));
4982: if (shell) PetscCall(MatHasOperation(mat, MATOP_GET_FACTOR, &hasop));
4983: if (hasop) {
4984: PetscUseTypeMethod(mat, getfactor, type, ftype, f);
4985: PetscFunctionReturn(PETSC_SUCCESS);
4986: }
4988: if (!type) {
4989: PetscBool foundbase;
4991: /* First try exact MatType registrations in solver registration order. If all matching backends
4992: decline this matrix instance by returning NULL, then try base-type registrations. */
4993: PetscCall(MatGetFactor_Private(mat, ftype, PETSC_TRUE, &foundtype, f));
4994: if (!*f) {
4995: PetscCall(MatGetFactor_Private(mat, ftype, PETSC_FALSE, &foundbase, f));
4996: foundtype = (PetscBool)(foundtype || foundbase);
4997: }
4998: PetscCheck(foundtype, 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);
4999: if (mat->factorprefix) PetscCall(MatSetOptionsPrefix(*f, mat->factorprefix));
5000: PetscFunctionReturn(PETSC_SUCCESS);
5001: }
5003: PetscCall(MatSolverTypeGet(type, ((PetscObject)mat)->type_name, ftype, &foundtype, &foundmtype, &conv));
5004: PetscCheck(foundtype, PetscObjectComm((PetscObject)mat), PETSC_ERR_MISSING_FACTOR, "Could not locate%s solver type%s%s for factorization type %s and matrix type %s.%s%s", !type ? " a" : "", type ? " " : "", type ? type : "", MatFactorTypes[ftype],
5005: ((PetscObject)mat)->type_name, type ? " Perhaps you must ./configure with --download-" : "", type ? type : "");
5006: PetscCheck(foundmtype, PetscObjectComm((PetscObject)mat), PETSC_ERR_MISSING_FACTOR, "MatSolverType %s does not support matrix type %s", type, ((PetscObject)mat)->type_name);
5007: 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);
5009: PetscCall((*conv)(mat, ftype, f));
5010: if (mat->factorprefix) PetscCall(MatSetOptionsPrefix(*f, mat->factorprefix));
5011: PetscFunctionReturn(PETSC_SUCCESS);
5012: }
5014: /*@
5015: MatGetFactorAvailable - Returns a flag if matrix supports particular type and factor type
5017: Not Collective
5019: Input Parameters:
5020: + mat - the matrix
5021: . type - name of solver type, for example, `superlu`, `petsc` (to use PETSc's default)
5022: - ftype - factor type, `MAT_FACTOR_LU`, `MAT_FACTOR_CHOLESKY`, `MAT_FACTOR_ICC`, `MAT_FACTOR_ILU`, `MAT_FACTOR_QR`
5024: Output Parameter:
5025: . flg - PETSC_TRUE if the factorization is available
5027: Level: intermediate
5029: Notes:
5030: Some PETSc matrix formats have alternative solvers available that are contained in alternative packages
5031: such as pastix, superlu, mumps etc.
5033: PETSc must have been ./configure to use the external solver, using the option --download-package
5035: Developer Note:
5036: This should actually be called `MatCreateFactorAvailable()` since `MatGetFactor()` creates a new factor object
5038: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatSolverType`, `MatFactorType`, `MatGetFactor()`, `MatCopy()`, `MatDuplicate()`, `MatSolverTypeRegister()`,
5039: `MAT_FACTOR_LU`, `MAT_FACTOR_CHOLESKY`, `MAT_FACTOR_ICC`, `MAT_FACTOR_ILU`, `MAT_FACTOR_QR`, `MatSolverTypeGet()`
5040: @*/
5041: PetscErrorCode MatGetFactorAvailable(Mat mat, MatSolverType type, MatFactorType ftype, PetscBool *flg)
5042: {
5043: PetscErrorCode (*gconv)(Mat, MatFactorType, Mat *);
5045: PetscFunctionBegin;
5047: PetscAssertPointer(flg, 4);
5049: *flg = PETSC_FALSE;
5050: if (!((PetscObject)mat)->type_name) PetscFunctionReturn(PETSC_SUCCESS);
5052: PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
5053: MatCheckPreallocated(mat, 1);
5055: PetscCall(MatSolverTypeGet(type, ((PetscObject)mat)->type_name, ftype, NULL, NULL, &gconv));
5056: *flg = gconv ? PETSC_TRUE : PETSC_FALSE;
5057: PetscFunctionReturn(PETSC_SUCCESS);
5058: }
5060: /*@
5061: MatDuplicate - Duplicates a matrix including the non-zero structure.
5063: Collective
5065: Input Parameters:
5066: + mat - the matrix
5067: - op - One of `MAT_DO_NOT_COPY_VALUES`, `MAT_COPY_VALUES`, or `MAT_SHARE_NONZERO_PATTERN`.
5068: See the manual page for `MatDuplicateOption()` for an explanation of these options.
5070: Output Parameter:
5071: . M - pointer to place new matrix
5073: Level: intermediate
5075: Notes:
5076: You cannot change the nonzero pattern for the parent or child matrix later if you use `MAT_SHARE_NONZERO_PATTERN`.
5078: If `op` is not `MAT_COPY_VALUES` the numerical values in the new matrix are zeroed.
5080: 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.
5082: When original mat is a product of matrix operation, e.g., an output of `MatMatMult()` or `MatCreateSubMatrix()`, only the matrix data structure of `mat`
5083: is duplicated and the internal data structures created for the reuse of previous matrix operations are not duplicated.
5084: User should not use `MatDuplicate()` to create new matrix `M` if `M` is intended to be reused as the product of matrix operation.
5086: .seealso: [](ch_matrices), `Mat`, `MatCopy()`, `MatConvert()`, `MatDuplicateOption`
5087: @*/
5088: PetscErrorCode MatDuplicate(Mat mat, MatDuplicateOption op, Mat *M)
5089: {
5090: Mat B;
5091: VecType vtype;
5092: PetscInt i;
5093: PetscObject dm, container_h, container_d;
5094: PetscErrorCodeFn *viewf;
5096: PetscFunctionBegin;
5099: PetscAssertPointer(M, 3);
5100: PetscCheck(op != MAT_COPY_VALUES || mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "MAT_COPY_VALUES not allowed for unassembled matrix");
5101: PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
5102: MatCheckPreallocated(mat, 1);
5104: PetscCall(PetscLogEventBegin(MAT_Convert, mat, 0, 0, 0));
5105: PetscUseTypeMethod(mat, duplicate, op, M);
5106: PetscCall(PetscLogEventEnd(MAT_Convert, mat, 0, 0, 0));
5107: B = *M;
5109: PetscCall(MatGetOperation(mat, MATOP_VIEW, &viewf));
5110: if (viewf) PetscCall(MatSetOperation(B, MATOP_VIEW, viewf));
5111: PetscCall(MatGetVecType(mat, &vtype));
5112: PetscCall(MatSetVecType(B, vtype));
5114: B->stencil.dim = mat->stencil.dim;
5115: B->stencil.noc = mat->stencil.noc;
5116: for (i = 0; i <= mat->stencil.dim + (mat->stencil.noc ? 0 : -1); i++) {
5117: B->stencil.dims[i] = mat->stencil.dims[i];
5118: B->stencil.starts[i] = mat->stencil.starts[i];
5119: }
5121: B->nooffproczerorows = mat->nooffproczerorows;
5122: B->nooffprocentries = mat->nooffprocentries;
5124: PetscCall(PetscObjectQuery((PetscObject)mat, "__PETSc_dm", &dm));
5125: if (dm) PetscCall(PetscObjectCompose((PetscObject)B, "__PETSc_dm", dm));
5126: PetscCall(PetscObjectQuery((PetscObject)mat, "__PETSc_MatCOOStruct_Host", &container_h));
5127: if (container_h) PetscCall(PetscObjectCompose((PetscObject)B, "__PETSc_MatCOOStruct_Host", container_h));
5128: PetscCall(PetscObjectQuery((PetscObject)mat, "__PETSc_MatCOOStruct_Device", &container_d));
5129: if (container_d) PetscCall(PetscObjectCompose((PetscObject)B, "__PETSc_MatCOOStruct_Device", container_d));
5130: if (op == MAT_COPY_VALUES) PetscCall(MatPropagateSymmetryOptions(mat, B));
5131: PetscCall(PetscObjectStateIncrease((PetscObject)B));
5132: PetscFunctionReturn(PETSC_SUCCESS);
5133: }
5135: /*@
5136: MatGetDiagonal - Gets the diagonal of a matrix as a `Vec`
5138: Logically Collective
5140: Input Parameter:
5141: . mat - the matrix
5143: Output Parameter:
5144: . v - the diagonal of the matrix
5146: Level: intermediate
5148: Note:
5149: If `mat` has local sizes `n` x `m`, this routine fills the first `ndiag = min(n, m)` entries
5150: of `v` with the diagonal values. Thus `v` must have local size of at least `ndiag`. If `v`
5151: is larger than `ndiag`, the values of the remaining entries are unspecified.
5153: Currently only correct in parallel for square matrices.
5155: .seealso: [](ch_matrices), `Mat`, `Vec`, `MatGetRow()`, `MatCreateSubMatrices()`, `MatCreateSubMatrix()`, `MatGetRowMaxAbs()`
5156: @*/
5157: PetscErrorCode MatGetDiagonal(Mat mat, Vec v)
5158: {
5159: PetscFunctionBegin;
5163: PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
5164: MatCheckPreallocated(mat, 1);
5165: if (PetscDefined(USE_DEBUG)) {
5166: PetscInt nv, row, col, ndiag;
5168: PetscCall(VecGetLocalSize(v, &nv));
5169: PetscCall(MatGetLocalSize(mat, &row, &col));
5170: ndiag = PetscMin(row, col);
5171: 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);
5172: }
5174: PetscUseTypeMethod(mat, getdiagonal, v);
5175: PetscCall(PetscObjectStateIncrease((PetscObject)v));
5176: PetscFunctionReturn(PETSC_SUCCESS);
5177: }
5179: /*@
5180: MatGetRowMin - Gets the minimum value (of the real part) of each
5181: row of the matrix
5183: Logically Collective
5185: Input Parameter:
5186: . mat - the matrix
5188: Output Parameters:
5189: + v - the vector for storing the maximums
5190: - idx - the indices of the column found for each row (optional, pass `NULL` if not needed)
5192: Level: intermediate
5194: Note:
5195: The result of this call are the same as if one converted the matrix to dense format
5196: and found the minimum value in each row (i.e. the implicit zeros are counted as zeros).
5198: This code is only implemented for a couple of matrix formats.
5200: .seealso: [](ch_matrices), `Mat`, `MatGetDiagonal()`, `MatCreateSubMatrices()`, `MatCreateSubMatrix()`, `MatGetRowMaxAbs()`, `MatGetRowMinAbs()`,
5201: `MatGetRowMax()`
5202: @*/
5203: PetscErrorCode MatGetRowMin(Mat mat, Vec v, PetscInt idx[])
5204: {
5205: PetscFunctionBegin;
5209: PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
5211: if (!mat->cmap->N) {
5212: PetscCall(VecSet(v, PETSC_MAX_REAL));
5213: if (idx) {
5214: PetscInt i, m = mat->rmap->n;
5215: for (i = 0; i < m; i++) idx[i] = -1;
5216: }
5217: } else {
5218: MatCheckPreallocated(mat, 1);
5219: }
5220: PetscUseTypeMethod(mat, getrowmin, v, idx);
5221: PetscCall(PetscObjectStateIncrease((PetscObject)v));
5222: PetscFunctionReturn(PETSC_SUCCESS);
5223: }
5225: /*@
5226: MatGetRowMinAbs - Gets the minimum value (in absolute value) of each
5227: row of the matrix
5229: Logically Collective
5231: Input Parameter:
5232: . mat - the matrix
5234: Output Parameters:
5235: + v - the vector for storing the minimums
5236: - idx - the indices of the column found for each row (or `NULL` if not needed)
5238: Level: intermediate
5240: Notes:
5241: if a row is completely empty or has only 0.0 values, then the `idx` value for that
5242: row is 0 (the first column).
5244: This code is only implemented for a couple of matrix formats.
5246: .seealso: [](ch_matrices), `Mat`, `MatGetDiagonal()`, `MatCreateSubMatrices()`, `MatCreateSubMatrix()`, `MatGetRowMax()`, `MatGetRowMaxAbs()`, `MatGetRowMin()`
5247: @*/
5248: PetscErrorCode MatGetRowMinAbs(Mat mat, Vec v, PetscInt idx[])
5249: {
5250: PetscFunctionBegin;
5254: PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
5255: PetscCheck(!mat->factortype, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
5257: if (!mat->cmap->N) {
5258: PetscCall(VecSet(v, 0.0));
5259: if (idx) {
5260: PetscInt i, m = mat->rmap->n;
5261: for (i = 0; i < m; i++) idx[i] = -1;
5262: }
5263: } else {
5264: MatCheckPreallocated(mat, 1);
5265: if (idx) PetscCall(PetscArrayzero(idx, mat->rmap->n));
5266: PetscUseTypeMethod(mat, getrowminabs, v, idx);
5267: }
5268: PetscCall(PetscObjectStateIncrease((PetscObject)v));
5269: PetscFunctionReturn(PETSC_SUCCESS);
5270: }
5272: /*@
5273: MatGetRowMax - Gets the maximum value (of the real part) of each
5274: row of the matrix
5276: Logically Collective
5278: Input Parameter:
5279: . mat - the matrix
5281: Output Parameters:
5282: + v - the vector for storing the maximums
5283: - idx - the indices of the column found for each row (optional, otherwise pass `NULL`)
5285: Level: intermediate
5287: Notes:
5288: The result of this call are the same as if one converted the matrix to dense format
5289: and found the minimum value in each row (i.e. the implicit zeros are counted as zeros).
5291: This code is only implemented for a couple of matrix formats.
5293: .seealso: [](ch_matrices), `Mat`, `MatGetDiagonal()`, `MatCreateSubMatrices()`, `MatCreateSubMatrix()`, `MatGetRowMaxAbs()`, `MatGetRowMin()`, `MatGetRowMinAbs()`
5294: @*/
5295: PetscErrorCode MatGetRowMax(Mat mat, Vec v, PetscInt idx[])
5296: {
5297: PetscFunctionBegin;
5301: PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
5303: if (!mat->cmap->N) {
5304: PetscCall(VecSet(v, PETSC_MIN_REAL));
5305: if (idx) {
5306: PetscInt i, m = mat->rmap->n;
5307: for (i = 0; i < m; i++) idx[i] = -1;
5308: }
5309: } else {
5310: MatCheckPreallocated(mat, 1);
5311: PetscUseTypeMethod(mat, getrowmax, v, idx);
5312: }
5313: PetscCall(PetscObjectStateIncrease((PetscObject)v));
5314: PetscFunctionReturn(PETSC_SUCCESS);
5315: }
5317: /*@
5318: MatGetRowMaxAbs - Gets the maximum value (in absolute value) of each
5319: row of the matrix
5321: Logically Collective
5323: Input Parameter:
5324: . mat - the matrix
5326: Output Parameters:
5327: + v - the vector for storing the maximums
5328: - idx - the indices of the column found for each row (or `NULL` if not needed)
5330: Level: intermediate
5332: Notes:
5333: if a row is completely empty or has only 0.0 values, then the `idx` value for that
5334: row is 0 (the first column).
5336: This code is only implemented for a couple of matrix formats.
5338: .seealso: [](ch_matrices), `Mat`, `MatGetDiagonal()`, `MatCreateSubMatrices()`, `MatCreateSubMatrix()`, `MatGetRowSum()`, `MatGetRowMin()`, `MatGetRowMinAbs()`
5339: @*/
5340: PetscErrorCode MatGetRowMaxAbs(Mat mat, Vec v, PetscInt idx[])
5341: {
5342: PetscFunctionBegin;
5346: PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
5348: if (!mat->cmap->N) {
5349: PetscCall(VecSet(v, 0.0));
5350: if (idx) {
5351: PetscInt i, m = mat->rmap->n;
5352: for (i = 0; i < m; i++) idx[i] = -1;
5353: }
5354: } else {
5355: MatCheckPreallocated(mat, 1);
5356: if (idx) PetscCall(PetscArrayzero(idx, mat->rmap->n));
5357: PetscUseTypeMethod(mat, getrowmaxabs, v, idx);
5358: }
5359: PetscCall(PetscObjectStateIncrease((PetscObject)v));
5360: PetscFunctionReturn(PETSC_SUCCESS);
5361: }
5363: /*@
5364: MatGetRowSumAbs - Gets the sum value (in absolute value) of each row of the matrix
5366: Logically Collective
5368: Input Parameter:
5369: . mat - the matrix
5371: Output Parameter:
5372: . v - the vector for storing the sum
5374: Level: intermediate
5376: This code is only implemented for a couple of matrix formats.
5378: .seealso: [](ch_matrices), `Mat`, `MatGetDiagonal()`, `MatCreateSubMatrices()`, `MatCreateSubMatrix()`, `MatGetRowMax()`, `MatGetRowMin()`, `MatGetRowMinAbs()`
5379: @*/
5380: PetscErrorCode MatGetRowSumAbs(Mat mat, Vec v)
5381: {
5382: PetscFunctionBegin;
5386: PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
5388: if (!mat->cmap->N) PetscCall(VecSet(v, 0.0));
5389: else {
5390: MatCheckPreallocated(mat, 1);
5391: PetscUseTypeMethod(mat, getrowsumabs, v);
5392: }
5393: PetscCall(PetscObjectStateIncrease((PetscObject)v));
5394: PetscFunctionReturn(PETSC_SUCCESS);
5395: }
5397: /*@
5398: MatGetRowSum - Gets the sum of each row of the matrix
5400: Logically or Neighborhood Collective
5402: Input Parameter:
5403: . mat - the matrix
5405: Output Parameter:
5406: . v - the vector for storing the sum of rows
5408: Level: intermediate
5410: Note:
5411: This code is slow since it is not currently specialized for different formats
5413: .seealso: [](ch_matrices), `Mat`, `MatGetDiagonal()`, `MatCreateSubMatrices()`, `MatCreateSubMatrix()`, `MatGetRowMax()`, `MatGetRowMin()`, `MatGetRowMaxAbs()`, `MatGetRowMinAbs()`, `MatGetRowSumAbs()`
5414: @*/
5415: PetscErrorCode MatGetRowSum(Mat mat, Vec v)
5416: {
5417: Vec ones;
5419: PetscFunctionBegin;
5423: PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
5424: MatCheckPreallocated(mat, 1);
5425: PetscCall(MatCreateVecs(mat, &ones, NULL));
5426: PetscCall(VecSet(ones, 1.));
5427: PetscCall(MatMult(mat, ones, v));
5428: PetscCall(VecDestroy(&ones));
5429: PetscFunctionReturn(PETSC_SUCCESS);
5430: }
5432: /*@
5433: MatTransposeSetPrecursor - Set the matrix from which the second matrix will receive numerical transpose data with a call to `MatTranspose`(A,`MAT_REUSE_MATRIX`,&B)
5434: when B was not obtained with `MatTranspose`(A,`MAT_INITIAL_MATRIX`,&B)
5436: Collective
5438: Input Parameter:
5439: . mat - the matrix to provide the transpose
5441: Output Parameter:
5442: . 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
5444: Level: advanced
5446: Note:
5447: 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
5448: routine allows bypassing that call.
5450: .seealso: [](ch_matrices), `Mat`, `MatTransposeSymbolic()`, `MatTranspose()`, `MatMultTranspose()`, `MatMultTransposeAdd()`, `MatIsTranspose()`, `MatReuse`, `MAT_INITIAL_MATRIX`, `MAT_REUSE_MATRIX`, `MAT_INPLACE_MATRIX`
5451: @*/
5452: PetscErrorCode MatTransposeSetPrecursor(Mat mat, Mat B)
5453: {
5454: MatParentState *rb = NULL;
5456: PetscFunctionBegin;
5457: PetscCall(PetscNew(&rb));
5458: rb->id = ((PetscObject)mat)->id;
5459: rb->state = 0;
5460: PetscCall(MatGetNonzeroState(mat, &rb->nonzerostate));
5461: PetscCall(PetscObjectContainerCompose((PetscObject)B, "MatTransposeParent", rb, PetscCtxDestroyDefault));
5462: PetscFunctionReturn(PETSC_SUCCESS);
5463: }
5465: static PetscErrorCode MatTranspose_Private(Mat mat, MatReuse reuse, Mat *B, PetscBool conjugate)
5466: {
5467: PetscContainer rB = NULL;
5468: MatParentState *rb = NULL;
5469: PetscErrorCode (*f)(Mat, MatReuse, Mat *) = NULL;
5471: PetscFunctionBegin;
5474: PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
5475: PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
5476: PetscCheck(reuse != MAT_INPLACE_MATRIX || mat == *B, PetscObjectComm((PetscObject)mat), PETSC_ERR_SUP, "MAT_INPLACE_MATRIX requires last matrix to match first");
5477: PetscCheck(reuse != MAT_REUSE_MATRIX || mat != *B, PetscObjectComm((PetscObject)mat), PETSC_ERR_SUP, "Perhaps you mean MAT_INPLACE_MATRIX");
5478: MatCheckPreallocated(mat, 1);
5479: if (reuse == MAT_REUSE_MATRIX) {
5480: PetscCall(PetscObjectQuery((PetscObject)*B, "MatTransposeParent", (PetscObject *)&rB));
5481: PetscCheck(rB, PetscObjectComm((PetscObject)*B), PETSC_ERR_ARG_WRONG, "Reuse matrix used was not generated from call to MatTranspose(). Suggest MatTransposeSetPrecursor().");
5482: PetscCall(PetscContainerGetPointer(rB, &rb));
5483: PetscCheck(rb->id == ((PetscObject)mat)->id, PetscObjectComm((PetscObject)*B), PETSC_ERR_ARG_WRONG, "Reuse matrix used was not generated from input matrix");
5484: if (rb->state == ((PetscObject)mat)->state) PetscFunctionReturn(PETSC_SUCCESS);
5485: }
5487: if (conjugate) {
5488: f = mat->ops->hermitiantranspose;
5489: if (f) PetscCall((*f)(mat, reuse, B));
5490: }
5491: if (!f && !(reuse == MAT_INPLACE_MATRIX && mat->hermitian == PETSC_BOOL3_TRUE && conjugate)) {
5492: PetscCall(PetscLogEventBegin(MAT_Transpose, mat, 0, 0, 0));
5493: if (reuse != MAT_INPLACE_MATRIX || mat->symmetric != PETSC_BOOL3_TRUE) {
5494: PetscUseTypeMethod(mat, transpose, reuse, B);
5495: PetscCall(PetscObjectStateIncrease((PetscObject)*B));
5496: }
5497: PetscCall(PetscLogEventEnd(MAT_Transpose, mat, 0, 0, 0));
5498: if (conjugate) PetscCall(MatConjugate(*B));
5499: }
5501: if (reuse == MAT_INITIAL_MATRIX) PetscCall(MatTransposeSetPrecursor(mat, *B));
5502: if (reuse != MAT_INPLACE_MATRIX) {
5503: PetscCall(PetscObjectQuery((PetscObject)*B, "MatTransposeParent", (PetscObject *)&rB));
5504: PetscCall(PetscContainerGetPointer(rB, &rb));
5505: rb->state = ((PetscObject)mat)->state;
5506: rb->nonzerostate = mat->nonzerostate;
5507: }
5508: PetscFunctionReturn(PETSC_SUCCESS);
5509: }
5511: /*@
5512: MatTranspose - Computes the transpose of a matrix, either in-place or out-of-place.
5514: Collective
5516: Input Parameters:
5517: + mat - the matrix to transpose
5518: - reuse - either `MAT_INITIAL_MATRIX`, `MAT_REUSE_MATRIX`, or `MAT_INPLACE_MATRIX`
5520: Output Parameter:
5521: . B - the transpose of the matrix
5523: Level: intermediate
5525: Notes:
5526: If you use `MAT_INPLACE_MATRIX` then you must pass in `&mat` for `B`
5528: `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
5529: transpose, call `MatTransposeSetPrecursor(mat, B)` before calling this routine.
5531: 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.
5533: Consider using `MatCreateTranspose()` instead if you only need a matrix that behaves like the transpose but don't need the storage to be changed.
5534: For example, the result of `MatCreateTranspose()` will compute the transpose of the given matrix times a vector for matrix-vector products computed with `MatMult()`.
5536: If `mat` is unchanged from the last call this function returns immediately without recomputing the result
5538: If you only need the symbolic transpose of a matrix, and not the numerical values, use `MatTransposeSymbolic()`
5540: .seealso: [](ch_matrices), `Mat`, `MatTransposeSetPrecursor()`, `MatMultTranspose()`, `MatMultTransposeAdd()`, `MatIsTranspose()`, `MatReuse`, `MAT_INITIAL_MATRIX`, `MAT_REUSE_MATRIX`, `MAT_INPLACE_MATRIX`,
5541: `MatTransposeSymbolic()`, `MatCreateTranspose()`
5542: @*/
5543: PetscErrorCode MatTranspose(Mat mat, MatReuse reuse, Mat *B)
5544: {
5545: PetscFunctionBegin;
5546: PetscCall(MatTranspose_Private(mat, reuse, B, PETSC_FALSE));
5547: PetscFunctionReturn(PETSC_SUCCESS);
5548: }
5550: /*@
5551: MatTransposeSymbolic - Computes the symbolic part of the transpose of a matrix.
5553: Collective
5555: Input Parameter:
5556: . A - the matrix to transpose
5558: Output Parameter:
5559: . 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
5560: numerical portion.
5562: Level: intermediate
5564: Note:
5565: This is not supported for many matrix types, use `MatTranspose()` in those cases
5567: .seealso: [](ch_matrices), `Mat`, `MatTransposeSetPrecursor()`, `MatTranspose()`, `MatMultTranspose()`, `MatMultTransposeAdd()`, `MatIsTranspose()`, `MatReuse`, `MAT_INITIAL_MATRIX`, `MAT_REUSE_MATRIX`, `MAT_INPLACE_MATRIX`
5568: @*/
5569: PetscErrorCode MatTransposeSymbolic(Mat A, Mat *B)
5570: {
5571: PetscFunctionBegin;
5574: PetscCheck(A->assembled, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
5575: PetscCheck(!A->factortype, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
5576: PetscCall(PetscLogEventBegin(MAT_Transpose, A, 0, 0, 0));
5577: PetscUseTypeMethod(A, transposesymbolic, B);
5578: PetscCall(PetscLogEventEnd(MAT_Transpose, A, 0, 0, 0));
5580: PetscCall(MatTransposeSetPrecursor(A, *B));
5581: PetscFunctionReturn(PETSC_SUCCESS);
5582: }
5584: PetscErrorCode MatTransposeCheckNonzeroState_Private(Mat A, Mat B)
5585: {
5586: PetscContainer rB;
5587: MatParentState *rb;
5589: PetscFunctionBegin;
5592: PetscCheck(A->assembled, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
5593: PetscCheck(!A->factortype, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
5594: PetscCall(PetscObjectQuery((PetscObject)B, "MatTransposeParent", (PetscObject *)&rB));
5595: PetscCheck(rB, PetscObjectComm((PetscObject)B), PETSC_ERR_ARG_WRONG, "Reuse matrix used was not generated from call to MatTranspose()");
5596: PetscCall(PetscContainerGetPointer(rB, &rb));
5597: PetscCheck(rb->id == ((PetscObject)A)->id, PetscObjectComm((PetscObject)B), PETSC_ERR_ARG_WRONG, "Reuse matrix used was not generated from input matrix");
5598: PetscCheck(rb->nonzerostate == A->nonzerostate, PetscObjectComm((PetscObject)B), PETSC_ERR_ARG_WRONGSTATE, "Reuse matrix has changed nonzero structure");
5599: PetscFunctionReturn(PETSC_SUCCESS);
5600: }
5602: /*@
5603: MatIsTranspose - Test whether a matrix is another one's transpose,
5604: or its own, in which case it tests symmetry.
5606: Collective
5608: Input Parameters:
5609: + A - the matrix to test
5610: . B - the matrix to test against, this can equal the first parameter
5611: - tol - tolerance, differences between entries smaller than this are counted as zero
5613: Output Parameter:
5614: . flg - the result
5616: Level: intermediate
5618: Notes:
5619: The sequential algorithm has a running time of the order of the number of nonzeros; the parallel
5620: test involves parallel copies of the block off-diagonal parts of the matrix.
5622: .seealso: [](ch_matrices), `Mat`, `MatTranspose()`, `MatIsSymmetric()`, `MatIsHermitian()`
5623: @*/
5624: PetscErrorCode MatIsTranspose(Mat A, Mat B, PetscReal tol, PetscBool *flg)
5625: {
5626: PetscErrorCode (*f)(Mat, Mat, PetscReal, PetscBool *), (*g)(Mat, Mat, PetscReal, PetscBool *);
5628: PetscFunctionBegin;
5631: PetscAssertPointer(flg, 4);
5632: PetscCall(PetscObjectQueryFunction((PetscObject)A, "MatIsTranspose_C", &f));
5633: PetscCall(PetscObjectQueryFunction((PetscObject)B, "MatIsTranspose_C", &g));
5634: *flg = PETSC_FALSE;
5635: if (f && g) {
5636: PetscCheck(f == g, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_NOTSAMETYPE, "Matrices do not have the same comparator for symmetry test");
5637: PetscCall((*f)(A, B, tol, flg));
5638: } else {
5639: MatType mattype;
5641: PetscCall(MatGetType(f ? B : A, &mattype));
5642: SETERRQ(PETSC_COMM_SELF, PETSC_ERR_SUP, "Matrix of type %s does not support checking for transpose", mattype);
5643: }
5644: PetscFunctionReturn(PETSC_SUCCESS);
5645: }
5647: /*@
5648: MatHermitianTranspose - Computes an in-place or out-of-place Hermitian transpose of a matrix in complex conjugate.
5650: Collective
5652: Input Parameters:
5653: + mat - the matrix to transpose and complex conjugate
5654: - reuse - either `MAT_INITIAL_MATRIX`, `MAT_REUSE_MATRIX`, or `MAT_INPLACE_MATRIX`
5656: Output Parameter:
5657: . B - the Hermitian transpose
5659: Level: intermediate
5661: .seealso: [](ch_matrices), `Mat`, `MatTranspose()`, `MatMultTranspose()`, `MatMultTransposeAdd()`, `MatIsTranspose()`, `MatReuse`
5662: @*/
5663: PetscErrorCode MatHermitianTranspose(Mat mat, MatReuse reuse, Mat *B)
5664: {
5665: PetscFunctionBegin;
5666: PetscCall(MatTranspose_Private(mat, reuse, B, PetscDefined(USE_COMPLEX) ? PETSC_TRUE : PETSC_FALSE));
5667: PetscFunctionReturn(PETSC_SUCCESS);
5668: }
5670: /*@
5671: MatIsHermitianTranspose - Test whether a matrix is another one's Hermitian transpose,
5673: Collective
5675: Input Parameters:
5676: + A - the matrix to test
5677: . B - the matrix to test against, this can equal the first parameter
5678: - tol - tolerance, differences between entries smaller than this are counted as zero
5680: Output Parameter:
5681: . flg - the result
5683: Level: intermediate
5685: Notes:
5686: Only available for `MATAIJ` matrices.
5688: The sequential algorithm
5689: has a running time of the order of the number of nonzeros; the parallel
5690: test involves parallel copies of the block off-diagonal parts of the matrix.
5692: .seealso: [](ch_matrices), `Mat`, `MatTranspose()`, `MatIsSymmetric()`, `MatIsHermitian()`, `MatIsTranspose()`
5693: @*/
5694: PetscErrorCode MatIsHermitianTranspose(Mat A, Mat B, PetscReal tol, PetscBool *flg)
5695: {
5696: PetscErrorCode (*f)(Mat, Mat, PetscReal, PetscBool *), (*g)(Mat, Mat, PetscReal, PetscBool *);
5698: PetscFunctionBegin;
5701: PetscAssertPointer(flg, 4);
5702: PetscCall(PetscObjectQueryFunction((PetscObject)A, "MatIsHermitianTranspose_C", &f));
5703: PetscCall(PetscObjectQueryFunction((PetscObject)B, "MatIsHermitianTranspose_C", &g));
5704: if (f && g) {
5705: PetscCheck(f == g, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_NOTSAMETYPE, "Matrices do not have the same comparator for Hermitian test");
5706: PetscCall((*f)(A, B, tol, flg));
5707: } else {
5708: MatType mattype;
5710: PetscCall(MatGetType(f ? B : A, &mattype));
5711: SETERRQ(PETSC_COMM_SELF, PETSC_ERR_SUP, "Matrix of type %s does not support checking for Hermitian transpose", mattype);
5712: }
5713: PetscFunctionReturn(PETSC_SUCCESS);
5714: }
5716: /*@
5717: MatPermute - Creates a new matrix with rows and columns permuted from the
5718: original.
5720: Collective
5722: Input Parameters:
5723: + mat - the matrix to permute
5724: . row - row permutation, each processor supplies only the permutation for its rows
5725: - col - column permutation, each processor supplies only the permutation for its columns
5727: Output Parameter:
5728: . B - the permuted matrix
5730: Level: advanced
5732: Note:
5733: The index sets map from row/col of permuted matrix to row/col of original matrix.
5734: The index sets should be on the same communicator as mat and have the same local sizes.
5736: Developer Note:
5737: If you want to implement `MatPermute()` for a matrix type, and your approach doesn't
5738: exploit the fact that row and col are permutations, consider implementing the
5739: more general `MatCreateSubMatrix()` instead.
5741: .seealso: [](ch_matrices), `Mat`, `MatGetOrdering()`, `ISAllGather()`, `MatCreateSubMatrix()`
5742: @*/
5743: PetscErrorCode MatPermute(Mat mat, IS row, IS col, Mat *B)
5744: {
5745: PetscFunctionBegin;
5750: PetscAssertPointer(B, 4);
5751: PetscCheckSameComm(mat, 1, row, 2);
5752: if (row != col) PetscCheckSameComm(row, 2, col, 3);
5753: PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
5754: PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
5755: PetscCheck(mat->ops->permute || mat->ops->createsubmatrix, PETSC_COMM_SELF, PETSC_ERR_SUP, "MatPermute not available for Mat type %s", ((PetscObject)mat)->type_name);
5756: MatCheckPreallocated(mat, 1);
5758: if (mat->ops->permute) {
5759: PetscUseTypeMethod(mat, permute, row, col, B);
5760: PetscCall(PetscObjectStateIncrease((PetscObject)*B));
5761: } else {
5762: PetscCall(MatCreateSubMatrix(mat, row, col, MAT_INITIAL_MATRIX, B));
5763: }
5764: PetscFunctionReturn(PETSC_SUCCESS);
5765: }
5767: /*@
5768: MatEqual - Compares two matrices.
5770: Collective
5772: Input Parameters:
5773: + A - the first matrix
5774: - B - the second matrix
5776: Output Parameter:
5777: . flg - `PETSC_TRUE` if the matrices are equal; `PETSC_FALSE` otherwise.
5779: Level: intermediate
5781: Note:
5782: If either of the matrix is "matrix-free", meaning the matrix entries are not stored explicitly then equality is determined by comparing
5783: the results of several matrix-vector product using randomly created vectors, see `MatMultEqual()`.
5785: .seealso: [](ch_matrices), `Mat`, `MatMultEqual()`
5786: @*/
5787: PetscErrorCode MatEqual(Mat A, Mat B, PetscBool *flg)
5788: {
5789: PetscFunctionBegin;
5794: PetscAssertPointer(flg, 3);
5795: PetscCheckSameComm(A, 1, B, 2);
5796: MatCheckPreallocated(A, 1);
5797: MatCheckPreallocated(B, 2);
5798: PetscCheck(A->assembled, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
5799: PetscCheck(B->assembled, PetscObjectComm((PetscObject)B), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
5800: 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,
5801: B->cmap->N);
5802: if (A->ops->equal && A->ops->equal == B->ops->equal) PetscUseTypeMethod(A, equal, B, flg);
5803: else PetscCall(MatMultEqual(A, B, 10, flg));
5804: PetscFunctionReturn(PETSC_SUCCESS);
5805: }
5807: /*@
5808: MatDiagonalScale - Scales a matrix on the left and right by diagonal
5809: matrices that are stored as vectors. Either of the two scaling
5810: matrices can be `NULL`.
5812: Collective
5814: Input Parameters:
5815: + mat - the matrix to be scaled
5816: . l - the left scaling vector (or `NULL`)
5817: - r - the right scaling vector (or `NULL`)
5819: Level: intermediate
5821: Note:
5822: `MatDiagonalScale()` computes $A = LAR$, where
5823: L = a diagonal matrix (stored as a vector), R = a diagonal matrix (stored as a vector)
5824: The L scales the rows of the matrix, the R scales the columns of the matrix.
5826: .seealso: [](ch_matrices), `Mat`, `MatScale()`, `MatShift()`, `MatDiagonalSet()`
5827: @*/
5828: PetscErrorCode MatDiagonalScale(Mat mat, Vec l, Vec r)
5829: {
5830: PetscBool flg = PETSC_FALSE;
5832: PetscFunctionBegin;
5835: if (l) {
5837: PetscCheckSameComm(mat, 1, l, 2);
5838: }
5839: if (r) {
5841: PetscCheckSameComm(mat, 1, r, 3);
5842: }
5843: PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
5844: PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
5845: MatCheckPreallocated(mat, 1);
5846: if (!l && !r) PetscFunctionReturn(PETSC_SUCCESS);
5848: PetscCall(PetscLogEventBegin(MAT_Scale, mat, 0, 0, 0));
5849: PetscUseTypeMethod(mat, diagonalscale, l, r);
5850: PetscCall(PetscLogEventEnd(MAT_Scale, mat, 0, 0, 0));
5851: PetscCall(PetscObjectStateIncrease((PetscObject)mat));
5852: if (l != r && (PetscBool3ToBool(mat->symmetric) || PetscBool3ToBool(mat->hermitian))) {
5853: if (!PetscDefined(USE_COMPLEX) || PetscBool3ToBool(mat->symmetric)) {
5854: if (l && r) PetscCall(VecEqual(l, r, &flg));
5855: if (!flg) {
5856: PetscCall(PetscObjectTypeCompareAny((PetscObject)mat, &flg, MATSEQSBAIJ, MATMPISBAIJ, ""));
5857: PetscCheck(!flg, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_OUTOFRANGE, "For symmetric format, left and right scaling vectors must be the same");
5858: mat->symmetric = mat->spd = PETSC_BOOL3_FALSE;
5859: if (!PetscDefined(USE_COMPLEX)) mat->hermitian = PETSC_BOOL3_FALSE;
5860: else mat->hermitian = PETSC_BOOL3_UNKNOWN;
5861: }
5862: }
5863: if (PetscDefined(USE_COMPLEX) && PetscBool3ToBool(mat->hermitian)) {
5864: flg = PETSC_FALSE;
5865: if (l && r) {
5866: Vec conjugate;
5868: PetscCall(VecDuplicate(l, &conjugate));
5869: PetscCall(VecCopy(l, conjugate));
5870: PetscCall(VecConjugate(conjugate));
5871: PetscCall(VecEqual(conjugate, r, &flg));
5872: PetscCall(VecDestroy(&conjugate));
5873: }
5874: if (!flg) {
5875: PetscCall(PetscObjectTypeCompareAny((PetscObject)mat, &flg, MATSEQSBAIJ, MATMPISBAIJ, ""));
5876: PetscCheck(!flg, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_OUTOFRANGE, "For symmetric format and Hermitian matrix, left and right scaling vectors must be conjugate one of the other");
5877: mat->hermitian = PETSC_BOOL3_FALSE;
5878: mat->symmetric = mat->spd = PETSC_BOOL3_UNKNOWN;
5879: }
5880: }
5881: }
5882: PetscFunctionReturn(PETSC_SUCCESS);
5883: }
5885: /*@
5886: MatScale - Scales all elements of a matrix by a given number.
5888: Logically Collective
5890: Input Parameters:
5891: + mat - the matrix to be scaled
5892: - a - the scaling value
5894: Level: intermediate
5896: .seealso: [](ch_matrices), `Mat`, `MatDiagonalScale()`
5897: @*/
5898: PetscErrorCode MatScale(Mat mat, PetscScalar a)
5899: {
5900: PetscFunctionBegin;
5903: PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
5904: PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
5906: MatCheckPreallocated(mat, 1);
5908: PetscCall(PetscLogEventBegin(MAT_Scale, mat, 0, 0, 0));
5909: if (a != (PetscScalar)1.0) {
5910: PetscUseTypeMethod(mat, scale, a);
5911: PetscCall(PetscObjectStateIncrease((PetscObject)mat));
5912: }
5913: PetscCall(PetscLogEventEnd(MAT_Scale, mat, 0, 0, 0));
5914: PetscFunctionReturn(PETSC_SUCCESS);
5915: }
5917: /*@
5918: MatNorm - Calculates various norms of a matrix.
5920: Collective
5922: Input Parameters:
5923: + mat - the matrix
5924: - type - the type of norm, `NORM_1`, `NORM_FROBENIUS`, `NORM_INFINITY`
5926: Output Parameter:
5927: . nrm - the resulting norm
5929: Level: intermediate
5931: .seealso: [](ch_matrices), `Mat`, `MatNormApproximate()`
5932: @*/
5933: PetscErrorCode MatNorm(Mat mat, NormType type, PetscReal *nrm)
5934: {
5935: PetscFunctionBegin;
5939: PetscAssertPointer(nrm, 3);
5941: PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
5942: PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
5943: MatCheckPreallocated(mat, 1);
5945: PetscUseTypeMethod(mat, norm, type, nrm);
5946: PetscFunctionReturn(PETSC_SUCCESS);
5947: }
5949: static PetscErrorCode VecSetFinalNormApp_Private(Vec x)
5950: {
5951: PetscScalar *ax, nm1;
5952: PetscInt st, en, n;
5954: PetscFunctionBegin;
5955: PetscCall(VecGetSize(x, &n));
5956: if (n < 2) PetscFunctionReturn(PETSC_SUCCESS);
5957: nm1 = n - 1;
5958: PetscCall(VecGetOwnershipRange(x, &st, &en));
5959: PetscCall(VecGetArrayWrite(x, &ax));
5960: for (PetscInt i = st; i < en; i++) {
5961: const PetscInt ii = i - st;
5962: const PetscScalar s = i % 2 ? -1.0 : 1.0;
5964: ax[ii] = s * (1.0 + i / nm1);
5965: }
5966: PetscCall(VecRestoreArrayWrite(x, &ax));
5967: PetscFunctionReturn(PETSC_SUCCESS);
5968: }
5970: static PetscErrorCode MatNormApproximateForwardOnly_Private(Mat A, NormType normtype, PetscInt maxit, PetscBool boundtocpu, PetscReal *n)
5971: {
5972: Vec x, y;
5973: PetscReal normx, normy;
5974: PetscInt i, N;
5975: PetscRandom rnd;
5977: PetscFunctionBegin;
5978: if (maxit < 0) maxit = 1;
5979: PetscCall(PetscRandomCreate(PetscObjectComm((PetscObject)A), &rnd));
5980: PetscCall(PetscRandomSetFromOptions(rnd));
5981: PetscCall(MatCreateVecs(A, &x, &y));
5982: PetscCall(VecBindToCPU(x, boundtocpu));
5983: PetscCall(VecBindToCPU(y, boundtocpu));
5984: PetscCall(VecGetSize(x, &N));
5985: *n = 0.0;
5986: for (i = 0; i < maxit; i++) {
5987: PetscCall(VecSetRandom(x, rnd));
5988: switch (normtype) {
5989: case NORM_1:
5990: PetscCall(VecNorm(x, NORM_1, &normx));
5991: if (normx > 0.0) PetscCall(VecScale(x, 1.0 / normx));
5992: break;
5993: case NORM_INFINITY:
5994: PetscCall(VecShift(x, -0.5));
5995: PetscCall(VecPointwiseSign(x, x, VEC_SIGN_ZERO_TO_SIGNED_UNIT));
5996: break;
5997: case NORM_2:
5998: PetscCall(VecNormalize(x, NULL));
5999: break;
6000: default:
6001: PetscUnreachable();
6002: }
6003: PetscCall(MatMult(A, x, y));
6004: PetscCall(VecNorm(y, normtype, &normy));
6005: *n = PetscMax(*n, normy);
6006: PetscCall(PetscInfo(A, "%s norm forward-only sample %" PetscInt_FMT " -> %g\n", NormTypes[normtype], i, (double)normy));
6007: }
6008: PetscCall(VecDestroy(&x));
6009: PetscCall(VecDestroy(&y));
6010: PetscCall(PetscRandomDestroy(&rnd));
6011: PetscFunctionReturn(PETSC_SUCCESS);
6012: }
6014: /*@
6015: MatNormApproximate - Approximate the norm of a matrix.
6017: Collective
6019: Input Parameters:
6020: + A - the matrix
6021: . normtype - the `NormType`
6022: - maxit - maximum number of iterations to use
6024: Output Parameter:
6025: . n - the norm estimate
6027: Level: intermediate
6029: Notes:
6030: Does not need access to the matrix entries; it just performs matrix-vector and transposed matrix-vector products {cite}`Higham1992`, {cite}`doi:10.1137/S0895479899356080`.
6032: If `maxit` is negative, a default number of iterations (10 for `NORM_1` and `NORM_INFINITY` and 20 for `NORM_2`) is performed.
6034: .seealso: [](ch_matrices), `Mat`, `MatNorm()`
6035: @*/
6036: PetscErrorCode MatNormApproximate(Mat A, NormType normtype, PetscInt maxit, PetscReal *n)
6037: {
6038: Vec x, y, w, z;
6039: PetscReal normz, adot;
6040: PetscScalar dot;
6041: PetscInt i, j, N, jold = -1;
6042: PetscBool boundtocpu = PETSC_TRUE, setherm, isherm, hasop;
6044: PetscFunctionBegin;
6049: PetscAssertPointer(n, 4);
6050: #if PetscDefined(HAVE_DEVICE)
6051: boundtocpu = A->boundtocpu;
6052: #endif
6053: PetscCall(MatHasOperation(A, MATOP_MULT_HERMITIAN_TRANSPOSE, &hasop));
6054: switch (normtype) {
6055: case NORM_INFINITY:
6056: case NORM_1:
6057: if (!hasop) {
6058: PetscCall(MatNormApproximateForwardOnly_Private(A, normtype, maxit, boundtocpu, n));
6059: i = maxit;
6060: break;
6061: } else {
6062: PetscCall(MatIsHermitianKnown(A, &setherm, &isherm));
6063: if ((setherm && isherm) || normtype == NORM_1) PetscCall(PetscObjectReference((PetscObject)A));
6064: else {
6065: Mat B;
6067: PetscCall(MatCreateHermitianTranspose(A, &B));
6068: A = B;
6069: }
6070: }
6071: if (maxit < 0) maxit = 10; /* pure guess */
6072: PetscCall(MatCreateVecs(A, &x, &y));
6073: PetscCall(MatCreateVecs(A, &z, &w));
6074: PetscCall(VecBindToCPU(x, boundtocpu));
6075: PetscCall(VecBindToCPU(y, boundtocpu));
6076: PetscCall(VecBindToCPU(z, boundtocpu));
6077: PetscCall(VecBindToCPU(w, boundtocpu));
6078: PetscCall(VecGetSize(x, &N));
6079: PetscCall(VecSet(x, 1. / N));
6080: *n = 0.0;
6081: for (i = 0; i < maxit; i++) {
6082: PetscCall(MatMult(A, x, y));
6083: PetscCall(VecNorm(y, NORM_1, n));
6084: if (PetscDefined(USE_COMPLEX)) {
6085: PetscCall(VecCopy(y, w));
6086: PetscCall(VecAbs(w));
6087: PetscCall(VecPointwiseDivide(w, y, w));
6088: } else PetscCall(VecPointwiseSign(w, y, VEC_SIGN_ZERO_TO_SIGNED_UNIT));
6089: PetscCall(MatMultHermitianTranspose(A, w, z));
6090: PetscCall(VecRealPart(z));
6091: PetscCall(VecNorm(z, NORM_INFINITY, &normz));
6092: PetscCall(VecDot(x, z, &dot));
6093: adot = PetscAbsScalar(dot);
6094: PetscCall(PetscInfo(A, "%s norm it %" PetscInt_FMT " -> %g (%g %g)\n", NormTypes[normtype], i, (double)*n, (double)normz, (double)adot));
6095: if (normz <= adot && i > 0) {
6096: PetscCall(PetscInfo(A, "%s norm converged\n", NormTypes[normtype]));
6097: break;
6098: }
6099: PetscCall(VecAbs(z));
6100: PetscCall(VecMax(z, &j, &normz));
6101: if (j == jold) {
6102: PetscCall(PetscInfo(A, "%s norm it %" PetscInt_FMT " -> breakdown (j==jold)\n", NormTypes[normtype], i));
6103: break;
6104: }
6105: jold = j;
6106: if (i < maxit - 1) PetscCall(VecSetStdBasis(x, j));
6107: }
6108: /* last check */
6109: if (N > 1) {
6110: PetscReal ny;
6112: PetscCall(VecSetFinalNormApp_Private(x));
6113: PetscCall(MatMult(A, x, y));
6114: PetscCall(VecNorm(y, NORM_1, &ny));
6115: ny = 2 * ny / (3 * N);
6116: PetscCall(PetscInfo(A, "%s norm final check: current %g test %g\n", NormTypes[normtype], (double)*n, (double)ny));
6117: *n = PetscMax(*n, ny);
6118: }
6119: PetscCall(MatDestroy(&A));
6120: PetscCall(VecDestroy(&x));
6121: PetscCall(VecDestroy(&w));
6122: PetscCall(VecDestroy(&y));
6123: PetscCall(VecDestroy(&z));
6124: break;
6125: case NORM_2:
6126: if (!hasop) {
6127: PetscCall(MatNormApproximateForwardOnly_Private(A, normtype, maxit, boundtocpu, n));
6128: i = maxit;
6129: break;
6130: }
6131: if (maxit < 0) maxit = 20; /* pure guess */
6132: PetscCall(MatCreateVecs(A, &x, &y));
6133: PetscCall(MatCreateVecs(A, &z, NULL));
6134: PetscCall(VecBindToCPU(x, boundtocpu));
6135: PetscCall(VecBindToCPU(y, boundtocpu));
6136: PetscCall(VecBindToCPU(z, boundtocpu));
6137: PetscCall(VecSetRandom(x, NULL));
6138: PetscCall(VecNormalize(x, NULL));
6139: *n = 0.0;
6140: for (i = 0; i < maxit; i++) {
6141: PetscCall(MatMult(A, x, y));
6142: PetscCall(VecNormalize(y, n));
6143: PetscCall(MatMultHermitianTranspose(A, y, z));
6144: PetscCall(VecNorm(z, NORM_2, &normz));
6145: PetscCall(VecDot(x, z, &dot));
6146: adot = PetscAbsScalar(dot);
6147: PetscCall(PetscInfo(A, "%s norm it %" PetscInt_FMT " -> %g (%g %g)\n", NormTypes[normtype], i, (double)*n, (double)normz, (double)adot));
6148: if (normz <= adot) {
6149: PetscCall(PetscInfo(A, "%s norm converged\n", NormTypes[normtype]));
6150: break;
6151: }
6152: if (i < maxit - 1) {
6153: Vec t;
6155: PetscCall(VecNormalize(z, NULL));
6156: t = x;
6157: x = z;
6158: z = t;
6159: }
6160: }
6161: PetscCall(VecDestroy(&x));
6162: PetscCall(VecDestroy(&y));
6163: PetscCall(VecDestroy(&z));
6164: break;
6165: default:
6166: SETERRQ(PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "%s norm not supported", NormTypes[normtype]);
6167: }
6168: PetscCall(PetscInfo(A, "%s norm %g computed in %" PetscInt_FMT " iterations\n", NormTypes[normtype], (double)*n, i));
6169: PetscFunctionReturn(PETSC_SUCCESS);
6170: }
6172: /*
6173: This variable is used to prevent counting of MatAssemblyBegin() that
6174: are called from within a MatAssemblyEnd().
6175: */
6176: static PetscInt MatAssemblyEnd_InUse = 0;
6177: /*@
6178: MatAssemblyBegin - Begins assembling the matrix. This routine should
6179: be called after completing all calls to `MatSetValues()`.
6181: Collective
6183: Input Parameters:
6184: + mat - the matrix
6185: - type - type of assembly, either `MAT_FLUSH_ASSEMBLY` or `MAT_FINAL_ASSEMBLY`
6187: Level: beginner
6189: Notes:
6190: `MatSetValues()` generally caches the values that belong to other MPI processes. The matrix is ready to
6191: use only after `MatAssemblyBegin()` and `MatAssemblyEnd()` have been called.
6193: Use `MAT_FLUSH_ASSEMBLY` when switching between `ADD_VALUES` and `INSERT_VALUES`
6194: in `MatSetValues()`; use `MAT_FINAL_ASSEMBLY` for the final assembly before
6195: using the matrix.
6197: ALL processes that share a matrix MUST call `MatAssemblyBegin()` and `MatAssemblyEnd()` the SAME NUMBER of times, and each time with the
6198: 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
6199: a global collective operation requiring all processes that share the matrix.
6201: Space for preallocated nonzeros that is not filled by a call to `MatSetValues()` or a related routine are compressed
6202: out by assembly. If you intend to use that extra space on a subsequent assembly, be sure to insert explicit zeros
6203: before `MAT_FINAL_ASSEMBLY` so the space is not compressed out.
6205: .seealso: [](ch_matrices), `Mat`, `MatAssemblyEnd()`, `MatSetValues()`, `MatAssembled()`
6206: @*/
6207: PetscErrorCode MatAssemblyBegin(Mat mat, MatAssemblyType type)
6208: {
6209: PetscFunctionBegin;
6212: MatCheckPreallocated(mat, 1);
6213: PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix. Did you forget to call MatSetUnfactored()?");
6214: if (mat->assembled) {
6215: mat->was_assembled = PETSC_TRUE;
6216: mat->assembled = PETSC_FALSE;
6217: }
6219: if (!MatAssemblyEnd_InUse) {
6220: PetscCall(PetscLogEventBegin(MAT_AssemblyBegin, mat, 0, 0, 0));
6221: PetscTryTypeMethod(mat, assemblybegin, type);
6222: PetscCall(PetscLogEventEnd(MAT_AssemblyBegin, mat, 0, 0, 0));
6223: } else PetscTryTypeMethod(mat, assemblybegin, type);
6224: PetscFunctionReturn(PETSC_SUCCESS);
6225: }
6227: /*@
6228: MatAssembled - Indicates if a matrix has been assembled and is ready for
6229: use; for example, in matrix-vector product.
6231: Not Collective
6233: Input Parameter:
6234: . mat - the matrix
6236: Output Parameter:
6237: . assembled - `PETSC_TRUE` or `PETSC_FALSE`
6239: Level: advanced
6241: .seealso: [](ch_matrices), `Mat`, `MatAssemblyEnd()`, `MatSetValues()`, `MatAssemblyBegin()`
6242: @*/
6243: PetscErrorCode MatAssembled(Mat mat, PetscBool *assembled)
6244: {
6245: PetscFunctionBegin;
6247: PetscAssertPointer(assembled, 2);
6248: *assembled = mat->assembled;
6249: PetscFunctionReturn(PETSC_SUCCESS);
6250: }
6252: /*@
6253: MatAssemblyEnd - Completes assembling the matrix. This routine should
6254: be called after `MatAssemblyBegin()`.
6256: Collective
6258: Input Parameters:
6259: + mat - the matrix
6260: - type - type of assembly, either `MAT_FLUSH_ASSEMBLY` or `MAT_FINAL_ASSEMBLY`
6262: Options Database Key:
6263: . -mat_view [viewertype][:...] - option name and values. See `MatViewFromOptions()`/`PetscObjectViewFromOptions()` for the possible arguments
6265: Level: beginner
6267: .seealso: [](ch_matrices), `Mat`, `MatAssemblyBegin()`, `MatSetValues()`, `PetscDrawOpenX()`, `PetscDrawCreate()`, `MatView()`, `MatAssembled()`, `PetscViewerSocketOpen()`,
6268: `MatViewFromOptions()`, `PetscObjectViewFromOptions()`
6269: @*/
6270: PetscErrorCode MatAssemblyEnd(Mat mat, MatAssemblyType type)
6271: {
6272: static PetscInt inassm = 0;
6273: PetscBool flg = PETSC_FALSE;
6275: PetscFunctionBegin;
6279: inassm++;
6280: MatAssemblyEnd_InUse++;
6281: if (MatAssemblyEnd_InUse == 1) { /* Do the logging only the first time through */
6282: PetscCall(PetscLogEventBegin(MAT_AssemblyEnd, mat, 0, 0, 0));
6283: PetscTryTypeMethod(mat, assemblyend, type);
6284: PetscCall(PetscLogEventEnd(MAT_AssemblyEnd, mat, 0, 0, 0));
6285: } else PetscTryTypeMethod(mat, assemblyend, type);
6287: /* Flush assembly is not a true assembly */
6288: if (type != MAT_FLUSH_ASSEMBLY) {
6289: if (mat->num_ass) {
6290: if (!mat->symmetry_eternal) {
6291: mat->symmetric = PETSC_BOOL3_UNKNOWN;
6292: mat->hermitian = PETSC_BOOL3_UNKNOWN;
6293: }
6294: if (!mat->structural_symmetry_eternal && mat->ass_nonzerostate != mat->nonzerostate) mat->structurally_symmetric = PETSC_BOOL3_UNKNOWN;
6295: if (!mat->spd_eternal) mat->spd = PETSC_BOOL3_UNKNOWN;
6296: }
6297: mat->num_ass++;
6298: mat->assembled = PETSC_TRUE;
6299: mat->ass_nonzerostate = mat->nonzerostate;
6300: }
6302: mat->insertmode = NOT_SET_VALUES;
6303: MatAssemblyEnd_InUse--;
6304: PetscCall(PetscObjectStateIncrease((PetscObject)mat));
6305: if (inassm == 1 && type != MAT_FLUSH_ASSEMBLY) {
6306: PetscCall(MatViewFromOptions(mat, NULL, "-mat_view"));
6308: if (mat->checksymmetryonassembly) {
6309: PetscCall(MatIsSymmetric(mat, mat->checksymmetrytol, &flg));
6310: if (flg) {
6311: PetscCall(PetscPrintf(PetscObjectComm((PetscObject)mat), "Matrix is symmetric (tolerance %g)\n", (double)mat->checksymmetrytol));
6312: } else {
6313: PetscCall(PetscPrintf(PetscObjectComm((PetscObject)mat), "Matrix is not symmetric (tolerance %g)\n", (double)mat->checksymmetrytol));
6314: }
6315: }
6316: if (mat->nullsp && mat->checknullspaceonassembly) PetscCall(MatNullSpaceTest(mat->nullsp, mat, NULL));
6317: }
6318: inassm--;
6319: PetscFunctionReturn(PETSC_SUCCESS);
6320: }
6322: // PetscClangLinter pragma disable: -fdoc-section-header-unknown
6323: /*@
6324: MatSetOption - Sets a parameter option for a matrix. Some options
6325: may be specific to certain storage formats. Some options
6326: determine how values will be inserted (or added). Sorted,
6327: row-oriented input will generally assemble the fastest. The default
6328: is row-oriented.
6330: Logically Collective for certain operations, such as `MAT_SPD`, not collective for `MAT_ROW_ORIENTED`, see `MatOption`
6332: Input Parameters:
6333: + mat - the matrix
6334: . op - the option, one of those listed below (and possibly others),
6335: - flg - turn the option on (`PETSC_TRUE`) or off (`PETSC_FALSE`)
6337: Options Describing Matrix Structure:
6338: + `MAT_SPD` - symmetric positive definite
6339: . `MAT_SYMMETRIC` - symmetric in terms of both structure and value
6340: . `MAT_HERMITIAN` - transpose is the complex conjugation
6341: . `MAT_STRUCTURALLY_SYMMETRIC` - symmetric nonzero structure
6342: . `MAT_SYMMETRY_ETERNAL` - indicates the symmetry (or Hermitian structure) or its absence will persist through any changes to the matrix
6343: . `MAT_STRUCTURAL_SYMMETRY_ETERNAL` - indicates the structural symmetry or its absence will persist through any changes to the matrix
6344: . `MAT_SPD_ETERNAL` - indicates the value of `MAT_SPD` (true or false) will persist through any changes to the matrix
6346: These are not really options of the matrix, they are knowledge about the structure of the matrix that users may provide so that they
6347: do not need to be computed (usually at a high cost)
6349: Options For Use with `MatSetValues()`:
6350: Insert a logically dense subblock, which can be
6351: . `MAT_ROW_ORIENTED` - row-oriented (default)
6353: These options reflect the data you pass in with `MatSetValues()`; it has
6354: nothing to do with how the data is stored internally in the matrix
6355: data structure.
6357: When (re)assembling a matrix, we can restrict the input for
6358: efficiency/debugging purposes. These options include
6359: . `MAT_NEW_NONZERO_LOCATIONS` - additional insertions will be allowed if they generate a new nonzero (slow)
6360: . `MAT_FORCE_DIAGONAL_ENTRIES` - forces diagonal entries to be allocated
6361: . `MAT_IGNORE_OFF_PROC_ENTRIES` - drops off-processor entries
6362: . `MAT_NEW_NONZERO_LOCATION_ERR` - generates an error for new matrix entry
6363: . `MAT_USE_HASH_TABLE` - uses a hash table to speed up matrix assembly
6364: . `MAT_NO_OFF_PROC_ENTRIES` - you know each process will only set values for its own rows, will generate an error if
6365: any process sets values for another process. This avoids all reductions in the MatAssembly routines and thus improves
6366: performance for very large process counts.
6367: - `MAT_SUBSET_OFF_PROC_ENTRIES` - you know that the first assembly after setting this flag will set a superset
6368: of the off-process entries required for all subsequent assemblies. This avoids a rendezvous step in the MatAssembly
6369: functions, instead sending only neighbor messages.
6371: Level: intermediate
6373: Notes:
6374: Except for `MAT_UNUSED_NONZERO_LOCATION_ERR` and `MAT_ROW_ORIENTED` all processes that share the matrix must pass the same value in flg!
6376: Some options are relevant only for particular matrix types and
6377: are thus ignored by others. Other options are not supported by
6378: certain matrix types and will generate an error message if set.
6380: If using Fortran to compute a matrix, one may need to
6381: use the column-oriented option (or convert to the row-oriented
6382: format).
6384: `MAT_NEW_NONZERO_LOCATIONS` set to `PETSC_FALSE` indicates that any add or insertion
6385: that would generate a new entry in the nonzero structure is instead
6386: ignored. Thus, if memory has not already been allocated for this particular
6387: data, then the insertion is ignored. For dense matrices, in which
6388: the entire array is allocated, no entries are ever ignored.
6389: Set after the first `MatAssemblyEnd()`. If this option is set, then the `MatAssemblyBegin()`/`MatAssemblyEnd()` processes has one less global reduction
6391: `MAT_NEW_NONZERO_LOCATION_ERR` set to PETSC_TRUE indicates that any add or insertion
6392: that would generate a new entry in the nonzero structure instead produces
6393: 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
6395: `MAT_NEW_NONZERO_ALLOCATION_ERR` set to `PETSC_TRUE` indicates that any add or insertion
6396: that would generate a new entry that has not been preallocated will
6397: instead produce an error. (Currently supported for `MATAIJ` and `MATBAIJ` formats
6398: only.) This is a useful flag when debugging matrix memory preallocation.
6399: If this option is set, then the `MatAssemblyBegin()`/`MatAssemblyEnd()` processes has one less global reduction
6401: `MAT_IGNORE_OFF_PROC_ENTRIES` set to `PETSC_TRUE` indicates entries destined for
6402: other processors should be dropped, rather than stashed.
6403: This is useful if you know that the "owning" processor is also
6404: always generating the correct matrix entries, so that PETSc need
6405: not transfer duplicate entries generated on another processor.
6407: `MAT_USE_HASH_TABLE` indicates that a hash table be used to improve the
6408: searches during matrix assembly. When this flag is set, the hash table
6409: is created during the first matrix assembly. This hash table is
6410: used the next time through, during `MatSetValues()`/`MatSetValuesBlocked()`
6411: to improve the searching of indices. `MAT_NEW_NONZERO_LOCATIONS` flag
6412: should be used with `MAT_USE_HASH_TABLE` flag. This option is currently
6413: supported by `MATMPIBAIJ` format only.
6415: `MAT_KEEP_NONZERO_PATTERN` indicates when `MatZeroRows()` is called the zeroed entries
6416: are kept in the nonzero structure. This flag is not used for `MatZeroRowsColumns()`
6418: `MAT_IGNORE_ZERO_ENTRIES` - for `MATAIJ` and `MATIS` matrices this will stop zero values from creating
6419: a zero location in the matrix
6421: `MAT_USE_INODES` - indicates using inode version of the code - works with `MATAIJ` matrix types
6423: `MAT_NO_OFF_PROC_ZERO_ROWS` - you know each process will only zero its own rows. This avoids all reductions in the
6424: zero row routines and thus improves performance for very large process counts.
6426: `MAT_IGNORE_LOWER_TRIANGULAR` - For `MATSBAIJ` matrices will ignore any insertions you make in the lower triangular
6427: part of the matrix (since they should match the upper triangular part).
6429: `MAT_SORTED_FULL` - each process provides exactly its local rows; all column indices for a given row are passed in a
6430: single call to `MatSetValues()`, preallocation is perfect, row-oriented, `INSERT_VALUES` is used. Common
6431: with finite difference schemes with non-periodic boundary conditions.
6433: Developer Note:
6434: `MAT_SYMMETRY_ETERNAL`, `MAT_STRUCTURAL_SYMMETRY_ETERNAL`, and `MAT_SPD_ETERNAL` are used by `MatAssemblyEnd()` and in other
6435: places where otherwise the value of `MAT_SYMMETRIC`, `MAT_STRUCTURALLY_SYMMETRIC` or `MAT_SPD` would need to be changed back
6436: to `PETSC_BOOL3_UNKNOWN` because the matrix values had changed so the code cannot be certain that the related property had
6437: not changed.
6439: .seealso: [](ch_matrices), `MatOption`, `Mat`, `MatGetOption()`
6440: @*/
6441: PetscErrorCode MatSetOption(Mat mat, MatOption op, PetscBool flg)
6442: {
6443: PetscFunctionBegin;
6445: if (op > 0) {
6448: }
6450: 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);
6452: switch (op) {
6453: case MAT_FORCE_DIAGONAL_ENTRIES:
6454: mat->force_diagonals = flg;
6455: PetscFunctionReturn(PETSC_SUCCESS);
6456: case MAT_NO_OFF_PROC_ENTRIES:
6457: mat->nooffprocentries = flg;
6458: PetscFunctionReturn(PETSC_SUCCESS);
6459: case MAT_SUBSET_OFF_PROC_ENTRIES:
6460: mat->assembly_subset = flg;
6461: if (!mat->assembly_subset) { /* See the same logic in VecAssembly wrt VEC_SUBSET_OFF_PROC_ENTRIES */
6462: #if !defined(PETSC_HAVE_MPIUNI)
6463: PetscCall(MatStashScatterDestroy_BTS(&mat->stash));
6464: #endif
6465: mat->stash.first_assembly_done = PETSC_FALSE;
6466: }
6467: PetscFunctionReturn(PETSC_SUCCESS);
6468: case MAT_NO_OFF_PROC_ZERO_ROWS:
6469: mat->nooffproczerorows = flg;
6470: PetscFunctionReturn(PETSC_SUCCESS);
6471: case MAT_SPD:
6472: if (flg) {
6473: mat->spd = PETSC_BOOL3_TRUE;
6474: mat->symmetric = PETSC_BOOL3_TRUE;
6475: mat->structurally_symmetric = PETSC_BOOL3_TRUE;
6476: #if !defined(PETSC_USE_COMPLEX)
6477: mat->hermitian = PETSC_BOOL3_TRUE;
6478: #endif
6479: } else {
6480: mat->spd = PETSC_BOOL3_FALSE;
6481: }
6482: break;
6483: case MAT_SYMMETRIC:
6484: mat->symmetric = PetscBoolToBool3(flg);
6485: if (flg) mat->structurally_symmetric = PETSC_BOOL3_TRUE;
6486: #if !defined(PETSC_USE_COMPLEX)
6487: mat->hermitian = PetscBoolToBool3(flg);
6488: #endif
6489: break;
6490: case MAT_HERMITIAN:
6491: mat->hermitian = PetscBoolToBool3(flg);
6492: if (flg) mat->structurally_symmetric = PETSC_BOOL3_TRUE;
6493: #if !defined(PETSC_USE_COMPLEX)
6494: mat->symmetric = PetscBoolToBool3(flg);
6495: #endif
6496: break;
6497: case MAT_STRUCTURALLY_SYMMETRIC:
6498: mat->structurally_symmetric = PetscBoolToBool3(flg);
6499: break;
6500: case MAT_SYMMETRY_ETERNAL:
6501: 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");
6502: mat->symmetry_eternal = flg;
6503: if (flg) mat->structural_symmetry_eternal = PETSC_TRUE;
6504: break;
6505: case MAT_STRUCTURAL_SYMMETRY_ETERNAL:
6506: 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");
6507: mat->structural_symmetry_eternal = flg;
6508: break;
6509: case MAT_SPD_ETERNAL:
6510: 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");
6511: mat->spd_eternal = flg;
6512: if (flg) {
6513: mat->structural_symmetry_eternal = PETSC_TRUE;
6514: mat->symmetry_eternal = PETSC_TRUE;
6515: }
6516: break;
6517: case MAT_STRUCTURE_ONLY:
6518: mat->structure_only = flg;
6519: break;
6520: case MAT_SORTED_FULL:
6521: mat->sortedfull = flg;
6522: break;
6523: default:
6524: break;
6525: }
6526: PetscTryTypeMethod(mat, setoption, op, flg);
6527: PetscFunctionReturn(PETSC_SUCCESS);
6528: }
6530: /*@
6531: MatGetOption - Gets a parameter option that has been set for a matrix.
6533: Logically Collective
6535: Input Parameters:
6536: + mat - the matrix
6537: - op - the option, this only responds to certain options, check the code for which ones
6539: Output Parameter:
6540: . flg - turn the option on (`PETSC_TRUE`) or off (`PETSC_FALSE`)
6542: Level: intermediate
6544: Notes:
6545: Can only be called after `MatSetSizes()` and `MatSetType()` have been set.
6547: Certain option values may be unknown, for those use the routines `MatIsSymmetric()`, `MatIsHermitian()`, `MatIsStructurallySymmetric()`, or
6548: `MatIsSymmetricKnown()`, `MatIsHermitianKnown()`, `MatIsStructurallySymmetricKnown()`
6550: .seealso: [](ch_matrices), `Mat`, `MatOption`, `MatSetOption()`, `MatIsSymmetric()`, `MatIsHermitian()`, `MatIsStructurallySymmetric()`,
6551: `MatIsSymmetricKnown()`, `MatIsHermitianKnown()`, `MatIsStructurallySymmetricKnown()`
6552: @*/
6553: PetscErrorCode MatGetOption(Mat mat, MatOption op, PetscBool *flg)
6554: {
6555: PetscFunctionBegin;
6559: 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);
6560: 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()");
6562: switch (op) {
6563: case MAT_NO_OFF_PROC_ENTRIES:
6564: *flg = mat->nooffprocentries;
6565: break;
6566: case MAT_NO_OFF_PROC_ZERO_ROWS:
6567: *flg = mat->nooffproczerorows;
6568: break;
6569: case MAT_SYMMETRIC:
6570: SETERRQ(PetscObjectComm((PetscObject)mat), PETSC_ERR_SUP, "Use MatIsSymmetric() or MatIsSymmetricKnown()");
6571: break;
6572: case MAT_HERMITIAN:
6573: SETERRQ(PetscObjectComm((PetscObject)mat), PETSC_ERR_SUP, "Use MatIsHermitian() or MatIsHermitianKnown()");
6574: break;
6575: case MAT_STRUCTURALLY_SYMMETRIC:
6576: SETERRQ(PetscObjectComm((PetscObject)mat), PETSC_ERR_SUP, "Use MatIsStructurallySymmetric() or MatIsStructurallySymmetricKnown()");
6577: break;
6578: case MAT_SPD:
6579: SETERRQ(PetscObjectComm((PetscObject)mat), PETSC_ERR_SUP, "Use MatIsSPDKnown()");
6580: break;
6581: case MAT_SYMMETRY_ETERNAL:
6582: *flg = mat->symmetry_eternal;
6583: break;
6584: case MAT_STRUCTURAL_SYMMETRY_ETERNAL:
6585: *flg = mat->symmetry_eternal;
6586: break;
6587: default:
6588: break;
6589: }
6590: PetscFunctionReturn(PETSC_SUCCESS);
6591: }
6593: /*@
6594: MatZeroEntries - Zeros all entries of a matrix. For sparse matrices
6595: this routine retains the old nonzero structure.
6597: Logically Collective
6599: Input Parameter:
6600: . mat - the matrix
6602: Level: intermediate
6604: Note:
6605: 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.
6606: See the Performance chapter of the users manual for information on preallocating matrices.
6608: .seealso: [](ch_matrices), `Mat`, `MatZeroRows()`, `MatZeroRowsColumns()`
6609: @*/
6610: PetscErrorCode MatZeroEntries(Mat mat)
6611: {
6612: PetscFunctionBegin;
6615: PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
6616: 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");
6617: MatCheckPreallocated(mat, 1);
6619: PetscCall(PetscLogEventBegin(MAT_ZeroEntries, mat, 0, 0, 0));
6620: PetscUseTypeMethod(mat, zeroentries);
6621: PetscCall(PetscLogEventEnd(MAT_ZeroEntries, mat, 0, 0, 0));
6622: PetscCall(PetscObjectStateIncrease((PetscObject)mat));
6623: PetscFunctionReturn(PETSC_SUCCESS);
6624: }
6626: /*@
6627: MatZeroRowsColumns - Zeros all entries (except possibly the main diagonal)
6628: of a set of rows and columns of a matrix.
6630: Collective
6632: Input Parameters:
6633: + mat - the matrix
6634: . numRows - the number of rows/columns to zero
6635: . rows - the global row indices
6636: . diag - value put in the diagonal of the eliminated rows
6637: . x - optional vector of the solution for zeroed rows (other entries in vector are not used), these must be set before this call
6638: - b - optional vector of the right-hand side, that will be adjusted by provided solution entries
6640: Level: intermediate
6642: Notes:
6643: This routine, along with `MatZeroRows()`, is typically used to eliminate known Dirichlet boundary conditions from a linear system.
6645: For each zeroed row, the value of the corresponding `b` is set to diag times the value of the corresponding `x`.
6646: 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
6648: If the resulting linear system is to be solved with `KSP` then one can (but does not have to) call `KSPSetInitialGuessNonzero()` to allow the
6649: Krylov method to take advantage of the known solution on the zeroed rows.
6651: For the parallel case, all processes that share the matrix (i.e.,
6652: those in the communicator used for matrix creation) MUST call this
6653: routine, regardless of whether any rows being zeroed are owned by
6654: them.
6656: Unlike `MatZeroRows()`, this ignores the `MAT_KEEP_NONZERO_PATTERN` option value set with `MatSetOption()`, it merely zeros those entries in the matrix, but never
6657: 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
6658: missing.
6660: Each processor can indicate any rows in the entire matrix to be zeroed (i.e. each process does NOT have to
6661: list only rows local to itself).
6663: The option `MAT_NO_OFF_PROC_ZERO_ROWS` does not apply to this routine.
6665: .seealso: [](ch_matrices), `Mat`, `MatZeroRowsIS()`, `MatZeroRows()`, `MatZeroRowsLocalIS()`, `MatZeroRowsStencil()`, `MatZeroEntries()`, `MatZeroRowsLocal()`, `MatSetOption()`,
6666: `MatZeroRowsColumnsLocal()`, `MatZeroRowsColumnsLocalIS()`, `MatZeroRowsColumnsIS()`, `MatZeroRowsColumnsStencil()`
6667: @*/
6668: PetscErrorCode MatZeroRowsColumns(Mat mat, PetscInt numRows, const PetscInt rows[], PetscScalar diag, Vec x, Vec b)
6669: {
6670: PetscFunctionBegin;
6673: if (numRows) PetscAssertPointer(rows, 3);
6674: PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
6675: PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
6676: MatCheckPreallocated(mat, 1);
6678: PetscUseTypeMethod(mat, zerorowscolumns, numRows, rows, diag, x, b);
6679: PetscCall(MatViewFromOptions(mat, NULL, "-mat_view"));
6680: PetscCall(PetscObjectStateIncrease((PetscObject)mat));
6681: PetscFunctionReturn(PETSC_SUCCESS);
6682: }
6684: /*@
6685: MatZeroRowsColumnsIS - Zeros all entries (except possibly the main diagonal)
6686: of a set of rows and columns of a matrix.
6688: Collective
6690: Input Parameters:
6691: + mat - the matrix
6692: . is - the rows to zero
6693: . diag - value put in all diagonals of eliminated rows (0.0 will even eliminate diagonal entry)
6694: . x - optional vector of solutions for zeroed rows (other entries in vector are not used)
6695: - b - optional vector of right-hand side, that will be adjusted by provided solution
6697: Level: intermediate
6699: Note:
6700: See `MatZeroRowsColumns()` for details on how this routine operates.
6702: .seealso: [](ch_matrices), `Mat`, `MatZeroRowsIS()`, `MatZeroRowsColumns()`, `MatZeroRowsLocalIS()`, `MatZeroRowsStencil()`, `MatZeroEntries()`, `MatZeroRowsLocal()`, `MatSetOption()`,
6703: `MatZeroRowsColumnsLocal()`, `MatZeroRowsColumnsLocalIS()`, `MatZeroRows()`, `MatZeroRowsColumnsStencil()`
6704: @*/
6705: PetscErrorCode MatZeroRowsColumnsIS(Mat mat, IS is, PetscScalar diag, Vec x, Vec b)
6706: {
6707: PetscInt numRows;
6708: const PetscInt *rows;
6710: PetscFunctionBegin;
6715: PetscCall(ISGetLocalSize(is, &numRows));
6716: PetscCall(ISGetIndices(is, &rows));
6717: PetscCall(MatZeroRowsColumns(mat, numRows, rows, diag, x, b));
6718: PetscCall(ISRestoreIndices(is, &rows));
6719: PetscFunctionReturn(PETSC_SUCCESS);
6720: }
6722: /*@
6723: MatZeroRows - Zeros all entries (except possibly the main diagonal)
6724: of a set of rows of a matrix.
6726: Collective
6728: Input Parameters:
6729: + mat - the matrix
6730: . numRows - the number of rows to zero
6731: . rows - the global row indices
6732: . diag - value put in the diagonal of the zeroed rows
6733: . x - optional vector of solutions for zeroed rows (other entries in vector are not used), these must be set before this call
6734: - b - optional vector of right-hand side, that will be adjusted by provided solution entries
6736: Level: intermediate
6738: Notes:
6739: This routine, along with `MatZeroRowsColumns()`, is typically used to eliminate known Dirichlet boundary conditions from a linear system.
6741: For each zeroed row, the value of the corresponding `b` is set to `diag` times the value of the corresponding `x`.
6743: If the resulting linear system is to be solved with `KSP` then one can (but does not have to) call `KSPSetInitialGuessNonzero()` to allow the
6744: Krylov method to take advantage of the known solution on the zeroed rows.
6746: 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)
6747: from the matrix.
6749: Unlike `MatZeroRowsColumns()` for the `MATAIJ` and `MATBAIJ` matrix formats this removes the old nonzero structure, from the eliminated rows of the matrix
6750: but does not release memory. Because of this removal matrix-vector products with the adjusted matrix will be a bit faster. For the dense
6751: formats this does not alter the nonzero structure.
6753: If the option `MatSetOption`(mat,`MAT_KEEP_NONZERO_PATTERN`,`PETSC_TRUE`) the nonzero structure
6754: of the matrix is not changed the values are
6755: merely zeroed.
6757: The user can set a value in the diagonal entry (or for the `MATAIJ` format
6758: formats can optionally remove the main diagonal entry from the
6759: nonzero structure as well, by passing 0.0 as the final argument).
6761: For the parallel case, all processes that share the matrix (i.e.,
6762: those in the communicator used for matrix creation) MUST call this
6763: routine, regardless of whether any rows being zeroed are owned by
6764: them.
6766: Each processor can indicate any rows in the entire matrix to be zeroed (i.e. each process does NOT have to
6767: list only rows local to itself).
6769: You can call `MatSetOption`(mat,`MAT_NO_OFF_PROC_ZERO_ROWS`,`PETSC_TRUE`) if each process indicates only rows it
6770: owns that are to be zeroed. This saves a global synchronization in the implementation.
6772: .seealso: [](ch_matrices), `Mat`, `MatZeroRowsIS()`, `MatZeroRowsColumns()`, `MatZeroRowsLocalIS()`, `MatZeroRowsStencil()`, `MatZeroEntries()`, `MatZeroRowsLocal()`, `MatSetOption()`,
6773: `MatZeroRowsColumnsLocal()`, `MatZeroRowsColumnsLocalIS()`, `MatZeroRowsColumnsIS()`, `MatZeroRowsColumnsStencil()`, `PCREDISTRIBUTE`, `MAT_KEEP_NONZERO_PATTERN`
6774: @*/
6775: PetscErrorCode MatZeroRows(Mat mat, PetscInt numRows, const PetscInt rows[], PetscScalar diag, Vec x, Vec b)
6776: {
6777: PetscFunctionBegin;
6780: if (numRows) PetscAssertPointer(rows, 3);
6781: PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
6782: PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
6783: MatCheckPreallocated(mat, 1);
6785: PetscUseTypeMethod(mat, zerorows, numRows, rows, diag, x, b);
6786: PetscCall(MatViewFromOptions(mat, NULL, "-mat_view"));
6787: PetscCall(PetscObjectStateIncrease((PetscObject)mat));
6788: PetscFunctionReturn(PETSC_SUCCESS);
6789: }
6791: /*@
6792: MatZeroRowsIS - Zeros all entries (except possibly the main diagonal)
6793: of a set of rows of a matrix indicated by an `IS`
6795: Collective
6797: Input Parameters:
6798: + mat - the matrix
6799: . is - index set, `IS`, of rows to remove (if `NULL` then no row is removed)
6800: . diag - value put in all diagonals of eliminated rows
6801: . x - optional vector of solutions for zeroed rows (other entries in vector are not used)
6802: - b - optional vector of right-hand side, that will be adjusted by provided solution
6804: Level: intermediate
6806: Note:
6807: See `MatZeroRows()` for details on how this routine operates.
6809: .seealso: [](ch_matrices), `Mat`, `MatZeroRows()`, `MatZeroRowsColumns()`, `MatZeroRowsLocalIS()`, `MatZeroRowsStencil()`, `MatZeroEntries()`, `MatZeroRowsLocal()`, `MatSetOption()`,
6810: `MatZeroRowsColumnsLocal()`, `MatZeroRowsColumnsLocalIS()`, `MatZeroRowsColumnsIS()`, `MatZeroRowsColumnsStencil()`, `IS`
6811: @*/
6812: PetscErrorCode MatZeroRowsIS(Mat mat, IS is, PetscScalar diag, Vec x, Vec b)
6813: {
6814: PetscInt numRows = 0;
6815: const PetscInt *rows = NULL;
6817: PetscFunctionBegin;
6820: if (is) {
6822: PetscCall(ISGetLocalSize(is, &numRows));
6823: PetscCall(ISGetIndices(is, &rows));
6824: }
6825: PetscCall(MatZeroRows(mat, numRows, rows, diag, x, b));
6826: if (is) PetscCall(ISRestoreIndices(is, &rows));
6827: PetscFunctionReturn(PETSC_SUCCESS);
6828: }
6830: /*@
6831: MatZeroRowsStencil - Zeros all entries (except possibly the main diagonal)
6832: of a set of rows of a matrix indicated by a `MatStencil`. These rows must be local to the process.
6834: Collective
6836: Input Parameters:
6837: + mat - the matrix
6838: . numRows - the number of rows to remove
6839: . rows - the grid coordinates (and component number when dof > 1) for matrix rows indicated by an array of `MatStencil`
6840: . diag - value put in all diagonals of eliminated rows (0.0 will even eliminate diagonal entry)
6841: . x - optional vector of solutions for zeroed rows (other entries in vector are not used)
6842: - b - optional vector of right-hand side, that will be adjusted by provided solution
6844: Level: intermediate
6846: Notes:
6847: See `MatZeroRows()` for details on how this routine operates.
6849: The grid coordinates are across the entire grid, not just the local portion
6851: For periodic boundary conditions use negative indices for values to the left (below 0; that are to be
6852: obtained by wrapping values from right edge). For values to the right of the last entry using that index plus one
6853: etc to obtain values that obtained by wrapping the values from the left edge. This does not work for anything but the
6854: `DM_BOUNDARY_PERIODIC` boundary type.
6856: 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
6857: a single value per point) you can skip filling those indices.
6859: Fortran Note:
6860: `idxm` and `idxn` should be declared as
6861: .vb
6862: MatStencil idxm(4, m)
6863: .ve
6864: and the values inserted using
6865: .vb
6866: idxm(MatStencil_i, 1) = i
6867: idxm(MatStencil_j, 1) = j
6868: idxm(MatStencil_k, 1) = k
6869: idxm(MatStencil_c, 1) = c
6870: etc
6871: .ve
6873: .seealso: [](ch_matrices), `Mat`, `MatStencil`, `MatZeroRowsIS()`, `MatZeroRowsColumns()`, `MatZeroRowsLocalIS()`, `MatZeroRows()`, `MatZeroEntries()`, `MatZeroRowsLocal()`, `MatSetOption()`,
6874: `MatZeroRowsColumnsLocal()`, `MatZeroRowsColumnsLocalIS()`, `MatZeroRowsColumnsIS()`, `MatZeroRowsColumnsStencil()`
6875: @*/
6876: PetscErrorCode MatZeroRowsStencil(Mat mat, PetscInt numRows, const MatStencil rows[], PetscScalar diag, Vec x, Vec b)
6877: {
6878: PetscInt dim = mat->stencil.dim;
6879: PetscInt sdim = dim - (1 - (PetscInt)mat->stencil.noc);
6880: PetscInt *dims = mat->stencil.dims + 1;
6881: PetscInt *starts = mat->stencil.starts;
6882: PetscInt *dxm = (PetscInt *)rows;
6883: PetscInt *jdxm, i, j, tmp, numNewRows = 0;
6885: PetscFunctionBegin;
6888: if (numRows) PetscAssertPointer(rows, 3);
6890: PetscCall(PetscMalloc1(numRows, &jdxm));
6891: for (i = 0; i < numRows; ++i) {
6892: /* Skip unused dimensions (they are ordered k, j, i, c) */
6893: for (j = 0; j < 3 - sdim; ++j) dxm++;
6894: /* Local index in X dir */
6895: tmp = *dxm++ - starts[0];
6896: /* Loop over remaining dimensions */
6897: for (j = 0; j < dim - 1; ++j) {
6898: /* If nonlocal, set index to be negative */
6899: if ((*dxm++ - starts[j + 1]) < 0 || tmp < 0) tmp = PETSC_INT_MIN;
6900: /* Update local index */
6901: else tmp = tmp * dims[j] + *(dxm - 1) - starts[j + 1];
6902: }
6903: /* Skip component slot if necessary */
6904: if (mat->stencil.noc) dxm++;
6905: /* Local row number */
6906: if (tmp >= 0) jdxm[numNewRows++] = tmp;
6907: }
6908: PetscCall(MatZeroRowsLocal(mat, numNewRows, jdxm, diag, x, b));
6909: PetscCall(PetscFree(jdxm));
6910: PetscFunctionReturn(PETSC_SUCCESS);
6911: }
6913: /*@
6914: MatZeroRowsColumnsStencil - Zeros all row and column entries (except possibly the main diagonal)
6915: of a set of rows and columns of a matrix.
6917: Collective
6919: Input Parameters:
6920: + mat - the matrix
6921: . numRows - the number of rows/columns to remove
6922: . rows - the grid coordinates (and component number when dof > 1) for matrix rows
6923: . diag - value put in all diagonals of eliminated rows (0.0 will even eliminate diagonal entry)
6924: . x - optional vector of solutions for zeroed rows (other entries in vector are not used)
6925: - b - optional vector of right-hand side, that will be adjusted by provided solution
6927: Level: intermediate
6929: Notes:
6930: See `MatZeroRowsColumns()` for details on how this routine operates.
6932: The grid coordinates are across the entire grid, not just the local portion
6934: For periodic boundary conditions use negative indices for values to the left (below 0; that are to be
6935: obtained by wrapping values from right edge). For values to the right of the last entry using that index plus one
6936: etc to obtain values that obtained by wrapping the values from the left edge. This does not work for anything but the
6937: `DM_BOUNDARY_PERIODIC` boundary type.
6939: 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
6940: a single value per point) you can skip filling those indices.
6942: Fortran Note:
6943: `idxm` and `idxn` should be declared as
6944: .vb
6945: MatStencil idxm(4, m)
6946: .ve
6947: and the values inserted using
6948: .vb
6949: idxm(MatStencil_i, 1) = i
6950: idxm(MatStencil_j, 1) = j
6951: idxm(MatStencil_k, 1) = k
6952: idxm(MatStencil_c, 1) = c
6953: etc
6954: .ve
6956: .seealso: [](ch_matrices), `Mat`, `MatZeroRowsIS()`, `MatZeroRowsColumns()`, `MatZeroRowsLocalIS()`, `MatZeroRowsStencil()`, `MatZeroEntries()`, `MatZeroRowsLocal()`, `MatSetOption()`,
6957: `MatZeroRowsColumnsLocal()`, `MatZeroRowsColumnsLocalIS()`, `MatZeroRowsColumnsIS()`, `MatZeroRows()`
6958: @*/
6959: PetscErrorCode MatZeroRowsColumnsStencil(Mat mat, PetscInt numRows, const MatStencil rows[], PetscScalar diag, Vec x, Vec b)
6960: {
6961: PetscInt dim = mat->stencil.dim;
6962: PetscInt sdim = dim - (1 - (PetscInt)mat->stencil.noc);
6963: PetscInt *dims = mat->stencil.dims + 1;
6964: PetscInt *starts = mat->stencil.starts;
6965: PetscInt *dxm = (PetscInt *)rows;
6966: PetscInt *jdxm, i, j, tmp, numNewRows = 0;
6968: PetscFunctionBegin;
6971: if (numRows) PetscAssertPointer(rows, 3);
6973: PetscCall(PetscMalloc1(numRows, &jdxm));
6974: for (i = 0; i < numRows; ++i) {
6975: /* Skip unused dimensions (they are ordered k, j, i, c) */
6976: for (j = 0; j < 3 - sdim; ++j) dxm++;
6977: /* Local index in X dir */
6978: tmp = *dxm++ - starts[0];
6979: /* Loop over remaining dimensions */
6980: for (j = 0; j < dim - 1; ++j) {
6981: /* If nonlocal, set index to be negative */
6982: if ((*dxm++ - starts[j + 1]) < 0 || tmp < 0) tmp = PETSC_INT_MIN;
6983: /* Update local index */
6984: else tmp = tmp * dims[j] + *(dxm - 1) - starts[j + 1];
6985: }
6986: /* Skip component slot if necessary */
6987: if (mat->stencil.noc) dxm++;
6988: /* Local row number */
6989: if (tmp >= 0) jdxm[numNewRows++] = tmp;
6990: }
6991: PetscCall(MatZeroRowsColumnsLocal(mat, numNewRows, jdxm, diag, x, b));
6992: PetscCall(PetscFree(jdxm));
6993: PetscFunctionReturn(PETSC_SUCCESS);
6994: }
6996: /*@
6997: MatZeroRowsLocal - Zeros all entries (except possibly the main diagonal)
6998: of a set of rows of a matrix; using local numbering of rows.
7000: Collective
7002: Input Parameters:
7003: + mat - the matrix
7004: . numRows - the number of rows to remove
7005: . rows - the local row indices
7006: . diag - value put in all diagonals of eliminated rows
7007: . x - optional vector of solutions for zeroed rows (other entries in vector are not used)
7008: - b - optional vector of right-hand side, that will be adjusted by provided solution
7010: Level: intermediate
7012: Notes:
7013: Before calling `MatZeroRowsLocal()`, the user must first set the
7014: local-to-global mapping by calling MatSetLocalToGlobalMapping(), this is often already set for matrices obtained with `DMCreateMatrix()`.
7016: See `MatZeroRows()` for details on how this routine operates.
7018: .seealso: [](ch_matrices), `Mat`, `MatZeroRowsIS()`, `MatZeroRowsColumns()`, `MatZeroRowsLocalIS()`, `MatZeroRowsStencil()`, `MatZeroEntries()`, `MatZeroRows()`, `MatSetOption()`,
7019: `MatZeroRowsColumnsLocal()`, `MatZeroRowsColumnsLocalIS()`, `MatZeroRowsColumnsIS()`, `MatZeroRowsColumnsStencil()`
7020: @*/
7021: PetscErrorCode MatZeroRowsLocal(Mat mat, PetscInt numRows, const PetscInt rows[], PetscScalar diag, Vec x, Vec b)
7022: {
7023: PetscFunctionBegin;
7026: if (numRows) PetscAssertPointer(rows, 3);
7027: PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
7028: PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
7029: MatCheckPreallocated(mat, 1);
7031: if (mat->ops->zerorowslocal) {
7032: PetscUseTypeMethod(mat, zerorowslocal, numRows, rows, diag, x, b);
7033: } else {
7034: IS is, newis;
7035: PetscInt *newRows, nl = 0;
7037: PetscCheck(mat->rmap->mapping, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Need to provide local to global mapping to matrix first");
7038: PetscCall(ISCreateGeneral(PETSC_COMM_SELF, numRows, rows, PETSC_USE_POINTER, &is));
7039: PetscCall(ISLocalToGlobalMappingApplyIS(mat->rmap->mapping, is, &newis));
7040: PetscCall(ISGetIndices(newis, (const PetscInt **)&newRows));
7041: for (PetscInt i = 0; i < numRows; i++)
7042: if (newRows[i] > -1) newRows[nl++] = newRows[i];
7043: PetscUseTypeMethod(mat, zerorows, nl, newRows, diag, x, b);
7044: PetscCall(ISRestoreIndices(newis, (const PetscInt **)&newRows));
7045: PetscCall(ISDestroy(&newis));
7046: PetscCall(ISDestroy(&is));
7047: }
7048: PetscCall(PetscObjectStateIncrease((PetscObject)mat));
7049: PetscFunctionReturn(PETSC_SUCCESS);
7050: }
7052: /*@
7053: MatZeroRowsLocalIS - Zeros all entries (except possibly the main diagonal)
7054: of a set of rows of a matrix; using local numbering of rows.
7056: Collective
7058: Input Parameters:
7059: + mat - the matrix
7060: . is - index set of rows to remove
7061: . diag - value put in all diagonals of eliminated rows
7062: . x - optional vector of solutions for zeroed rows (other entries in vector are not used)
7063: - b - optional vector of right-hand side, that will be adjusted by provided solution
7065: Level: intermediate
7067: Notes:
7068: Before calling `MatZeroRowsLocalIS()`, the user must first set the
7069: local-to-global mapping by calling `MatSetLocalToGlobalMapping()`, this is often already set for matrices obtained with `DMCreateMatrix()`.
7071: See `MatZeroRows()` for details on how this routine operates.
7073: .seealso: [](ch_matrices), `Mat`, `MatZeroRowsIS()`, `MatZeroRowsColumns()`, `MatZeroRows()`, `MatZeroRowsStencil()`, `MatZeroEntries()`, `MatZeroRowsLocal()`, `MatSetOption()`,
7074: `MatZeroRowsColumnsLocal()`, `MatZeroRowsColumnsLocalIS()`, `MatZeroRowsColumnsIS()`, `MatZeroRowsColumnsStencil()`
7075: @*/
7076: PetscErrorCode MatZeroRowsLocalIS(Mat mat, IS is, PetscScalar diag, Vec x, Vec b)
7077: {
7078: PetscInt numRows;
7079: const PetscInt *rows;
7081: PetscFunctionBegin;
7085: PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
7086: PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
7087: MatCheckPreallocated(mat, 1);
7089: PetscCall(ISGetLocalSize(is, &numRows));
7090: PetscCall(ISGetIndices(is, &rows));
7091: PetscCall(MatZeroRowsLocal(mat, numRows, rows, diag, x, b));
7092: PetscCall(ISRestoreIndices(is, &rows));
7093: PetscFunctionReturn(PETSC_SUCCESS);
7094: }
7096: /*@
7097: MatZeroRowsColumnsLocal - Zeros all entries (except possibly the main diagonal)
7098: of a set of rows and columns of a matrix; using local numbering of rows.
7100: Collective
7102: Input Parameters:
7103: + mat - the matrix
7104: . numRows - the number of rows to remove
7105: . rows - the global row indices
7106: . diag - value put in all diagonals of eliminated rows
7107: . x - optional vector of solutions for zeroed rows (other entries in vector are not used)
7108: - b - optional vector of right-hand side, that will be adjusted by provided solution
7110: Level: intermediate
7112: Notes:
7113: Before calling `MatZeroRowsColumnsLocal()`, the user must first set the
7114: local-to-global mapping by calling `MatSetLocalToGlobalMapping()`, this is often already set for matrices obtained with `DMCreateMatrix()`.
7116: See `MatZeroRowsColumns()` for details on how this routine operates.
7118: .seealso: [](ch_matrices), `Mat`, `MatZeroRowsIS()`, `MatZeroRowsColumns()`, `MatZeroRowsLocalIS()`, `MatZeroRowsStencil()`, `MatZeroEntries()`, `MatZeroRowsLocal()`, `MatSetOption()`,
7119: `MatZeroRows()`, `MatZeroRowsColumnsLocalIS()`, `MatZeroRowsColumnsIS()`, `MatZeroRowsColumnsStencil()`
7120: @*/
7121: PetscErrorCode MatZeroRowsColumnsLocal(Mat mat, PetscInt numRows, const PetscInt rows[], PetscScalar diag, Vec x, Vec b)
7122: {
7123: PetscFunctionBegin;
7126: if (numRows) PetscAssertPointer(rows, 3);
7127: PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
7128: PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
7129: MatCheckPreallocated(mat, 1);
7131: if (mat->ops->zerorowscolumnslocal) {
7132: PetscUseTypeMethod(mat, zerorowscolumnslocal, numRows, rows, diag, x, b);
7133: } else {
7134: IS is, newis;
7135: PetscInt *newRows, nl = 0;
7137: PetscCheck(mat->rmap->mapping, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Need to provide local to global mapping to matrix first");
7138: PetscCall(ISCreateGeneral(PETSC_COMM_SELF, numRows, rows, PETSC_USE_POINTER, &is));
7139: PetscCall(ISLocalToGlobalMappingApplyIS(mat->rmap->mapping, is, &newis));
7140: PetscCall(ISGetIndices(newis, (const PetscInt **)&newRows));
7141: for (PetscInt i = 0; i < numRows; i++)
7142: if (newRows[i] > -1) newRows[nl++] = newRows[i];
7143: PetscUseTypeMethod(mat, zerorowscolumns, nl, newRows, diag, x, b);
7144: PetscCall(ISRestoreIndices(newis, (const PetscInt **)&newRows));
7145: PetscCall(ISDestroy(&newis));
7146: PetscCall(ISDestroy(&is));
7147: }
7148: PetscCall(PetscObjectStateIncrease((PetscObject)mat));
7149: PetscFunctionReturn(PETSC_SUCCESS);
7150: }
7152: /*@
7153: MatZeroRowsColumnsLocalIS - Zeros all entries (except possibly the main diagonal)
7154: of a set of rows and columns of a matrix; using local numbering of rows.
7156: Collective
7158: Input Parameters:
7159: + mat - the matrix
7160: . is - index set of rows to remove
7161: . diag - value put in all diagonals of eliminated rows
7162: . x - optional vector of solutions for zeroed rows (other entries in vector are not used)
7163: - b - optional vector of right-hand side, that will be adjusted by provided solution
7165: Level: intermediate
7167: Notes:
7168: Before calling `MatZeroRowsColumnsLocalIS()`, the user must first set the
7169: local-to-global mapping by calling `MatSetLocalToGlobalMapping()`, this is often already set for matrices obtained with `DMCreateMatrix()`.
7171: See `MatZeroRowsColumns()` for details on how this routine operates.
7173: .seealso: [](ch_matrices), `Mat`, `MatZeroRowsIS()`, `MatZeroRowsColumns()`, `MatZeroRowsLocalIS()`, `MatZeroRowsStencil()`, `MatZeroEntries()`, `MatZeroRowsLocal()`, `MatSetOption()`,
7174: `MatZeroRowsColumnsLocal()`, `MatZeroRows()`, `MatZeroRowsColumnsIS()`, `MatZeroRowsColumnsStencil()`
7175: @*/
7176: PetscErrorCode MatZeroRowsColumnsLocalIS(Mat mat, IS is, PetscScalar diag, Vec x, Vec b)
7177: {
7178: PetscInt numRows;
7179: const PetscInt *rows;
7181: PetscFunctionBegin;
7185: PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
7186: PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
7187: MatCheckPreallocated(mat, 1);
7189: PetscCall(ISGetLocalSize(is, &numRows));
7190: PetscCall(ISGetIndices(is, &rows));
7191: PetscCall(MatZeroRowsColumnsLocal(mat, numRows, rows, diag, x, b));
7192: PetscCall(ISRestoreIndices(is, &rows));
7193: PetscFunctionReturn(PETSC_SUCCESS);
7194: }
7196: /*@
7197: MatGetSize - Returns the numbers of rows and columns in a matrix.
7199: Not Collective
7201: Input Parameter:
7202: . mat - the matrix
7204: Output Parameters:
7205: + m - the number of global rows
7206: - n - the number of global columns
7208: Level: beginner
7210: Note:
7211: Both output parameters can be `NULL` on input.
7213: .seealso: [](ch_matrices), `Mat`, `MatSetSizes()`, `MatGetLocalSize()`
7214: @*/
7215: PetscErrorCode MatGetSize(Mat mat, PetscInt *m, PetscInt *n)
7216: {
7217: PetscFunctionBegin;
7219: if (m) *m = mat->rmap->N;
7220: if (n) *n = mat->cmap->N;
7221: PetscFunctionReturn(PETSC_SUCCESS);
7222: }
7224: /*@
7225: MatGetLocalSize - For most matrix formats, excluding `MATELEMENTAL` and `MATSCALAPACK`, Returns the number of local rows and local columns
7226: of a matrix. For all matrices this is the local size of the left and right vectors as returned by `MatCreateVecs()`.
7228: Not Collective
7230: Input Parameter:
7231: . mat - the matrix
7233: Output Parameters:
7234: + m - the number of local rows, use `NULL` to not obtain this value
7235: - n - the number of local columns, use `NULL` to not obtain this value
7237: Level: beginner
7239: .seealso: [](ch_matrices), `Mat`, `MatSetSizes()`, `MatGetSize()`
7240: @*/
7241: PetscErrorCode MatGetLocalSize(Mat mat, PetscInt *m, PetscInt *n)
7242: {
7243: PetscFunctionBegin;
7245: if (m) PetscAssertPointer(m, 2);
7246: if (n) PetscAssertPointer(n, 3);
7247: if (m) *m = mat->rmap->n;
7248: if (n) *n = mat->cmap->n;
7249: PetscFunctionReturn(PETSC_SUCCESS);
7250: }
7252: /*@
7253: MatGetOwnershipRangeColumn - Returns the range of matrix columns associated with rows of a
7254: vector one multiplies this matrix by that are owned by this processor.
7256: Not Collective, unless matrix has not been allocated, then collective
7258: Input Parameter:
7259: . mat - the matrix
7261: Output Parameters:
7262: + m - the global index of the first local column, use `NULL` to not obtain this value
7263: - n - one more than the global index of the last local column, use `NULL` to not obtain this value
7265: Level: developer
7267: Notes:
7268: If the `Mat` was obtained from a `DM` with `DMCreateMatrix()`, then the range values are determined by the specific `DM`.
7270: If the `Mat` was created directly the range values are determined by the local size passed to `MatSetSizes()` or `MatCreateAIJ()`.
7271: If `PETSC_DECIDE` was passed as the local size, then the vector uses default values for the range using `PetscSplitOwnership()`.
7273: For certain `DM`, such as `DMDA`, it is better to use `DM` specific routines, such as `DMDAGetGhostCorners()`, to determine
7274: the local values in the matrix.
7276: Returns the columns of the "diagonal block" for most sparse matrix formats. See [Matrix
7277: Layouts](sec_matlayout) for details on matrix layouts.
7279: .seealso: [](ch_matrices), `Mat`, `MatGetOwnershipRange()`, `MatGetOwnershipRanges()`, `MatGetOwnershipRangesColumn()`, `PetscLayout`,
7280: `MatSetSizes()`, `MatCreateAIJ()`, `DMDAGetGhostCorners()`, `DM`
7281: @*/
7282: PetscErrorCode MatGetOwnershipRangeColumn(Mat mat, PetscInt *m, PetscInt *n)
7283: {
7284: PetscFunctionBegin;
7287: if (m) PetscAssertPointer(m, 2);
7288: if (n) PetscAssertPointer(n, 3);
7289: MatCheckPreallocated(mat, 1);
7290: if (m) *m = mat->cmap->rstart;
7291: if (n) *n = mat->cmap->rend;
7292: PetscFunctionReturn(PETSC_SUCCESS);
7293: }
7295: /*@
7296: MatGetOwnershipRange - For matrices that own values by row, excludes `MATELEMENTAL` and `MATSCALAPACK`, returns the range of matrix rows owned by
7297: this MPI process.
7299: Not Collective
7301: Input Parameter:
7302: . mat - the matrix
7304: Output Parameters:
7305: + m - the global index of the first local row, use `NULL` to not obtain this value
7306: - n - one more than the global index of the last local row, use `NULL` to not obtain this value
7308: Level: beginner
7310: Notes:
7311: If the `Mat` was obtained from a `DM` with `DMCreateMatrix()`, then the range values are determined by the specific `DM`.
7313: If the `Mat` was created directly the range values are determined by the local size passed to `MatSetSizes()` or `MatCreateAIJ()`.
7314: If `PETSC_DECIDE` was passed as the local size, then the vector uses default values for the range using `PetscSplitOwnership()`.
7316: For certain `DM`, such as `DMDA`, it is better to use `DM` specific routines, such as `DMDAGetGhostCorners()`, to determine
7317: the local values in the matrix.
7319: The high argument is one more than the last element stored locally.
7321: For all matrices it returns the range of matrix rows associated with rows of a vector that
7322: would contain the result of a matrix vector product with this matrix. See [Matrix
7323: Layouts](sec_matlayout) for details on matrix layouts.
7325: .seealso: [](ch_matrices), `Mat`, `MatGetOwnershipRanges()`, `MatGetOwnershipRangeColumn()`, `MatGetOwnershipRangesColumn()`, `PetscSplitOwnership()`,
7326: `PetscSplitOwnershipBlock()`, `PetscLayout`, `MatSetSizes()`, `MatCreateAIJ()`, `DMDAGetGhostCorners()`, `DM`
7327: @*/
7328: PetscErrorCode MatGetOwnershipRange(Mat mat, PetscInt *m, PetscInt *n)
7329: {
7330: PetscFunctionBegin;
7333: if (m) PetscAssertPointer(m, 2);
7334: if (n) PetscAssertPointer(n, 3);
7335: MatCheckPreallocated(mat, 1);
7336: if (m) *m = mat->rmap->rstart;
7337: if (n) *n = mat->rmap->rend;
7338: PetscFunctionReturn(PETSC_SUCCESS);
7339: }
7341: /*@C
7342: MatGetOwnershipRanges - For matrices that own values by row, excludes `MATELEMENTAL` and
7343: `MATSCALAPACK`, returns the range of matrix rows owned by each process.
7345: Not Collective, unless matrix has not been allocated
7347: Input Parameter:
7348: . mat - the matrix
7350: Output Parameter:
7351: . ranges - start of each processors portion plus one more than the total length at the end, of length `size` + 1
7352: where `size` is the number of MPI processes used by `mat`
7354: Level: beginner
7356: Notes:
7357: If the `Mat` was obtained from a `DM` with `DMCreateMatrix()`, then the range values are determined by the specific `DM`.
7359: If the `Mat` was created directly the range values are determined by the local size passed to `MatSetSizes()` or `MatCreateAIJ()`.
7360: If `PETSC_DECIDE` was passed as the local size, then the vector uses default values for the range using `PetscSplitOwnership()`.
7362: For certain `DM`, such as `DMDA`, it is better to use `DM` specific routines, such as `DMDAGetGhostCorners()`, to determine
7363: the local values in the matrix.
7365: For all matrices it returns the ranges of matrix rows associated with rows of a vector that
7366: would contain the result of a matrix vector product with this matrix. See [Matrix
7367: Layouts](sec_matlayout) for details on matrix layouts.
7369: .seealso: [](ch_matrices), `Mat`, `MatGetOwnershipRange()`, `MatGetOwnershipRangeColumn()`, `MatGetOwnershipRangesColumn()`, `PetscLayout`,
7370: `PetscSplitOwnership()`, `PetscSplitOwnershipBlock()`, `MatSetSizes()`, `MatCreateAIJ()`,
7371: `DMDAGetGhostCorners()`, `DM`
7372: @*/
7373: PetscErrorCode MatGetOwnershipRanges(Mat mat, const PetscInt *ranges[])
7374: {
7375: PetscFunctionBegin;
7378: MatCheckPreallocated(mat, 1);
7379: PetscCall(PetscLayoutGetRanges(mat->rmap, ranges));
7380: PetscFunctionReturn(PETSC_SUCCESS);
7381: }
7383: /*@C
7384: MatGetOwnershipRangesColumn - Returns the ranges of matrix columns associated with rows of a
7385: vector one multiplies this vector by that are owned by each processor.
7387: Not Collective, unless matrix has not been allocated
7389: Input Parameter:
7390: . mat - the matrix
7392: Output Parameter:
7393: . ranges - start of each processors portion plus one more than the total length at the end
7395: Level: beginner
7397: Notes:
7398: If the `Mat` was obtained from a `DM` with `DMCreateMatrix()`, then the range values are determined by the specific `DM`.
7400: If the `Mat` was created directly the range values are determined by the local size passed to `MatSetSizes()` or `MatCreateAIJ()`.
7401: If `PETSC_DECIDE` was passed as the local size, then the vector uses default values for the range using `PetscSplitOwnership()`.
7403: For certain `DM`, such as `DMDA`, it is better to use `DM` specific routines, such as `DMDAGetGhostCorners()`, to determine
7404: the local values in the matrix.
7406: Returns the columns of the "diagonal blocks", for most sparse matrix formats. See [Matrix
7407: Layouts](sec_matlayout) for details on matrix layouts.
7409: .seealso: [](ch_matrices), `Mat`, `MatGetOwnershipRange()`, `MatGetOwnershipRangeColumn()`, `MatGetOwnershipRanges()`,
7410: `PetscSplitOwnership()`, `PetscSplitOwnershipBlock()`, `PetscLayout`, `MatSetSizes()`, `MatCreateAIJ()`,
7411: `DMDAGetGhostCorners()`, `DM`
7412: @*/
7413: PetscErrorCode MatGetOwnershipRangesColumn(Mat mat, const PetscInt *ranges[])
7414: {
7415: PetscFunctionBegin;
7418: MatCheckPreallocated(mat, 1);
7419: PetscCall(PetscLayoutGetRanges(mat->cmap, ranges));
7420: PetscFunctionReturn(PETSC_SUCCESS);
7421: }
7423: /*@
7424: MatGetOwnershipIS - Get row and column ownership of a matrices' values as index sets.
7426: Not Collective
7428: Input Parameter:
7429: . A - matrix
7431: Output Parameters:
7432: + rows - rows in which this process owns elements, , use `NULL` to not obtain this value
7433: - cols - columns in which this process owns elements, use `NULL` to not obtain this value
7435: Level: intermediate
7437: Note:
7438: You should call `ISDestroy()` on the returned `IS`
7440: For most matrices, excluding `MATELEMENTAL` and `MATSCALAPACK`, this corresponds to values
7441: returned by `MatGetOwnershipRange()`, `MatGetOwnershipRangeColumn()`. For `MATELEMENTAL` and
7442: `MATSCALAPACK` the ownership is more complicated. See [Matrix Layouts](sec_matlayout) for
7443: details on matrix layouts.
7445: .seealso: [](ch_matrices), `IS`, `Mat`, `MatGetOwnershipRanges()`, `MatSetValues()`, `MATELEMENTAL`, `MATSCALAPACK`
7446: @*/
7447: PetscErrorCode MatGetOwnershipIS(Mat A, IS *rows, IS *cols)
7448: {
7449: PetscErrorCode (*f)(Mat, IS *, IS *);
7451: PetscFunctionBegin;
7454: MatCheckPreallocated(A, 1);
7455: PetscCall(PetscObjectQueryFunction((PetscObject)A, "MatGetOwnershipIS_C", &f));
7456: if (f) {
7457: PetscCall((*f)(A, rows, cols));
7458: } else { /* Create a standard row-based partition, each process is responsible for ALL columns in their row block */
7459: if (rows) PetscCall(ISCreateStride(PETSC_COMM_SELF, A->rmap->n, A->rmap->rstart, 1, rows));
7460: if (cols) PetscCall(ISCreateStride(PETSC_COMM_SELF, A->cmap->N, 0, 1, cols));
7461: }
7462: PetscFunctionReturn(PETSC_SUCCESS);
7463: }
7465: /*@
7466: MatILUFactorSymbolic - Performs symbolic ILU factorization of a matrix obtained with `MatGetFactor()`
7467: Uses levels of fill only, not drop tolerance. Use `MatLUFactorNumeric()`
7468: to complete the factorization.
7470: Collective
7472: Input Parameters:
7473: + fact - the factorized matrix obtained with `MatGetFactor()`
7474: . mat - the matrix
7475: . row - row permutation
7476: . col - column permutation
7477: - info - structure containing
7478: .vb
7479: levels - number of levels of fill.
7480: expected fill - as ratio of original fill.
7481: 1 or 0 - indicating force fill on diagonal (improves robustness for matrices
7482: missing diagonal entries)
7483: .ve
7485: Level: developer
7487: Notes:
7488: See [Matrix Factorization](sec_matfactor) for additional information.
7490: Most users should employ the `KSP` interface for linear solvers
7491: instead of working directly with matrix algebra routines such as this.
7492: See, e.g., `KSPCreate()`.
7494: Uses the definition of level of fill as in Y. Saad, {cite}`saad2003`
7496: Fortran Note:
7497: A valid (non-null) `info` argument must be provided
7499: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatGetFactor()`, `MatLUFactorSymbolic()`, `MatLUFactorNumeric()`, `MatCholeskyFactor()`,
7500: `MatGetOrdering()`, `MatFactorInfo`
7501: @*/
7502: PetscErrorCode MatILUFactorSymbolic(Mat fact, Mat mat, IS row, IS col, const MatFactorInfo *info)
7503: {
7504: PetscFunctionBegin;
7509: PetscAssertPointer(info, 5);
7510: PetscAssertPointer(fact, 1);
7511: PetscCheck(info->levels >= 0, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_OUTOFRANGE, "Levels of fill negative %" PetscInt_FMT, (PetscInt)info->levels);
7512: PetscCheck(info->fill >= 1.0, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_OUTOFRANGE, "Expected fill less than 1.0 %g", (double)info->fill);
7513: PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
7514: PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
7515: MatCheckPreallocated(mat, 2);
7517: if (!fact->trivialsymbolic) PetscCall(PetscLogEventBegin(MAT_ILUFactorSymbolic, mat, row, col, 0));
7518: PetscUseTypeMethod(fact, ilufactorsymbolic, mat, row, col, info);
7519: if (!fact->trivialsymbolic) PetscCall(PetscLogEventEnd(MAT_ILUFactorSymbolic, mat, row, col, 0));
7520: PetscFunctionReturn(PETSC_SUCCESS);
7521: }
7523: /*@
7524: MatICCFactorSymbolic - Performs symbolic incomplete
7525: Cholesky factorization for a symmetric matrix. Use
7526: `MatCholeskyFactorNumeric()` to complete the factorization.
7528: Collective
7530: Input Parameters:
7531: + fact - the factorized matrix obtained with `MatGetFactor()`
7532: . mat - the matrix to be factored
7533: . perm - row and column permutation
7534: - info - structure containing
7535: .vb
7536: levels - number of levels of fill.
7537: expected fill - as ratio of original fill.
7538: .ve
7540: Level: developer
7542: Notes:
7543: Most users should employ the `KSP` interface for linear solvers
7544: instead of working directly with matrix algebra routines such as this.
7545: See, e.g., `KSPCreate()`.
7547: This uses the definition of level of fill as in Y. Saad {cite}`saad2003`
7549: Fortran Note:
7550: A valid (non-null) `info` argument must be provided
7552: .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatCholeskyFactorNumeric()`, `MatCholeskyFactor()`, `MatFactorInfo`
7553: @*/
7554: PetscErrorCode MatICCFactorSymbolic(Mat fact, Mat mat, IS perm, const MatFactorInfo *info)
7555: {
7556: PetscFunctionBegin;
7560: PetscAssertPointer(info, 4);
7561: PetscAssertPointer(fact, 1);
7562: PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
7563: PetscCheck(info->levels >= 0, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_OUTOFRANGE, "Levels negative %" PetscInt_FMT, (PetscInt)info->levels);
7564: PetscCheck(info->fill >= 1.0, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_OUTOFRANGE, "Expected fill less than 1.0 %g", (double)info->fill);
7565: PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
7566: MatCheckPreallocated(mat, 2);
7568: if (!fact->trivialsymbolic) PetscCall(PetscLogEventBegin(MAT_ICCFactorSymbolic, mat, perm, 0, 0));
7569: PetscUseTypeMethod(fact, iccfactorsymbolic, mat, perm, info);
7570: if (!fact->trivialsymbolic) PetscCall(PetscLogEventEnd(MAT_ICCFactorSymbolic, mat, perm, 0, 0));
7571: PetscFunctionReturn(PETSC_SUCCESS);
7572: }
7574: /*@C
7575: MatCreateSubMatrices - Extracts several submatrices from a matrix. If submat
7576: points to an array of valid matrices, they may be reused to store the new
7577: submatrices.
7579: Collective
7581: Input Parameters:
7582: + mat - the matrix
7583: . n - the number of submatrixes to be extracted (on this processor, may be zero)
7584: . irow - index set of rows to extract
7585: . icol - index set of columns to extract
7586: - scall - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`
7588: Output Parameter:
7589: . submat - the array of submatrices
7591: Level: advanced
7593: Notes:
7594: `MatCreateSubMatrices()` can extract ONLY sequential submatrices
7595: (from both sequential and parallel matrices). Use `MatCreateSubMatrix()`
7596: to extract a parallel submatrix.
7598: Some matrix types place restrictions on the row and column
7599: indices, such as that they be sorted or that they be equal to each other.
7601: The index sets may not have duplicate entries.
7603: When extracting submatrices from a parallel matrix, each processor can
7604: form a different submatrix by setting the rows and columns of its
7605: individual index sets according to the local submatrix desired.
7607: When finished using the submatrices, the user should destroy
7608: them with `MatDestroySubMatrices()`.
7610: `MAT_REUSE_MATRIX` can only be used when the nonzero structure of the
7611: original matrix has not changed from that last call to `MatCreateSubMatrices()`.
7613: This routine creates the matrices in submat; you should NOT create them before
7614: calling it. It also allocates the array of matrix pointers submat.
7616: For `MATBAIJ` matrices the index sets must respect the block structure, that is if they
7617: request one row/column in a block, they must request all rows/columns that are in
7618: that block. For example, if the block size is 2 you cannot request just row 0 and
7619: column 0.
7621: Fortran Note:
7622: .vb
7623: Mat, pointer :: submat(:)
7624: .ve
7626: .seealso: [](ch_matrices), `Mat`, `MatDestroySubMatrices()`, `MatCreateSubMatrix()`, `MatGetRow()`, `MatGetDiagonal()`, `MatReuse`
7627: @*/
7628: PetscErrorCode MatCreateSubMatrices(Mat mat, PetscInt n, const IS irow[], const IS icol[], MatReuse scall, Mat *submat[])
7629: {
7630: PetscInt i;
7631: PetscBool eq;
7633: PetscFunctionBegin;
7636: if (n) {
7637: PetscAssertPointer(irow, 3);
7639: PetscAssertPointer(icol, 4);
7641: }
7642: PetscAssertPointer(submat, 6);
7643: if (n && scall == MAT_REUSE_MATRIX) {
7644: PetscAssertPointer(*submat, 6);
7646: }
7647: PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
7648: PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
7649: MatCheckPreallocated(mat, 1);
7650: PetscCall(PetscLogEventBegin(MAT_CreateSubMats, mat, 0, 0, 0));
7651: PetscUseTypeMethod(mat, createsubmatrices, n, irow, icol, scall, submat);
7652: PetscCall(PetscLogEventEnd(MAT_CreateSubMats, mat, 0, 0, 0));
7653: for (i = 0; i < n; i++) {
7654: (*submat)[i]->factortype = MAT_FACTOR_NONE; /* in case in place factorization was previously done on submatrix */
7655: PetscCall(ISEqualUnsorted(irow[i], icol[i], &eq));
7656: if (eq) PetscCall(MatPropagateSymmetryOptions(mat, (*submat)[i]));
7657: #if defined(PETSC_HAVE_VIENNACL) || defined(PETSC_HAVE_CUDA) || defined(PETSC_HAVE_HIP)
7658: if (mat->boundtocpu && mat->bindingpropagates) {
7659: PetscCall(MatBindToCPU((*submat)[i], PETSC_TRUE));
7660: PetscCall(MatSetBindingPropagates((*submat)[i], PETSC_TRUE));
7661: }
7662: #endif
7663: }
7664: PetscFunctionReturn(PETSC_SUCCESS);
7665: }
7667: /*@C
7668: MatCreateSubMatricesMPI - Extracts MPI submatrices across a sub communicator of `mat` (by pairs of `IS` that may live on subcomms).
7670: Collective
7672: Input Parameters:
7673: + mat - the matrix
7674: . n - the number of submatrixes to be extracted
7675: . irow - index set of rows to extract
7676: . icol - index set of columns to extract
7677: - scall - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`
7679: Output Parameter:
7680: . submat - the array of submatrices
7682: Level: advanced
7684: Note:
7685: This is used by `PCGASM`
7687: .seealso: [](ch_matrices), `Mat`, `PCGASM`, `MatCreateSubMatrices()`, `MatCreateSubMatrix()`, `MatGetRow()`, `MatGetDiagonal()`, `MatReuse`
7688: @*/
7689: PetscErrorCode MatCreateSubMatricesMPI(Mat mat, PetscInt n, const IS irow[], const IS icol[], MatReuse scall, Mat *submat[])
7690: {
7691: PetscInt i;
7692: PetscBool eq;
7694: PetscFunctionBegin;
7697: if (n) {
7698: PetscAssertPointer(irow, 3);
7700: PetscAssertPointer(icol, 4);
7702: }
7703: PetscAssertPointer(submat, 6);
7704: if (n && scall == MAT_REUSE_MATRIX) {
7705: PetscAssertPointer(*submat, 6);
7707: }
7708: PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
7709: PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
7710: MatCheckPreallocated(mat, 1);
7712: PetscCall(PetscLogEventBegin(MAT_CreateSubMats, mat, 0, 0, 0));
7713: PetscUseTypeMethod(mat, createsubmatricesmpi, n, irow, icol, scall, submat);
7714: PetscCall(PetscLogEventEnd(MAT_CreateSubMats, mat, 0, 0, 0));
7715: for (i = 0; i < n; i++) {
7716: PetscCall(ISEqualUnsorted(irow[i], icol[i], &eq));
7717: if (eq) PetscCall(MatPropagateSymmetryOptions(mat, (*submat)[i]));
7718: }
7719: PetscFunctionReturn(PETSC_SUCCESS);
7720: }
7722: /*@C
7723: MatDestroyMatrices - Destroys an array of matrices
7725: Collective
7727: Input Parameters:
7728: + n - the number of local matrices
7729: - mat - the matrices (this is a pointer to the array of matrices)
7731: Level: advanced
7733: Notes:
7734: Frees not only the matrices, but also the array that contains the matrices
7736: For matrices obtained with `MatCreateSubMatrices()` use `MatDestroySubMatrices()`
7738: .seealso: [](ch_matrices), `Mat`, `MatCreateSubMatrices()`, `MatDestroySubMatrices()`
7739: @*/
7740: PetscErrorCode MatDestroyMatrices(PetscInt n, Mat *mat[])
7741: {
7742: PetscInt i;
7744: PetscFunctionBegin;
7745: if (!*mat) PetscFunctionReturn(PETSC_SUCCESS);
7746: PetscCheck(n >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Trying to destroy negative number of matrices %" PetscInt_FMT, n);
7747: PetscAssertPointer(mat, 2);
7749: for (i = 0; i < n; i++) PetscCall(MatDestroy(&(*mat)[i]));
7751: /* memory is allocated even if n = 0 */
7752: PetscCall(PetscFree(*mat));
7753: PetscFunctionReturn(PETSC_SUCCESS);
7754: }
7756: /*@C
7757: MatDestroySubMatrices - Destroys a set of matrices obtained with `MatCreateSubMatrices()`.
7759: Collective
7761: Input Parameters:
7762: + n - the number of local matrices
7763: - mat - the matrices (this is a pointer to the array of matrices, to match the calling sequence of `MatCreateSubMatrices()`)
7765: Level: advanced
7767: Note:
7768: Frees not only the matrices, but also the array that contains the matrices
7770: .seealso: [](ch_matrices), `Mat`, `MatCreateSubMatrices()`, `MatDestroyMatrices()`
7771: @*/
7772: PetscErrorCode MatDestroySubMatrices(PetscInt n, Mat *mat[])
7773: {
7774: Mat mat0;
7776: PetscFunctionBegin;
7777: if (!*mat) PetscFunctionReturn(PETSC_SUCCESS);
7778: /* mat[] is an array of length n+1, see MatCreateSubMatrices_xxx() */
7779: PetscCheck(n >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Trying to destroy negative number of matrices %" PetscInt_FMT, n);
7780: PetscAssertPointer(mat, 2);
7782: mat0 = (*mat)[0];
7783: if (mat0 && mat0->ops->destroysubmatrices) {
7784: PetscCall((*mat0->ops->destroysubmatrices)(n, mat));
7785: } else {
7786: PetscCall(MatDestroyMatrices(n, mat));
7787: }
7788: PetscFunctionReturn(PETSC_SUCCESS);
7789: }
7791: /*@
7792: MatGetSeqNonzeroStructure - Extracts the nonzero structure from a matrix and stores it, in its entirety, on each process
7794: Collective
7796: Input Parameter:
7797: . mat - the matrix
7799: Output Parameter:
7800: . matstruct - the sequential matrix with the nonzero structure of `mat`
7802: Level: developer
7804: .seealso: [](ch_matrices), `Mat`, `MatDestroySeqNonzeroStructure()`, `MatCreateSubMatrices()`, `MatDestroyMatrices()`
7805: @*/
7806: PetscErrorCode MatGetSeqNonzeroStructure(Mat mat, Mat *matstruct)
7807: {
7808: PetscFunctionBegin;
7810: PetscAssertPointer(matstruct, 2);
7813: PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
7814: MatCheckPreallocated(mat, 1);
7816: PetscCall(PetscLogEventBegin(MAT_GetSeqNonzeroStructure, mat, 0, 0, 0));
7817: PetscUseTypeMethod(mat, getseqnonzerostructure, matstruct);
7818: PetscCall(PetscLogEventEnd(MAT_GetSeqNonzeroStructure, mat, 0, 0, 0));
7819: PetscFunctionReturn(PETSC_SUCCESS);
7820: }
7822: /*@C
7823: MatDestroySeqNonzeroStructure - Destroys matrix obtained with `MatGetSeqNonzeroStructure()`.
7825: Collective
7827: Input Parameter:
7828: . mat - the matrix
7830: Level: advanced
7832: Note:
7833: This is not needed, one can just call `MatDestroy()`
7835: .seealso: [](ch_matrices), `Mat`, `MatGetSeqNonzeroStructure()`
7836: @*/
7837: PetscErrorCode MatDestroySeqNonzeroStructure(Mat *mat)
7838: {
7839: PetscFunctionBegin;
7840: PetscAssertPointer(mat, 1);
7841: PetscCall(MatDestroy(mat));
7842: PetscFunctionReturn(PETSC_SUCCESS);
7843: }
7845: /*@
7846: MatIncreaseOverlap - Given a set of submatrices indicated by index sets,
7847: replaces the index sets by larger ones that represent submatrices with
7848: additional overlap.
7850: Collective
7852: Input Parameters:
7853: + mat - the matrix
7854: . n - the number of index sets
7855: . is - the array of index sets (these index sets will changed during the call)
7856: - ov - the additional overlap requested
7858: Options Database Key:
7859: . -mat_increase_overlap_scalable - use a scalable algorithm to compute the overlap (supported by MPIAIJ matrix)
7861: Level: developer
7863: Note:
7864: The computed overlap preserves the matrix block sizes when the blocks are square.
7865: That is: if a matrix nonzero for a given block would increase the overlap all columns associated with
7866: that block are included in the overlap regardless of whether each specific column would increase the overlap.
7868: .seealso: [](ch_matrices), `Mat`, `PCASM`, `MatSetBlockSize()`, `MatIncreaseOverlapSplit()`, `MatCreateSubMatrices()`
7869: @*/
7870: PetscErrorCode MatIncreaseOverlap(Mat mat, PetscInt n, IS is[], PetscInt ov)
7871: {
7872: PetscInt i, bs, cbs;
7874: PetscFunctionBegin;
7878: PetscCheck(n >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Must have one or more domains, you have %" PetscInt_FMT, n);
7879: if (n) {
7880: PetscAssertPointer(is, 3);
7882: }
7883: PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
7884: PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
7885: MatCheckPreallocated(mat, 1);
7887: if (!ov || !n) PetscFunctionReturn(PETSC_SUCCESS);
7888: PetscCall(PetscLogEventBegin(MAT_IncreaseOverlap, mat, 0, 0, 0));
7889: PetscUseTypeMethod(mat, increaseoverlap, n, is, ov);
7890: PetscCall(PetscLogEventEnd(MAT_IncreaseOverlap, mat, 0, 0, 0));
7891: PetscCall(MatGetBlockSizes(mat, &bs, &cbs));
7892: if (bs == cbs) {
7893: for (i = 0; i < n; i++) PetscCall(ISSetBlockSize(is[i], bs));
7894: }
7895: PetscFunctionReturn(PETSC_SUCCESS);
7896: }
7898: PetscErrorCode MatIncreaseOverlapSplit_Single(Mat, IS *, PetscInt);
7900: /*@
7901: MatIncreaseOverlapSplit - Given a set of submatrices indicated by index sets across
7902: a sub communicator, replaces the index sets by larger ones that represent submatrices with
7903: additional overlap.
7905: Collective
7907: Input Parameters:
7908: + mat - the matrix
7909: . n - the number of index sets
7910: . is - the array of index sets (these index sets will changed during the call)
7911: - ov - the additional overlap requested
7913: ` Options Database Key:
7914: . -mat_increase_overlap_scalable - use a scalable algorithm to compute the overlap (supported by MPIAIJ matrix)
7916: Level: developer
7918: .seealso: [](ch_matrices), `Mat`, `MatCreateSubMatrices()`, `MatIncreaseOverlap()`
7919: @*/
7920: PetscErrorCode MatIncreaseOverlapSplit(Mat mat, PetscInt n, IS is[], PetscInt ov)
7921: {
7922: PetscInt i;
7924: PetscFunctionBegin;
7927: PetscCheck(n >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Must have one or more domains, you have %" PetscInt_FMT, n);
7928: if (n) {
7929: PetscAssertPointer(is, 3);
7931: }
7932: PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
7933: PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
7934: MatCheckPreallocated(mat, 1);
7935: if (!ov) PetscFunctionReturn(PETSC_SUCCESS);
7936: PetscCall(PetscLogEventBegin(MAT_IncreaseOverlap, mat, 0, 0, 0));
7937: for (i = 0; i < n; i++) PetscCall(MatIncreaseOverlapSplit_Single(mat, &is[i], ov));
7938: PetscCall(PetscLogEventEnd(MAT_IncreaseOverlap, mat, 0, 0, 0));
7939: PetscFunctionReturn(PETSC_SUCCESS);
7940: }
7942: /*@
7943: MatGetBlockSize - Returns the matrix block size.
7945: Not Collective
7947: Input Parameter:
7948: . mat - the matrix
7950: Output Parameter:
7951: . bs - block size
7953: Level: intermediate
7955: Notes:
7956: Block row formats are `MATBAIJ` and `MATSBAIJ` ALWAYS have square block storage in the matrix.
7958: If the block size has not been set yet this routine returns 1.
7960: .seealso: [](ch_matrices), `Mat`, `MATBAIJ`, `MATSBAIJ`, `MatCreateSeqBAIJ()`, `MatCreateBAIJ()`, `MatGetBlockSizes()`
7961: @*/
7962: PetscErrorCode MatGetBlockSize(Mat mat, PetscInt *bs)
7963: {
7964: PetscFunctionBegin;
7966: PetscAssertPointer(bs, 2);
7967: *bs = mat->rmap->bs;
7968: PetscFunctionReturn(PETSC_SUCCESS);
7969: }
7971: /*@
7972: MatGetBlockSizes - Returns the matrix block row and column sizes.
7974: Not Collective
7976: Input Parameter:
7977: . mat - the matrix
7979: Output Parameters:
7980: + rbs - row block size
7981: - cbs - column block size
7983: Level: intermediate
7985: Notes:
7986: Block row formats are `MATBAIJ` and `MATSBAIJ` ALWAYS have square block storage in the matrix.
7987: If you pass a different block size for the columns than the rows, the row block size determines the square block storage.
7989: If a block size has not been set yet this routine returns 1.
7991: .seealso: [](ch_matrices), `Mat`, `MATBAIJ`, `MATSBAIJ`, `MatCreateSeqBAIJ()`, `MatCreateBAIJ()`, `MatGetBlockSize()`, `MatSetBlockSize()`, `MatSetBlockSizes()`
7992: @*/
7993: PetscErrorCode MatGetBlockSizes(Mat mat, PetscInt *rbs, PetscInt *cbs)
7994: {
7995: PetscFunctionBegin;
7997: if (rbs) PetscAssertPointer(rbs, 2);
7998: if (cbs) PetscAssertPointer(cbs, 3);
7999: if (rbs) *rbs = mat->rmap->bs;
8000: if (cbs) *cbs = mat->cmap->bs;
8001: PetscFunctionReturn(PETSC_SUCCESS);
8002: }
8004: /*@
8005: MatSetBlockSize - Sets the matrix block size.
8007: Logically Collective
8009: Input Parameters:
8010: + mat - the matrix
8011: - bs - block size
8013: Level: intermediate
8015: Notes:
8016: Block row formats are `MATBAIJ` and `MATSBAIJ` formats ALWAYS have square block storage in the matrix.
8017: This must be called before `MatSetUp()` or MatXXXSetPreallocation() (or will default to 1) and the block size cannot be changed later.
8019: For `MATAIJ` matrix format, this function can be called at a later stage, provided that the specified block size
8020: is compatible with the matrix local sizes.
8022: .seealso: [](ch_matrices), `Mat`, `MATBAIJ`, `MATSBAIJ`, `MATAIJ`, `MatCreateSeqBAIJ()`, `MatCreateBAIJ()`, `MatGetBlockSize()`, `MatSetBlockSizes()`, `MatGetBlockSizes()`
8023: @*/
8024: PetscErrorCode MatSetBlockSize(Mat mat, PetscInt bs)
8025: {
8026: PetscFunctionBegin;
8029: PetscCall(MatSetBlockSizes(mat, bs, bs));
8030: PetscFunctionReturn(PETSC_SUCCESS);
8031: }
8033: typedef struct {
8034: PetscInt n;
8035: IS *is;
8036: Mat *mat;
8037: PetscObjectState nonzerostate;
8038: Mat C;
8039: } EnvelopeData;
8041: static PetscErrorCode EnvelopeDataDestroy(PetscCtxRt ptr)
8042: {
8043: EnvelopeData *edata = *(EnvelopeData **)ptr;
8045: PetscFunctionBegin;
8046: for (PetscInt i = 0; i < edata->n; i++) PetscCall(ISDestroy(&edata->is[i]));
8047: PetscCall(PetscFree(edata->is));
8048: PetscCall(PetscFree(edata));
8049: PetscFunctionReturn(PETSC_SUCCESS);
8050: }
8052: /*@
8053: MatComputeVariableBlockEnvelope - Given a matrix whose nonzeros are in blocks along the diagonal this computes and stores
8054: the sizes of these blocks in the matrix. An individual block may lie over several processes.
8056: Collective
8058: Input Parameter:
8059: . mat - the matrix
8061: Level: intermediate
8063: Notes:
8064: There can be zeros within the blocks
8066: The blocks can overlap between processes, including laying on more than two processes
8068: .seealso: [](ch_matrices), `Mat`, `MatInvertVariableBlockEnvelope()`, `MatSetVariableBlockSizes()`
8069: @*/
8070: PetscErrorCode MatComputeVariableBlockEnvelope(Mat mat)
8071: {
8072: PetscInt n, *sizes, *starts, i = 0, env = 0, tbs = 0, lblocks = 0, rstart, II, ln = 0, cnt = 0, cstart, cend;
8073: PetscInt *diag, *odiag, sc;
8074: VecScatter scatter;
8075: PetscScalar *seqv;
8076: const PetscScalar *parv;
8077: const PetscInt *ia, *ja;
8078: PetscBool set, flag, done;
8079: Mat AA = mat, A;
8080: MPI_Comm comm;
8081: PetscMPIInt rank, size, tag;
8082: MPI_Status status;
8083: PetscContainer container;
8084: EnvelopeData *edata;
8085: Vec seq, par;
8086: IS isglobal;
8088: PetscFunctionBegin;
8090: PetscCall(MatIsSymmetricKnown(mat, &set, &flag));
8091: if (!set || !flag) {
8092: /* TODO: only needs nonzero structure of transpose */
8093: PetscCall(MatTranspose(mat, MAT_INITIAL_MATRIX, &AA));
8094: PetscCall(MatAXPY(AA, 1.0, mat, DIFFERENT_NONZERO_PATTERN));
8095: }
8096: PetscCall(MatAIJGetLocalMat(AA, &A));
8097: PetscCall(MatGetRowIJ(A, 0, PETSC_FALSE, PETSC_FALSE, &n, &ia, &ja, &done));
8098: PetscCheck(done, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "Unable to get IJ structure from matrix");
8100: PetscCall(MatGetLocalSize(mat, &n, NULL));
8101: PetscCall(PetscObjectGetNewTag((PetscObject)mat, &tag));
8102: PetscCall(PetscObjectGetComm((PetscObject)mat, &comm));
8103: PetscCallMPI(MPI_Comm_size(comm, &size));
8104: PetscCallMPI(MPI_Comm_rank(comm, &rank));
8106: PetscCall(PetscMalloc2(n, &sizes, n, &starts));
8108: if (rank > 0) {
8109: PetscCallMPI(MPI_Recv(&env, 1, MPIU_INT, rank - 1, tag, comm, &status));
8110: PetscCallMPI(MPI_Recv(&tbs, 1, MPIU_INT, rank - 1, tag, comm, &status));
8111: }
8112: PetscCall(MatGetOwnershipRange(mat, &rstart, NULL));
8113: for (i = 0; i < n; i++) {
8114: env = PetscMax(env, ja[ia[i + 1] - 1]);
8115: II = rstart + i;
8116: if (env == II) {
8117: starts[lblocks] = tbs;
8118: sizes[lblocks++] = 1 + II - tbs;
8119: tbs = 1 + II;
8120: }
8121: }
8122: if (rank < size - 1) {
8123: PetscCallMPI(MPI_Send(&env, 1, MPIU_INT, rank + 1, tag, comm));
8124: PetscCallMPI(MPI_Send(&tbs, 1, MPIU_INT, rank + 1, tag, comm));
8125: }
8127: PetscCall(MatRestoreRowIJ(A, 0, PETSC_FALSE, PETSC_FALSE, &n, &ia, &ja, &done));
8128: if (!set || !flag) PetscCall(MatDestroy(&AA));
8129: PetscCall(MatDestroy(&A));
8131: PetscCall(PetscNew(&edata));
8132: PetscCall(MatGetNonzeroState(mat, &edata->nonzerostate));
8133: edata->n = lblocks;
8134: /* create IS needed for extracting blocks from the original matrix */
8135: PetscCall(PetscMalloc1(lblocks, &edata->is));
8136: for (PetscInt i = 0; i < lblocks; i++) PetscCall(ISCreateStride(PETSC_COMM_SELF, sizes[i], starts[i], 1, &edata->is[i]));
8138: /* Create the resulting inverse matrix nonzero structure with preallocation information */
8139: PetscCall(MatCreate(PetscObjectComm((PetscObject)mat), &edata->C));
8140: PetscCall(MatSetSizes(edata->C, mat->rmap->n, mat->cmap->n, mat->rmap->N, mat->cmap->N));
8141: PetscCall(MatSetBlockSizesFromMats(edata->C, mat, mat));
8142: PetscCall(MatSetType(edata->C, MATAIJ));
8144: /* Communicate the start and end of each row, from each block to the correct rank */
8145: /* TODO: Use PetscSF instead of VecScatter */
8146: for (PetscInt i = 0; i < lblocks; i++) ln += sizes[i];
8147: PetscCall(VecCreateSeq(PETSC_COMM_SELF, 2 * ln, &seq));
8148: PetscCall(VecGetArrayWrite(seq, &seqv));
8149: for (PetscInt i = 0; i < lblocks; i++) {
8150: for (PetscInt j = 0; j < sizes[i]; j++) {
8151: seqv[cnt] = starts[i];
8152: seqv[cnt + 1] = starts[i] + sizes[i];
8153: cnt += 2;
8154: }
8155: }
8156: PetscCall(VecRestoreArrayWrite(seq, &seqv));
8157: PetscCallMPI(MPI_Scan(&cnt, &sc, 1, MPIU_INT, MPI_SUM, PetscObjectComm((PetscObject)mat)));
8158: sc -= cnt;
8159: PetscCall(VecCreateMPI(PetscObjectComm((PetscObject)mat), 2 * mat->rmap->n, 2 * mat->rmap->N, &par));
8160: PetscCall(ISCreateStride(PETSC_COMM_SELF, cnt, sc, 1, &isglobal));
8161: PetscCall(VecScatterCreate(seq, NULL, par, isglobal, &scatter));
8162: PetscCall(ISDestroy(&isglobal));
8163: PetscCall(VecScatterBegin(scatter, seq, par, INSERT_VALUES, SCATTER_FORWARD));
8164: PetscCall(VecScatterEnd(scatter, seq, par, INSERT_VALUES, SCATTER_FORWARD));
8165: PetscCall(VecScatterDestroy(&scatter));
8166: PetscCall(VecDestroy(&seq));
8167: PetscCall(MatGetOwnershipRangeColumn(mat, &cstart, &cend));
8168: PetscCall(PetscMalloc2(mat->rmap->n, &diag, mat->rmap->n, &odiag));
8169: PetscCall(VecGetArrayRead(par, &parv));
8170: cnt = 0;
8171: PetscCall(MatGetSize(mat, NULL, &n));
8172: for (PetscInt i = 0; i < mat->rmap->n; i++) {
8173: PetscInt start, end, d = 0, od = 0;
8175: start = (PetscInt)PetscRealPart(parv[cnt]);
8176: end = (PetscInt)PetscRealPart(parv[cnt + 1]);
8177: cnt += 2;
8179: if (start < cstart) {
8180: od += cstart - start + n - cend;
8181: d += cend - cstart;
8182: } else if (start < cend) {
8183: od += n - cend;
8184: d += cend - start;
8185: } else od += n - start;
8186: if (end <= cstart) {
8187: od -= cstart - end + n - cend;
8188: d -= cend - cstart;
8189: } else if (end < cend) {
8190: od -= n - cend;
8191: d -= cend - end;
8192: } else od -= n - end;
8194: odiag[i] = od;
8195: diag[i] = d;
8196: }
8197: PetscCall(VecRestoreArrayRead(par, &parv));
8198: PetscCall(VecDestroy(&par));
8199: PetscCall(MatXAIJSetPreallocation(edata->C, mat->rmap->bs, diag, odiag, NULL, NULL));
8200: PetscCall(PetscFree2(diag, odiag));
8201: PetscCall(PetscFree2(sizes, starts));
8203: PetscCall(PetscContainerCreate(PETSC_COMM_SELF, &container));
8204: PetscCall(PetscContainerSetPointer(container, edata));
8205: PetscCall(PetscContainerSetCtxDestroy(container, EnvelopeDataDestroy));
8206: PetscCall(PetscObjectCompose((PetscObject)mat, "EnvelopeData", (PetscObject)container));
8207: PetscCall(PetscObjectDereference((PetscObject)container));
8208: PetscFunctionReturn(PETSC_SUCCESS);
8209: }
8211: /*@
8212: MatInvertVariableBlockEnvelope - set matrix C to be the inverted block diagonal of matrix A
8214: Collective
8216: Input Parameters:
8217: + A - the matrix
8218: - reuse - indicates if the `C` matrix was obtained from a previous call to this routine
8220: Output Parameter:
8221: . C - matrix with inverted block diagonal of `A`
8223: Level: advanced
8225: Note:
8226: For efficiency the matrix `A` should have all the nonzero entries clustered in smallish blocks along the diagonal.
8228: .seealso: [](ch_matrices), `Mat`, `MatInvertBlockDiagonal()`, `MatComputeBlockDiagonal()`
8229: @*/
8230: PetscErrorCode MatInvertVariableBlockEnvelope(Mat A, MatReuse reuse, Mat *C)
8231: {
8232: PetscContainer container;
8233: EnvelopeData *edata;
8234: PetscObjectState nonzerostate;
8236: PetscFunctionBegin;
8237: PetscCall(PetscObjectQuery((PetscObject)A, "EnvelopeData", (PetscObject *)&container));
8238: if (!container) {
8239: PetscCall(MatComputeVariableBlockEnvelope(A));
8240: PetscCall(PetscObjectQuery((PetscObject)A, "EnvelopeData", (PetscObject *)&container));
8241: }
8242: PetscCall(PetscContainerGetPointer(container, &edata));
8243: PetscCall(MatGetNonzeroState(A, &nonzerostate));
8244: PetscCheck(nonzerostate <= edata->nonzerostate, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "Cannot handle changes to matrix nonzero structure");
8245: PetscCheck(reuse != MAT_REUSE_MATRIX || *C == edata->C, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "C matrix must be the same as previously output");
8247: PetscCall(MatCreateSubMatrices(A, edata->n, edata->is, edata->is, MAT_INITIAL_MATRIX, &edata->mat));
8248: *C = edata->C;
8250: for (PetscInt i = 0; i < edata->n; i++) {
8251: Mat D;
8252: PetscScalar *dvalues;
8254: PetscCall(MatConvert(edata->mat[i], MATSEQDENSE, MAT_INITIAL_MATRIX, &D));
8255: PetscCall(MatSetOption(*C, MAT_ROW_ORIENTED, PETSC_FALSE));
8256: PetscCall(MatSeqDenseInvert(D));
8257: PetscCall(MatDenseGetArray(D, &dvalues));
8258: PetscCall(MatSetValuesIS(*C, edata->is[i], edata->is[i], dvalues, INSERT_VALUES));
8259: PetscCall(MatDestroy(&D));
8260: }
8261: PetscCall(MatDestroySubMatrices(edata->n, &edata->mat));
8262: PetscCall(MatAssemblyBegin(*C, MAT_FINAL_ASSEMBLY));
8263: PetscCall(MatAssemblyEnd(*C, MAT_FINAL_ASSEMBLY));
8264: PetscFunctionReturn(PETSC_SUCCESS);
8265: }
8267: /*@
8268: MatSetVariableBlockSizes - Sets diagonal point-blocks of the matrix that need not be of the same size
8270: Not Collective
8272: Input Parameters:
8273: + mat - the matrix
8274: . nblocks - the number of blocks on this process, each block can only exist on a single process
8275: - bsizes - the block sizes
8277: Level: intermediate
8279: Notes:
8280: Currently used by `PCVPBJACOBI` for `MATAIJ` matrices
8282: 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.
8284: .seealso: [](ch_matrices), `Mat`, `MatCreateSeqBAIJ()`, `MatCreateBAIJ()`, `MatGetBlockSize()`, `MatSetBlockSizes()`, `MatGetBlockSizes()`, `MatGetVariableBlockSizes()`,
8285: `MatComputeVariableBlockEnvelope()`, `PCVPBJACOBI`
8286: @*/
8287: PetscErrorCode MatSetVariableBlockSizes(Mat mat, PetscInt nblocks, const PetscInt bsizes[])
8288: {
8289: PetscInt ncnt = 0, nlocal;
8291: PetscFunctionBegin;
8293: PetscCall(MatGetLocalSize(mat, &nlocal, NULL));
8294: 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);
8295: for (PetscInt i = 0; i < nblocks; i++) ncnt += bsizes[i];
8296: 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);
8297: PetscCall(PetscFree(mat->bsizes));
8298: mat->nblocks = nblocks;
8299: PetscCall(PetscMalloc1(nblocks, &mat->bsizes));
8300: PetscCall(PetscArraycpy(mat->bsizes, bsizes, nblocks));
8301: PetscFunctionReturn(PETSC_SUCCESS);
8302: }
8304: /*@C
8305: MatGetVariableBlockSizes - Gets a diagonal blocks of the matrix that need not be of the same size
8307: Not Collective; No Fortran Support
8309: Input Parameter:
8310: . mat - the matrix
8312: Output Parameters:
8313: + nblocks - the number of blocks on this process
8314: - bsizes - the block sizes
8316: Level: intermediate
8318: .seealso: [](ch_matrices), `Mat`, `MatCreateSeqBAIJ()`, `MatCreateBAIJ()`, `MatGetBlockSize()`, `MatSetBlockSizes()`, `MatGetBlockSizes()`, `MatSetVariableBlockSizes()`, `MatComputeVariableBlockEnvelope()`
8319: @*/
8320: PetscErrorCode MatGetVariableBlockSizes(Mat mat, PetscInt *nblocks, const PetscInt *bsizes[])
8321: {
8322: PetscFunctionBegin;
8324: if (nblocks) *nblocks = mat->nblocks;
8325: if (bsizes) *bsizes = mat->bsizes;
8326: PetscFunctionReturn(PETSC_SUCCESS);
8327: }
8329: /*@
8330: MatSelectVariableBlockSizes - When creating a submatrix, pass on the variable block sizes
8332: Not Collective
8334: Input Parameter:
8335: + subA - the submatrix
8336: . A - the original matrix
8337: - isrow - The `IS` of selected rows for the submatrix, must be sorted
8339: Level: developer
8341: Notes:
8342: If the index set is not sorted or contains off-process entries, this function will do nothing.
8344: .seealso: [](ch_matrices), `Mat`, `MatSetVariableBlockSizes()`, `MatComputeVariableBlockEnvelope()`
8345: @*/
8346: PetscErrorCode MatSelectVariableBlockSizes(Mat subA, Mat A, IS isrow)
8347: {
8348: const PetscInt *rows;
8349: PetscInt n, rStart, rEnd, Nb = 0;
8350: PetscBool flg = A->bsizes ? PETSC_TRUE : PETSC_FALSE;
8352: PetscFunctionBegin;
8353: // The code for block size extraction does not support an unsorted IS
8354: if (flg) PetscCall(ISSorted(isrow, &flg));
8355: // We don't support originally off-diagonal blocks
8356: if (flg) {
8357: PetscCall(MatGetOwnershipRange(A, &rStart, &rEnd));
8358: PetscCall(ISGetLocalSize(isrow, &n));
8359: PetscCall(ISGetIndices(isrow, &rows));
8360: for (PetscInt i = 0; i < n && flg; ++i) {
8361: if (rows[i] < rStart || rows[i] >= rEnd) flg = PETSC_FALSE;
8362: }
8363: PetscCall(ISRestoreIndices(isrow, &rows));
8364: }
8365: // quiet return if we can't extract block size
8366: PetscCallMPI(MPIU_Allreduce(MPI_IN_PLACE, &flg, 1, MPI_C_BOOL, MPI_LAND, PetscObjectComm((PetscObject)subA)));
8367: if (!flg) PetscFunctionReturn(PETSC_SUCCESS);
8369: // extract block sizes
8370: PetscCall(ISGetIndices(isrow, &rows));
8371: for (PetscInt b = 0, gr = rStart, i = 0; b < A->nblocks; ++b) {
8372: PetscBool occupied = PETSC_FALSE;
8374: for (PetscInt br = 0; br < A->bsizes[b]; ++br) {
8375: const PetscInt row = gr + br;
8377: if (i == n) break;
8378: if (rows[i] == row) {
8379: occupied = PETSC_TRUE;
8380: ++i;
8381: }
8382: while (i < n && rows[i] < row) ++i;
8383: }
8384: gr += A->bsizes[b];
8385: if (occupied) ++Nb;
8386: }
8387: subA->nblocks = Nb;
8388: PetscCall(PetscFree(subA->bsizes));
8389: PetscCall(PetscMalloc1(subA->nblocks, &subA->bsizes));
8390: PetscInt sb = 0;
8391: for (PetscInt b = 0, gr = rStart, i = 0; b < A->nblocks; ++b) {
8392: if (sb < subA->nblocks) subA->bsizes[sb] = 0;
8393: for (PetscInt br = 0; br < A->bsizes[b]; ++br) {
8394: const PetscInt row = gr + br;
8396: if (i == n) break;
8397: if (rows[i] == row) {
8398: ++subA->bsizes[sb];
8399: ++i;
8400: }
8401: while (i < n && rows[i] < row) ++i;
8402: }
8403: gr += A->bsizes[b];
8404: if (sb < subA->nblocks && subA->bsizes[sb]) ++sb;
8405: }
8406: PetscCheck(sb == subA->nblocks, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Invalid number of blocks %" PetscInt_FMT " != %" PetscInt_FMT, sb, subA->nblocks);
8407: PetscInt nlocal, ncnt = 0;
8408: PetscCall(MatGetLocalSize(subA, &nlocal, NULL));
8409: 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);
8410: for (PetscInt i = 0; i < subA->nblocks; i++) ncnt += subA->bsizes[i];
8411: 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);
8412: PetscCall(ISRestoreIndices(isrow, &rows));
8413: PetscFunctionReturn(PETSC_SUCCESS);
8414: }
8416: /*@
8417: MatSetBlockSizes - Sets the matrix block row and column sizes.
8419: Logically Collective
8421: Input Parameters:
8422: + mat - the matrix
8423: . rbs - row block size
8424: - cbs - column block size
8426: Level: intermediate
8428: Notes:
8429: Block row formats are `MATBAIJ` and `MATSBAIJ`. These formats ALWAYS have square block storage in the matrix.
8430: If you pass a different block size for the columns than the rows, the row block size determines the square block storage.
8431: This must be called before `MatSetUp()` or MatXXXSetPreallocation() (or will default to 1) and the block size cannot be changed later.
8433: For `MATAIJ` matrix this function can be called at a later stage, provided that the specified block sizes
8434: are compatible with the matrix local sizes.
8436: The row and column block size determine the blocksize of the "row" and "column" vectors returned by `MatCreateVecs()`.
8438: .seealso: [](ch_matrices), `Mat`, `MatCreateSeqBAIJ()`, `MatCreateBAIJ()`, `MatGetBlockSize()`, `MatSetBlockSize()`, `MatGetBlockSizes()`
8439: @*/
8440: PetscErrorCode MatSetBlockSizes(Mat mat, PetscInt rbs, PetscInt cbs)
8441: {
8442: PetscFunctionBegin;
8446: PetscTryTypeMethod(mat, setblocksizes, rbs, cbs);
8447: if (mat->rmap->refcnt) {
8448: ISLocalToGlobalMapping l2g = NULL;
8449: PetscLayout nmap = NULL;
8451: PetscCall(PetscLayoutDuplicate(mat->rmap, &nmap));
8452: if (mat->rmap->mapping) PetscCall(ISLocalToGlobalMappingDuplicate(mat->rmap->mapping, &l2g));
8453: PetscCall(PetscLayoutDestroy(&mat->rmap));
8454: mat->rmap = nmap;
8455: mat->rmap->mapping = l2g;
8456: }
8457: if (mat->cmap->refcnt) {
8458: ISLocalToGlobalMapping l2g = NULL;
8459: PetscLayout nmap = NULL;
8461: PetscCall(PetscLayoutDuplicate(mat->cmap, &nmap));
8462: if (mat->cmap->mapping) PetscCall(ISLocalToGlobalMappingDuplicate(mat->cmap->mapping, &l2g));
8463: PetscCall(PetscLayoutDestroy(&mat->cmap));
8464: mat->cmap = nmap;
8465: mat->cmap->mapping = l2g;
8466: }
8467: PetscCall(PetscLayoutSetBlockSize(mat->rmap, rbs));
8468: PetscCall(PetscLayoutSetBlockSize(mat->cmap, cbs));
8469: PetscFunctionReturn(PETSC_SUCCESS);
8470: }
8472: /*@
8473: MatSetBlockSizesFromMats - Sets the matrix block row and column sizes to match a pair of matrices
8475: Logically Collective
8477: Input Parameters:
8478: + mat - the matrix
8479: . fromRow - matrix from which to copy row block size
8480: - fromCol - matrix from which to copy column block size (can be same as `fromRow`)
8482: Level: developer
8484: .seealso: [](ch_matrices), `Mat`, `MatCreateSeqBAIJ()`, `MatCreateBAIJ()`, `MatGetBlockSize()`, `MatSetBlockSizes()`
8485: @*/
8486: PetscErrorCode MatSetBlockSizesFromMats(Mat mat, Mat fromRow, Mat fromCol)
8487: {
8488: PetscFunctionBegin;
8492: PetscTryTypeMethod(mat, setblocksizes, fromRow->rmap->bs, fromCol->cmap->bs);
8493: PetscCall(PetscLayoutSetBlockSize(mat->rmap, fromRow->rmap->bs));
8494: PetscCall(PetscLayoutSetBlockSize(mat->cmap, fromCol->cmap->bs));
8495: PetscFunctionReturn(PETSC_SUCCESS);
8496: }
8498: /*@
8499: MatResidual - Default routine to calculate the residual r = b - Ax
8501: Collective
8503: Input Parameters:
8504: + mat - the matrix
8505: . b - the right-hand-side
8506: - x - the approximate solution
8508: Output Parameter:
8509: . r - location to store the residual
8511: Level: developer
8513: .seealso: [](ch_matrices), `Mat`, `MatMult()`, `MatMultAdd()`, `PCMGSetResidual()`
8514: @*/
8515: PetscErrorCode MatResidual(Mat mat, Vec b, Vec x, Vec r)
8516: {
8517: PetscFunctionBegin;
8523: MatCheckPreallocated(mat, 1);
8524: PetscCall(PetscLogEventBegin(MAT_Residual, mat, 0, 0, 0));
8525: if (!mat->ops->residual) {
8526: PetscCall(MatMult(mat, x, r));
8527: PetscCall(VecAYPX(r, -1.0, b));
8528: } else {
8529: PetscUseTypeMethod(mat, residual, b, x, r);
8530: }
8531: PetscCall(PetscLogEventEnd(MAT_Residual, mat, 0, 0, 0));
8532: PetscFunctionReturn(PETSC_SUCCESS);
8533: }
8535: /*@C
8536: MatGetRowIJ - Returns the compressed row storage i and j indices for the local rows of a sparse matrix
8538: Collective
8540: Input Parameters:
8541: + mat - the matrix
8542: . shift - 0 or 1 indicating we want the indices starting at 0 or 1
8543: . symmetric - `PETSC_TRUE` or `PETSC_FALSE` indicating the matrix data structure should be symmetrized
8544: - inodecompressed - `PETSC_TRUE` or `PETSC_FALSE` indicating if the nonzero structure of the
8545: inodes or the nonzero elements is wanted. For `MATBAIJ` matrices the compressed version is
8546: always used.
8548: Output Parameters:
8549: + n - number of local rows in the (possibly compressed) matrix, use `NULL` if not needed
8550: . 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
8551: . ja - the column indices, use `NULL` if not needed
8552: - done - indicates if the routine actually worked and returned appropriate ia[] and ja[] arrays; callers
8553: are responsible for handling the case when done == `PETSC_FALSE` and ia and ja are not set
8555: Level: developer
8557: Notes:
8558: You CANNOT change any of the ia[] or ja[] values.
8560: Use `MatRestoreRowIJ()` when you are finished accessing the ia[] and ja[] values.
8562: Fortran Notes:
8563: Use
8564: .vb
8565: PetscInt, pointer :: ia(:),ja(:)
8566: call MatGetRowIJ(mat,shift,symmetric,inodecompressed,n,ia,ja,done,ierr)
8567: ! Access the ith and jth entries via ia(i) and ja(j)
8568: .ve
8570: .seealso: [](ch_matrices), `Mat`, `MATAIJ`, `MatGetColumnIJ()`, `MatRestoreRowIJ()`, `MatSeqAIJGetArray()`
8571: @*/
8572: PetscErrorCode MatGetRowIJ(Mat mat, PetscInt shift, PetscBool symmetric, PetscBool inodecompressed, PetscInt *n, const PetscInt *ia[], const PetscInt *ja[], PetscBool *done)
8573: {
8574: PetscFunctionBegin;
8577: if (n) PetscAssertPointer(n, 5);
8578: if (ia) PetscAssertPointer(ia, 6);
8579: if (ja) PetscAssertPointer(ja, 7);
8580: if (done) PetscAssertPointer(done, 8);
8581: MatCheckPreallocated(mat, 1);
8582: if (!mat->ops->getrowij && done) *done = PETSC_FALSE;
8583: else {
8584: if (done) *done = PETSC_TRUE;
8585: PetscCall(PetscLogEventBegin(MAT_GetRowIJ, mat, 0, 0, 0));
8586: PetscUseTypeMethod(mat, getrowij, shift, symmetric, inodecompressed, n, ia, ja, done);
8587: PetscCall(PetscLogEventEnd(MAT_GetRowIJ, mat, 0, 0, 0));
8588: }
8589: PetscFunctionReturn(PETSC_SUCCESS);
8590: }
8592: /*@C
8593: MatGetColumnIJ - Returns the compressed column storage i and j indices for sequential matrices.
8595: Collective
8597: Input Parameters:
8598: + mat - the matrix
8599: . shift - 1 or zero indicating we want the indices starting at 0 or 1
8600: . symmetric - `PETSC_TRUE` or `PETSC_FALSE` indicating the matrix data structure should be
8601: symmetrized
8602: - inodecompressed - `PETSC_TRUE` or `PETSC_FALSE` indicating if the nonzero structure of the
8603: inodes or the nonzero elements is wanted. For `MATBAIJ` matrices the compressed version is
8604: always used.
8606: Output Parameters:
8607: + n - number of columns in the (possibly compressed) matrix
8608: . ia - the column pointers; that is ia[0] = 0, ia[col] = i[col-1] + number of elements in that col of the matrix
8609: . ja - the row indices
8610: - done - `PETSC_TRUE` or `PETSC_FALSE`, indicating whether the values have been returned
8612: Level: developer
8614: .seealso: [](ch_matrices), `Mat`, `MatGetRowIJ()`, `MatRestoreColumnIJ()`
8615: @*/
8616: PetscErrorCode MatGetColumnIJ(Mat mat, PetscInt shift, PetscBool symmetric, PetscBool inodecompressed, PetscInt *n, const PetscInt *ia[], const PetscInt *ja[], PetscBool *done)
8617: {
8618: PetscFunctionBegin;
8621: PetscAssertPointer(n, 5);
8622: if (ia) PetscAssertPointer(ia, 6);
8623: if (ja) PetscAssertPointer(ja, 7);
8624: PetscAssertPointer(done, 8);
8625: MatCheckPreallocated(mat, 1);
8626: if (!mat->ops->getcolumnij) *done = PETSC_FALSE;
8627: else {
8628: *done = PETSC_TRUE;
8629: PetscUseTypeMethod(mat, getcolumnij, shift, symmetric, inodecompressed, n, ia, ja, done);
8630: }
8631: PetscFunctionReturn(PETSC_SUCCESS);
8632: }
8634: /*@C
8635: MatRestoreRowIJ - Call after you are completed with the ia,ja indices obtained with `MatGetRowIJ()`.
8637: Collective
8639: Input Parameters:
8640: + mat - the matrix
8641: . shift - 1 or zero indicating we want the indices starting at 0 or 1
8642: . symmetric - `PETSC_TRUE` or `PETSC_FALSE` indicating the matrix data structure should be symmetrized
8643: . inodecompressed - `PETSC_TRUE` or `PETSC_FALSE` indicating if the nonzero structure of the
8644: inodes or the nonzero elements is wanted. For `MATBAIJ` matrices the compressed version is
8645: always used.
8646: . n - size of (possibly compressed) matrix
8647: . ia - the row pointers
8648: - ja - the column indices
8650: Output Parameter:
8651: . done - `PETSC_TRUE` or `PETSC_FALSE` indicated that the values have been returned
8653: Level: developer
8655: Note:
8656: This routine zeros out `n`, `ia`, and `ja`. This is to prevent accidental
8657: us of the array after it has been restored. If you pass `NULL`, it will
8658: not zero the pointers. Use of ia or ja after `MatRestoreRowIJ()` is invalid.
8660: .seealso: [](ch_matrices), `Mat`, `MatGetRowIJ()`, `MatRestoreColumnIJ()`
8661: @*/
8662: PetscErrorCode MatRestoreRowIJ(Mat mat, PetscInt shift, PetscBool symmetric, PetscBool inodecompressed, PetscInt *n, const PetscInt *ia[], const PetscInt *ja[], PetscBool *done)
8663: {
8664: PetscFunctionBegin;
8667: if (ia) PetscAssertPointer(ia, 6);
8668: if (ja) PetscAssertPointer(ja, 7);
8669: if (done) PetscAssertPointer(done, 8);
8670: MatCheckPreallocated(mat, 1);
8672: if (!mat->ops->restorerowij && done) *done = PETSC_FALSE;
8673: else {
8674: if (done) *done = PETSC_TRUE;
8675: PetscUseTypeMethod(mat, restorerowij, shift, symmetric, inodecompressed, n, ia, ja, done);
8676: if (n) *n = 0;
8677: if (ia) *ia = NULL;
8678: if (ja) *ja = NULL;
8679: }
8680: PetscFunctionReturn(PETSC_SUCCESS);
8681: }
8683: /*@C
8684: MatRestoreColumnIJ - Call after you are completed with the ia,ja indices obtained with `MatGetColumnIJ()`.
8686: Collective
8688: Input Parameters:
8689: + mat - the matrix
8690: . shift - 1 or zero indicating we want the indices starting at 0 or 1
8691: . symmetric - `PETSC_TRUE` or `PETSC_FALSE` indicating the matrix data structure should be symmetrized
8692: - inodecompressed - `PETSC_TRUE` or `PETSC_FALSE` indicating if the nonzero structure of the
8693: inodes or the nonzero elements is wanted. For `MATBAIJ` matrices the compressed version is
8694: always used.
8696: Output Parameters:
8697: + n - size of (possibly compressed) matrix
8698: . ia - the column pointers
8699: . ja - the row indices
8700: - done - `PETSC_TRUE` or `PETSC_FALSE` indicated that the values have been returned
8702: Level: developer
8704: .seealso: [](ch_matrices), `Mat`, `MatGetColumnIJ()`, `MatRestoreRowIJ()`
8705: @*/
8706: PetscErrorCode MatRestoreColumnIJ(Mat mat, PetscInt shift, PetscBool symmetric, PetscBool inodecompressed, PetscInt *n, const PetscInt *ia[], const PetscInt *ja[], PetscBool *done)
8707: {
8708: PetscFunctionBegin;
8711: if (ia) PetscAssertPointer(ia, 6);
8712: if (ja) PetscAssertPointer(ja, 7);
8713: PetscAssertPointer(done, 8);
8714: MatCheckPreallocated(mat, 1);
8716: if (!mat->ops->restorecolumnij) *done = PETSC_FALSE;
8717: else {
8718: *done = PETSC_TRUE;
8719: PetscUseTypeMethod(mat, restorecolumnij, shift, symmetric, inodecompressed, n, ia, ja, done);
8720: if (n) *n = 0;
8721: if (ia) *ia = NULL;
8722: if (ja) *ja = NULL;
8723: }
8724: PetscFunctionReturn(PETSC_SUCCESS);
8725: }
8727: /*@
8728: MatColoringPatch - Used inside matrix coloring routines that use `MatGetRowIJ()` and/or
8729: `MatGetColumnIJ()`.
8731: Collective
8733: Input Parameters:
8734: + mat - the matrix
8735: . ncolors - maximum color value
8736: . n - number of entries in colorarray
8737: - colorarray - array indicating color for each column
8739: Output Parameter:
8740: . iscoloring - coloring generated using colorarray information
8742: Level: developer
8744: .seealso: [](ch_matrices), `Mat`, `MatGetRowIJ()`, `MatGetColumnIJ()`
8745: @*/
8746: PetscErrorCode MatColoringPatch(Mat mat, PetscInt ncolors, PetscInt n, ISColoringValue colorarray[], ISColoring *iscoloring)
8747: {
8748: PetscFunctionBegin;
8751: PetscAssertPointer(colorarray, 4);
8752: PetscAssertPointer(iscoloring, 5);
8753: MatCheckPreallocated(mat, 1);
8755: if (!mat->ops->coloringpatch) {
8756: PetscCall(ISColoringCreate(PetscObjectComm((PetscObject)mat), ncolors, n, colorarray, PETSC_OWN_POINTER, iscoloring));
8757: } else {
8758: PetscUseTypeMethod(mat, coloringpatch, ncolors, n, colorarray, iscoloring);
8759: }
8760: PetscFunctionReturn(PETSC_SUCCESS);
8761: }
8763: /*@
8764: MatSetUnfactored - Resets a factored matrix to be treated as unfactored.
8766: Logically Collective
8768: Input Parameter:
8769: . mat - the factored matrix to be reset
8771: Level: developer
8773: Notes:
8774: This routine should be used only with factored matrices formed by in-place
8775: factorization via ILU(0) (or by in-place LU factorization for the `MATSEQDENSE`
8776: format). This option can save memory, for example, when solving nonlinear
8777: systems with a matrix-free Newton-Krylov method and a matrix-based, in-place
8778: ILU(0) preconditioner.
8780: One can specify in-place ILU(0) factorization by calling
8781: .vb
8782: PCType(pc,PCILU);
8783: PCFactorSeUseInPlace(pc);
8784: .ve
8785: or by using the options -pc_type ilu -pc_factor_in_place
8787: In-place factorization ILU(0) can also be used as a local
8788: solver for the blocks within the block Jacobi or additive Schwarz
8789: methods (runtime option: -sub_pc_factor_in_place). See Users-Manual: ch_pc
8790: for details on setting local solver options.
8792: Most users should employ the `KSP` interface for linear solvers
8793: instead of working directly with matrix algebra routines such as this.
8794: See, e.g., `KSPCreate()`.
8796: .seealso: [](ch_matrices), `Mat`, `PCFactorSetUseInPlace()`, `PCFactorGetUseInPlace()`
8797: @*/
8798: PetscErrorCode MatSetUnfactored(Mat mat)
8799: {
8800: PetscFunctionBegin;
8803: MatCheckPreallocated(mat, 1);
8804: mat->factortype = MAT_FACTOR_NONE;
8805: if (!mat->ops->setunfactored) PetscFunctionReturn(PETSC_SUCCESS);
8806: PetscUseTypeMethod(mat, setunfactored);
8807: PetscFunctionReturn(PETSC_SUCCESS);
8808: }
8810: /*@
8811: MatCreateSubMatrix - Gets a single submatrix on the same number of processors
8812: as the original matrix.
8814: Collective
8816: Input Parameters:
8817: + mat - the original matrix
8818: . isrow - parallel `IS` containing the rows this processor should obtain
8819: . 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.
8820: - cll - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`
8822: Output Parameter:
8823: . newmat - the new submatrix, of the same type as the original matrix
8825: Level: advanced
8827: Notes:
8828: The submatrix will be able to be multiplied with vectors using the same layout as `iscol`.
8830: Some matrix types place restrictions on the row and column indices, such
8831: 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;
8832: for example, if the block size is 3 one cannot select the 0 and 2 rows without selecting the 1 row.
8834: The index sets may not have duplicate entries.
8836: The first time this is called you should use a `cll` of `MAT_INITIAL_MATRIX`,
8837: the `MatCreateSubMatrix()` routine will create the newmat for you. Any additional calls
8838: to this routine with a mat of the same nonzero structure and with a call of `MAT_REUSE_MATRIX`
8839: will reuse the matrix generated the first time. You should call `MatDestroy()` on `newmat` when
8840: you are finished using it.
8842: The communicator of the newly obtained matrix is ALWAYS the same as the communicator of
8843: the input matrix.
8845: If `iscol` is `NULL` then all columns are obtained (not supported in Fortran).
8847: If `isrow` and `iscol` have a nontrivial block-size, then the resulting matrix has this block-size as well. This feature
8848: is used by `PCFIELDSPLIT` to allow easy nesting of its use.
8850: Example usage:
8851: Consider the following 8x8 matrix with 34 non-zero values, that is
8852: assembled across 3 processors. Let's assume that proc0 owns 3 rows,
8853: proc1 owns 3 rows, proc2 owns 2 rows. This division can be shown
8854: as follows
8855: .vb
8856: 1 2 0 | 0 3 0 | 0 4
8857: Proc0 0 5 6 | 7 0 0 | 8 0
8858: 9 0 10 | 11 0 0 | 12 0
8859: -------------------------------------
8860: 13 0 14 | 15 16 17 | 0 0
8861: Proc1 0 18 0 | 19 20 21 | 0 0
8862: 0 0 0 | 22 23 0 | 24 0
8863: -------------------------------------
8864: Proc2 25 26 27 | 0 0 28 | 29 0
8865: 30 0 0 | 31 32 33 | 0 34
8866: .ve
8868: Suppose `isrow` = [0 1 | 4 | 6 7] and `iscol` = [1 2 | 3 4 5 | 6]. The resulting submatrix is
8870: .vb
8871: 2 0 | 0 3 0 | 0
8872: Proc0 5 6 | 7 0 0 | 8
8873: -------------------------------
8874: Proc1 18 0 | 19 20 21 | 0
8875: -------------------------------
8876: Proc2 26 27 | 0 0 28 | 29
8877: 0 0 | 31 32 33 | 0
8878: .ve
8880: .seealso: [](ch_matrices), `Mat`, `MatCreateSubMatrices()`, `MatCreateSubMatricesMPI()`, `MatCreateSubMatrixVirtual()`, `MatSubMatrixVirtualUpdate()`
8881: @*/
8882: PetscErrorCode MatCreateSubMatrix(Mat mat, IS isrow, IS iscol, MatReuse cll, Mat *newmat)
8883: {
8884: PetscMPIInt size;
8885: Mat *local;
8886: IS iscoltmp;
8887: PetscBool flg;
8889: PetscFunctionBegin;
8893: PetscAssertPointer(newmat, 5);
8896: PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
8897: PetscCheck(cll != MAT_IGNORE_MATRIX, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Cannot use MAT_IGNORE_MATRIX");
8898: PetscCheck(cll != MAT_INPLACE_MATRIX, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Cannot use MAT_INPLACE_MATRIX");
8900: MatCheckPreallocated(mat, 1);
8901: PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)mat), &size));
8903: if (!iscol || isrow == iscol) {
8904: PetscBool stride;
8905: PetscMPIInt grabentirematrix = 0, grab;
8906: PetscCall(PetscObjectTypeCompare((PetscObject)isrow, ISSTRIDE, &stride));
8907: if (stride) {
8908: PetscInt first, step, n, rstart, rend;
8909: PetscCall(ISStrideGetInfo(isrow, &first, &step));
8910: if (step == 1) {
8911: PetscCall(MatGetOwnershipRange(mat, &rstart, &rend));
8912: if (rstart == first) {
8913: PetscCall(ISGetLocalSize(isrow, &n));
8914: if (n == rend - rstart) grabentirematrix = 1;
8915: }
8916: }
8917: }
8918: PetscCallMPI(MPIU_Allreduce(&grabentirematrix, &grab, 1, MPI_INT, MPI_MIN, PetscObjectComm((PetscObject)mat)));
8919: if (grab) {
8920: PetscCall(PetscInfo(mat, "Getting entire matrix as submatrix\n"));
8921: if (cll == MAT_INITIAL_MATRIX) {
8922: *newmat = mat;
8923: PetscCall(PetscObjectReference((PetscObject)mat));
8924: }
8925: PetscFunctionReturn(PETSC_SUCCESS);
8926: }
8927: }
8929: if (!iscol) {
8930: PetscCall(ISCreateStride(PetscObjectComm((PetscObject)mat), mat->cmap->n, mat->cmap->rstart, 1, &iscoltmp));
8931: } else {
8932: iscoltmp = iscol;
8933: }
8935: /* if original matrix is on just one processor then use submatrix generated */
8936: if (mat->ops->createsubmatrices && !mat->ops->createsubmatrix && size == 1 && cll == MAT_REUSE_MATRIX) {
8937: PetscCall(MatCreateSubMatrices(mat, 1, &isrow, &iscoltmp, MAT_REUSE_MATRIX, &newmat));
8938: goto setproperties;
8939: } else if (mat->ops->createsubmatrices && !mat->ops->createsubmatrix && size == 1) {
8940: PetscCall(MatCreateSubMatrices(mat, 1, &isrow, &iscoltmp, MAT_INITIAL_MATRIX, &local));
8941: *newmat = *local;
8942: PetscCall(PetscFree(local));
8943: goto setproperties;
8944: } else if (!mat->ops->createsubmatrix) {
8945: /* Create a new matrix type that implements the operation using the full matrix */
8946: PetscCall(PetscLogEventBegin(MAT_CreateSubMat, mat, 0, 0, 0));
8947: switch (cll) {
8948: case MAT_INITIAL_MATRIX:
8949: PetscCall(MatCreateSubMatrixVirtual(mat, isrow, iscoltmp, newmat));
8950: break;
8951: case MAT_REUSE_MATRIX:
8952: PetscCall(MatSubMatrixVirtualUpdate(*newmat, mat, isrow, iscoltmp));
8953: break;
8954: default:
8955: SETERRQ(PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_OUTOFRANGE, "Invalid MatReuse, must be either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX");
8956: }
8957: PetscCall(PetscLogEventEnd(MAT_CreateSubMat, mat, 0, 0, 0));
8958: goto setproperties;
8959: }
8961: PetscCall(PetscLogEventBegin(MAT_CreateSubMat, mat, 0, 0, 0));
8962: PetscUseTypeMethod(mat, createsubmatrix, isrow, iscoltmp, cll, newmat);
8963: PetscCall(PetscLogEventEnd(MAT_CreateSubMat, mat, 0, 0, 0));
8965: setproperties:
8966: if ((*newmat)->symmetric == PETSC_BOOL3_UNKNOWN && (*newmat)->structurally_symmetric == PETSC_BOOL3_UNKNOWN && (*newmat)->spd == PETSC_BOOL3_UNKNOWN && (*newmat)->hermitian == PETSC_BOOL3_UNKNOWN) {
8967: PetscCall(ISEqualUnsorted(isrow, iscoltmp, &flg));
8968: if (flg) PetscCall(MatPropagateSymmetryOptions(mat, *newmat));
8969: }
8970: if (!iscol) PetscCall(ISDestroy(&iscoltmp));
8971: if (*newmat && cll == MAT_INITIAL_MATRIX) PetscCall(PetscObjectStateIncrease((PetscObject)*newmat));
8972: if (!iscol || isrow == iscol) PetscCall(MatSelectVariableBlockSizes(*newmat, mat, isrow));
8973: PetscFunctionReturn(PETSC_SUCCESS);
8974: }
8976: /*@
8977: MatPropagateSymmetryOptions - Propagates symmetry options set on a matrix to another matrix
8979: Not Collective
8981: Input Parameters:
8982: + A - the matrix we wish to propagate options from
8983: - B - the matrix we wish to propagate options to
8985: Level: beginner
8987: Note:
8988: Propagates the options associated to `MAT_SYMMETRY_ETERNAL`, `MAT_STRUCTURALLY_SYMMETRIC`, `MAT_HERMITIAN`, `MAT_SPD`, `MAT_SYMMETRIC`, and `MAT_STRUCTURAL_SYMMETRY_ETERNAL`
8990: .seealso: [](ch_matrices), `Mat`, `MatSetOption()`, `MatIsSymmetricKnown()`, `MatIsSPDKnown()`, `MatIsHermitianKnown()`, `MatIsStructurallySymmetricKnown()`
8991: @*/
8992: PetscErrorCode MatPropagateSymmetryOptions(Mat A, Mat B)
8993: {
8994: PetscFunctionBegin;
8997: B->symmetry_eternal = A->symmetry_eternal;
8998: B->structural_symmetry_eternal = A->structural_symmetry_eternal;
8999: B->symmetric = A->symmetric;
9000: B->structurally_symmetric = A->structurally_symmetric;
9001: B->spd = A->spd;
9002: B->hermitian = A->hermitian;
9003: PetscFunctionReturn(PETSC_SUCCESS);
9004: }
9006: /*@
9007: MatStashSetInitialSize - sets the sizes of the matrix stash, that is
9008: used during the assembly process to store values that belong to
9009: other processors.
9011: Not Collective
9013: Input Parameters:
9014: + mat - the matrix
9015: . size - the initial size of the stash.
9016: - bsize - the initial size of the block-stash(if used).
9018: Options Database Keys:
9019: + -matstash_initial_size size or size0,size1,...,sizep-1 - set initial size
9020: - -matstash_block_initial_size bsize or bsize0,bsize1,...,bsizep-1 - set initial block size
9022: Level: intermediate
9024: Notes:
9025: The block-stash is used for values set with `MatSetValuesBlocked()` while
9026: the stash is used for values set with `MatSetValues()`
9028: Run with the option -info and look for output of the form
9029: MatAssemblyBegin_MPIXXX:Stash has MM entries, uses nn mallocs.
9030: to determine the appropriate value, MM, to use for size and
9031: MatAssemblyBegin_MPIXXX:Block-Stash has BMM entries, uses nn mallocs.
9032: to determine the value, BMM to use for bsize
9034: .seealso: [](ch_matrices), `MatAssemblyBegin()`, `MatAssemblyEnd()`, `Mat`, `MatStashGetInfo()`
9035: @*/
9036: PetscErrorCode MatStashSetInitialSize(Mat mat, PetscInt size, PetscInt bsize)
9037: {
9038: PetscFunctionBegin;
9041: PetscCall(MatStashSetInitialSize_Private(&mat->stash, size));
9042: PetscCall(MatStashSetInitialSize_Private(&mat->bstash, bsize));
9043: PetscFunctionReturn(PETSC_SUCCESS);
9044: }
9046: /*@
9047: MatInterpolateAdd - $w = y + A*x$ or $A^T*x$ depending on the shape of
9048: the matrix
9050: Neighbor-wise Collective
9052: Input Parameters:
9053: + A - the matrix
9054: . x - the vector to be multiplied by the interpolation operator
9055: - y - the vector to be added to the result
9057: Output Parameter:
9058: . w - the resulting vector
9060: Level: intermediate
9062: Notes:
9063: `w` may be the same vector as `y`.
9065: This allows one to use either the restriction or interpolation (its transpose)
9066: matrix to do the interpolation
9068: .seealso: [](ch_matrices), `Mat`, `MatMultAdd()`, `MatMultTransposeAdd()`, `MatRestrict()`, `PCMG`
9069: @*/
9070: PetscErrorCode MatInterpolateAdd(Mat A, Vec x, Vec y, Vec w)
9071: {
9072: PetscInt M, N, Ny;
9074: PetscFunctionBegin;
9079: PetscCall(MatGetSize(A, &M, &N));
9080: PetscCall(VecGetSize(y, &Ny));
9081: if (M == Ny) PetscCall(MatMultAdd(A, x, y, w));
9082: else PetscCall(MatMultTransposeAdd(A, x, y, w));
9083: PetscFunctionReturn(PETSC_SUCCESS);
9084: }
9086: /*@
9087: MatInterpolate - $y = A*x$ or $A^T*x$ depending on the shape of
9088: the matrix
9090: Neighbor-wise Collective
9092: Input Parameters:
9093: + A - the matrix
9094: - x - the vector to be interpolated
9096: Output Parameter:
9097: . y - the resulting vector
9099: Level: intermediate
9101: Note:
9102: This allows one to use either the restriction or interpolation (its transpose)
9103: matrix to do the interpolation
9105: .seealso: [](ch_matrices), `Mat`, `MatMultAdd()`, `MatMultTransposeAdd()`, `MatRestrict()`, `PCMG`
9106: @*/
9107: PetscErrorCode MatInterpolate(Mat A, Vec x, Vec y)
9108: {
9109: PetscInt M, N, Ny;
9111: PetscFunctionBegin;
9115: PetscCall(MatGetSize(A, &M, &N));
9116: PetscCall(VecGetSize(y, &Ny));
9117: if (M == Ny) PetscCall(MatMult(A, x, y));
9118: else PetscCall(MatMultTranspose(A, x, y));
9119: PetscFunctionReturn(PETSC_SUCCESS);
9120: }
9122: /*@
9123: MatRestrict - $y = A*x$ or $A^T*x$
9125: Neighbor-wise Collective
9127: Input Parameters:
9128: + A - the matrix
9129: - x - the vector to be restricted
9131: Output Parameter:
9132: . y - the resulting vector
9134: Level: intermediate
9136: Note:
9137: This allows one to use either the restriction or interpolation (its transpose)
9138: matrix to do the restriction
9140: .seealso: [](ch_matrices), `Mat`, `MatMultAdd()`, `MatMultTransposeAdd()`, `MatInterpolate()`, `PCMG`
9141: @*/
9142: PetscErrorCode MatRestrict(Mat A, Vec x, Vec y)
9143: {
9144: PetscInt M, N, Nx;
9146: PetscFunctionBegin;
9150: PetscCall(MatGetSize(A, &M, &N));
9151: PetscCall(VecGetSize(x, &Nx));
9152: if (M == Nx) PetscCall(MatMultTranspose(A, x, y));
9153: else PetscCall(MatMult(A, x, y));
9154: PetscFunctionReturn(PETSC_SUCCESS);
9155: }
9157: /*@
9158: MatMatInterpolateAdd - $Y = W + A*X$ or $W + A^T*X$ depending on the shape of `A`
9160: Neighbor-wise Collective
9162: Input Parameters:
9163: + A - the matrix
9164: . x - the input dense matrix to be multiplied
9165: - w - the input dense matrix to be added to the result
9167: Output Parameter:
9168: . y - the output dense matrix
9170: Level: intermediate
9172: Note:
9173: This allows one to use either the restriction or interpolation (its transpose)
9174: matrix to do the interpolation. `y` matrix can be reused if already created with the proper sizes,
9175: otherwise it will be recreated. `y` must be initialized to `NULL` if not supplied.
9177: .seealso: [](ch_matrices), `Mat`, `MatInterpolateAdd()`, `MatMatInterpolate()`, `MatMatRestrict()`, `PCMG`
9178: @*/
9179: PetscErrorCode MatMatInterpolateAdd(Mat A, Mat x, Mat w, Mat *y)
9180: {
9181: PetscInt M, N, Mx, Nx, Mo, My = 0, Ny = 0;
9182: PetscBool trans = PETSC_TRUE;
9183: MatReuse reuse = MAT_INITIAL_MATRIX;
9185: PetscFunctionBegin;
9191: PetscCall(MatGetSize(A, &M, &N));
9192: PetscCall(MatGetSize(x, &Mx, &Nx));
9193: if (N == Mx) trans = PETSC_FALSE;
9194: 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);
9195: Mo = trans ? N : M;
9196: if (*y) {
9197: PetscCall(MatGetSize(*y, &My, &Ny));
9198: if (Mo == My && Nx == Ny) reuse = MAT_REUSE_MATRIX;
9199: else {
9200: 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);
9201: PetscCall(MatDestroy(y));
9202: }
9203: }
9205: if (w && *y == w) { /* this is to minimize changes in PCMG */
9206: PetscBool flg;
9208: PetscCall(PetscObjectQuery((PetscObject)*y, "__MatMatIntAdd_w", (PetscObject *)&w));
9209: if (w) {
9210: PetscInt My, Ny, Mw, Nw;
9212: PetscCall(PetscObjectTypeCompare((PetscObject)*y, ((PetscObject)w)->type_name, &flg));
9213: PetscCall(MatGetSize(*y, &My, &Ny));
9214: PetscCall(MatGetSize(w, &Mw, &Nw));
9215: if (!flg || My != Mw || Ny != Nw) w = NULL;
9216: }
9217: if (!w) {
9218: PetscCall(MatDuplicate(*y, MAT_COPY_VALUES, &w));
9219: PetscCall(PetscObjectCompose((PetscObject)*y, "__MatMatIntAdd_w", (PetscObject)w));
9220: PetscCall(PetscObjectDereference((PetscObject)w));
9221: } else PetscCall(MatCopy(*y, w, UNKNOWN_NONZERO_PATTERN));
9222: }
9223: if (!trans) PetscCall(MatMatMult(A, x, reuse, PETSC_DETERMINE, y));
9224: else PetscCall(MatTransposeMatMult(A, x, reuse, PETSC_DETERMINE, y));
9225: if (w) PetscCall(MatAXPY(*y, 1.0, w, UNKNOWN_NONZERO_PATTERN));
9226: PetscFunctionReturn(PETSC_SUCCESS);
9227: }
9229: /*@
9230: MatMatInterpolate - $Y = A*X$ or $A^T*X$ depending on the shape of `A`
9232: Neighbor-wise Collective
9234: Input Parameters:
9235: + A - the matrix
9236: - x - the input dense matrix
9238: Output Parameter:
9239: . y - the output dense matrix
9241: Level: intermediate
9243: Note:
9244: This allows one to use either the restriction or interpolation (its transpose)
9245: matrix to do the interpolation. `y` matrix can be reused if already created with the proper sizes,
9246: otherwise it will be recreated. `y` must be initialized to `NULL` if not supplied.
9248: .seealso: [](ch_matrices), `Mat`, `MatInterpolate()`, `MatRestrict()`, `MatMatRestrict()`, `PCMG`
9249: @*/
9250: PetscErrorCode MatMatInterpolate(Mat A, Mat x, Mat *y)
9251: {
9252: PetscFunctionBegin;
9253: PetscCall(MatMatInterpolateAdd(A, x, NULL, y));
9254: PetscFunctionReturn(PETSC_SUCCESS);
9255: }
9257: /*@
9258: MatMatRestrict - $Y = A*X$ or $A^T*X$ depending on the shape of `A`
9260: Neighbor-wise Collective
9262: Input Parameters:
9263: + A - the matrix
9264: - x - the input dense matrix
9266: Output Parameter:
9267: . y - the output dense matrix
9269: Level: intermediate
9271: Note:
9272: This allows one to use either the restriction or interpolation (its transpose)
9273: matrix to do the restriction. `y` matrix can be reused if already created with the proper sizes,
9274: otherwise it will be recreated. `y` must be initialized to `NULL` if not supplied.
9276: .seealso: [](ch_matrices), `Mat`, `MatRestrict()`, `MatInterpolate()`, `MatMatInterpolate()`, `PCMG`
9277: @*/
9278: PetscErrorCode MatMatRestrict(Mat A, Mat x, Mat *y)
9279: {
9280: PetscFunctionBegin;
9281: PetscCall(MatMatInterpolateAdd(A, x, NULL, y));
9282: PetscFunctionReturn(PETSC_SUCCESS);
9283: }
9285: /*@
9286: MatGetNullSpace - retrieves the null space of a matrix.
9288: Logically Collective
9290: Input Parameters:
9291: + mat - the matrix
9292: - nullsp - the null space object
9294: Level: developer
9296: .seealso: [](ch_matrices), `Mat`, `MatCreate()`, `MatNullSpaceCreate()`, `MatSetNearNullSpace()`, `MatSetNullSpace()`, `MatNullSpace`
9297: @*/
9298: PetscErrorCode MatGetNullSpace(Mat mat, MatNullSpace *nullsp)
9299: {
9300: PetscFunctionBegin;
9302: PetscAssertPointer(nullsp, 2);
9303: *nullsp = (mat->symmetric == PETSC_BOOL3_TRUE && !mat->nullsp) ? mat->transnullsp : mat->nullsp;
9304: PetscFunctionReturn(PETSC_SUCCESS);
9305: }
9307: /*@C
9308: MatGetNullSpaces - gets the null spaces, transpose null spaces, and near null spaces from an array of matrices
9310: Logically Collective
9312: Input Parameters:
9313: + n - the number of matrices
9314: - mat - the array of matrices
9316: Output Parameters:
9317: . nullsp - an array of null spaces, `NULL` for each matrix that does not have a null space, length 3 * `n`
9319: Level: developer
9321: Note:
9322: Call `MatRestoreNullspaces()` to provide these to another array of matrices
9324: .seealso: [](ch_matrices), `Mat`, `MatCreate()`, `MatNullSpaceCreate()`, `MatSetNearNullSpace()`, `MatGetNullSpace()`, `MatSetTransposeNullSpace()`, `MatGetTransposeNullSpace()`,
9325: `MatNullSpaceRemove()`, `MatRestoreNullSpaces()`
9326: @*/
9327: PetscErrorCode MatGetNullSpaces(PetscInt n, Mat mat[], MatNullSpace *nullsp[])
9328: {
9329: PetscFunctionBegin;
9330: PetscCheck(n >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Number of matrices %" PetscInt_FMT " must be non-negative", n);
9331: PetscAssertPointer(mat, 2);
9332: PetscAssertPointer(nullsp, 3);
9334: PetscCall(PetscCalloc1(3 * n, nullsp));
9335: for (PetscInt i = 0; i < n; i++) {
9337: (*nullsp)[i] = mat[i]->nullsp;
9338: PetscCall(PetscObjectReference((PetscObject)(*nullsp)[i]));
9339: (*nullsp)[n + i] = mat[i]->nearnullsp;
9340: PetscCall(PetscObjectReference((PetscObject)(*nullsp)[n + i]));
9341: (*nullsp)[2 * n + i] = mat[i]->transnullsp;
9342: PetscCall(PetscObjectReference((PetscObject)(*nullsp)[2 * n + i]));
9343: }
9344: PetscFunctionReturn(PETSC_SUCCESS);
9345: }
9347: /*@C
9348: MatRestoreNullSpaces - sets the null spaces, transpose null spaces, and near null spaces obtained with `MatGetNullSpaces()` for an array of matrices
9350: Logically Collective
9352: Input Parameters:
9353: + n - the number of matrices
9354: . mat - the array of matrices
9355: - nullsp - an array of null spaces
9357: Level: developer
9359: Note:
9360: Call `MatGetNullSpaces()` to create `nullsp`
9362: .seealso: [](ch_matrices), `Mat`, `MatCreate()`, `MatNullSpaceCreate()`, `MatSetNearNullSpace()`, `MatGetNullSpace()`, `MatSetTransposeNullSpace()`, `MatGetTransposeNullSpace()`,
9363: `MatNullSpaceRemove()`, `MatGetNullSpaces()`
9364: @*/
9365: PetscErrorCode MatRestoreNullSpaces(PetscInt n, Mat mat[], MatNullSpace *nullsp[])
9366: {
9367: PetscFunctionBegin;
9368: PetscCheck(n >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Number of matrices %" PetscInt_FMT " must be non-negative", n);
9369: PetscAssertPointer(mat, 2);
9370: PetscAssertPointer(nullsp, 3);
9371: PetscAssertPointer(*nullsp, 3);
9373: for (PetscInt i = 0; i < n; i++) {
9375: PetscCall(MatSetNullSpace(mat[i], (*nullsp)[i]));
9376: PetscCall(PetscObjectDereference((PetscObject)(*nullsp)[i]));
9377: PetscCall(MatSetNearNullSpace(mat[i], (*nullsp)[n + i]));
9378: PetscCall(PetscObjectDereference((PetscObject)(*nullsp)[n + i]));
9379: PetscCall(MatSetTransposeNullSpace(mat[i], (*nullsp)[2 * n + i]));
9380: PetscCall(PetscObjectDereference((PetscObject)(*nullsp)[2 * n + i]));
9381: }
9382: PetscCall(PetscFree(*nullsp));
9383: PetscFunctionReturn(PETSC_SUCCESS);
9384: }
9386: /*@
9387: MatSetNullSpace - attaches a null space to a matrix.
9389: Logically Collective
9391: Input Parameters:
9392: + mat - the matrix
9393: - nullsp - the null space object
9395: Level: advanced
9397: Notes:
9398: This null space is used by the `KSP` linear solvers to solve singular systems.
9400: 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`
9402: 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
9403: to zero but the linear system will still be solved in a least squares sense.
9405: The fundamental theorem of linear algebra (Gilbert Strang, Introduction to Applied Mathematics, page 72) states that
9406: 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)$.
9407: 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
9408: $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
9409: 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)$.
9410: This $\hat{b}$ can be obtained by calling `MatNullSpaceRemove()` with the null space of the transpose of the matrix.
9412: If the matrix is known to be symmetric because it is an `MATSBAIJ` matrix or one has called
9413: `MatSetOption`(mat,`MAT_SYMMETRIC` or possibly `MAT_SYMMETRY_ETERNAL`,`PETSC_TRUE`); this
9414: routine also automatically calls `MatSetTransposeNullSpace()`.
9416: The user should call `MatNullSpaceDestroy()`.
9418: .seealso: [](ch_matrices), `Mat`, `MatCreate()`, `MatNullSpaceCreate()`, `MatSetNearNullSpace()`, `MatGetNullSpace()`, `MatSetTransposeNullSpace()`, `MatGetTransposeNullSpace()`, `MatNullSpaceRemove()`,
9419: `KSPSetPCSide()`
9420: @*/
9421: PetscErrorCode MatSetNullSpace(Mat mat, MatNullSpace nullsp)
9422: {
9423: PetscFunctionBegin;
9426: PetscCall(PetscObjectReference((PetscObject)nullsp));
9427: PetscCall(MatNullSpaceDestroy(&mat->nullsp));
9428: mat->nullsp = nullsp;
9429: if (mat->symmetric == PETSC_BOOL3_TRUE) PetscCall(MatSetTransposeNullSpace(mat, nullsp));
9430: PetscFunctionReturn(PETSC_SUCCESS);
9431: }
9433: /*@
9434: MatGetTransposeNullSpace - retrieves the null space of the transpose of a matrix.
9436: Logically Collective
9438: Input Parameters:
9439: + mat - the matrix
9440: - nullsp - the null space object
9442: Level: developer
9444: .seealso: [](ch_matrices), `Mat`, `MatNullSpace`, `MatCreate()`, `MatNullSpaceCreate()`, `MatSetNearNullSpace()`, `MatSetTransposeNullSpace()`, `MatSetNullSpace()`, `MatGetNullSpace()`
9445: @*/
9446: PetscErrorCode MatGetTransposeNullSpace(Mat mat, MatNullSpace *nullsp)
9447: {
9448: PetscFunctionBegin;
9451: PetscAssertPointer(nullsp, 2);
9452: *nullsp = (mat->symmetric == PETSC_BOOL3_TRUE && !mat->transnullsp) ? mat->nullsp : mat->transnullsp;
9453: PetscFunctionReturn(PETSC_SUCCESS);
9454: }
9456: /*@
9457: MatSetTransposeNullSpace - attaches the null space of a transpose of a matrix to the matrix
9459: Logically Collective
9461: Input Parameters:
9462: + mat - the matrix
9463: - nullsp - the null space object
9465: Level: advanced
9467: Notes:
9468: This allows solving singular linear systems defined by the transpose of the matrix using `KSP` solvers with left preconditioning.
9470: See `MatSetNullSpace()`
9472: .seealso: [](ch_matrices), `Mat`, `MatNullSpace`, `MatCreate()`, `MatNullSpaceCreate()`, `MatSetNearNullSpace()`, `MatGetNullSpace()`, `MatSetNullSpace()`, `MatGetTransposeNullSpace()`, `MatNullSpaceRemove()`, `KSPSetPCSide()`
9473: @*/
9474: PetscErrorCode MatSetTransposeNullSpace(Mat mat, MatNullSpace nullsp)
9475: {
9476: PetscFunctionBegin;
9479: PetscCall(PetscObjectReference((PetscObject)nullsp));
9480: PetscCall(MatNullSpaceDestroy(&mat->transnullsp));
9481: mat->transnullsp = nullsp;
9482: PetscFunctionReturn(PETSC_SUCCESS);
9483: }
9485: /*@
9486: MatSetNearNullSpace - attaches a null space to a matrix, which is often the null space (rigid body modes) of the operator without boundary conditions
9487: This null space will be used to provide near null space vectors to a multigrid preconditioner built from this matrix.
9489: Logically Collective
9491: Input Parameters:
9492: + mat - the matrix
9493: - nullsp - the null space object
9495: Level: advanced
9497: Notes:
9498: Overwrites any previous near null space that may have been attached
9500: You can remove the null space by calling this routine with an `nullsp` of `NULL`
9502: .seealso: [](ch_matrices), `Mat`, `MatNullSpace`, `MatCreate()`, `MatNullSpaceCreate()`, `MatSetNullSpace()`, `MatNullSpaceCreateRigidBody()`, `MatGetNearNullSpace()`
9503: @*/
9504: PetscErrorCode MatSetNearNullSpace(Mat mat, MatNullSpace nullsp)
9505: {
9506: PetscFunctionBegin;
9510: MatCheckPreallocated(mat, 1);
9511: PetscCall(PetscObjectReference((PetscObject)nullsp));
9512: PetscCall(MatNullSpaceDestroy(&mat->nearnullsp));
9513: mat->nearnullsp = nullsp;
9514: PetscFunctionReturn(PETSC_SUCCESS);
9515: }
9517: /*@
9518: MatGetNearNullSpace - Get null space attached with `MatSetNearNullSpace()`
9520: Not Collective
9522: Input Parameter:
9523: . mat - the matrix
9525: Output Parameter:
9526: . nullsp - the null space object, `NULL` if not set
9528: Level: advanced
9530: .seealso: [](ch_matrices), `Mat`, `MatNullSpace`, `MatSetNearNullSpace()`, `MatGetNullSpace()`, `MatNullSpaceCreate()`
9531: @*/
9532: PetscErrorCode MatGetNearNullSpace(Mat mat, MatNullSpace *nullsp)
9533: {
9534: PetscFunctionBegin;
9537: PetscAssertPointer(nullsp, 2);
9538: MatCheckPreallocated(mat, 1);
9539: *nullsp = mat->nearnullsp;
9540: PetscFunctionReturn(PETSC_SUCCESS);
9541: }
9543: /*@
9544: MatICCFactor - Performs in-place incomplete Cholesky factorization of matrix.
9546: Collective
9548: Input Parameters:
9549: + mat - the matrix
9550: . row - row/column permutation
9551: - info - information on desired factorization process
9553: Level: developer
9555: Notes:
9556: Probably really in-place only when level of fill is zero, otherwise allocates
9557: new space to store factored matrix and deletes previous memory.
9559: Most users should employ the `KSP` interface for linear solvers
9560: instead of working directly with matrix algebra routines such as this.
9561: See, e.g., `KSPCreate()`.
9563: Fortran Note:
9564: A valid (non-null) `info` argument must be provided
9566: .seealso: [](ch_matrices), `Mat`, `MatFactorInfo`, `MatGetFactor()`, `MatICCFactorSymbolic()`, `MatLUFactorNumeric()`, `MatCholeskyFactor()`
9567: @*/
9568: PetscErrorCode MatICCFactor(Mat mat, IS row, const MatFactorInfo *info)
9569: {
9570: PetscFunctionBegin;
9574: PetscAssertPointer(info, 3);
9575: PetscCheck(mat->rmap->N == mat->cmap->N, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONG, "matrix must be square");
9576: PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
9577: PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
9578: MatCheckPreallocated(mat, 1);
9579: PetscUseTypeMethod(mat, iccfactor, row, info);
9580: PetscCall(PetscObjectStateIncrease((PetscObject)mat));
9581: PetscFunctionReturn(PETSC_SUCCESS);
9582: }
9584: /*@
9585: MatDiagonalScaleLocal - Scales columns of a matrix given the scaling values including the
9586: ghosted ones.
9588: Not Collective
9590: Input Parameters:
9591: + mat - the matrix
9592: - diag - the diagonal values, including ghost ones
9594: Level: developer
9596: Notes:
9597: Works only for `MATMPIAIJ` and `MATMPIBAIJ` matrices
9599: This allows one to avoid during communication to perform the scaling that must be done with `MatDiagonalScale()`
9601: .seealso: [](ch_matrices), `Mat`, `MatDiagonalScale()`
9602: @*/
9603: PetscErrorCode MatDiagonalScaleLocal(Mat mat, Vec diag)
9604: {
9605: PetscMPIInt size;
9607: PetscFunctionBegin;
9612: PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Matrix must be already assembled");
9613: PetscCall(PetscLogEventBegin(MAT_Scale, mat, 0, 0, 0));
9614: PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)mat), &size));
9615: if (size == 1) {
9616: PetscInt n, m;
9617: PetscCall(VecGetSize(diag, &n));
9618: PetscCall(MatGetSize(mat, NULL, &m));
9619: PetscCheck(m == n, PETSC_COMM_SELF, PETSC_ERR_SUP, "Only supported for sequential matrices when no ghost points/periodic conditions");
9620: PetscCall(MatDiagonalScale(mat, NULL, diag));
9621: } else PetscUseMethod(mat, "MatDiagonalScaleLocal_C", (Mat, Vec), (mat, diag));
9622: PetscCall(PetscLogEventEnd(MAT_Scale, mat, 0, 0, 0));
9623: PetscCall(PetscObjectStateIncrease((PetscObject)mat));
9624: PetscFunctionReturn(PETSC_SUCCESS);
9625: }
9627: /*@
9628: MatGetInertia - Gets the inertia from a factored matrix
9630: Collective
9632: Input Parameter:
9633: . mat - the matrix
9635: Output Parameters:
9636: + nneg - number of negative eigenvalues
9637: . nzero - number of zero eigenvalues
9638: - npos - number of positive eigenvalues
9640: Level: advanced
9642: Note:
9643: Matrix must have been factored by `MatCholeskyFactor()`
9645: .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatCholeskyFactor()`
9646: @*/
9647: PetscErrorCode MatGetInertia(Mat mat, PetscInt *nneg, PetscInt *nzero, PetscInt *npos)
9648: {
9649: PetscFunctionBegin;
9652: PetscCheck(mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Unfactored matrix");
9653: PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Numeric factor mat is not assembled");
9654: PetscUseTypeMethod(mat, getinertia, nneg, nzero, npos);
9655: PetscFunctionReturn(PETSC_SUCCESS);
9656: }
9658: /*@C
9659: MatSolves - Solves $A x = b$, given a factored matrix, for a collection of vectors
9661: Neighbor-wise Collective
9663: Input Parameters:
9664: + mat - the factored matrix obtained with `MatGetFactor()`
9665: - b - the right-hand-side vectors
9667: Output Parameter:
9668: . x - the result vectors
9670: Level: developer
9672: Note:
9673: The vectors `b` and `x` cannot be the same. I.e., one cannot
9674: call `MatSolves`(A,x,x).
9676: .seealso: [](ch_matrices), `Mat`, `Vecs`, `MatSolveAdd()`, `MatSolveTranspose()`, `MatSolveTransposeAdd()`, `MatSolve()`
9677: @*/
9678: PetscErrorCode MatSolves(Mat mat, Vecs b, Vecs x)
9679: {
9680: PetscFunctionBegin;
9683: PetscCheck(x != b, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_IDN, "x and b must be different vectors");
9684: PetscCheck(mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Unfactored matrix");
9685: if (!mat->rmap->N && !mat->cmap->N) PetscFunctionReturn(PETSC_SUCCESS);
9687: MatCheckPreallocated(mat, 1);
9688: PetscCall(PetscLogEventBegin(MAT_Solves, mat, 0, 0, 0));
9689: PetscUseTypeMethod(mat, solves, b, x);
9690: PetscCall(PetscLogEventEnd(MAT_Solves, mat, 0, 0, 0));
9691: PetscFunctionReturn(PETSC_SUCCESS);
9692: }
9694: /*@
9695: MatIsSymmetric - Test whether a matrix is symmetric
9697: Collective
9699: Input Parameters:
9700: + A - the matrix to test
9701: - tol - difference between value and its transpose less than this amount counts as equal (use 0.0 for exact transpose)
9703: Output Parameter:
9704: . flg - the result
9706: Level: intermediate
9708: Notes:
9709: For real numbers `MatIsSymmetric()` and `MatIsHermitian()` return identical results
9711: If the matrix does not yet know if it is symmetric or not this can be an expensive operation, also available `MatIsSymmetricKnown()`
9713: One can declare that a matrix is symmetric with `MatSetOption`(mat,`MAT_SYMMETRIC`,`PETSC_TRUE`) and if it is known to remain symmetric
9714: after changes to the matrices values one can call `MatSetOption`(mat,`MAT_SYMMETRY_ETERNAL`,`PETSC_TRUE`)
9716: .seealso: [](ch_matrices), `Mat`, `MatTranspose()`, `MatIsTranspose()`, `MatIsHermitian()`, `MatIsStructurallySymmetric()`, `MatSetOption()`, `MatIsSymmetricKnown()`,
9717: `MAT_SYMMETRIC`, `MAT_SYMMETRY_ETERNAL`
9718: @*/
9719: PetscErrorCode MatIsSymmetric(Mat A, PetscReal tol, PetscBool *flg)
9720: {
9721: PetscFunctionBegin;
9723: PetscAssertPointer(flg, 3);
9724: if (A->symmetric != PETSC_BOOL3_UNKNOWN && !tol) *flg = PetscBool3ToBool(A->symmetric);
9725: else {
9726: if (A->ops->issymmetric) PetscUseTypeMethod(A, issymmetric, tol, flg);
9727: else PetscCall(MatIsTranspose(A, A, tol, flg));
9728: if (!tol) PetscCall(MatSetOption(A, MAT_SYMMETRIC, *flg));
9729: }
9730: PetscFunctionReturn(PETSC_SUCCESS);
9731: }
9733: /*@
9734: MatIsHermitian - Test whether a matrix is Hermitian
9736: Collective
9738: Input Parameters:
9739: + A - the matrix to test
9740: - tol - difference between value and its transpose less than this amount counts as equal (use 0.0 for exact Hermitian)
9742: Output Parameter:
9743: . flg - the result
9745: Level: intermediate
9747: Notes:
9748: For real numbers `MatIsSymmetric()` and `MatIsHermitian()` return identical results
9750: If the matrix does not yet know if it is Hermitian or not this can be an expensive operation, also available `MatIsHermitianKnown()`
9752: One can declare that a matrix is Hermitian with `MatSetOption`(mat,`MAT_HERMITIAN`,`PETSC_TRUE`) and if it is known to remain Hermitian
9753: after changes to the matrices values one can call `MatSetOption`(mat,`MAT_SYMEMTRY_ETERNAL`,`PETSC_TRUE`)
9755: .seealso: [](ch_matrices), `Mat`, `MatTranspose()`, `MatIsTranspose()`, `MatIsHermitianKnown()`, `MatIsStructurallySymmetric()`, `MatSetOption()`,
9756: `MatIsSymmetricKnown()`, `MatIsSymmetric()`, `MAT_HERMITIAN`, `MAT_SYMMETRY_ETERNAL`
9757: @*/
9758: PetscErrorCode MatIsHermitian(Mat A, PetscReal tol, PetscBool *flg)
9759: {
9760: PetscFunctionBegin;
9762: PetscAssertPointer(flg, 3);
9763: if (A->hermitian != PETSC_BOOL3_UNKNOWN && !tol) *flg = PetscBool3ToBool(A->hermitian);
9764: else {
9765: if (A->ops->ishermitian) PetscUseTypeMethod(A, ishermitian, tol, flg);
9766: else PetscCall(MatIsHermitianTranspose(A, A, tol, flg));
9767: if (!tol) PetscCall(MatSetOption(A, MAT_HERMITIAN, *flg));
9768: }
9769: PetscFunctionReturn(PETSC_SUCCESS);
9770: }
9772: /*@
9773: MatIsSymmetricKnown - Checks if a matrix knows if it is symmetric or not and its symmetric state
9775: Not Collective
9777: Input Parameter:
9778: . A - the matrix to check
9780: Output Parameters:
9781: + set - `PETSC_TRUE` if the matrix knows its symmetry state (this tells you if the next flag is valid)
9782: - flg - the result (only valid if set is `PETSC_TRUE`)
9784: Level: advanced
9786: Notes:
9787: Does not check the matrix values directly, so this may return unknown (set = `PETSC_FALSE`). Use `MatIsSymmetric()`
9788: if you want it explicitly checked
9790: One can declare that a matrix is symmetric with `MatSetOption`(mat,`MAT_SYMMETRIC`,`PETSC_TRUE`) and if it is known to remain symmetric
9791: after changes to the matrices values one can call `MatSetOption`(mat,`MAT_SYMMETRY_ETERNAL`,`PETSC_TRUE`)
9793: .seealso: [](ch_matrices), `Mat`, `MAT_SYMMETRY_ETERNAL`, `MatTranspose()`, `MatIsTranspose()`, `MatIsHermitian()`, `MatIsStructurallySymmetric()`, `MatSetOption()`, `MatIsSymmetric()`, `MatIsHermitianKnown()`
9794: @*/
9795: PetscErrorCode MatIsSymmetricKnown(Mat A, PetscBool *set, PetscBool *flg)
9796: {
9797: PetscFunctionBegin;
9799: PetscAssertPointer(set, 2);
9800: PetscAssertPointer(flg, 3);
9801: if (A->symmetric != PETSC_BOOL3_UNKNOWN) {
9802: *set = PETSC_TRUE;
9803: *flg = PetscBool3ToBool(A->symmetric);
9804: } else *set = PETSC_FALSE;
9805: PetscFunctionReturn(PETSC_SUCCESS);
9806: }
9808: /*@
9809: MatIsSPDKnown - Checks if a matrix knows if it is symmetric positive definite or not and its symmetric positive definite state
9811: Not Collective
9813: Input Parameter:
9814: . A - the matrix to check
9816: Output Parameters:
9817: + set - `PETSC_TRUE` if the matrix knows its symmetric positive definite state (this tells you if the next flag is valid)
9818: - flg - the result (only valid if set is `PETSC_TRUE`)
9820: Level: advanced
9822: Notes:
9823: Does not check the matrix values directly, so this may return unknown (set = `PETSC_FALSE`).
9825: One can declare that a matrix is SPD with `MatSetOption`(mat,`MAT_SPD`,`PETSC_TRUE`) and if it is known to remain SPD
9826: after changes to the matrices values one can call `MatSetOption`(mat,`MAT_SPD_ETERNAL`,`PETSC_TRUE`)
9828: .seealso: [](ch_matrices), `Mat`, `MAT_SPD_ETERNAL`, `MAT_SPD`, `MatTranspose()`, `MatIsTranspose()`, `MatIsHermitian()`, `MatIsStructurallySymmetric()`, `MatSetOption()`, `MatIsSymmetric()`, `MatIsHermitianKnown()`
9829: @*/
9830: PetscErrorCode MatIsSPDKnown(Mat A, PetscBool *set, PetscBool *flg)
9831: {
9832: PetscFunctionBegin;
9834: PetscAssertPointer(set, 2);
9835: PetscAssertPointer(flg, 3);
9836: if (A->spd != PETSC_BOOL3_UNKNOWN) {
9837: *set = PETSC_TRUE;
9838: *flg = PetscBool3ToBool(A->spd);
9839: } else *set = PETSC_FALSE;
9840: PetscFunctionReturn(PETSC_SUCCESS);
9841: }
9843: /*@
9844: MatIsHermitianKnown - Checks if a matrix knows if it is Hermitian or not and its Hermitian state
9846: Not Collective
9848: Input Parameter:
9849: . A - the matrix to check
9851: Output Parameters:
9852: + set - `PETSC_TRUE` if the matrix knows its Hermitian state (this tells you if the next flag is valid)
9853: - flg - the result (only valid if set is `PETSC_TRUE`)
9855: Level: advanced
9857: Notes:
9858: Does not check the matrix values directly, so this may return unknown (set = `PETSC_FALSE`). Use `MatIsHermitian()`
9859: if you want it explicitly checked
9861: One can declare that a matrix is Hermitian with `MatSetOption`(mat,`MAT_HERMITIAN`,`PETSC_TRUE`) and if it is known to remain Hermitian
9862: after changes to the matrices values one can call `MatSetOption`(mat,`MAT_SYMMETRY_ETERNAL`,`PETSC_TRUE`)
9864: .seealso: [](ch_matrices), `Mat`, `MAT_SYMMETRY_ETERNAL`, `MAT_HERMITIAN`, `MatTranspose()`, `MatIsTranspose()`, `MatIsHermitian()`, `MatIsStructurallySymmetric()`, `MatSetOption()`, `MatIsSymmetric()`
9865: @*/
9866: PetscErrorCode MatIsHermitianKnown(Mat A, PetscBool *set, PetscBool *flg)
9867: {
9868: PetscFunctionBegin;
9870: PetscAssertPointer(set, 2);
9871: PetscAssertPointer(flg, 3);
9872: if (A->hermitian != PETSC_BOOL3_UNKNOWN) {
9873: *set = PETSC_TRUE;
9874: *flg = PetscBool3ToBool(A->hermitian);
9875: } else *set = PETSC_FALSE;
9876: PetscFunctionReturn(PETSC_SUCCESS);
9877: }
9879: /*@
9880: MatIsStructurallySymmetric - Test whether a matrix is structurally symmetric
9882: Collective
9884: Input Parameter:
9885: . A - the matrix to test
9887: Output Parameter:
9888: . flg - the result
9890: Level: intermediate
9892: Notes:
9893: If the matrix does yet know it is structurally symmetric this can be an expensive operation, also available `MatIsStructurallySymmetricKnown()`
9895: 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
9896: symmetric after changes to the matrices values one can call `MatSetOption`(mat,`MAT_STRUCTURAL_SYMMETRY_ETERNAL`,`PETSC_TRUE`)
9898: .seealso: [](ch_matrices), `Mat`, `MAT_STRUCTURALLY_SYMMETRIC`, `MAT_STRUCTURAL_SYMMETRY_ETERNAL`, `MatTranspose()`, `MatIsTranspose()`, `MatIsHermitian()`, `MatIsSymmetric()`, `MatSetOption()`, `MatIsStructurallySymmetricKnown()`
9899: @*/
9900: PetscErrorCode MatIsStructurallySymmetric(Mat A, PetscBool *flg)
9901: {
9902: PetscFunctionBegin;
9904: PetscAssertPointer(flg, 2);
9905: if (A->structurally_symmetric != PETSC_BOOL3_UNKNOWN) *flg = PetscBool3ToBool(A->structurally_symmetric);
9906: else {
9907: PetscUseTypeMethod(A, isstructurallysymmetric, flg);
9908: PetscCall(MatSetOption(A, MAT_STRUCTURALLY_SYMMETRIC, *flg));
9909: }
9910: PetscFunctionReturn(PETSC_SUCCESS);
9911: }
9913: /*@
9914: MatIsStructurallySymmetricKnown - Checks if a matrix knows if it is structurally symmetric or not and its structurally symmetric state
9916: Not Collective
9918: Input Parameter:
9919: . A - the matrix to check
9921: Output Parameters:
9922: + set - PETSC_TRUE if the matrix knows its structurally symmetric state (this tells you if the next flag is valid)
9923: - flg - the result (only valid if set is PETSC_TRUE)
9925: Level: advanced
9927: Notes:
9928: 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
9929: symmetric after changes to the matrices values one can call `MatSetOption`(mat,`MAT_STRUCTURAL_SYMMETRY_ETERNAL`,`PETSC_TRUE`)
9931: Use `MatIsStructurallySymmetric()` to explicitly check if a matrix is structurally symmetric (this is an expensive operation)
9933: .seealso: [](ch_matrices), `Mat`, `MAT_STRUCTURALLY_SYMMETRIC`, `MatTranspose()`, `MatIsTranspose()`, `MatIsHermitian()`, `MatIsStructurallySymmetric()`, `MatSetOption()`, `MatIsSymmetric()`, `MatIsHermitianKnown()`
9934: @*/
9935: PetscErrorCode MatIsStructurallySymmetricKnown(Mat A, PetscBool *set, PetscBool *flg)
9936: {
9937: PetscFunctionBegin;
9939: PetscAssertPointer(set, 2);
9940: PetscAssertPointer(flg, 3);
9941: if (A->structurally_symmetric != PETSC_BOOL3_UNKNOWN) {
9942: *set = PETSC_TRUE;
9943: *flg = PetscBool3ToBool(A->structurally_symmetric);
9944: } else *set = PETSC_FALSE;
9945: PetscFunctionReturn(PETSC_SUCCESS);
9946: }
9948: /*@
9949: MatStashGetInfo - Gets how many values are currently in the matrix stash, i.e. need
9950: to be communicated to other processors during the `MatAssemblyBegin()`/`MatAssemblyEnd()` process
9952: Not Collective
9954: Input Parameter:
9955: . mat - the matrix
9957: Output Parameters:
9958: + nstash - the size of the stash
9959: . reallocs - the number of additional mallocs incurred.
9960: . bnstash - the size of the block stash
9961: - breallocs - the number of additional mallocs incurred.in the block stash
9963: Level: advanced
9965: .seealso: [](ch_matrices), `MatAssemblyBegin()`, `MatAssemblyEnd()`, `Mat`, `MatStashSetInitialSize()`
9966: @*/
9967: PetscErrorCode MatStashGetInfo(Mat mat, PetscInt *nstash, PetscInt *reallocs, PetscInt *bnstash, PetscInt *breallocs)
9968: {
9969: PetscFunctionBegin;
9970: PetscCall(MatStashGetInfo_Private(&mat->stash, nstash, reallocs));
9971: PetscCall(MatStashGetInfo_Private(&mat->bstash, bnstash, breallocs));
9972: PetscFunctionReturn(PETSC_SUCCESS);
9973: }
9975: /*@
9976: MatCreateVecs - Get vector(s) compatible with the matrix, i.e. with the same
9977: parallel layout, `PetscLayout` for rows and columns
9979: Collective
9981: Input Parameter:
9982: . mat - the matrix
9984: Output Parameters:
9985: + right - (optional) vector that the matrix can be multiplied against
9986: - left - (optional) vector that the matrix vector product can be stored in
9988: Options Database Key:
9989: . -mat_vec_type type - set the `VecType` of the created vectors during `MatSetFromOptions()`
9991: Level: advanced
9993: Notes:
9994: 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()`.
9996: The `VecType` of the created vectors is determined by the `MatType` of `mat`. This can be overridden by using `MatSetVecType()` or the option `-mat_vec_type`.
9998: These are new vectors which are not owned by the `mat`, they should be destroyed with `VecDestroy()` when no longer needed.
10000: PETSc `Vec` always have all zero entries when created with `MatCreateVecs()` until routines such as `VecSet()` or `VecSetValues()`
10001: are used to change the values. There is no reason to call `VecZeroEntries()` after creation.
10003: .seealso: [](ch_matrices), `Mat`, `Vec`, `VecCreate()`, `VecDestroy()`, `DMCreateGlobalVector()`, `MatSetVecType()`
10004: @*/
10005: PetscErrorCode MatCreateVecs(Mat mat, Vec *right, Vec *left)
10006: {
10007: PetscFunctionBegin;
10010: if (mat->ops->getvecs) {
10011: PetscUseTypeMethod(mat, getvecs, right, left);
10012: } else {
10013: if (right) {
10014: PetscCheck(mat->cmap->n >= 0, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "PetscLayout for columns not yet setup");
10015: PetscCall(VecCreateWithLayout_Private(mat->cmap, right));
10016: PetscCall(VecSetType(*right, mat->defaultvectype));
10017: #if defined(PETSC_HAVE_VIENNACL) || defined(PETSC_HAVE_CUDA) || defined(PETSC_HAVE_HIP)
10018: if (mat->boundtocpu && mat->bindingpropagates) {
10019: PetscCall(VecSetBindingPropagates(*right, PETSC_TRUE));
10020: PetscCall(VecBindToCPU(*right, PETSC_TRUE));
10021: }
10022: #endif
10023: }
10024: if (left) {
10025: PetscCheck(mat->rmap->n >= 0, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "PetscLayout for rows not yet setup");
10026: PetscCall(VecCreateWithLayout_Private(mat->rmap, left));
10027: PetscCall(VecSetType(*left, mat->defaultvectype));
10028: #if defined(PETSC_HAVE_VIENNACL) || defined(PETSC_HAVE_CUDA) || defined(PETSC_HAVE_HIP)
10029: if (mat->boundtocpu && mat->bindingpropagates) {
10030: PetscCall(VecSetBindingPropagates(*left, PETSC_TRUE));
10031: PetscCall(VecBindToCPU(*left, PETSC_TRUE));
10032: }
10033: #endif
10034: }
10035: }
10036: PetscFunctionReturn(PETSC_SUCCESS);
10037: }
10039: /*@
10040: MatFactorInfoInitialize - Initializes a `MatFactorInfo` data structure
10041: with default values.
10043: Not Collective
10045: Input Parameter:
10046: . info - the `MatFactorInfo` data structure
10048: Level: developer
10050: Notes:
10051: The solvers are generally used through the `KSP` and `PC` objects, for example
10052: `PCLU`, `PCILU`, `PCCHOLESKY`, `PCICC`
10054: Once the data structure is initialized one may change certain entries as desired for the particular factorization to be performed
10056: .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatFactorInfo`
10057: @*/
10058: PetscErrorCode MatFactorInfoInitialize(MatFactorInfo *info)
10059: {
10060: PetscFunctionBegin;
10061: PetscCall(PetscMemzero(info, sizeof(MatFactorInfo)));
10062: PetscFunctionReturn(PETSC_SUCCESS);
10063: }
10065: /*@
10066: MatFactorSetSchurIS - Set indices corresponding to the Schur complement you wish to have computed
10068: Collective
10070: Input Parameters:
10071: + mat - the factored matrix
10072: - is - the index set defining the Schur indices (0-based)
10074: Level: advanced
10076: Notes:
10077: Call `MatFactorSolveSchurComplement()` or `MatFactorSolveSchurComplementTranspose()` after this call to solve a Schur complement system.
10079: You can call `MatFactorGetSchurComplement()` or `MatFactorCreateSchurComplement()` after this call.
10081: This functionality is only supported for `MATSOLVERMUMPS` and `MATSOLVERMKL_PARDISO`
10083: .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatFactorGetSchurComplement()`, `MatFactorRestoreSchurComplement()`, `MatFactorCreateSchurComplement()`, `MatFactorSolveSchurComplement()`,
10084: `MatFactorSolveSchurComplementTranspose()`, `MATSOLVERMUMPS`, `MATSOLVERMKL_PARDISO`
10085: @*/
10086: PetscErrorCode MatFactorSetSchurIS(Mat mat, IS is)
10087: {
10088: PetscErrorCode (*f)(Mat, IS);
10090: PetscFunctionBegin;
10095: PetscCheckSameComm(mat, 1, is, 2);
10096: PetscCheck(mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Only for factored matrix");
10097: PetscCall(PetscObjectQueryFunction((PetscObject)mat, "MatFactorSetSchurIS_C", &f));
10098: PetscCheck(f, PetscObjectComm((PetscObject)mat), PETSC_ERR_SUP, "The selected MatSolverType does not support Schur complement computation. You should use MATSOLVERMUMPS or MATSOLVERMKL_PARDISO");
10099: PetscCall((*f)(mat, is));
10100: PetscCheck(mat->schur, PetscObjectComm((PetscObject)mat), PETSC_ERR_PLIB, "Schur complement has not been created");
10101: PetscFunctionReturn(PETSC_SUCCESS);
10102: }
10104: /*@
10105: MatFactorCreateSchurComplement - Create a Schur complement matrix object using Schur data computed during the factorization step
10107: Logically Collective
10109: Input Parameters:
10110: + F - the factored matrix obtained by calling `MatGetFactor()`
10111: . S - location where to return the Schur complement, can be `NULL`
10112: - status - the status of the Schur complement matrix, can be `NULL`
10114: Level: advanced
10116: Notes:
10117: You must call `MatFactorSetSchurIS()` before calling this routine.
10119: This functionality is only supported for `MATSOLVERMUMPS` and `MATSOLVERMKL_PARDISO`
10121: The routine provides a copy of the Schur matrix stored within the solver data structures.
10122: The caller must destroy the object when it is no longer needed.
10123: If `MatFactorInvertSchurComplement()` has been called, the routine gets back the inverse.
10125: 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)
10127: See `MatCreateSchurComplement()` or `MatGetSchurComplement()` for ways to create virtual or approximate Schur complements.
10129: Developer Note:
10130: The reason this routine exists is because the representation of the Schur complement within the factor matrix may be different than a standard PETSc
10131: matrix representation and we normally do not want to use the time or memory to make a copy as a regular PETSc matrix.
10133: .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatFactorSetSchurIS()`, `MatFactorGetSchurComplement()`, `MatFactorSchurStatus`, `MATSOLVERMUMPS`, `MATSOLVERMKL_PARDISO`
10134: @*/
10135: PetscErrorCode MatFactorCreateSchurComplement(Mat F, Mat *S, MatFactorSchurStatus *status)
10136: {
10137: PetscFunctionBegin;
10139: if (S) PetscAssertPointer(S, 2);
10140: if (status) PetscAssertPointer(status, 3);
10141: if (S) {
10142: PetscErrorCode (*f)(Mat, Mat *);
10144: PetscCall(PetscObjectQueryFunction((PetscObject)F, "MatFactorCreateSchurComplement_C", &f));
10145: if (f) PetscCall((*f)(F, S));
10146: else PetscCall(MatDuplicate(F->schur, MAT_COPY_VALUES, S));
10147: }
10148: if (status) *status = F->schur_status;
10149: PetscFunctionReturn(PETSC_SUCCESS);
10150: }
10152: /*@
10153: MatFactorGetSchurComplement - Gets access to a Schur complement matrix using the current Schur data within a factored matrix
10155: Logically Collective
10157: Input Parameters:
10158: + F - the factored matrix obtained by calling `MatGetFactor()`
10159: . S - location where to return the Schur complement, can be `NULL`
10160: - status - the status of the Schur complement matrix, can be `NULL`
10162: Level: advanced
10164: Notes:
10165: You must call `MatFactorSetSchurIS()` before calling this routine.
10167: Schur complement mode is currently implemented for sequential matrices with factor type of `MATSOLVERMUMPS`
10169: The routine returns a the Schur Complement stored within the data structures of the solver.
10171: If `MatFactorInvertSchurComplement()` has previously been called, the returned matrix is actually the inverse of the Schur complement.
10173: The returned matrix should not be destroyed; the caller should call `MatFactorRestoreSchurComplement()` when the object is no longer needed.
10175: Use `MatFactorCreateSchurComplement()` to create a copy of the Schur complement matrix that is within a factored matrix
10177: See `MatCreateSchurComplement()` or `MatGetSchurComplement()` for ways to create virtual or approximate Schur complements.
10179: .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatFactorSetSchurIS()`, `MatFactorRestoreSchurComplement()`, `MatFactorCreateSchurComplement()`, `MatFactorSchurStatus`
10180: @*/
10181: PetscErrorCode MatFactorGetSchurComplement(Mat F, Mat *S, MatFactorSchurStatus *status)
10182: {
10183: PetscFunctionBegin;
10185: if (S) {
10186: PetscAssertPointer(S, 2);
10187: *S = F->schur;
10188: }
10189: if (status) {
10190: PetscAssertPointer(status, 3);
10191: *status = F->schur_status;
10192: }
10193: PetscFunctionReturn(PETSC_SUCCESS);
10194: }
10196: static PetscErrorCode MatFactorUpdateSchurStatus_Private(Mat F)
10197: {
10198: Mat S = F->schur;
10200: PetscFunctionBegin;
10201: switch (F->schur_status) {
10202: case MAT_FACTOR_SCHUR_UNFACTORED: // fall-through
10203: case MAT_FACTOR_SCHUR_INVERTED:
10204: if (S) {
10205: S->ops->solve = NULL;
10206: S->ops->matsolve = NULL;
10207: S->ops->solvetranspose = NULL;
10208: S->ops->matsolvetranspose = NULL;
10209: S->ops->solveadd = NULL;
10210: S->ops->solvetransposeadd = NULL;
10211: S->factortype = MAT_FACTOR_NONE;
10212: PetscCall(PetscFree(S->solvertype));
10213: }
10214: case MAT_FACTOR_SCHUR_FACTORED: // fall-through
10215: break;
10216: default:
10217: SETERRQ(PetscObjectComm((PetscObject)F), PETSC_ERR_SUP, "Unhandled MatFactorSchurStatus %d", F->schur_status);
10218: }
10219: PetscFunctionReturn(PETSC_SUCCESS);
10220: }
10222: /*@
10223: MatFactorRestoreSchurComplement - Restore the Schur complement matrix object obtained from a call to `MatFactorGetSchurComplement()`
10225: Logically Collective
10227: Input Parameters:
10228: + F - the factored matrix obtained by calling `MatGetFactor()`
10229: . S - location where the Schur complement is stored
10230: - status - the status of the Schur complement matrix (see `MatFactorSchurStatus`)
10232: Level: advanced
10234: .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatFactorSetSchurIS()`, `MatFactorCreateSchurComplement()`, `MatFactorSchurStatus`
10235: @*/
10236: PetscErrorCode MatFactorRestoreSchurComplement(Mat F, Mat *S, MatFactorSchurStatus status)
10237: {
10238: PetscFunctionBegin;
10240: if (S) {
10242: *S = NULL;
10243: }
10244: F->schur_status = status;
10245: PetscCall(MatFactorUpdateSchurStatus_Private(F));
10246: PetscFunctionReturn(PETSC_SUCCESS);
10247: }
10249: /*@
10250: MatFactorSolveSchurComplementTranspose - Solve the transpose of the Schur complement system computed during the factorization step
10252: Logically Collective
10254: Input Parameters:
10255: + F - the factored matrix obtained by calling `MatGetFactor()`
10256: . rhs - location where the right-hand side of the Schur complement system is stored
10257: - sol - location where the solution of the Schur complement system has to be returned
10259: Level: advanced
10261: Notes:
10262: The sizes of the vectors should match the size of the Schur complement
10264: Must be called after `MatFactorSetSchurIS()`
10266: .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatFactorSetSchurIS()`, `MatFactorSolveSchurComplement()`
10267: @*/
10268: PetscErrorCode MatFactorSolveSchurComplementTranspose(Mat F, Vec rhs, Vec sol)
10269: {
10270: PetscFunctionBegin;
10277: PetscCheckSameComm(F, 1, rhs, 2);
10278: PetscCheckSameComm(F, 1, sol, 3);
10279: PetscCall(MatFactorFactorizeSchurComplement(F));
10280: switch (F->schur_status) {
10281: case MAT_FACTOR_SCHUR_FACTORED:
10282: PetscCall(MatSolveTranspose(F->schur, rhs, sol));
10283: break;
10284: case MAT_FACTOR_SCHUR_INVERTED:
10285: PetscCall(MatMultTranspose(F->schur, rhs, sol));
10286: break;
10287: default:
10288: SETERRQ(PetscObjectComm((PetscObject)F), PETSC_ERR_SUP, "Unhandled MatFactorSchurStatus %d", F->schur_status);
10289: }
10290: PetscFunctionReturn(PETSC_SUCCESS);
10291: }
10293: /*@
10294: MatFactorSolveSchurComplement - Solve the Schur complement system computed during the factorization step
10296: Logically Collective
10298: Input Parameters:
10299: + F - the factored matrix obtained by calling `MatGetFactor()`
10300: . rhs - location where the right-hand side of the Schur complement system is stored
10301: - sol - location where the solution of the Schur complement system has to be returned
10303: Level: advanced
10305: Notes:
10306: The sizes of the vectors should match the size of the Schur complement
10308: Must be called after `MatFactorSetSchurIS()`
10310: .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatFactorSetSchurIS()`, `MatFactorSolveSchurComplementTranspose()`
10311: @*/
10312: PetscErrorCode MatFactorSolveSchurComplement(Mat F, Vec rhs, Vec sol)
10313: {
10314: PetscFunctionBegin;
10321: PetscCheckSameComm(F, 1, rhs, 2);
10322: PetscCheckSameComm(F, 1, sol, 3);
10323: PetscCall(MatFactorFactorizeSchurComplement(F));
10324: switch (F->schur_status) {
10325: case MAT_FACTOR_SCHUR_FACTORED:
10326: PetscCall(MatSolve(F->schur, rhs, sol));
10327: break;
10328: case MAT_FACTOR_SCHUR_INVERTED:
10329: PetscCall(MatMult(F->schur, rhs, sol));
10330: break;
10331: default:
10332: SETERRQ(PetscObjectComm((PetscObject)F), PETSC_ERR_SUP, "Unhandled MatFactorSchurStatus %d", F->schur_status);
10333: }
10334: PetscFunctionReturn(PETSC_SUCCESS);
10335: }
10337: PETSC_SINGLE_LIBRARY_INTERN PetscErrorCode MatSeqDenseInvertFactors_Private(Mat);
10338: #if PetscDefined(HAVE_CUDA)
10339: PETSC_SINGLE_LIBRARY_INTERN PetscErrorCode MatSeqDenseCUDAInvertFactors_Internal(Mat);
10340: #endif
10342: /* Schur status updated in the interface */
10343: static PetscErrorCode MatFactorInvertSchurComplement_Private(Mat F)
10344: {
10345: Mat S = F->schur;
10347: PetscFunctionBegin;
10348: if (S) {
10349: PetscMPIInt size;
10350: PetscBool isdense, isdensecuda;
10352: PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)S), &size));
10353: PetscCheck(size <= 1, PetscObjectComm((PetscObject)S), PETSC_ERR_SUP, "Not yet implemented");
10354: PetscCall(PetscObjectTypeCompare((PetscObject)S, MATSEQDENSE, &isdense));
10355: PetscCall(PetscObjectTypeCompare((PetscObject)S, MATSEQDENSECUDA, &isdensecuda));
10356: PetscCheck(isdense || isdensecuda, PetscObjectComm((PetscObject)S), PETSC_ERR_SUP, "Not implemented for type %s", ((PetscObject)S)->type_name);
10357: PetscCall(PetscLogEventBegin(MAT_FactorInvS, F, 0, 0, 0));
10358: if (isdense) {
10359: PetscCall(MatSeqDenseInvertFactors_Private(S));
10360: } else if (isdensecuda) {
10361: #if defined(PETSC_HAVE_CUDA)
10362: PetscCall(MatSeqDenseCUDAInvertFactors_Internal(S));
10363: #endif
10364: }
10365: // HIP??????????????
10366: PetscCall(PetscLogEventEnd(MAT_FactorInvS, F, 0, 0, 0));
10367: }
10368: PetscFunctionReturn(PETSC_SUCCESS);
10369: }
10371: /*@
10372: MatFactorInvertSchurComplement - Invert the Schur complement matrix computed during the factorization step
10374: Logically Collective
10376: Input Parameter:
10377: . F - the factored matrix obtained by calling `MatGetFactor()`
10379: Level: advanced
10381: Notes:
10382: Must be called after `MatFactorSetSchurIS()`.
10384: Call `MatFactorGetSchurComplement()` or `MatFactorCreateSchurComplement()` AFTER this call to actually compute the inverse and get access to it.
10386: .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatFactorSetSchurIS()`, `MatFactorGetSchurComplement()`, `MatFactorCreateSchurComplement()`
10387: @*/
10388: PetscErrorCode MatFactorInvertSchurComplement(Mat F)
10389: {
10390: PetscFunctionBegin;
10393: if (F->schur_status == MAT_FACTOR_SCHUR_INVERTED) PetscFunctionReturn(PETSC_SUCCESS);
10394: PetscCall(MatFactorFactorizeSchurComplement(F));
10395: PetscCall(MatFactorInvertSchurComplement_Private(F));
10396: F->schur_status = MAT_FACTOR_SCHUR_INVERTED;
10397: PetscFunctionReturn(PETSC_SUCCESS);
10398: }
10400: /*@
10401: MatFactorFactorizeSchurComplement - Factorize the Schur complement matrix computed during the factorization step
10403: Logically Collective
10405: Input Parameter:
10406: . F - the factored matrix obtained by calling `MatGetFactor()`
10408: Level: advanced
10410: Note:
10411: Must be called after `MatFactorSetSchurIS()`
10413: .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatFactorSetSchurIS()`, `MatFactorInvertSchurComplement()`
10414: @*/
10415: PetscErrorCode MatFactorFactorizeSchurComplement(Mat F)
10416: {
10417: MatFactorInfo info;
10419: PetscFunctionBegin;
10422: if (F->schur_status == MAT_FACTOR_SCHUR_INVERTED || F->schur_status == MAT_FACTOR_SCHUR_FACTORED) PetscFunctionReturn(PETSC_SUCCESS);
10423: PetscCall(PetscLogEventBegin(MAT_FactorFactS, F, 0, 0, 0));
10424: PetscCall(PetscMemzero(&info, sizeof(MatFactorInfo)));
10425: if (F->factortype == MAT_FACTOR_CHOLESKY) { /* LDL^t regarded as Cholesky */
10426: PetscCall(MatCholeskyFactor(F->schur, NULL, &info));
10427: } else {
10428: PetscCall(MatLUFactor(F->schur, NULL, NULL, &info));
10429: }
10430: PetscCall(PetscLogEventEnd(MAT_FactorFactS, F, 0, 0, 0));
10431: F->schur_status = MAT_FACTOR_SCHUR_FACTORED;
10432: PetscFunctionReturn(PETSC_SUCCESS);
10433: }
10435: /*@
10436: MatPtAP - Creates the matrix product $C = P^T * A * P$
10438: Neighbor-wise Collective
10440: Input Parameters:
10441: + A - the matrix
10442: . P - the projection matrix
10443: . scall - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`
10444: - 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
10445: if the result is a dense matrix this is irrelevant
10447: Output Parameter:
10448: . C - the product matrix
10450: Level: intermediate
10452: Notes:
10453: `C` will be created and must be destroyed by the user with `MatDestroy()`.
10455: This is a convenience routine that wraps the use of the `MatProductCreate()` with a `MatProductType` of `MATPRODUCT_PtAP`
10456: functionality into a single function call. For more involved matrix-matrix operations see `MatProductCreate()`.
10458: The deprecated `PETSC_DEFAULT` in `fill` also means use the current value
10460: Developer Note:
10461: For matrix types without special implementation the function fallbacks to `MatMatMult()` followed by `MatTransposeMatMult()`.
10463: .seealso: [](ch_matrices), `Mat`, `MatProductCreate()`, `MatMatMult()`, `MatRARt()`
10464: @*/
10465: PetscErrorCode MatPtAP(Mat A, Mat P, MatReuse scall, PetscReal fill, Mat *C)
10466: {
10467: PetscFunctionBegin;
10468: if (scall == MAT_REUSE_MATRIX) MatCheckProduct(*C, 5);
10469: PetscCheck(scall != MAT_INPLACE_MATRIX, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "Inplace product not supported");
10471: if (scall == MAT_INITIAL_MATRIX) {
10472: PetscCall(MatProductCreate(A, P, NULL, C));
10473: PetscCall(MatProductSetType(*C, MATPRODUCT_PtAP));
10474: PetscCall(MatProductSetAlgorithm(*C, "default"));
10475: PetscCall(MatProductSetFill(*C, fill));
10477: (*C)->product->api_user = PETSC_TRUE;
10478: PetscCall(MatProductSetFromOptions(*C));
10479: 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);
10480: PetscCall(MatProductSymbolic(*C));
10481: } else { /* scall == MAT_REUSE_MATRIX */
10482: PetscCall(MatProductReplaceMats(A, P, NULL, *C));
10483: }
10485: PetscCall(MatProductNumeric(*C));
10486: if (A->symmetric == PETSC_BOOL3_TRUE) {
10487: PetscCall(MatSetOption(*C, MAT_SYMMETRIC, PETSC_TRUE));
10488: (*C)->spd = A->spd;
10489: }
10490: PetscFunctionReturn(PETSC_SUCCESS);
10491: }
10493: /*@
10494: MatRARt - Creates the matrix product $C = R * A * R^T$
10496: Neighbor-wise Collective
10498: Input Parameters:
10499: + A - the matrix
10500: . R - the projection matrix
10501: . scall - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`
10502: - fill - expected fill as ratio of nnz(C)/nnz(A), use `PETSC_DETERMINE` or `PETSC_CURRENT` if you do not have a good estimate
10503: if the result is a dense matrix this is irrelevant
10505: Output Parameter:
10506: . C - the product matrix
10508: Level: intermediate
10510: Notes:
10511: `C` will be created and must be destroyed by the user with `MatDestroy()`.
10513: This is a convenience routine that wraps the use of the `MatProductCreate()` with a `MatProductType` of `MATPRODUCT_RARt`
10514: functionality into a single function call. For more involved matrix-matrix operations see `MatProductCreate()`.
10516: This routine is currently only implemented for pairs of `MATAIJ` matrices and classes
10517: which inherit from `MATAIJ`. Due to PETSc sparse matrix block row distribution among processes,
10518: the parallel `MatRARt()` is implemented computing the explicit transpose of `R`, which can be very expensive.
10519: We recommend using `MatPtAP()` when possible.
10521: The deprecated `PETSC_DEFAULT` in `fill` also means use the current value
10523: .seealso: [](ch_matrices), `Mat`, `MatProductCreate()`, `MatMatMult()`, `MatPtAP()`
10524: @*/
10525: PetscErrorCode MatRARt(Mat A, Mat R, MatReuse scall, PetscReal fill, Mat *C)
10526: {
10527: PetscFunctionBegin;
10528: if (scall == MAT_REUSE_MATRIX) MatCheckProduct(*C, 5);
10529: PetscCheck(scall != MAT_INPLACE_MATRIX, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "Inplace product not supported");
10531: if (scall == MAT_INITIAL_MATRIX) {
10532: PetscCall(MatProductCreate(A, R, NULL, C));
10533: PetscCall(MatProductSetType(*C, MATPRODUCT_RARt));
10534: PetscCall(MatProductSetAlgorithm(*C, "default"));
10535: PetscCall(MatProductSetFill(*C, fill));
10537: (*C)->product->api_user = PETSC_TRUE;
10538: PetscCall(MatProductSetFromOptions(*C));
10539: 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);
10540: PetscCall(MatProductSymbolic(*C));
10541: } else { /* scall == MAT_REUSE_MATRIX */
10542: PetscCall(MatProductReplaceMats(A, R, NULL, *C));
10543: }
10545: PetscCall(MatProductNumeric(*C));
10546: if (A->symmetric == PETSC_BOOL3_TRUE) PetscCall(MatSetOption(*C, MAT_SYMMETRIC, PETSC_TRUE));
10547: PetscFunctionReturn(PETSC_SUCCESS);
10548: }
10550: static PetscErrorCode MatProduct_Private(Mat A, Mat B, MatReuse scall, PetscReal fill, MatProductType ptype, Mat *C)
10551: {
10552: PetscBool flg = PETSC_TRUE;
10554: PetscFunctionBegin;
10555: PetscCheck(scall != MAT_INPLACE_MATRIX, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "MAT_INPLACE_MATRIX product not supported");
10556: if (scall == MAT_INITIAL_MATRIX) {
10557: PetscCall(PetscInfo(A, "Calling MatProduct API with MAT_INITIAL_MATRIX and product type %s\n", MatProductTypes[ptype]));
10558: PetscCall(MatProductCreate(A, B, NULL, C));
10559: PetscCall(MatProductSetAlgorithm(*C, MATPRODUCTALGORITHMDEFAULT));
10560: PetscCall(MatProductSetFill(*C, fill));
10561: } else { /* scall == MAT_REUSE_MATRIX */
10562: Mat_Product *product = (*C)->product;
10564: PetscCall(PetscObjectBaseTypeCompareAny((PetscObject)*C, &flg, MATSEQDENSE, MATMPIDENSE, ""));
10565: if (flg && product && product->type != ptype) {
10566: PetscCall(MatProductClear(*C));
10567: product = NULL;
10568: }
10569: PetscCall(PetscInfo(A, "Calling MatProduct API with MAT_REUSE_MATRIX %s product present and product type %s\n", product ? "with" : "without", MatProductTypes[ptype]));
10570: if (!product) { /* user provide the dense matrix *C without calling MatProductCreate() or reusing it from previous calls */
10571: PetscCheck(flg, PetscObjectComm((PetscObject)*C), PETSC_ERR_SUP, "Call MatProductCreate() first");
10572: PetscCall(MatProductCreate_Private(A, B, NULL, *C));
10573: product = (*C)->product;
10574: product->fill = fill;
10575: product->clear = PETSC_TRUE;
10576: } else { /* user may change input matrices A or B when MAT_REUSE_MATRIX */
10577: flg = PETSC_FALSE;
10578: PetscCall(MatProductReplaceMats(A, B, NULL, *C));
10579: }
10580: }
10581: if (flg) {
10582: (*C)->product->api_user = PETSC_TRUE;
10583: PetscCall(MatProductSetType(*C, ptype));
10584: PetscCall(MatProductSetFromOptions(*C));
10585: PetscCall(MatProductSymbolic(*C));
10586: }
10587: PetscCall(MatProductNumeric(*C));
10588: PetscFunctionReturn(PETSC_SUCCESS);
10589: }
10591: /*@
10592: MatMatMult - Performs matrix-matrix multiplication $ C=A*B $.
10594: Neighbor-wise Collective
10596: Input Parameters:
10597: + A - the left matrix
10598: . B - the right matrix
10599: . scall - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`
10600: - 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
10601: if the result is a dense matrix this is irrelevant
10603: Output Parameter:
10604: . C - the product matrix
10606: Notes:
10607: Unless scall is `MAT_REUSE_MATRIX` C will be created.
10609: `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
10610: call to this function with `MAT_INITIAL_MATRIX`.
10612: To determine the correct fill value, run with `-info` and search for the string "Fill ratio" to see the value actually needed.
10614: 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`,
10615: rather than first having `MatMatMult()` create it for you. You can NEVER do this if the matrix `C` is sparse.
10617: The deprecated `PETSC_DEFAULT` in `fill` also means use the current value
10619: This is a convenience routine that wraps the use of the `MatProductCreate()` with a `MatProductType` of `MATPRODUCT_AB`
10620: functionality into a single function call. For more involved matrix-matrix operations see `MatProductCreate()`.
10622: Example of Usage:
10623: .vb
10624: MatProductCreate(A,B,NULL,&C);
10625: MatProductSetType(C,MATPRODUCT_AB);
10626: MatProductSymbolic(C);
10627: MatProductNumeric(C); // compute C=A * B
10628: MatProductReplaceMats(A1,B1,NULL,C); // compute C=A1 * B1
10629: MatProductNumeric(C);
10630: MatProductReplaceMats(A2,NULL,NULL,C); // compute C=A2 * B1
10631: MatProductNumeric(C);
10632: .ve
10634: Level: intermediate
10636: .seealso: [](ch_matrices), `Mat`, `MatProductType`, `MATPRODUCT_AB`, `MatTransposeMatMult()`, `MatMatTransposeMult()`, `MatPtAP()`, `MatProductCreate()`, `MatProductSymbolic()`, `MatProductReplaceMats()`, `MatProductNumeric()`
10637: @*/
10638: PetscErrorCode MatMatMult(Mat A, Mat B, MatReuse scall, PetscReal fill, Mat *C)
10639: {
10640: PetscFunctionBegin;
10641: PetscCall(MatProduct_Private(A, B, scall, fill, MATPRODUCT_AB, C));
10642: PetscFunctionReturn(PETSC_SUCCESS);
10643: }
10645: /*@
10646: MatMatTransposeMult - Performs matrix-matrix multiplication $C = A*B^T$.
10648: Neighbor-wise Collective
10650: Input Parameters:
10651: + A - the left matrix
10652: . B - the right matrix
10653: . scall - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`
10654: - fill - expected fill as ratio of nnz(C)/(nnz(A) + nnz(B)), use `PETSC_DETERMINE` or `PETSC_CURRENT` if not known
10656: Output Parameter:
10657: . C - the product matrix
10659: Options Database Key:
10660: . -matmattransmult_mpidense_mpidense_via {allgatherv,cyclic} - Choose between algorithms for `MATMPIDENSE` matrices: the
10661: first redundantly copies the transposed `B` matrix on each process and requires O(log P) communication complexity;
10662: the second never stores more than one portion of the `B` matrix at a time but requires O(P) communication complexity.
10664: Level: intermediate
10666: Notes:
10667: C will be created if `MAT_INITIAL_MATRIX` and must be destroyed by the user with `MatDestroy()`.
10669: `MAT_REUSE_MATRIX` can only be used if the matrices A and B have the same nonzero pattern as in the previous call
10671: To determine the correct fill value, run with -info and search for the string "Fill ratio" to see the value
10672: actually needed.
10674: This routine is currently only implemented for pairs of `MATSEQAIJ` matrices, for the `MATSEQDENSE` class,
10675: and for pairs of `MATMPIDENSE` matrices.
10677: This is a convenience routine that wraps the use of the `MatProductCreate()` with a `MatProductType` of `MATPRODUCT_ABt`
10678: functionality into a single function call. For more involved matrix-matrix operations see `MatProductCreate()`.
10680: The deprecated `PETSC_DEFAULT` in `fill` also means use the current value
10682: .seealso: [](ch_matrices), `Mat`, `MatProductCreate()`, `MATPRODUCT_ABt`, `MatMatMult()`, `MatTransposeMatMult()`, `MatPtAP()`, `MatProductAlgorithm`, `MatProductType`
10683: @*/
10684: PetscErrorCode MatMatTransposeMult(Mat A, Mat B, MatReuse scall, PetscReal fill, Mat *C)
10685: {
10686: PetscFunctionBegin;
10687: PetscCall(MatProduct_Private(A, B, scall, fill, MATPRODUCT_ABt, C));
10688: if (A == B) PetscCall(MatSetOption(*C, MAT_SYMMETRIC, PETSC_TRUE));
10689: PetscFunctionReturn(PETSC_SUCCESS);
10690: }
10692: /*@
10693: MatTransposeMatMult - Performs matrix-matrix multiplication $C = A^T*B$.
10695: Neighbor-wise Collective
10697: Input Parameters:
10698: + A - the left matrix
10699: . B - the right matrix
10700: . scall - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`
10701: - fill - expected fill as ratio of nnz(C)/(nnz(A) + nnz(B)), use `PETSC_DETERMINE` or `PETSC_CURRENT` if not known
10703: Output Parameter:
10704: . C - the product matrix
10706: Level: intermediate
10708: Notes:
10709: `C` will be created if `MAT_INITIAL_MATRIX` and must be destroyed by the user with `MatDestroy()`.
10711: `MAT_REUSE_MATRIX` can only be used if `A` and `B` have the same nonzero pattern as in the previous call.
10713: This is a convenience routine that wraps the use of `MatProductCreate()` with a `MatProductType` of `MATPRODUCT_AtB`
10714: functionality into a single function call. For more involved matrix-matrix operations see `MatProductCreate()`.
10716: To determine the correct fill value, run with -info and search for the string "Fill ratio" to see the value
10717: actually needed.
10719: This routine is currently implemented for pairs of `MATAIJ` matrices and pairs of `MATSEQDENSE` matrices and classes
10720: which inherit from `MATSEQAIJ`. `C` will be of the same type as the input matrices.
10722: The deprecated `PETSC_DEFAULT` in `fill` also means use the current value
10724: .seealso: [](ch_matrices), `Mat`, `MatProductCreate()`, `MATPRODUCT_AtB`, `MatMatMult()`, `MatMatTransposeMult()`, `MatPtAP()`
10725: @*/
10726: PetscErrorCode MatTransposeMatMult(Mat A, Mat B, MatReuse scall, PetscReal fill, Mat *C)
10727: {
10728: PetscFunctionBegin;
10729: PetscCall(MatProduct_Private(A, B, scall, fill, MATPRODUCT_AtB, C));
10730: PetscFunctionReturn(PETSC_SUCCESS);
10731: }
10733: /*@
10734: MatMatMatMult - Performs matrix-matrix-matrix multiplication D=A*B*C.
10736: Neighbor-wise Collective
10738: Input Parameters:
10739: + A - the left matrix
10740: . B - the middle matrix
10741: . C - the right matrix
10742: . scall - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`
10743: - 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
10744: if the result is a dense matrix this is irrelevant
10746: Output Parameter:
10747: . D - the product matrix
10749: Level: intermediate
10751: Notes:
10752: Unless `scall` is `MAT_REUSE_MATRIX` `D` will be created.
10754: `MAT_REUSE_MATRIX` can only be used if the matrices `A`, `B`, and `C` have the same nonzero pattern as in the previous call
10756: This is a convenience routine that wraps the use of the `MatProductCreate()` with a `MatProductType` of `MATPRODUCT_ABC`
10757: functionality into a single function call. For more involved matrix-matrix operations see `MatProductCreate()`.
10759: To determine the correct fill value, run with `-info` and search for the string "Fill ratio" to see the value
10760: actually needed.
10762: If you have many matrices with the same non-zero structure to multiply, you
10763: should use `MAT_REUSE_MATRIX` in all calls but the first
10765: The deprecated `PETSC_DEFAULT` in `fill` also means use the current value
10767: .seealso: [](ch_matrices), `Mat`, `MatProductCreate()`, `MATPRODUCT_ABC`, `MatMatMult`, `MatPtAP()`, `MatMatTransposeMult()`, `MatTransposeMatMult()`
10768: @*/
10769: PetscErrorCode MatMatMatMult(Mat A, Mat B, Mat C, MatReuse scall, PetscReal fill, Mat *D)
10770: {
10771: PetscFunctionBegin;
10772: if (scall == MAT_REUSE_MATRIX) MatCheckProduct(*D, 6);
10773: PetscCheck(scall != MAT_INPLACE_MATRIX, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "Inplace product not supported");
10775: if (scall == MAT_INITIAL_MATRIX) {
10776: PetscCall(MatProductCreate(A, B, C, D));
10777: PetscCall(MatProductSetType(*D, MATPRODUCT_ABC));
10778: PetscCall(MatProductSetAlgorithm(*D, "default"));
10779: PetscCall(MatProductSetFill(*D, fill));
10781: (*D)->product->api_user = PETSC_TRUE;
10782: PetscCall(MatProductSetFromOptions(*D));
10783: 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,
10784: ((PetscObject)C)->type_name);
10785: PetscCall(MatProductSymbolic(*D));
10786: } else { /* user may change input matrices when REUSE */
10787: PetscCall(MatProductReplaceMats(A, B, C, *D));
10788: }
10789: PetscCall(MatProductNumeric(*D));
10790: PetscFunctionReturn(PETSC_SUCCESS);
10791: }
10793: /*@
10794: MatCreateRedundantMatrix - Create redundant matrices and put them into processors of subcommunicators.
10796: Collective
10798: Input Parameters:
10799: + mat - the matrix
10800: . nsubcomm - the number of subcommunicators (= number of redundant parallel or sequential matrices)
10801: . subcomm - MPI communicator split from the communicator where mat resides in (or `MPI_COMM_NULL` if nsubcomm is used)
10802: - reuse - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`
10804: Output Parameter:
10805: . matredundant - redundant matrix
10807: Level: advanced
10809: Notes:
10810: `MAT_REUSE_MATRIX` can only be used when the nonzero structure of the
10811: original matrix has not changed from that last call to `MatCreateRedundantMatrix()`.
10813: This routine creates the duplicated matrices in the subcommunicators; you should NOT create them before
10814: calling it.
10816: `PetscSubcommCreate()` can be used to manage the creation of the subcomm but need not be.
10818: .seealso: [](ch_matrices), `Mat`, `MatDestroy()`, `PetscSubcommCreate()`, `PetscSubcomm`
10819: @*/
10820: PetscErrorCode MatCreateRedundantMatrix(Mat mat, PetscInt nsubcomm, MPI_Comm subcomm, MatReuse reuse, Mat *matredundant)
10821: {
10822: MPI_Comm comm;
10823: PetscMPIInt size;
10824: PetscInt mloc_sub, nloc_sub, rstart, rend, M = mat->rmap->N, N = mat->cmap->N, bs = mat->rmap->bs;
10825: Mat_Redundant *redund = NULL;
10826: PetscSubcomm psubcomm = NULL;
10827: MPI_Comm subcomm_in = subcomm;
10828: Mat *matseq;
10829: IS isrow, iscol;
10830: PetscBool newsubcomm = PETSC_FALSE;
10832: PetscFunctionBegin;
10834: if (nsubcomm && reuse == MAT_REUSE_MATRIX) {
10835: PetscAssertPointer(*matredundant, 5);
10837: }
10839: PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)mat), &size));
10840: if (size == 1 || nsubcomm == 1) {
10841: if (reuse == MAT_INITIAL_MATRIX) {
10842: PetscCall(MatDuplicate(mat, MAT_COPY_VALUES, matredundant));
10843: } else {
10844: 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");
10845: PetscCall(MatCopy(mat, *matredundant, SAME_NONZERO_PATTERN));
10846: }
10847: PetscFunctionReturn(PETSC_SUCCESS);
10848: }
10850: PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
10851: PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
10852: MatCheckPreallocated(mat, 1);
10854: PetscCall(PetscLogEventBegin(MAT_RedundantMat, mat, 0, 0, 0));
10855: if (subcomm_in == MPI_COMM_NULL && reuse == MAT_INITIAL_MATRIX) { /* get subcomm if user does not provide subcomm */
10856: /* create psubcomm, then get subcomm */
10857: PetscCall(PetscObjectGetComm((PetscObject)mat, &comm));
10858: PetscCallMPI(MPI_Comm_size(comm, &size));
10859: PetscCheck(nsubcomm >= 1 && nsubcomm <= size, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "nsubcomm must between 1 and %d", size);
10861: PetscCall(PetscSubcommCreate(comm, &psubcomm));
10862: PetscCall(PetscSubcommSetNumber(psubcomm, nsubcomm));
10863: PetscCall(PetscSubcommSetType(psubcomm, PETSC_SUBCOMM_CONTIGUOUS));
10864: PetscCall(PetscSubcommSetFromOptions(psubcomm));
10865: PetscCall(PetscCommDuplicate(PetscSubcommChild(psubcomm), &subcomm, NULL));
10866: newsubcomm = PETSC_TRUE;
10867: PetscCall(PetscSubcommDestroy(&psubcomm));
10868: }
10870: /* get isrow, iscol and a local sequential matrix matseq[0] */
10871: if (reuse == MAT_INITIAL_MATRIX) {
10872: mloc_sub = PETSC_DECIDE;
10873: nloc_sub = PETSC_DECIDE;
10874: if (bs < 1) {
10875: PetscCall(PetscSplitOwnership(subcomm, &mloc_sub, &M));
10876: PetscCall(PetscSplitOwnership(subcomm, &nloc_sub, &N));
10877: } else {
10878: PetscCall(PetscSplitOwnershipBlock(subcomm, bs, &mloc_sub, &M));
10879: PetscCall(PetscSplitOwnershipBlock(subcomm, bs, &nloc_sub, &N));
10880: }
10881: PetscCallMPI(MPI_Scan(&mloc_sub, &rend, 1, MPIU_INT, MPI_SUM, subcomm));
10882: rstart = rend - mloc_sub;
10883: PetscCall(ISCreateStride(PETSC_COMM_SELF, mloc_sub, rstart, 1, &isrow));
10884: PetscCall(ISCreateStride(PETSC_COMM_SELF, N, 0, 1, &iscol));
10885: PetscCall(ISSetIdentity(iscol));
10886: } else { /* reuse == MAT_REUSE_MATRIX */
10887: 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");
10888: /* retrieve subcomm */
10889: PetscCall(PetscObjectGetComm((PetscObject)*matredundant, &subcomm));
10890: redund = (*matredundant)->redundant;
10891: isrow = redund->isrow;
10892: iscol = redund->iscol;
10893: matseq = redund->matseq;
10894: }
10895: PetscCall(MatCreateSubMatrices(mat, 1, &isrow, &iscol, reuse, &matseq));
10897: /* get matredundant over subcomm */
10898: if (reuse == MAT_INITIAL_MATRIX) {
10899: PetscCall(MatCreateMPIMatConcatenateSeqMat(subcomm, matseq[0], nloc_sub, reuse, matredundant));
10901: /* create a supporting struct and attach it to C for reuse */
10902: PetscCall(PetscNew(&redund));
10903: (*matredundant)->redundant = redund;
10904: redund->isrow = isrow;
10905: redund->iscol = iscol;
10906: redund->matseq = matseq;
10907: if (newsubcomm) {
10908: redund->subcomm = subcomm;
10909: } else {
10910: redund->subcomm = MPI_COMM_NULL;
10911: }
10912: } else {
10913: PetscCall(MatCreateMPIMatConcatenateSeqMat(subcomm, matseq[0], PETSC_DECIDE, reuse, matredundant));
10914: }
10915: #if defined(PETSC_HAVE_VIENNACL) || defined(PETSC_HAVE_CUDA) || defined(PETSC_HAVE_HIP)
10916: if (matseq[0]->boundtocpu && matseq[0]->bindingpropagates) {
10917: PetscCall(MatBindToCPU(*matredundant, PETSC_TRUE));
10918: PetscCall(MatSetBindingPropagates(*matredundant, PETSC_TRUE));
10919: }
10920: #endif
10921: PetscCall(PetscLogEventEnd(MAT_RedundantMat, mat, 0, 0, 0));
10922: PetscFunctionReturn(PETSC_SUCCESS);
10923: }
10925: /*@C
10926: MatGetMultiProcBlock - Create multiple 'parallel submatrices' from
10927: a given `Mat`. Each submatrix can span multiple procs.
10929: Collective
10931: Input Parameters:
10932: + mat - the matrix
10933: . subComm - the sub communicator obtained as if by `MPI_Comm_split(PetscObjectComm((PetscObject)mat))`
10934: - scall - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`
10936: Output Parameter:
10937: . subMat - parallel sub-matrices each spanning a given `subcomm`
10939: Level: advanced
10941: Notes:
10942: The submatrix partition across processors is dictated by `subComm` a
10943: communicator obtained by `MPI_comm_split()` or via `PetscSubcommCreate()`. The `subComm`
10944: is not restricted to be grouped with consecutive original MPI processes.
10946: Due the `MPI_Comm_split()` usage, the parallel layout of the submatrices
10947: map directly to the layout of the original matrix [wrt the local
10948: row,col partitioning]. So the original 'DiagonalMat' naturally maps
10949: into the 'DiagonalMat' of the `subMat`, hence it is used directly from
10950: the `subMat`. However the offDiagMat looses some columns - and this is
10951: reconstructed with `MatSetValues()`
10953: This is used by `PCBJACOBI` when a single block spans multiple MPI processes.
10955: .seealso: [](ch_matrices), `Mat`, `MatCreateRedundantMatrix()`, `MatCreateSubMatrices()`, `PCBJACOBI`
10956: @*/
10957: PetscErrorCode MatGetMultiProcBlock(Mat mat, MPI_Comm subComm, MatReuse scall, Mat *subMat)
10958: {
10959: PetscMPIInt commsize, subCommSize;
10961: PetscFunctionBegin;
10962: PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)mat), &commsize));
10963: PetscCallMPI(MPI_Comm_size(subComm, &subCommSize));
10964: PetscCheck(subCommSize <= commsize, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_OUTOFRANGE, "CommSize %d < SubCommZize %d", commsize, subCommSize);
10966: 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");
10967: PetscCall(PetscLogEventBegin(MAT_GetMultiProcBlock, mat, 0, 0, 0));
10968: PetscUseTypeMethod(mat, getmultiprocblock, subComm, scall, subMat);
10969: PetscCall(PetscLogEventEnd(MAT_GetMultiProcBlock, mat, 0, 0, 0));
10970: PetscFunctionReturn(PETSC_SUCCESS);
10971: }
10973: /*@
10974: MatGetLocalSubMatrix - Gets a reference to a submatrix specified in local numbering
10976: Not Collective
10978: Input Parameters:
10979: + mat - matrix to extract local submatrix from
10980: . isrow - local row indices for submatrix
10981: - iscol - local column indices for submatrix
10983: Output Parameter:
10984: . submat - the submatrix
10986: Level: intermediate
10988: Notes:
10989: `submat` should be disposed of with `MatRestoreLocalSubMatrix()`.
10991: Depending on the format of `mat`, the returned `submat` may not implement `MatMult()`. Its communicator may be
10992: the same as `mat`, it may be `PETSC_COMM_SELF`, or some other sub-communictor of `mat`'s.
10994: `submat` always implements `MatSetValuesLocal()`. If `isrow` and `iscol` have the same block size, then
10995: `MatSetValuesBlockedLocal()` will also be implemented.
10997: `mat` must have had a `ISLocalToGlobalMapping` provided to it with `MatSetLocalToGlobalMapping()`.
10998: Matrices obtained with `DMCreateMatrix()` generally already have the local to global mapping provided.
11000: .seealso: [](ch_matrices), `Mat`, `MatRestoreLocalSubMatrix()`, `MatCreateLocalRef()`, `MatSetLocalToGlobalMapping()`
11001: @*/
11002: PetscErrorCode MatGetLocalSubMatrix(Mat mat, IS isrow, IS iscol, Mat *submat)
11003: {
11004: PetscFunctionBegin;
11008: PetscCheckSameComm(isrow, 2, iscol, 3);
11009: PetscAssertPointer(submat, 4);
11010: PetscCheck(mat->rmap->mapping, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Matrix must have local to global mapping provided before this call");
11012: if (mat->ops->getlocalsubmatrix) {
11013: PetscUseTypeMethod(mat, getlocalsubmatrix, isrow, iscol, submat);
11014: } else {
11015: PetscCall(MatCreateLocalRef(mat, isrow, iscol, submat));
11016: }
11017: (*submat)->assembled = mat->assembled;
11018: PetscFunctionReturn(PETSC_SUCCESS);
11019: }
11021: /*@
11022: MatRestoreLocalSubMatrix - Restores a reference to a submatrix specified in local numbering obtained with `MatGetLocalSubMatrix()`
11024: Not Collective
11026: Input Parameters:
11027: + mat - matrix to extract local submatrix from
11028: . isrow - local row indices for submatrix
11029: . iscol - local column indices for submatrix
11030: - submat - the submatrix
11032: Level: intermediate
11034: .seealso: [](ch_matrices), `Mat`, `MatGetLocalSubMatrix()`
11035: @*/
11036: PetscErrorCode MatRestoreLocalSubMatrix(Mat mat, IS isrow, IS iscol, Mat *submat)
11037: {
11038: PetscFunctionBegin;
11042: PetscCheckSameComm(isrow, 2, iscol, 3);
11043: PetscAssertPointer(submat, 4);
11046: if (mat->ops->restorelocalsubmatrix) {
11047: PetscUseTypeMethod(mat, restorelocalsubmatrix, isrow, iscol, submat);
11048: } else {
11049: PetscCall(MatDestroy(submat));
11050: }
11051: *submat = NULL;
11052: PetscFunctionReturn(PETSC_SUCCESS);
11053: }
11055: /*@
11056: MatFindZeroDiagonals - Finds all the rows of a matrix that have zero or no diagonal entry in the matrix
11058: Collective
11060: Input Parameter:
11061: . mat - the matrix
11063: Output Parameter:
11064: . is - if any rows have zero diagonals this contains the list of them
11066: Level: developer
11068: .seealso: [](ch_matrices), `Mat`, `MatMultTranspose()`, `MatMultAdd()`, `MatMultTransposeAdd()`
11069: @*/
11070: PetscErrorCode MatFindZeroDiagonals(Mat mat, IS *is)
11071: {
11072: PetscFunctionBegin;
11075: PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
11076: PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
11078: if (!mat->ops->findzerodiagonals) {
11079: Vec diag;
11080: const PetscScalar *a;
11081: PetscInt *rows;
11082: PetscInt rStart, rEnd, r, nrow = 0;
11084: PetscCall(MatCreateVecs(mat, &diag, NULL));
11085: PetscCall(MatGetDiagonal(mat, diag));
11086: PetscCall(MatGetOwnershipRange(mat, &rStart, &rEnd));
11087: PetscCall(VecGetArrayRead(diag, &a));
11088: for (r = 0; r < rEnd - rStart; ++r)
11089: if (a[r] == 0.0) ++nrow;
11090: PetscCall(PetscMalloc1(nrow, &rows));
11091: nrow = 0;
11092: for (r = 0; r < rEnd - rStart; ++r)
11093: if (a[r] == 0.0) rows[nrow++] = r + rStart;
11094: PetscCall(VecRestoreArrayRead(diag, &a));
11095: PetscCall(VecDestroy(&diag));
11096: PetscCall(ISCreateGeneral(PetscObjectComm((PetscObject)mat), nrow, rows, PETSC_OWN_POINTER, is));
11097: } else {
11098: PetscUseTypeMethod(mat, findzerodiagonals, is);
11099: }
11100: PetscFunctionReturn(PETSC_SUCCESS);
11101: }
11103: /*@
11104: MatFindOffBlockDiagonalEntries - Finds all the rows of a matrix that have entries outside of the main diagonal block (defined by the matrix block size)
11106: Collective
11108: Input Parameter:
11109: . mat - the matrix
11111: Output Parameter:
11112: . is - contains the list of rows with off block diagonal entries
11114: Level: developer
11116: .seealso: [](ch_matrices), `Mat`, `MatMultTranspose()`, `MatMultAdd()`, `MatMultTransposeAdd()`
11117: @*/
11118: PetscErrorCode MatFindOffBlockDiagonalEntries(Mat mat, IS *is)
11119: {
11120: PetscFunctionBegin;
11123: PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
11124: PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
11126: PetscUseTypeMethod(mat, findoffblockdiagonalentries, is);
11127: PetscFunctionReturn(PETSC_SUCCESS);
11128: }
11130: /*@C
11131: MatInvertBlockDiagonal - Inverts the block diagonal entries.
11133: Collective; No Fortran Support
11135: Input Parameter:
11136: . mat - the matrix
11138: Output Parameter:
11139: . values - the block inverses in column major order (FORTRAN-like)
11141: Level: advanced
11143: Notes:
11144: The size of the blocks is determined by the block size of the matrix.
11146: The blocks never overlap between two MPI processes, use `MatInvertVariableBlockEnvelope()` for that case
11148: The blocks all have the same size, use `MatInvertVariableBlockDiagonal()` for variable block size
11150: .seealso: [](ch_matrices), `Mat`, `MatInvertVariableBlockEnvelope()`, `MatInvertBlockDiagonalMat()`
11151: @*/
11152: PetscErrorCode MatInvertBlockDiagonal(Mat mat, const PetscScalar *values[])
11153: {
11154: PetscFunctionBegin;
11156: PetscCheck(mat->assembled, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
11157: PetscCheck(!mat->factortype, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
11158: PetscUseTypeMethod(mat, invertblockdiagonal, values);
11159: PetscFunctionReturn(PETSC_SUCCESS);
11160: }
11162: /*@
11163: MatInvertVariableBlockDiagonal - Inverts the point block diagonal entries.
11165: Collective; No Fortran Support
11167: Input Parameters:
11168: + mat - the matrix
11169: . nblocks - the number of blocks on the process, set with `MatSetVariableBlockSizes()`
11170: - bsizes - the size of each block on the process, set with `MatSetVariableBlockSizes()`
11172: Output Parameter:
11173: . values - the block inverses in column major order (FORTRAN-like)
11175: Level: advanced
11177: Notes:
11178: Use `MatInvertBlockDiagonal()` if all blocks have the same size
11180: The blocks never overlap between two MPI processes, use `MatInvertVariableBlockEnvelope()` for that case
11182: .seealso: [](ch_matrices), `Mat`, `MatInvertBlockDiagonal()`, `MatSetVariableBlockSizes()`, `MatInvertVariableBlockEnvelope()`
11183: @*/
11184: PetscErrorCode MatInvertVariableBlockDiagonal(Mat mat, PetscInt nblocks, const PetscInt bsizes[], PetscScalar values[])
11185: {
11186: PetscFunctionBegin;
11188: PetscCheck(mat->assembled, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
11189: PetscCheck(!mat->factortype, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
11190: PetscUseTypeMethod(mat, invertvariableblockdiagonal, nblocks, bsizes, values);
11191: PetscFunctionReturn(PETSC_SUCCESS);
11192: }
11194: /*@
11195: MatInvertBlockDiagonalMat - set the values of matrix C to be the inverted block diagonal of matrix A
11197: Collective
11199: Input Parameters:
11200: + A - the matrix
11201: - C - matrix with inverted block diagonal of `A`. This matrix should be created and may have its type set.
11203: Level: advanced
11205: Note:
11206: The blocksize of the matrix is used to determine the blocks on the diagonal of `C`
11208: .seealso: [](ch_matrices), `Mat`, `MatInvertBlockDiagonal()`
11209: @*/
11210: PetscErrorCode MatInvertBlockDiagonalMat(Mat A, Mat C)
11211: {
11212: const PetscScalar *vals;
11213: PetscInt *dnnz;
11214: PetscInt m, rstart, rend, bs, i, j;
11216: PetscFunctionBegin;
11217: PetscCall(MatInvertBlockDiagonal(A, &vals));
11218: PetscCall(MatGetBlockSize(A, &bs));
11219: PetscCall(MatGetLocalSize(A, &m, NULL));
11220: PetscCall(MatSetLayouts(C, A->rmap, A->cmap));
11221: PetscCall(MatSetBlockSizes(C, A->rmap->bs, A->cmap->bs));
11222: PetscCall(PetscMalloc1(m / bs, &dnnz));
11223: for (j = 0; j < m / bs; j++) dnnz[j] = 1;
11224: PetscCall(MatXAIJSetPreallocation(C, bs, dnnz, NULL, NULL, NULL));
11225: PetscCall(PetscFree(dnnz));
11226: PetscCall(MatGetOwnershipRange(C, &rstart, &rend));
11227: PetscCall(MatSetOption(C, MAT_ROW_ORIENTED, PETSC_FALSE));
11228: for (i = rstart / bs; i < rend / bs; i++) PetscCall(MatSetValuesBlocked(C, 1, &i, 1, &i, &vals[(i - rstart / bs) * bs * bs], INSERT_VALUES));
11229: PetscCall(MatSetOption(C, MAT_NO_OFF_PROC_ENTRIES, PETSC_TRUE));
11230: PetscCall(MatAssemblyBegin(C, MAT_FINAL_ASSEMBLY));
11231: PetscCall(MatAssemblyEnd(C, MAT_FINAL_ASSEMBLY));
11232: PetscCall(MatSetOption(C, MAT_NO_OFF_PROC_ENTRIES, PETSC_FALSE));
11233: PetscCall(MatSetOption(C, MAT_ROW_ORIENTED, PETSC_TRUE));
11234: PetscFunctionReturn(PETSC_SUCCESS);
11235: }
11237: /*@
11238: MatTransposeColoringDestroy - Destroys a coloring context for matrix product $C = A*B^T$ that was created
11239: via `MatTransposeColoringCreate()`.
11241: Collective
11243: Input Parameter:
11244: . c - coloring context
11246: Level: intermediate
11248: .seealso: [](ch_matrices), `Mat`, `MatTransposeColoringCreate()`
11249: @*/
11250: PetscErrorCode MatTransposeColoringDestroy(MatTransposeColoring *c)
11251: {
11252: MatTransposeColoring matcolor = *c;
11254: PetscFunctionBegin;
11255: if (!matcolor) PetscFunctionReturn(PETSC_SUCCESS);
11256: if (--((PetscObject)matcolor)->refct > 0) {
11257: matcolor = NULL;
11258: PetscFunctionReturn(PETSC_SUCCESS);
11259: }
11261: PetscCall(PetscFree3(matcolor->ncolumns, matcolor->nrows, matcolor->colorforrow));
11262: PetscCall(PetscFree(matcolor->rows));
11263: PetscCall(PetscFree(matcolor->den2sp));
11264: PetscCall(PetscFree(matcolor->colorforcol));
11265: PetscCall(PetscFree(matcolor->columns));
11266: if (matcolor->brows > 0) PetscCall(PetscFree(matcolor->lstart));
11267: PetscCall(PetscHeaderDestroy(c));
11268: PetscFunctionReturn(PETSC_SUCCESS);
11269: }
11271: /*@
11272: MatTransColoringApplySpToDen - Given a symbolic matrix product $C = A*B^T$ for which
11273: a `MatTransposeColoring` context has been created, computes a dense $B^T$ by applying
11274: `MatTransposeColoring` to sparse `B`.
11276: Collective
11278: Input Parameters:
11279: + coloring - coloring context created with `MatTransposeColoringCreate()`
11280: - B - sparse matrix
11282: Output Parameter:
11283: . Btdense - dense matrix $B^T$
11285: Level: developer
11287: Note:
11288: These are used internally for some implementations of `MatRARt()`
11290: .seealso: [](ch_matrices), `Mat`, `MatTransposeColoringCreate()`, `MatTransposeColoringDestroy()`, `MatTransColoringApplyDenToSp()`
11291: @*/
11292: PetscErrorCode MatTransColoringApplySpToDen(MatTransposeColoring coloring, Mat B, Mat Btdense)
11293: {
11294: PetscFunctionBegin;
11299: PetscCall((*B->ops->transcoloringapplysptoden)(coloring, B, Btdense));
11300: PetscFunctionReturn(PETSC_SUCCESS);
11301: }
11303: /*@
11304: MatTransColoringApplyDenToSp - Given a symbolic matrix product $C_{sp} = A*B^T$ for which
11305: a `MatTransposeColoring` context has been created and a dense matrix $C_{den} = A*B^T_{dense}$
11306: in which `B^T_{dens}` is obtained from `MatTransColoringApplySpToDen()`, recover sparse matrix
11307: $C_{sp}$ from $C_{den}$.
11309: Collective
11311: Input Parameters:
11312: + matcoloring - coloring context created with `MatTransposeColoringCreate()`
11313: - Cden - matrix product of a sparse matrix and a dense matrix Btdense
11315: Output Parameter:
11316: . Csp - sparse matrix
11318: Level: developer
11320: Note:
11321: These are used internally for some implementations of `MatRARt()`
11323: .seealso: [](ch_matrices), `Mat`, `MatTransposeColoringCreate()`, `MatTransposeColoringDestroy()`, `MatTransColoringApplySpToDen()`
11324: @*/
11325: PetscErrorCode MatTransColoringApplyDenToSp(MatTransposeColoring matcoloring, Mat Cden, Mat Csp)
11326: {
11327: PetscFunctionBegin;
11332: PetscCall((*Csp->ops->transcoloringapplydentosp)(matcoloring, Cden, Csp));
11333: PetscCall(MatAssemblyBegin(Csp, MAT_FINAL_ASSEMBLY));
11334: PetscCall(MatAssemblyEnd(Csp, MAT_FINAL_ASSEMBLY));
11335: PetscFunctionReturn(PETSC_SUCCESS);
11336: }
11338: /*@
11339: MatTransposeColoringCreate - Creates a matrix coloring context for the matrix product $C = A*B^T$.
11341: Collective
11343: Input Parameters:
11344: + mat - the matrix product C
11345: - iscoloring - the coloring of the matrix; usually obtained with `MatColoringCreate()` or `DMCreateColoring()`
11347: Output Parameter:
11348: . color - the new coloring context
11350: Level: intermediate
11352: .seealso: [](ch_matrices), `Mat`, `MatTransposeColoringDestroy()`, `MatTransColoringApplySpToDen()`,
11353: `MatTransColoringApplyDenToSp()`
11354: @*/
11355: PetscErrorCode MatTransposeColoringCreate(Mat mat, ISColoring iscoloring, MatTransposeColoring *color)
11356: {
11357: MatTransposeColoring c;
11358: MPI_Comm comm;
11360: PetscFunctionBegin;
11361: PetscAssertPointer(color, 3);
11363: PetscCall(PetscLogEventBegin(MAT_TransposeColoringCreate, mat, 0, 0, 0));
11364: PetscCall(PetscObjectGetComm((PetscObject)mat, &comm));
11365: PetscCall(PetscHeaderCreate(c, MAT_TRANSPOSECOLORING_CLASSID, "MatTransposeColoring", "Matrix product C=A*B^T via coloring", "Mat", comm, MatTransposeColoringDestroy, NULL));
11366: c->ctype = iscoloring->ctype;
11367: PetscUseTypeMethod(mat, transposecoloringcreate, iscoloring, c);
11368: *color = c;
11369: PetscCall(PetscLogEventEnd(MAT_TransposeColoringCreate, mat, 0, 0, 0));
11370: PetscFunctionReturn(PETSC_SUCCESS);
11371: }
11373: /*@
11374: MatGetNonzeroState - Returns a 64-bit integer representing the current state of nonzeros in the matrix. If the
11375: matrix has had new nonzero locations added to (or removed from) the matrix since the previous call, the value will be larger.
11377: Not Collective
11379: Input Parameter:
11380: . mat - the matrix
11382: Output Parameter:
11383: . state - the current state
11385: Level: intermediate
11387: Notes:
11388: You can only compare states from two different calls to the SAME matrix, you cannot compare calls between
11389: different matrices
11391: Use `PetscObjectStateGet()` to check for changes to the numerical values in a matrix
11393: Use the result of `PetscObjectGetId()` to compare if a previously checked matrix is the same as the current matrix, do not compare object pointers.
11395: .seealso: [](ch_matrices), `Mat`, `PetscObjectStateGet()`, `PetscObjectGetId()`
11396: @*/
11397: PetscErrorCode MatGetNonzeroState(Mat mat, PetscObjectState *state)
11398: {
11399: PetscFunctionBegin;
11401: *state = mat->nonzerostate;
11402: PetscFunctionReturn(PETSC_SUCCESS);
11403: }
11405: /*@
11406: MatCreateMPIMatConcatenateSeqMat - Creates a single large PETSc matrix by concatenating sequential
11407: matrices from each processor
11409: Collective
11411: Input Parameters:
11412: + comm - the communicators the parallel matrix will live on
11413: . seqmat - the input sequential matrices
11414: . n - number of local columns (or `PETSC_DECIDE`)
11415: - reuse - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`
11417: Output Parameter:
11418: . mpimat - the parallel matrix generated
11420: Level: developer
11422: Note:
11423: The number of columns of the matrix in EACH processor MUST be the same.
11425: .seealso: [](ch_matrices), `Mat`
11426: @*/
11427: PetscErrorCode MatCreateMPIMatConcatenateSeqMat(MPI_Comm comm, Mat seqmat, PetscInt n, MatReuse reuse, Mat *mpimat)
11428: {
11429: PetscMPIInt size;
11431: PetscFunctionBegin;
11432: PetscCallMPI(MPI_Comm_size(comm, &size));
11433: if (size == 1) {
11434: if (reuse == MAT_INITIAL_MATRIX) {
11435: PetscCall(MatDuplicate(seqmat, MAT_COPY_VALUES, mpimat));
11436: } else {
11437: PetscCall(MatCopy(seqmat, *mpimat, SAME_NONZERO_PATTERN));
11438: }
11439: PetscFunctionReturn(PETSC_SUCCESS);
11440: }
11442: 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");
11444: PetscCall(PetscLogEventBegin(MAT_Merge, seqmat, 0, 0, 0));
11445: PetscCall((*seqmat->ops->creatempimatconcatenateseqmat)(comm, seqmat, n, reuse, mpimat));
11446: PetscCall(PetscLogEventEnd(MAT_Merge, seqmat, 0, 0, 0));
11447: PetscFunctionReturn(PETSC_SUCCESS);
11448: }
11450: /*@
11451: MatSubdomainsCreateCoalesce - Creates index subdomains by coalescing adjacent MPI processes' ownership ranges.
11453: Collective
11455: Input Parameters:
11456: + A - the matrix to create subdomains from
11457: - N - requested number of subdomains
11459: Output Parameters:
11460: + n - number of subdomains resulting on this MPI process
11461: - iss - `IS` list with indices of subdomains on this MPI process
11463: Level: advanced
11465: Note:
11466: The number of subdomains must be smaller than the communicator size
11468: .seealso: [](ch_matrices), `Mat`, `IS`
11469: @*/
11470: PetscErrorCode MatSubdomainsCreateCoalesce(Mat A, PetscInt N, PetscInt *n, IS *iss[])
11471: {
11472: MPI_Comm comm, subcomm;
11473: PetscMPIInt size, rank, color;
11474: PetscInt rstart, rend, k;
11476: PetscFunctionBegin;
11477: PetscCall(PetscObjectGetComm((PetscObject)A, &comm));
11478: PetscCallMPI(MPI_Comm_size(comm, &size));
11479: PetscCallMPI(MPI_Comm_rank(comm, &rank));
11480: 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);
11481: *n = 1;
11482: k = size / N + (size % N > 0); /* There are up to k ranks to a color */
11483: color = rank / k;
11484: PetscCallMPI(MPI_Comm_split(comm, color, rank, &subcomm));
11485: PetscCall(PetscMalloc1(1, iss));
11486: PetscCall(MatGetOwnershipRange(A, &rstart, &rend));
11487: PetscCall(ISCreateStride(subcomm, rend - rstart, rstart, 1, iss[0]));
11488: PetscCallMPI(MPI_Comm_free(&subcomm));
11489: PetscFunctionReturn(PETSC_SUCCESS);
11490: }
11492: /*@
11493: MatGalerkin - Constructs the coarse grid problem matrix via Galerkin projection.
11495: If the interpolation and restriction operators are the same, uses `MatPtAP()`.
11496: If they are not the same, uses `MatMatMatMult()`.
11498: Once the coarse grid problem is constructed, correct for interpolation operators
11499: that are not of full rank, which can legitimately happen in the case of non-nested
11500: geometric multigrid.
11502: Input Parameters:
11503: + restrct - restriction operator
11504: . dA - fine grid matrix
11505: . interpolate - interpolation operator
11506: . reuse - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`
11507: - fill - expected fill, use `PETSC_DETERMINE` or `PETSC_DETERMINE` if you do not have a good estimate
11509: Output Parameter:
11510: . A - the Galerkin coarse matrix
11512: Options Database Key:
11513: . -pc_mg_galerkin (both|pmat|mat|none) - for what matrices the Galerkin process should be used
11515: Level: developer
11517: Note:
11518: The deprecated `PETSC_DEFAULT` in `fill` also means use the current value
11520: .seealso: [](ch_matrices), `Mat`, `MatPtAP()`, `MatMatMatMult()`
11521: @*/
11522: PetscErrorCode MatGalerkin(Mat restrct, Mat dA, Mat interpolate, MatReuse reuse, PetscReal fill, Mat *A)
11523: {
11524: IS zerorows;
11525: Vec diag;
11527: PetscFunctionBegin;
11528: PetscCheck(reuse != MAT_INPLACE_MATRIX, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "Inplace product not supported");
11529: /* Construct the coarse grid matrix */
11530: if (interpolate == restrct) {
11531: PetscCall(MatPtAP(dA, interpolate, reuse, fill, A));
11532: } else {
11533: PetscCall(MatMatMatMult(restrct, dA, interpolate, reuse, fill, A));
11534: }
11536: /* If the interpolation matrix is not of full rank, A will have zero rows.
11537: This can legitimately happen in the case of non-nested geometric multigrid.
11538: In that event, we set the rows of the matrix to the rows of the identity,
11539: ignoring the equations (as the RHS will also be zero). */
11541: PetscCall(MatFindZeroRows(*A, &zerorows));
11543: if (zerorows != NULL) { /* if there are any zero rows */
11544: PetscCall(MatCreateVecs(*A, &diag, NULL));
11545: PetscCall(MatGetDiagonal(*A, diag));
11546: PetscCall(VecISSet(diag, zerorows, 1.0));
11547: PetscCall(MatDiagonalSet(*A, diag, INSERT_VALUES));
11548: PetscCall(VecDestroy(&diag));
11549: PetscCall(ISDestroy(&zerorows));
11550: }
11551: PetscFunctionReturn(PETSC_SUCCESS);
11552: }
11554: /*@C
11555: MatSetOperation - Allows user to set a matrix operation for any matrix type
11557: Logically Collective
11559: Input Parameters:
11560: + mat - the matrix
11561: . op - the name of the operation
11562: - f - the function that provides the operation
11564: Level: developer
11566: Example Usage:
11567: .vb
11568: extern PetscErrorCode usermult(Mat, Vec, Vec);
11570: PetscCall(MatCreateXXX(comm, ..., &A));
11571: PetscCall(MatSetOperation(A, MATOP_MULT, (PetscErrorCodeFn *)usermult));
11572: .ve
11574: Notes:
11575: See the file `include/petscmat.h` for a complete list of matrix
11576: operations, which all have the form MATOP_<OPERATION>, where
11577: <OPERATION> is the name (in all capital letters) of the
11578: user interface routine (e.g., `MatMult()` -> `MATOP_MULT`).
11580: All user-provided functions (except for `MATOP_DESTROY`) should have the same calling
11581: sequence as the usual matrix interface routines, since they
11582: are intended to be accessed via the usual matrix interface
11583: routines, e.g.,
11584: .vb
11585: MatMult(Mat, Vec, Vec) -> usermult(Mat, Vec, Vec)
11586: .ve
11588: In particular each function MUST return `PETSC_SUCCESS` on success and
11589: nonzero on failure.
11591: This routine is distinct from `MatShellSetOperation()` in that it can be called on any matrix type.
11593: .seealso: [](ch_matrices), `Mat`, `MatGetOperation()`, `MatCreateShell()`, `MatShellSetContext()`, `MatShellSetOperation()`
11594: @*/
11595: PetscErrorCode MatSetOperation(Mat mat, MatOperation op, PetscErrorCodeFn *f)
11596: {
11597: PetscFunctionBegin;
11600: if (op == MATOP_VIEW && !mat->ops->viewnative && f != (PetscErrorCodeFn *)mat->ops->view) mat->ops->viewnative = mat->ops->view;
11601: #if !defined(PETSC_USE_COMPLEX)
11602: if (op == MATOP_MULT_HERMITIAN_TRANSPOSE) op = MATOP_MULT_TRANSPOSE;
11603: else if (op == MATOP_MULT_HERMITIAN_TRANS_ADD) op = MATOP_MULT_TRANSPOSE_ADD;
11604: else if (op == MATOP_HERMITIAN_TRANSPOSE) op = MATOP_TRANSPOSE;
11605: #endif
11606: (((PetscErrorCodeFn **)mat->ops)[op]) = f;
11607: PetscFunctionReturn(PETSC_SUCCESS);
11608: }
11610: /*@C
11611: MatGetOperation - Gets a matrix operation for any matrix type.
11613: Not Collective
11615: Input Parameters:
11616: + mat - the matrix
11617: - op - the name of the operation
11619: Output Parameter:
11620: . f - the function that provides the operation
11622: Level: developer
11624: Example Usage:
11625: .vb
11626: PetscErrorCode (*usermult)(Mat, Vec, Vec);
11628: MatGetOperation(A, MATOP_MULT, (PetscErrorCodeFn **)&usermult);
11629: .ve
11631: Notes:
11632: See the file `include/petscmat.h` for a complete list of matrix
11633: operations, which all have the form MATOP_<OPERATION>, where
11634: <OPERATION> is the name (in all capital letters) of the
11635: user interface routine (e.g., `MatMult()` -> `MATOP_MULT`).
11637: This routine is distinct from `MatShellGetOperation()` in that it can be called on any matrix type.
11639: .seealso: [](ch_matrices), `Mat`, `MatSetOperation()`, `MatCreateShell()`, `MatShellGetContext()`, `MatShellGetOperation()`
11640: @*/
11641: PetscErrorCode MatGetOperation(Mat mat, MatOperation op, PetscErrorCodeFn **f)
11642: {
11643: PetscFunctionBegin;
11645: PetscAssertPointer(f, 3);
11646: #if !defined(PETSC_USE_COMPLEX)
11647: if (op == MATOP_MULT_HERMITIAN_TRANSPOSE) op = MATOP_MULT_TRANSPOSE;
11648: else if (op == MATOP_MULT_HERMITIAN_TRANS_ADD) op = MATOP_MULT_TRANSPOSE_ADD;
11649: else if (op == MATOP_HERMITIAN_TRANSPOSE) op = MATOP_TRANSPOSE;
11650: #endif
11651: *f = (((PetscErrorCodeFn **)mat->ops)[op]);
11652: PetscFunctionReturn(PETSC_SUCCESS);
11653: }
11655: /*@
11656: MatHasOperation - Determines whether the given matrix supports the particular operation.
11658: Not Collective
11660: Input Parameters:
11661: + mat - the matrix
11662: - op - the operation, for example, `MATOP_GET_DIAGONAL`
11664: Output Parameter:
11665: . has - either `PETSC_TRUE` or `PETSC_FALSE`
11667: Level: advanced
11669: Note:
11670: See `MatSetOperation()` for additional discussion on naming convention and usage of `op`.
11672: .seealso: [](ch_matrices), `Mat`, `MatCreateShell()`, `MatGetOperation()`, `MatSetOperation()`
11673: @*/
11674: PetscErrorCode MatHasOperation(Mat mat, MatOperation op, PetscBool *has)
11675: {
11676: PetscFunctionBegin;
11678: PetscAssertPointer(has, 3);
11679: #if !defined(PETSC_USE_COMPLEX)
11680: if (op == MATOP_MULT_HERMITIAN_TRANSPOSE) op = MATOP_MULT_TRANSPOSE;
11681: else if (op == MATOP_MULT_HERMITIAN_TRANS_ADD) op = MATOP_MULT_TRANSPOSE_ADD;
11682: else if (op == MATOP_HERMITIAN_TRANSPOSE) op = MATOP_TRANSPOSE;
11683: #endif
11684: if (mat->ops->hasoperation) {
11685: PetscUseTypeMethod(mat, hasoperation, op, has);
11686: } else {
11687: if (((void **)mat->ops)[op]) *has = PETSC_TRUE;
11688: else {
11689: *has = PETSC_FALSE;
11690: if (op == MATOP_CREATE_SUBMATRIX) {
11691: PetscMPIInt size;
11693: PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)mat), &size));
11694: if (size == 1) PetscCall(MatHasOperation(mat, MATOP_CREATE_SUBMATRICES, has));
11695: }
11696: }
11697: }
11698: PetscFunctionReturn(PETSC_SUCCESS);
11699: }
11701: /*@
11702: MatHasCongruentLayouts - Determines whether the rows and columns layouts of the matrix are congruent
11704: Collective
11706: Input Parameter:
11707: . mat - the matrix
11709: Output Parameter:
11710: . cong - either `PETSC_TRUE` or `PETSC_FALSE`
11712: Level: beginner
11714: .seealso: [](ch_matrices), `Mat`, `MatCreate()`, `MatSetSizes()`, `PetscLayout`
11715: @*/
11716: PetscErrorCode MatHasCongruentLayouts(Mat mat, PetscBool *cong)
11717: {
11718: PetscFunctionBegin;
11721: PetscAssertPointer(cong, 2);
11722: if (!mat->rmap || !mat->cmap) {
11723: *cong = mat->rmap == mat->cmap ? PETSC_TRUE : PETSC_FALSE;
11724: PetscFunctionReturn(PETSC_SUCCESS);
11725: }
11726: if (mat->congruentlayouts == PETSC_DECIDE) { /* first time we compare rows and cols layouts */
11727: PetscCall(PetscLayoutSetUp(mat->rmap));
11728: PetscCall(PetscLayoutSetUp(mat->cmap));
11729: PetscCall(PetscLayoutCompare(mat->rmap, mat->cmap, cong));
11730: if (*cong) mat->congruentlayouts = 1;
11731: else mat->congruentlayouts = 0;
11732: } else *cong = mat->congruentlayouts ? PETSC_TRUE : PETSC_FALSE;
11733: PetscFunctionReturn(PETSC_SUCCESS);
11734: }
11736: PetscErrorCode MatSetInf(Mat A)
11737: {
11738: PetscFunctionBegin;
11739: PetscUseTypeMethod(A, setinf);
11740: PetscFunctionReturn(PETSC_SUCCESS);
11741: }
11743: /*@
11744: 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
11745: and possibly removes small values from the graph structure.
11747: Collective
11749: Input Parameters:
11750: + A - the matrix
11751: . sym - `PETSC_TRUE` indicates that the graph should be symmetrized
11752: . scale - `PETSC_TRUE` indicates that the graph edge weights should be symmetrically scaled with the diagonal entry
11753: . filter - filter value - < 0: does nothing; == 0: removes only 0.0 entries; otherwise: removes entries with abs(entries) <= value
11754: . num_idx - size of `index` array
11755: - index - array of block indices to use for graph strength of connection weight
11757: Output Parameter:
11758: . graph - the resulting graph
11760: Level: advanced
11762: .seealso: [](ch_matrices), `Mat`, `MatCreate()`, `PCGAMG`
11763: @*/
11764: PetscErrorCode MatCreateGraph(Mat A, PetscBool sym, PetscBool scale, PetscReal filter, PetscInt num_idx, PetscInt index[], Mat *graph)
11765: {
11766: PetscFunctionBegin;
11770: PetscAssertPointer(graph, 7);
11771: PetscCall(PetscLogEventBegin(MAT_CreateGraph, A, 0, 0, 0));
11772: PetscUseTypeMethod(A, creategraph, sym, scale, filter, num_idx, index, graph);
11773: PetscCall(PetscLogEventEnd(MAT_CreateGraph, A, 0, 0, 0));
11774: PetscFunctionReturn(PETSC_SUCCESS);
11775: }
11777: /*@
11778: MatEliminateZeros - eliminate the nondiagonal zero entries in place from the nonzero structure of a sparse `Mat` in place,
11779: meaning the same memory is used for the matrix, and no new memory is allocated.
11781: Collective
11783: Input Parameters:
11784: + A - the matrix
11785: - 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
11787: Level: intermediate
11789: Developer Note:
11790: The entries in the sparse matrix data structure are shifted to fill in the unneeded locations in the data. Thus the end
11791: of the arrays in the data structure are unneeded.
11793: .seealso: [](ch_matrices), `Mat`, `MatCreate()`, `MatCreateGraph()`, `MatFilter()`
11794: @*/
11795: PetscErrorCode MatEliminateZeros(Mat A, PetscBool keep)
11796: {
11797: PetscFunctionBegin;
11799: PetscUseTypeMethod(A, eliminatezeros, keep);
11800: PetscFunctionReturn(PETSC_SUCCESS);
11801: }
11803: /*@C
11804: MatGetCurrentMemType - Get the memory location of the matrix
11806: Not Collective, but the result will be the same on all MPI processes
11808: Input Parameter:
11809: . A - the matrix whose memory type we are checking
11811: Output Parameter:
11812: . m - the memory type
11814: Level: intermediate
11816: .seealso: [](ch_matrices), `Mat`, `MatBoundToCPU()`, `PetscMemType`
11817: @*/
11818: PetscErrorCode MatGetCurrentMemType(Mat A, PetscMemType *m)
11819: {
11820: PetscFunctionBegin;
11822: PetscAssertPointer(m, 2);
11823: if (A->ops->getcurrentmemtype) PetscUseTypeMethod(A, getcurrentmemtype, m);
11824: else *m = PETSC_MEMTYPE_HOST;
11825: PetscFunctionReturn(PETSC_SUCCESS);
11826: }