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>
10: #include <petscsf.h>
12: /* Logging support */
13: PetscClassId MAT_CLASSID;
14: PetscClassId MAT_COLORING_CLASSID;
15: PetscClassId MAT_FDCOLORING_CLASSID;
16: PetscClassId MAT_TRANSPOSECOLORING_CLASSID;
18: PetscLogEvent MAT_Mult, MAT_MultAdd, MAT_MultTranspose;
19: PetscLogEvent MAT_ADot, MAT_ANorm;
20: PetscLogEvent MAT_MultTransposeAdd, MAT_Solve, MAT_Solves, MAT_SolveAdd, MAT_SolveTranspose, MAT_MatSolve, MAT_MatTrSolve;
21: PetscLogEvent MAT_SolveTransposeAdd, MAT_SOR, MAT_ForwardSolve, MAT_BackwardSolve, MAT_LUFactor, MAT_LUFactorSymbolic;
22: PetscLogEvent MAT_LUFactorNumeric, MAT_CholeskyFactor, MAT_CholeskyFactorSymbolic, MAT_CholeskyFactorNumeric, MAT_ILUFactor;
23: PetscLogEvent MAT_ILUFactorSymbolic, MAT_ICCFactorSymbolic, MAT_Copy, MAT_Convert, MAT_Scale, MAT_AssemblyBegin;
24: PetscLogEvent MAT_QRFactorNumeric, MAT_QRFactorSymbolic, MAT_QRFactor;
25: PetscLogEvent MAT_AssemblyEnd, MAT_SetValues, MAT_GetValues, MAT_GetRow, MAT_GetRowIJ, MAT_CreateSubMats, MAT_GetOrdering, MAT_RedundantMat, MAT_GetSeqNonzeroStructure;
26: PetscLogEvent MAT_IncreaseOverlap, MAT_Partitioning, MAT_PartitioningND, MAT_Coarsen, MAT_ZeroEntries, MAT_Load, MAT_View, MAT_AXPY, MAT_FDColoringCreate;
27: PetscLogEvent MAT_FDColoringSetUp, MAT_FDColoringApply, MAT_Transpose, MAT_FDColoringFunction, MAT_CreateSubMat;
28: PetscLogEvent MAT_TransposeColoringCreate;
29: PetscLogEvent MAT_MatMult, MAT_MatMultSymbolic, MAT_MatMultNumeric;
30: PetscLogEvent MAT_PtAP, MAT_PtAPSymbolic, MAT_PtAPNumeric, MAT_RARt, MAT_RARtSymbolic, MAT_RARtNumeric;
31: PetscLogEvent MAT_MatTransposeMult, MAT_MatTransposeMultSymbolic, MAT_MatTransposeMultNumeric;
32: PetscLogEvent MAT_TransposeMatMult, MAT_TransposeMatMultSymbolic, MAT_TransposeMatMultNumeric;
33: PetscLogEvent MAT_MatMatMult, MAT_MatMatMultSymbolic, MAT_MatMatMultNumeric;
34: PetscLogEvent MAT_MultHermitianTranspose, MAT_MultHermitianTransposeAdd;
35: PetscLogEvent MAT_Getsymtransreduced, MAT_GetBrowsOfAcols;
36: PetscLogEvent MAT_GetBrowsOfAocols, MAT_Getlocalmat, MAT_Getlocalmatcondensed, MAT_Seqstompi, MAT_Seqstompinum, MAT_Seqstompisym;
37: PetscLogEvent MAT_GetMultiProcBlock;
38: PetscLogEvent MAT_CUSPARSECopyToGPU, MAT_CUSPARSECopyFromGPU, MAT_CUSPARSEGenerateTranspose, MAT_CUSPARSESolveAnalysis;
39: PetscLogEvent MAT_HIPSPARSECopyToGPU, MAT_HIPSPARSECopyFromGPU, MAT_HIPSPARSEGenerateTranspose, MAT_HIPSPARSESolveAnalysis;
40: PetscLogEvent MAT_PreallCOO, MAT_SetVCOO;
41: PetscLogEvent MAT_CreateGraph;
42: PetscLogEvent MAT_SetValuesBatch;
43: PetscLogEvent MAT_ViennaCLCopyToGPU;
44: PetscLogEvent MAT_CUDACopyToGPU, MAT_HIPCopyToGPU;
45: PetscLogEvent MAT_DenseCopyToGPU, MAT_DenseCopyFromGPU;
46: PetscLogEvent MAT_Merge, MAT_Residual, MAT_SetRandom;
47: PetscLogEvent MAT_FactorFactS, MAT_FactorInvS;
48: PetscLogEvent MATCOLORING_Apply, MATCOLORING_Comm, MATCOLORING_Local, MATCOLORING_ISCreate, MATCOLORING_SetUp, MATCOLORING_Weights;
49: PetscLogEvent MAT_H2Opus_Build, MAT_H2Opus_Compress, MAT_H2Opus_Orthog, MAT_H2Opus_LR;
51: const char *const MatFactorTypes[] = {"NONE", "LU", "CHOLESKY", "ILU", "ICC", "ILUDT", "QR", "MatFactorType", "MAT_FACTOR_", NULL};
53: /*@
54: MatSetRandom - Sets all components of a matrix to random numbers.
56: Logically Collective
58: Input Parameters:
59: + x - the matrix
60: - rctx - the `PetscRandom` object, formed by `PetscRandomCreate()`, or `NULL` and
61: it will create one internally.
63: Level: intermediate
65: Notes:
66: For sparse matrices that have been preallocated but not been assembled, it randomly selects appropriate locations,
68: for sparse matrices that already have nonzero locations, it fills the locations with random numbers.
70: It generates an error if used on unassembled sparse matrices that have not been preallocated.
72: If values have been inserted with `MatSetValues()`, call `MatAssemblyBegin()` and `MatAssemblyEnd()` before calling this routine.
73: The matrix is assembled on return.
75: Example Usage:
76: .vb
77: PetscRandomCreate(PETSC_COMM_WORLD, &rctx);
78: MatSetRandom(x, rctx);
79: PetscRandomDestroy(&rctx);
80: .ve
82: Developer Notes:
83: Implementations must leave the matrix assembled with increased object state, assembling it themselves when it is not already the case.
84: Implementations that insert only local entries can temporarily set `MAT_NO_OFF_PROC_ENTRIES` to `PETSC_TRUE` during assembly, restoring its previous value afterwards.
86: .seealso: [](ch_matrices), `Mat`, `PetscRandom`, `PetscRandomCreate()`, `MatZeroEntries()`, `MatSetValues()`, `PetscRandomDestroy()`
87: @*/
88: PetscErrorCode MatSetRandom(Mat x, PetscRandom rctx)
89: {
90: PetscRandom randObj = NULL;
92: PetscFunctionBegin;
96: PetscCheck(x->insertmode == NOT_SET_VALUES, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for matrices where you have set values but not yet assembled");
97: MatCheckPreallocated(x, 1);
99: if (!rctx) {
100: MPI_Comm comm;
101: PetscCall(PetscObjectGetComm((PetscObject)x, &comm));
102: PetscCall(PetscRandomCreate(comm, &randObj));
103: PetscCall(PetscRandomSetType(randObj, x->defaultrandtype));
104: PetscCall(PetscRandomSetFromOptions(randObj));
105: rctx = randObj;
106: }
107: PetscCall(PetscLogEventBegin(MAT_SetRandom, x, rctx, 0, 0));
108: PetscUseTypeMethod(x, setrandom, rctx);
109: PetscCall(PetscLogEventEnd(MAT_SetRandom, x, rctx, 0, 0));
111: PetscCall(PetscRandomDestroy(&randObj));
112: PetscFunctionReturn(PETSC_SUCCESS);
113: }
115: /*@
116: MatCopyHashToXAIJ - copy hash table entries into an XAIJ matrix type
118: Logically Collective
120: Input Parameter:
121: . A - A matrix in unassembled, hash table form
123: Output Parameter:
124: . B - The XAIJ matrix. This can either be `A` or some matrix of equivalent size, e.g. obtained from `A` via `MatDuplicate()`
126: Example:
127: .vb
128: PetscCall(MatDuplicate(A, MAT_DO_NOT_COPY_VALUES, &B));
129: PetscCall(MatCopyHashToXAIJ(A, B));
130: .ve
132: Level: advanced
134: Notes:
135: If `B` is `A`, then the hash table data structure will be destroyed. `B` is assembled
137: .seealso: [](ch_matrices), `Mat`, `MAT_USE_HASH_TABLE`
138: @*/
139: PetscErrorCode MatCopyHashToXAIJ(Mat A, Mat B)
140: {
141: PetscFunctionBegin;
143: PetscUseTypeMethod(A, copyhashtoxaij, B);
144: PetscFunctionReturn(PETSC_SUCCESS);
145: }
147: /*@
148: MatFactorGetErrorZeroPivot - returns the pivot value that was determined to be zero and the row it occurred in
150: Logically Collective
152: Input Parameter:
153: . mat - the factored matrix
155: Output Parameters:
156: + pivot - the pivot value computed
157: - row - the row that the zero pivot occurred. This row value must be interpreted carefully due to row reorderings and which processes
158: the share the matrix
160: Level: advanced
162: Notes:
163: This routine does not work for factorizations done with external packages.
165: This routine should only be called if `MatGetFactorError()` returns a value of `MAT_FACTOR_NUMERIC_ZEROPIVOT`
167: This can also be called on non-factored matrices that come from, for example, matrices used in SOR.
169: .seealso: [](ch_matrices), `Mat`, `MatZeroEntries()`, `MatFactor()`, `MatGetFactor()`,
170: `MatLUFactorSymbolic()`, `MatCholeskyFactorSymbolic()`, `MatFactorClearError()`,
171: `MAT_FACTOR_NUMERIC_ZEROPIVOT`
172: @*/
173: PetscErrorCode MatFactorGetErrorZeroPivot(Mat mat, PetscReal *pivot, PetscInt *row)
174: {
175: PetscFunctionBegin;
177: PetscAssertPointer(pivot, 2);
178: PetscAssertPointer(row, 3);
179: *pivot = mat->factorerror_zeropivot_value;
180: *row = mat->factorerror_zeropivot_row;
181: PetscFunctionReturn(PETSC_SUCCESS);
182: }
184: /*@
185: MatFactorGetError - gets the error code from a factorization
187: Logically Collective
189: Input Parameter:
190: . mat - the factored matrix
192: Output Parameter:
193: . err - the error code
195: Level: advanced
197: Note:
198: This can also be called on non-factored matrices that come from, for example, matrices used in SOR.
200: .seealso: [](ch_matrices), `Mat`, `MatZeroEntries()`, `MatFactor()`, `MatGetFactor()`, `MatLUFactorSymbolic()`, `MatCholeskyFactorSymbolic()`,
201: `MatFactorClearError()`, `MatFactorGetErrorZeroPivot()`, `MatFactorError`
202: @*/
203: PetscErrorCode MatFactorGetError(Mat mat, MatFactorError *err)
204: {
205: PetscFunctionBegin;
207: PetscAssertPointer(err, 2);
208: *err = mat->factorerrortype;
209: PetscFunctionReturn(PETSC_SUCCESS);
210: }
212: /*@
213: MatFactorClearError - clears the error code in a factorization
215: Logically Collective
217: Input Parameter:
218: . mat - the factored matrix
220: Level: developer
222: Note:
223: This can also be called on non-factored matrices that come from, for example, matrices used in SOR.
225: .seealso: [](ch_matrices), `Mat`, `MatZeroEntries()`, `MatFactor()`, `MatGetFactor()`, `MatLUFactorSymbolic()`, `MatCholeskyFactorSymbolic()`, `MatFactorGetError()`, `MatFactorGetErrorZeroPivot()`,
226: `MatGetErrorCode()`, `MatFactorError`
227: @*/
228: PetscErrorCode MatFactorClearError(Mat mat)
229: {
230: PetscFunctionBegin;
232: mat->factorerrortype = MAT_FACTOR_NOERROR;
233: mat->factorerror_zeropivot_value = 0.0;
234: mat->factorerror_zeropivot_row = 0;
235: PetscFunctionReturn(PETSC_SUCCESS);
236: }
238: PetscErrorCode MatFindNonzeroRowsOrCols_Basic(Mat mat, PetscBool cols, PetscReal tol, IS *nonzero)
239: {
240: Vec r, l;
241: const PetscScalar *al;
242: PetscInt i, nz, gnz, N, n, st;
244: PetscFunctionBegin;
245: PetscCall(MatCreateVecs(mat, &r, &l));
246: if (!cols) { /* nonzero rows */
247: PetscCall(MatGetOwnershipRange(mat, &st, NULL));
248: PetscCall(MatGetSize(mat, &N, NULL));
249: PetscCall(MatGetLocalSize(mat, &n, NULL));
250: PetscCall(VecSetRandom(r, NULL));
251: PetscCall(MatMult(mat, r, l));
252: PetscCall(VecGetArrayRead(l, &al));
253: } else { /* nonzero columns */
254: PetscCall(MatGetOwnershipRangeColumn(mat, &st, NULL));
255: PetscCall(MatGetSize(mat, NULL, &N));
256: PetscCall(MatGetLocalSize(mat, NULL, &n));
257: PetscCall(VecSet(r, 0.0));
258: PetscCall(VecSetRandom(l, NULL));
259: PetscCall(MatMultTranspose(mat, l, r));
260: PetscCall(VecGetArrayRead(r, &al));
261: }
262: if (tol <= 0.0) {
263: for (i = 0, nz = 0; i < n; i++)
264: if (al[i] != 0.0) nz++;
265: } else {
266: for (i = 0, nz = 0; i < n; i++)
267: if (PetscAbsScalar(al[i]) > tol) nz++;
268: }
269: PetscCallMPI(MPIU_Allreduce(&nz, &gnz, 1, MPIU_INT, MPI_SUM, PetscObjectComm((PetscObject)mat)));
270: if (gnz != N) {
271: PetscInt *nzr;
272: PetscCall(PetscMalloc1(nz, &nzr));
273: if (nz) {
274: if (tol < 0) {
275: for (i = 0, nz = 0; i < n; i++)
276: if (al[i] != 0.0) nzr[nz++] = i + st;
277: } else {
278: for (i = 0, nz = 0; i < n; i++)
279: if (PetscAbsScalar(al[i]) > tol) nzr[nz++] = i + st;
280: }
281: }
282: PetscCall(ISCreateGeneral(PetscObjectComm((PetscObject)mat), nz, nzr, PETSC_OWN_POINTER, nonzero));
283: } else *nonzero = NULL;
284: if (!cols) { /* nonzero rows */
285: PetscCall(VecRestoreArrayRead(l, &al));
286: } else {
287: PetscCall(VecRestoreArrayRead(r, &al));
288: }
289: PetscCall(VecDestroy(&l));
290: PetscCall(VecDestroy(&r));
291: PetscFunctionReturn(PETSC_SUCCESS);
292: }
294: /*@
295: MatFindNonzeroRows - Locate all rows that are not completely zero in the matrix
297: Input Parameter:
298: . mat - the matrix
300: Output Parameter:
301: . keptrows - the rows that are not completely zero
303: Level: intermediate
305: Note:
306: `keptrows` is set to `NULL` if all rows are nonzero.
308: Developer Note:
309: If `keptrows` is not `NULL`, it must be sorted.
311: .seealso: [](ch_matrices), `Mat`, `MatFindZeroRows()`
312: @*/
313: PetscErrorCode MatFindNonzeroRows(Mat mat, IS *keptrows)
314: {
315: PetscFunctionBegin;
318: PetscAssertPointer(keptrows, 2);
319: PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
320: PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
321: if (mat->ops->findnonzerorows) PetscUseTypeMethod(mat, findnonzerorows, keptrows);
322: else PetscCall(MatFindNonzeroRowsOrCols_Basic(mat, PETSC_FALSE, 0.0, keptrows));
323: if (keptrows && *keptrows) PetscCall(ISSetInfo(*keptrows, IS_SORTED, IS_GLOBAL, PETSC_FALSE, PETSC_TRUE));
324: PetscFunctionReturn(PETSC_SUCCESS);
325: }
327: /*@
328: MatFindZeroRows - Locate all rows that are completely zero in the matrix
330: Input Parameter:
331: . mat - the matrix
333: Output Parameter:
334: . zerorows - the rows that are completely zero
336: Level: intermediate
338: Note:
339: `zerorows` is set to `NULL` if no rows are zero.
341: .seealso: [](ch_matrices), `Mat`, `MatFindNonzeroRows()`
342: @*/
343: PetscErrorCode MatFindZeroRows(Mat mat, IS *zerorows)
344: {
345: IS keptrows;
346: PetscInt m, n;
348: PetscFunctionBegin;
351: PetscAssertPointer(zerorows, 2);
352: PetscCall(MatFindNonzeroRows(mat, &keptrows));
353: /* MatFindNonzeroRows sets keptrows to NULL if there are no zero rows.
354: In keeping with this convention, we set zerorows to NULL if there are no zero
355: rows. */
356: if (keptrows == NULL) {
357: *zerorows = NULL;
358: } else {
359: PetscCall(MatGetOwnershipRange(mat, &m, &n));
360: PetscCall(ISComplement(keptrows, m, n, zerorows));
361: PetscCall(ISDestroy(&keptrows));
362: }
363: PetscFunctionReturn(PETSC_SUCCESS);
364: }
366: /*@
367: MatGetDiagonalBlock - Returns the part of the matrix associated with the on-process coupling
369: Not Collective
371: Input Parameter:
372: . A - the matrix
374: Output Parameter:
375: . a - the diagonal part (which is a SEQUENTIAL matrix)
377: Level: advanced
379: Notes:
380: See `MatCreateAIJ()` for more information on the "diagonal part" of the matrix.
382: Use caution, as the reference count on the returned matrix is not incremented and it is used as part of `A`'s normal operation.
384: .seealso: [](ch_matrices), `Mat`, `MatCreateAIJ()`, `MATAIJ`, `MATBAIJ`, `MATSBAIJ`
385: @*/
386: PetscErrorCode MatGetDiagonalBlock(Mat A, Mat *a)
387: {
388: PetscFunctionBegin;
391: PetscAssertPointer(a, 2);
392: PetscCheck(!A->factortype, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
393: if (A->ops->getdiagonalblock) PetscUseTypeMethod(A, getdiagonalblock, a);
394: else {
395: PetscMPIInt size;
397: PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)A), &size));
398: PetscCheck(size == 1, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "Not for parallel matrix type %s", ((PetscObject)A)->type_name);
399: *a = A;
400: }
401: PetscFunctionReturn(PETSC_SUCCESS);
402: }
404: /*@
405: MatGetMultPetscSF - Returns the `PetscSF` that communicates to each MPI process the values held on other MPI processes that are coupled to it by the `Mat`
407: Not Collective
409: Input Parameter:
410: . A - the matrix
412: Output Parameter:
413: . sf - the `PetscSF`.
415: Level: advanced
417: Notes:
418: The returned `PetscSF` is owned by the matrix; do not destroy it.
420: It is only valid if this function is called after the matrix has been assembled
421: (and for `MATMPIDENSE` after a `MatMult()` has been additionally called).
423: This is only implemented for the matrix types listed below; calling it on a sequential matrix or a type that does not
424: build such a `PetscSF` raises an error.
426: For `MATMPIAIJ`, `MATMPIBAIJ`, `MATMPIDENSE`, and `MATMPISELL`, this `PetscSF` is used within
427: `MatMult()` to provide the contribution of vector entries that are not local to each MPI process to the matrix-vector product.
428: For `MATMPISBAIJ` the returned `PetscSF` is instead the off-process column gather used by operations such as
429: `MatDiagonalScale()`; `MatMult_MPISBAIJ()` uses a separate, augmented scatter context.
430: In all cases the `PetscSF` maps the global vector layout (the matrix column layout) onto the off-process columns that the local rows couple to,
431: so it can be reused to communicate any per-column data, for example with `PetscSFBcastBegin()`.
433: For `MATMPIDENSE` this `PetscSF` is an allgather: every process gathers all columns, including its own, in the natural global
434: order rather than a sparse `garray` order. The leaf set and ordering therefore differ across matrix types, so callers should use
435: `PetscSFGetGraph()` rather than assume a particular leaf layout.
437: .seealso: [](ch_matrices), `Mat`, `PetscSF`, `MatGetDiagonalBlock()`, `MatMPIAIJGetSeqAIJ()`, `PetscSFBcastBegin()`, `MatMult()`
438: @*/
439: PetscErrorCode MatGetMultPetscSF(Mat A, PetscSF *sf)
440: {
441: PetscFunctionBegin;
444: PetscAssertPointer(sf, 2);
445: PetscCheck(A->assembled, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
446: *sf = NULL;
447: PetscUseMethod(A, "MatGetMultPetscSF_C", (Mat, PetscSF *), (A, sf));
448: PetscFunctionReturn(PETSC_SUCCESS);
449: }
451: /*@
452: MatGetTrace - Gets the trace of a matrix. The sum of the diagonal entries.
454: Collective
456: Input Parameter:
457: . mat - the matrix
459: Output Parameter:
460: . trace - the sum of the diagonal entries
462: Level: advanced
464: .seealso: [](ch_matrices), `Mat`
465: @*/
466: PetscErrorCode MatGetTrace(Mat mat, PetscScalar *trace)
467: {
468: Vec diag;
470: PetscFunctionBegin;
472: PetscAssertPointer(trace, 2);
473: PetscCall(MatCreateVecs(mat, &diag, NULL));
474: PetscCall(MatGetDiagonal(mat, diag));
475: PetscCall(VecSum(diag, trace));
476: PetscCall(VecDestroy(&diag));
477: PetscFunctionReturn(PETSC_SUCCESS);
478: }
480: /*@
481: MatRealPart - Zeros out the imaginary part of the matrix
483: Logically Collective
485: Input Parameter:
486: . mat - the matrix
488: Level: advanced
490: .seealso: [](ch_matrices), `Mat`, `MatImaginaryPart()`
491: @*/
492: PetscErrorCode MatRealPart(Mat mat)
493: {
494: PetscFunctionBegin;
497: PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
498: PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
499: MatCheckPreallocated(mat, 1);
500: PetscUseTypeMethod(mat, realpart);
501: PetscCall(PetscObjectStateIncrease((PetscObject)mat));
502: PetscFunctionReturn(PETSC_SUCCESS);
503: }
505: /*@
506: MatGetGhosts - Get the global indices of all ghost nodes defined by the sparse matrix
508: Collective
510: Input Parameter:
511: . mat - the matrix
513: Output Parameters:
514: + nghosts - number of ghosts (for `MATBAIJ` and `MATSBAIJ` matrices there is one ghost for each matrix block)
515: - ghosts - the global indices of the ghost points
517: Level: advanced
519: Note:
520: `nghosts` and `ghosts` are suitable to pass into `VecCreateGhost()` or `VecCreateGhostBlock()`
522: .seealso: [](ch_matrices), `Mat`, `VecCreateGhost()`, `VecCreateGhostBlock()`
523: @*/
524: PetscErrorCode MatGetGhosts(Mat mat, PetscInt *nghosts, const PetscInt *ghosts[])
525: {
526: PetscFunctionBegin;
529: PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
530: PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
531: if (mat->ops->getghosts) PetscUseTypeMethod(mat, getghosts, nghosts, ghosts);
532: else {
533: if (nghosts) *nghosts = 0;
534: if (ghosts) *ghosts = NULL;
535: }
536: PetscFunctionReturn(PETSC_SUCCESS);
537: }
539: /*@
540: MatImaginaryPart - Moves the imaginary part of the matrix to the real part and zeros the imaginary part
542: Logically Collective
544: Input Parameter:
545: . mat - the matrix
547: Level: advanced
549: .seealso: [](ch_matrices), `Mat`, `MatRealPart()`
550: @*/
551: PetscErrorCode MatImaginaryPart(Mat mat)
552: {
553: PetscFunctionBegin;
556: PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
557: PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
558: MatCheckPreallocated(mat, 1);
559: PetscUseTypeMethod(mat, imaginarypart);
560: PetscCall(PetscObjectStateIncrease((PetscObject)mat));
561: PetscFunctionReturn(PETSC_SUCCESS);
562: }
564: // PetscClangLinter pragma disable: -fdoc-section-header-unknown
565: /*@
566: MatGetRow - Gets a row of a matrix. You MUST call `MatRestoreRow()`
567: for each row that you get to ensure that your application does
568: not bleed memory.
570: Not Collective
572: Input Parameters:
573: + mat - the matrix
574: - row - the row to get
576: Output Parameters:
577: + ncols - if not `NULL`, the number of nonzeros in `row`
578: . cols - if not `NULL`, the column numbers
579: - vals - if not `NULL`, the numerical values
581: Level: advanced
583: Notes:
584: This routine is provided for people who need to have direct access
585: to the structure of a matrix. We hope that we provide enough
586: high-level matrix routines that few users will need it.
588: `MatGetRow()` always returns 0-based column indices, regardless of
589: whether the internal representation is 0-based (default) or 1-based.
591: For better efficiency, set `cols` and/or `vals` to `NULL` if you do
592: not wish to extract these quantities. `vals` must be `NULL` for a matrix with
593: the `MAT_STRUCTURE_ONLY` option set to true, since no numerical values are stored.
595: The user can only examine the values extracted with `MatGetRow()`;
596: the values CANNOT be altered. To change the matrix entries, one
597: must use `MatSetValues()`.
599: You can only have one call to `MatGetRow()` outstanding for a particular
600: matrix at a time, per process. `MatGetRow()` can only obtain rows
601: associated with the given process, it cannot get rows from the
602: other processes; for that we suggest using `MatCreateSubMatrices()`, then
603: `MatGetRow()` on the submatrix. The row index passed to `MatGetRow()`
604: is in the global number of rows.
606: Use `MatGetRowIJ()` and `MatRestoreRowIJ()` to access all the local indices of the sparse matrix.
608: Use `MatSeqAIJGetArray()` and similar functions to access the numerical values for certain matrix types directly.
610: Fortran Note:
611: .vb
612: PetscInt, pointer :: cols(:)
613: PetscScalar, pointer :: vals(:)
614: .ve
616: .seealso: [](ch_matrices), `Mat`, `MatRestoreRow()`, `MatSetValues()`, `MatGetValues()`, `MatCreateSubMatrices()`, `MatGetDiagonal()`, `MatGetRowIJ()`, `MatRestoreRowIJ()`
617: @*/
618: PetscErrorCode MatGetRow(Mat mat, PetscInt row, PetscInt *ncols, const PetscInt *cols[], const PetscScalar *vals[])
619: {
620: PetscInt incols;
622: PetscFunctionBegin;
625: PetscCheck(mat->assembled, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
626: PetscCheck(!mat->factortype, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
627: PetscCheck(!mat->structure_only || vals == NULL, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for matrix with MAT_STRUCTURE_ONLY");
628: MatCheckPreallocated(mat, 1);
629: 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);
630: PetscCall(PetscLogEventBegin(MAT_GetRow, mat, 0, 0, 0));
631: PetscUseTypeMethod(mat, getrow, row, &incols, (PetscInt **)cols, (PetscScalar **)vals);
632: if (ncols) *ncols = incols;
633: PetscCall(PetscLogEventEnd(MAT_GetRow, mat, 0, 0, 0));
634: PetscFunctionReturn(PETSC_SUCCESS);
635: }
637: /*@
638: MatConjugate - replaces the matrix values with their complex conjugates
640: Logically Collective
642: Input Parameter:
643: . mat - the matrix
645: Level: advanced
647: .seealso: [](ch_matrices), `Mat`, `MatRealPart()`, `MatImaginaryPart()`, `VecConjugate()`, `MatTranspose()`
648: @*/
649: PetscErrorCode MatConjugate(Mat mat)
650: {
651: PetscFunctionBegin;
653: PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
654: if (PetscDefined(USE_COMPLEX) && !(mat->symmetric == PETSC_BOOL3_TRUE && mat->hermitian == PETSC_BOOL3_TRUE)) {
655: PetscUseTypeMethod(mat, conjugate);
656: PetscCall(PetscObjectStateIncrease((PetscObject)mat));
657: }
658: PetscFunctionReturn(PETSC_SUCCESS);
659: }
661: /*@
662: MatRestoreRow - Frees any temporary space allocated by `MatGetRow()`.
664: Not Collective
666: Input Parameters:
667: + mat - the matrix
668: . row - the row to get
669: . ncols - the number of nonzeros
670: . cols - the columns of the nonzeros
671: - vals - if nonzero the column values
673: Level: advanced
675: Notes:
676: This routine should be called after you have finished examining the entries.
678: This routine zeros out `ncols`, `cols`, and `vals`. This is to prevent accidental
679: us of the array after it has been restored. If you pass `NULL`, it will
680: not zero the pointers. Use of `cols` or `vals` after `MatRestoreRow()` is invalid.
682: Fortran Note:
683: .vb
684: PetscInt, pointer :: cols(:)
685: PetscScalar, pointer :: vals(:)
686: .ve
688: .seealso: [](ch_matrices), `Mat`, `MatGetRow()`
689: @*/
690: PetscErrorCode MatRestoreRow(Mat mat, PetscInt row, PetscInt *ncols, const PetscInt *cols[], const PetscScalar *vals[])
691: {
692: PetscFunctionBegin;
694: if (ncols) PetscAssertPointer(ncols, 3);
695: PetscCheck(mat->assembled, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
696: PetscTryTypeMethod(mat, restorerow, row, ncols, (PetscInt **)cols, (PetscScalar **)vals);
697: if (ncols) *ncols = 0;
698: if (cols) *cols = NULL;
699: if (vals) *vals = NULL;
700: PetscFunctionReturn(PETSC_SUCCESS);
701: }
703: /*@
704: MatGetRowUpperTriangular - Sets a flag to enable calls to `MatGetRow()` for matrix in `MATSBAIJ` format.
705: You should call `MatRestoreRowUpperTriangular()` after calling` MatGetRow()` and `MatRestoreRow()` to disable the flag.
707: Not Collective
709: Input Parameter:
710: . mat - the matrix
712: Level: advanced
714: Note:
715: 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.
717: .seealso: [](ch_matrices), `Mat`, `MATSBAIJ`, `MatRestoreRowUpperTriangular()`
718: @*/
719: PetscErrorCode MatGetRowUpperTriangular(Mat mat)
720: {
721: PetscFunctionBegin;
724: PetscCheck(mat->assembled, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
725: PetscCheck(!mat->factortype, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
726: MatCheckPreallocated(mat, 1);
727: PetscTryTypeMethod(mat, getrowuppertriangular);
728: PetscFunctionReturn(PETSC_SUCCESS);
729: }
731: /*@
732: MatRestoreRowUpperTriangular - Disable calls to `MatGetRow()` for matrix in `MATSBAIJ` format.
734: Not Collective
736: Input Parameter:
737: . mat - the matrix
739: Level: advanced
741: Note:
742: This routine should be called after you have finished calls to `MatGetRow()` and `MatRestoreRow()`.
744: .seealso: [](ch_matrices), `Mat`, `MATSBAIJ`, `MatGetRowUpperTriangular()`
745: @*/
746: PetscErrorCode MatRestoreRowUpperTriangular(Mat mat)
747: {
748: PetscFunctionBegin;
751: PetscCheck(mat->assembled, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
752: PetscCheck(!mat->factortype, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
753: MatCheckPreallocated(mat, 1);
754: PetscTryTypeMethod(mat, restorerowuppertriangular);
755: PetscFunctionReturn(PETSC_SUCCESS);
756: }
758: /*@
759: MatSetOptionsPrefix - Sets the prefix used for searching for all
760: `Mat` options in the database.
762: Logically Collective
764: Input Parameters:
765: + A - the matrix
766: - prefix - the prefix to prepend to all option names
768: Level: advanced
770: Notes:
771: A hyphen (-) must NOT be given at the beginning of the prefix name.
772: The first character of all runtime options is AUTOMATICALLY the hyphen.
774: This is NOT used for options for the factorization of the matrix. Normally the
775: prefix is automatically passed in from the PC calling the factorization. To set
776: it directly use `MatSetOptionsPrefixFactor()`
778: .seealso: [](ch_matrices), `Mat`, `MatSetFromOptions()`, `MatSetOptionsPrefixFactor()`
779: @*/
780: PetscErrorCode MatSetOptionsPrefix(Mat A, const char prefix[])
781: {
782: PetscFunctionBegin;
784: PetscCall(PetscObjectSetOptionsPrefix((PetscObject)A, prefix));
785: PetscTryMethod(A, "MatSetOptionsPrefix_C", (Mat, const char[]), (A, prefix));
786: PetscFunctionReturn(PETSC_SUCCESS);
787: }
789: /*@
790: MatSetOptionsPrefixFactor - Sets the prefix used for searching for all matrix factor options in the database for
791: for matrices created with `MatGetFactor()`
793: Logically Collective
795: Input Parameters:
796: + A - the matrix
797: - prefix - the prefix to prepend to all option names for the factored matrix
799: Level: developer
801: Notes:
802: A hyphen (-) must NOT be given at the beginning of the prefix name.
803: The first character of all runtime options is AUTOMATICALLY the hyphen.
805: Normally the prefix is automatically passed in from the `PC` calling the factorization. To set
806: it directly when not using `KSP`/`PC` use `MatSetOptionsPrefixFactor()`
808: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatGetFactor()`, `MatSetFromOptions()`, `MatSetOptionsPrefix()`, `MatAppendOptionsPrefixFactor()`
809: @*/
810: PetscErrorCode MatSetOptionsPrefixFactor(Mat A, const char prefix[])
811: {
812: PetscFunctionBegin;
814: if (prefix) {
815: PetscAssertPointer(prefix, 2);
816: PetscCheck(prefix[0] != '-', PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_WRONG, "Options prefix should not begin with a hyphen");
817: if (prefix != A->factorprefix) {
818: PetscCall(PetscFree(A->factorprefix));
819: PetscCall(PetscStrallocpy(prefix, &A->factorprefix));
820: }
821: } else PetscCall(PetscFree(A->factorprefix));
822: PetscFunctionReturn(PETSC_SUCCESS);
823: }
825: /*@
826: MatAppendOptionsPrefixFactor - Appends to the prefix used for searching for all matrix factor options in the database for
827: for matrices created with `MatGetFactor()`
829: Logically Collective
831: Input Parameters:
832: + A - the matrix
833: - prefix - the prefix to prepend to all option names for the factored matrix
835: Level: developer
837: Notes:
838: A hyphen (-) must NOT be given at the beginning of the prefix name.
839: The first character of all runtime options is AUTOMATICALLY the hyphen.
841: Normally the prefix is automatically passed in from the `PC` calling the factorization. To set
842: it directly when not using `KSP`/`PC` use `MatAppendOptionsPrefixFactor()`
844: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatGetFactor()`, `PetscOptionsCreate()`, `PetscOptionsDestroy()`, `PetscObjectSetOptionsPrefix()`, `PetscObjectPrependOptionsPrefix()`,
845: `PetscObjectGetOptionsPrefix()`, `TSAppendOptionsPrefix()`, `SNESAppendOptionsPrefix()`, `KSPAppendOptionsPrefix()`, `MatSetOptionsPrefixFactor()`,
846: `MatSetOptionsPrefix()`
847: @*/
848: PetscErrorCode MatAppendOptionsPrefixFactor(Mat A, const char prefix[])
849: {
850: size_t len1, len2, new_len;
852: PetscFunctionBegin;
854: if (!prefix) PetscFunctionReturn(PETSC_SUCCESS);
855: if (!A->factorprefix) {
856: PetscCall(MatSetOptionsPrefixFactor(A, prefix));
857: PetscFunctionReturn(PETSC_SUCCESS);
858: }
859: PetscCheck(prefix[0] != '-', PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_WRONG, "Options prefix should not begin with a hyphen");
861: PetscCall(PetscStrlen(A->factorprefix, &len1));
862: PetscCall(PetscStrlen(prefix, &len2));
863: new_len = len1 + len2 + 1;
864: PetscCall(PetscRealloc(new_len * sizeof(*A->factorprefix), &A->factorprefix));
865: PetscCall(PetscStrncpy(A->factorprefix + len1, prefix, len2 + 1));
866: PetscFunctionReturn(PETSC_SUCCESS);
867: }
869: /*@
870: MatAppendOptionsPrefix - Appends to the prefix used for searching for all
871: matrix options in the database.
873: Logically Collective
875: Input Parameters:
876: + A - the matrix
877: - prefix - the prefix to prepend to all option names
879: Level: advanced
881: Note:
882: A hyphen (-) must NOT be given at the beginning of the prefix name.
883: The first character of all runtime options is AUTOMATICALLY the hyphen.
885: .seealso: [](ch_matrices), `Mat`, `MatGetOptionsPrefix()`, `MatAppendOptionsPrefixFactor()`, `MatSetOptionsPrefix()`
886: @*/
887: PetscErrorCode MatAppendOptionsPrefix(Mat A, const char prefix[])
888: {
889: PetscFunctionBegin;
891: PetscCall(PetscObjectAppendOptionsPrefix((PetscObject)A, prefix));
892: PetscTryMethod(A, "MatAppendOptionsPrefix_C", (Mat, const char[]), (A, prefix));
893: PetscFunctionReturn(PETSC_SUCCESS);
894: }
896: /*@
897: MatGetOptionsPrefix - Gets the prefix used for searching for all
898: matrix options in the database.
900: Not Collective
902: Input Parameter:
903: . A - the matrix
905: Output Parameter:
906: . prefix - pointer to the prefix string used
908: Level: advanced
910: .seealso: [](ch_matrices), `Mat`, `MatAppendOptionsPrefix()`, `MatSetOptionsPrefix()`, `MatAppendOptionsPrefixFactor()`, `MatSetOptionsPrefixFactor()`
911: @*/
912: PetscErrorCode MatGetOptionsPrefix(Mat A, const char *prefix[])
913: {
914: PetscFunctionBegin;
916: PetscAssertPointer(prefix, 2);
917: PetscCall(PetscObjectGetOptionsPrefix((PetscObject)A, prefix));
918: PetscFunctionReturn(PETSC_SUCCESS);
919: }
921: /*@
922: MatGetState - Gets a snapshot of the state of a `Mat`
924: Not Collective
926: Input Parameter:
927: . A - the matrix
929: Output Parameter:
930: . state - the matrix state
932: Level: developer
934: Note:
935: The snapshot includes the matrix object id, state, and nonzero state. Use `MatStateCompare()` to determine whether two snapshots are the same, or `MatStateCompareUpdate()` to compare and update a saved snapshot.
937: .seealso: [](ch_matrices), `Mat`, `MatState`, `MatStateCompare()`, `MatStateCompareUpdate()`, `MatStateInvalidate()`, `PetscObjectStateGet()`, `PetscObjectGetId()`, `MatGetNonzeroState()`
938: @*/
939: PetscErrorCode MatGetState(Mat A, MatState *state)
940: {
941: PetscFunctionBegin;
943: PetscAssertPointer(state, 2);
944: state->id = ((PetscObject)A)->id;
945: state->state = ((PetscObject)A)->state;
946: state->nonzerostate = A->nonzerostate;
947: PetscFunctionReturn(PETSC_SUCCESS);
948: }
950: /*@
951: MatStateCompare - Compares two matrix state snapshots
953: Not Collective
955: Input Parameters:
956: + state1 - the first matrix state
957: - state2 - the second matrix state
959: Output Parameter:
960: . same - `PETSC_TRUE` if the matrix object id, state, and nonzero state are the same, `PETSC_FALSE` otherwise
962: Level: developer
964: .seealso: [](ch_matrices), `Mat`, `MatState`, `MatGetState()`, `MatStateCompareUpdate()`, `MatStateInvalidate()`
965: @*/
966: PetscErrorCode MatStateCompare(MatState state1, MatState state2, PetscBool *same)
967: {
968: PetscFunctionBegin;
969: PetscAssertPointer(same, 3);
970: *same = (PetscBool)(state1.id == state2.id && state1.state == state2.state && state1.nonzerostate == state2.nonzerostate);
971: PetscFunctionReturn(PETSC_SUCCESS);
972: }
974: /*@
975: MatStateCompareUpdate - Compares a matrix with a state snapshot, then updates the snapshot
977: Not Collective
979: Input Parameter:
980: . A - the matrix
982: Input/Output Parameter:
983: . state - the matrix state snapshot to compare with and update
985: Output Parameter:
986: . same - `PETSC_TRUE` if the matrix state matched the snapshot before it was updated, `PETSC_FALSE` otherwise
988: Level: developer
990: .seealso: [](ch_matrices), `Mat`, `MatState`, `MatGetState()`, `MatStateCompare()`, `MatStateInvalidate()`
991: @*/
992: PetscErrorCode MatStateCompareUpdate(Mat A, MatState *state, PetscBool *same)
993: {
994: MatState current;
996: PetscFunctionBegin;
998: PetscAssertPointer(state, 2);
999: PetscAssertPointer(same, 3);
1000: PetscCall(MatGetState(A, ¤t));
1001: PetscCall(MatStateCompare(current, *state, same));
1002: *state = current;
1003: PetscFunctionReturn(PETSC_SUCCESS);
1004: }
1006: /*@
1007: MatResetPreallocation - Reset matrix to use the original preallocation values provided by the user, for example with `MatXAIJSetPreallocation()`
1009: Collective
1011: Input Parameter:
1012: . A - the matrix
1014: Level: beginner
1016: Notes:
1017: After calling `MatAssemblyBegin()` and `MatAssemblyEnd()` with `MAT_FINAL_ASSEMBLY` the matrix data structures represent the nonzeros assigned to the
1018: matrix. If that space is less than the preallocated space that extra preallocated space is no longer available to take on new values. `MatResetPreallocation()`
1019: makes all of the preallocation space available
1021: Current values in the matrix are lost in this call
1023: Currently only supported for `MATAIJ` matrices.
1025: .seealso: [](ch_matrices), `Mat`, `MatSeqAIJSetPreallocation()`, `MatMPIAIJSetPreallocation()`, `MatXAIJSetPreallocation()`
1026: @*/
1027: PetscErrorCode MatResetPreallocation(Mat A)
1028: {
1029: PetscFunctionBegin;
1032: PetscUseMethod(A, "MatResetPreallocation_C", (Mat), (A));
1033: PetscFunctionReturn(PETSC_SUCCESS);
1034: }
1036: /*@
1037: MatResetHash - Reset the matrix so that it will use a hash table for the next round of `MatSetValues()` and `MatAssemblyBegin()`/`MatAssemblyEnd()`.
1039: Collective
1041: Input Parameter:
1042: . A - the matrix
1044: Level: intermediate
1046: Notes:
1047: The matrix will again delete the hash table data structures after following calls to `MatAssemblyBegin()`/`MatAssemblyEnd()` with `MAT_FINAL_ASSEMBLY`.
1049: Currently only supported for `MATAIJ` matrices.
1051: .seealso: [](ch_matrices), `Mat`, `MatResetPreallocation()`
1052: @*/
1053: PetscErrorCode MatResetHash(Mat A)
1054: {
1055: PetscFunctionBegin;
1058: 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()");
1059: if (A->num_ass == 0) PetscFunctionReturn(PETSC_SUCCESS);
1060: PetscUseMethod(A, "MatResetHash_C", (Mat), (A));
1061: /* These flags are used to determine whether certain setups occur */
1062: A->was_assembled = PETSC_FALSE;
1063: A->assembled = PETSC_FALSE;
1064: /* Log that the state of this object has changed; this will help guarantee that preconditioners get re-setup */
1065: PetscCall(PetscObjectStateIncrease((PetscObject)A));
1066: PetscFunctionReturn(PETSC_SUCCESS);
1067: }
1069: /*@
1070: MatSetUp - Sets up the internal matrix data structures for later use by the matrix
1072: Collective
1074: Input Parameter:
1075: . A - the matrix
1077: Level: advanced
1079: Notes:
1080: If no preallocation has been provided for a `MATAIJ`, `MATBAIJ`, or `MATSBAIJ` matrix, `MatSetUp()` makes it record the
1081: values given to `MatSetValues()` in a hash table, and the first assembly determines the nonzero pattern from it. Providing
1082: preallocation instead, for example with `MatXAIJSetPreallocation()` or `MatSetPreallocationCOO()`, disables hash-table mode.
1084: This routine is called internally by other `Mat` functions when needed so rarely needs to be called by users
1086: .seealso: [](ch_matrices), `Mat`, `MatMult()`, `MatCreate()`, `MatDestroy()`, `MatXAIJSetPreallocation()`
1087: @*/
1088: PetscErrorCode MatSetUp(Mat A)
1089: {
1090: PetscFunctionBegin;
1092: if (!((PetscObject)A)->type_name) {
1093: PetscMPIInt size;
1095: PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)A), &size));
1096: PetscCall(MatSetType(A, size == 1 ? MATSEQAIJ : MATMPIAIJ));
1097: }
1098: if (!A->preallocated) PetscTryTypeMethod(A, setup);
1099: PetscCall(PetscLayoutSetUp(A->rmap));
1100: PetscCall(PetscLayoutSetUp(A->cmap));
1101: A->preallocated = PETSC_TRUE;
1102: PetscFunctionReturn(PETSC_SUCCESS);
1103: }
1105: #if PetscDefined(HAVE_SAWS)
1106: #include <petscviewersaws.h>
1107: #endif
1109: /*
1110: If threadsafety is on extraneous matrices may be printed
1112: This flag cannot be stored in the matrix because the original matrix in MatView() may assemble a new matrix which is passed into MatViewFromOptions()
1113: */
1114: #if !PetscDefined(HAVE_THREADSAFETY)
1115: static PetscInt insidematview = 0;
1116: #endif
1118: /*@
1119: MatViewFromOptions - View properties of the matrix based on options set in the options database
1121: Collective
1123: Input Parameters:
1124: + A - the matrix
1125: . obj - optional additional object that provides the options prefix to use
1126: - name - command line option
1128: Options Database Key:
1129: . -name viewer_specification - See `PetscOptionsCreateViewer()` for the values of `viewer_specification`
1131: Level: intermediate
1133: Note:
1134: This checks the options database, creates the viewer on-the-fly, uses it and then destroys it. Hence it should not be called in heavily used routines,
1135: rather `PetscOptionsCreateViewer()` should be used to construct the viewer once which can then be utilized in the heavily used routine.
1137: .seealso: [](ch_matrices), `Mat`, `MatView()`, `PetscObjectViewFromOptions()`, `MatCreate()`, `PetscOptionsCreateViewer()`
1138: @*/
1139: PetscErrorCode MatViewFromOptions(Mat A, PetscObject obj, const char name[])
1140: {
1141: PetscFunctionBegin;
1143: #if !PetscDefined(HAVE_THREADSAFETY)
1144: if (insidematview) PetscFunctionReturn(PETSC_SUCCESS);
1145: #endif
1146: PetscCall(PetscObjectViewFromOptions((PetscObject)A, obj, name));
1147: PetscFunctionReturn(PETSC_SUCCESS);
1148: }
1150: /*@
1151: MatView - display information about a matrix in a variety ways
1153: Collective on viewer
1155: Input Parameters:
1156: + mat - the matrix
1157: - viewer - visualization context
1159: Options Database Key:
1160: . -mat_view viewer_specification - Call `MatView()` at the conclusion of `MatAssemblyEnd()` or other routines that have changed the matrix values.
1161: See `PetscOptionsCreateViewer()` for the values of `viewer_specification`.
1163: Level: beginner
1165: Notes:
1166: The available visualization contexts include
1167: + `PETSC_VIEWER_STDOUT_SELF` - for sequential matrices
1168: . `PETSC_VIEWER_STDOUT_WORLD` - for parallel matrices created on `PETSC_COMM_WORLD`
1169: . `PETSC_VIEWER_STDOUT_`(comm) - for matrices created on MPI communicator comm
1170: - `PETSC_VIEWER_DRAW_WORLD` - graphical display of nonzero structure
1172: The user can open alternative visualization contexts with
1173: + `PetscViewerASCIIOpen()` - Outputs matrix to a specified file
1174: . `PetscViewerBinaryOpen()` - Outputs matrix in binary to a specified file; corresponding input uses `MatLoad()`
1175: . `PetscViewerDrawOpen()` - Outputs nonzero matrix nonzero structure to an X window display
1176: - `PetscViewerSocketOpen()` - Outputs matrix to Socket viewer, `PETSCVIEWERSOCKET`. Only the `MATSEQDENSE` and `MATAIJ` types support this viewer.
1178: The user can call `PetscViewerPushFormat()` to specify the output
1179: format of ASCII printed objects (when using `PETSC_VIEWER_STDOUT_SELF`,
1180: `PETSC_VIEWER_STDOUT_WORLD` and `PetscViewerASCIIOpen()`). Available formats include
1181: + `PETSC_VIEWER_DEFAULT` - default, prints matrix contents
1182: . `PETSC_VIEWER_ASCII_MATLAB` - prints matrix contents in MATLAB format
1183: . `PETSC_VIEWER_ASCII_DENSE` - prints entire matrix including zeros
1184: . `PETSC_VIEWER_ASCII_COMMON` - prints matrix contents, using a sparse format common among all matrix types
1185: . `PETSC_VIEWER_ASCII_IMPL` - prints matrix contents, using an implementation-specific format (which is in many cases the same as the default)
1186: . `PETSC_VIEWER_ASCII_INFO` - prints basic information about the matrix size and structure (not the matrix entries)
1187: - `PETSC_VIEWER_ASCII_INFO_DETAIL` - prints more detailed information about the matrix nonzero structure (still not vector or matrix entries)
1189: The ASCII viewers are only recommended for small matrices on at most a moderate number of processes,
1190: the program will seemingly hang and take hours for larger matrices, for larger matrices one should use the binary format.
1192: In the debugger you can do "call MatView(mat,0)" to display the matrix. (The same holds for any PETSc object viewer).
1194: See the manual page for `MatLoad()` for the exact format of the binary file when the binary
1195: viewer is used.
1197: `MatViewFromOptions()` provides an alternative to this routine that only views the matrix if the requested value
1198: is provided in the options database.
1200: See `share/petsc/matlab/PetscBinaryRead.m` for a MATLAB code that can read in the binary file when the binary
1201: viewer is used and `lib/petsc/bin/PetscBinaryIO.py` for loading them into Python.
1203: One can use `-mat_view draw -draw_pause -1` to pause the graphical display of matrix nonzero structure,
1204: and then use the following mouse functions.
1205: .vb
1206: left mouse: zoom in
1207: middle mouse: zoom out
1208: right mouse: continue with the simulation
1209: .ve
1211: .seealso: [](ch_matrices), `Mat`, `PetscViewerPushFormat()`, `PetscViewerASCIIOpen()`, `PetscViewerDrawOpen()`, `PetscViewer`,
1212: `PetscViewerSocketOpen()`, `PetscViewerBinaryOpen()`, `MatLoad()`, `MatViewFromOptions()`, `PetscOptionsCreateViewer()`
1213: @*/
1214: PetscErrorCode MatView(Mat mat, PetscViewer viewer)
1215: {
1216: PetscInt rows, cols, rbs, cbs;
1217: PetscBool isascii, isstring, issaws;
1218: PetscViewerFormat format;
1219: PetscMPIInt size;
1221: PetscFunctionBegin;
1224: if (!viewer) PetscCall(PetscViewerASCIIGetStdout(PetscObjectComm((PetscObject)mat), &viewer));
1227: PetscCall(PetscViewerGetFormat(viewer, &format));
1228: PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)viewer), &size));
1229: if (size == 1 && format == PETSC_VIEWER_LOAD_BALANCE) PetscFunctionReturn(PETSC_SUCCESS);
1231: #if !PetscDefined(HAVE_THREADSAFETY)
1232: insidematview++;
1233: #endif
1234: PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERSTRING, &isstring));
1235: PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERASCII, &isascii));
1236: PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERSAWS, &issaws));
1237: 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");
1239: PetscCall(PetscLogEventBegin(MAT_View, mat, viewer, 0, 0));
1240: if (isascii) {
1241: if (!mat->preallocated) {
1242: PetscCall(PetscViewerASCIIPrintf(viewer, "Matrix has not been preallocated yet\n"));
1243: #if !PetscDefined(HAVE_THREADSAFETY)
1244: insidematview--;
1245: #endif
1246: PetscCall(PetscLogEventEnd(MAT_View, mat, viewer, 0, 0));
1247: PetscFunctionReturn(PETSC_SUCCESS);
1248: }
1249: if (!mat->assembled) {
1250: PetscCall(PetscViewerASCIIPrintf(viewer, "Matrix has not been assembled yet\n"));
1251: #if !PetscDefined(HAVE_THREADSAFETY)
1252: insidematview--;
1253: #endif
1254: PetscCall(PetscLogEventEnd(MAT_View, mat, viewer, 0, 0));
1255: PetscFunctionReturn(PETSC_SUCCESS);
1256: }
1257: PetscCall(PetscObjectPrintClassNamePrefixType((PetscObject)mat, viewer));
1258: if (format == PETSC_VIEWER_ASCII_INFO || format == PETSC_VIEWER_ASCII_INFO_DETAIL) {
1259: MatNullSpace nullsp, transnullsp;
1260: PetscBool nz_factor = PETSC_TRUE;
1262: PetscCall(PetscViewerASCIIPushTab(viewer));
1263: PetscCall(MatGetSize(mat, &rows, &cols));
1264: PetscCall(MatGetBlockSizes(mat, &rbs, &cbs));
1265: if (rbs != 1 || cbs != 1) {
1266: 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" : ""));
1267: else PetscCall(PetscViewerASCIIPrintf(viewer, "rows=%" PetscInt_FMT ", cols=%" PetscInt_FMT ", bs=%" PetscInt_FMT "%s\n", rows, cols, rbs, mat->bsizes ? " variable blocks set" : ""));
1268: } else PetscCall(PetscViewerASCIIPrintf(viewer, "rows=%" PetscInt_FMT ", cols=%" PetscInt_FMT "\n", rows, cols));
1269: if (mat->factortype) {
1270: MatSolverType solver;
1272: PetscCall(MatFactorGetSolverType(mat, &solver));
1273: PetscCall(PetscViewerASCIIPrintf(viewer, "package used to perform factorization: %s\n", solver));
1274: PetscCall(PetscStrcmpAny(solver, &nz_factor, MATSOLVERUMFPACK, MATSOLVERCHOLMOD, MATSOLVERSUPERLU, MATSOLVERSUPERLU_DIST, MATSOLVERSTRUMPACK, MATSOLVERHTOOL, ""));
1275: nz_factor = !nz_factor;
1276: }
1277: if (mat->ops->getinfo) {
1278: PetscBool is_constant_or_diagonal;
1280: // Don't print nonzero information for constant or diagonal matrices, it just adds noise to the output
1281: PetscCall(PetscObjectTypeCompareAny((PetscObject)mat, &is_constant_or_diagonal, MATCONSTANTDIAGONAL, MATDIAGONAL, ""));
1282: if (!is_constant_or_diagonal && nz_factor) {
1283: MatInfo info;
1285: PetscCall(MatGetInfo(mat, MAT_GLOBAL_SUM, &info));
1286: PetscCall(PetscViewerASCIIPrintf(viewer, "total: nonzeros=%.f, allocated nonzeros=%.f\n", info.nz_used, info.nz_allocated));
1287: if (!mat->factortype) PetscCall(PetscViewerASCIIPrintf(viewer, "total number of mallocs used during MatSetValues calls=%" PetscInt_FMT "\n", (PetscInt)info.mallocs));
1288: }
1289: }
1290: PetscCall(MatGetNullSpace(mat, &nullsp));
1291: PetscCall(MatGetTransposeNullSpace(mat, &transnullsp));
1292: if (nullsp) PetscCall(PetscViewerASCIIPrintf(viewer, " has attached null space\n"));
1293: if (transnullsp && transnullsp != nullsp) PetscCall(PetscViewerASCIIPrintf(viewer, " has attached transposed null space\n"));
1294: PetscCall(MatGetNearNullSpace(mat, &nullsp));
1295: if (nullsp) PetscCall(PetscViewerASCIIPrintf(viewer, " has attached near null space\n"));
1296: PetscCall(PetscViewerASCIIPushTab(viewer));
1297: PetscCall(MatProductView(mat, viewer));
1298: PetscCall(PetscViewerASCIIPopTab(viewer));
1299: if (mat->bsizes && format == PETSC_VIEWER_ASCII_INFO_DETAIL) {
1300: IS tmp;
1302: PetscCall(ISCreateGeneral(PetscObjectComm((PetscObject)viewer), mat->nblocks, mat->bsizes, PETSC_USE_POINTER, &tmp));
1303: PetscCall(PetscObjectSetName((PetscObject)tmp, "Block Sizes"));
1304: PetscCall(PetscViewerASCIIPushTab(viewer));
1305: PetscCall(ISView(tmp, viewer));
1306: PetscCall(PetscViewerASCIIPopTab(viewer));
1307: PetscCall(ISDestroy(&tmp));
1308: }
1309: }
1310: } else if (issaws) {
1311: #if PetscDefined(HAVE_SAWS)
1312: PetscMPIInt rank;
1314: PetscCall(PetscObjectName((PetscObject)mat));
1315: PetscCallMPI(MPI_Comm_rank(PETSC_COMM_WORLD, &rank));
1316: if (!((PetscObject)mat)->amsmem && rank == 0) PetscCall(PetscObjectViewSAWs((PetscObject)mat, viewer));
1317: #endif
1318: } else if (isstring) {
1319: const char *type;
1320: PetscCall(MatGetType(mat, &type));
1321: PetscCall(PetscViewerStringSPrintf(viewer, " MatType: %-7.7s", type));
1322: PetscTryTypeMethod(mat, view, viewer);
1323: }
1324: if ((format == PETSC_VIEWER_NATIVE || format == PETSC_VIEWER_LOAD_BALANCE) && mat->ops->viewnative) {
1325: PetscCall(PetscViewerASCIIPushTab(viewer));
1326: PetscUseTypeMethod(mat, viewnative, viewer);
1327: PetscCall(PetscViewerASCIIPopTab(viewer));
1328: } else if (mat->ops->view) {
1329: PetscCall(PetscViewerASCIIPushTab(viewer));
1330: PetscUseTypeMethod(mat, view, viewer);
1331: PetscCall(PetscViewerASCIIPopTab(viewer));
1332: }
1333: if (isascii) {
1334: PetscCall(PetscViewerGetFormat(viewer, &format));
1335: if (format == PETSC_VIEWER_ASCII_INFO || format == PETSC_VIEWER_ASCII_INFO_DETAIL) PetscCall(PetscViewerASCIIPopTab(viewer));
1336: }
1337: PetscCall(PetscLogEventEnd(MAT_View, mat, viewer, 0, 0));
1338: #if !PetscDefined(HAVE_THREADSAFETY)
1339: insidematview--;
1340: #endif
1341: PetscFunctionReturn(PETSC_SUCCESS);
1342: }
1344: #if PetscDefined(USE_DEBUG)
1345: #include <../src/sys/totalview/tv_data_display.h>
1346: PETSC_UNUSED static int TV_display_type(const struct _p_Mat *mat)
1347: {
1348: TV_add_row("Local rows", "int", &mat->rmap->n);
1349: TV_add_row("Local columns", "int", &mat->cmap->n);
1350: TV_add_row("Global rows", "int", &mat->rmap->N);
1351: TV_add_row("Global columns", "int", &mat->cmap->N);
1352: TV_add_row("Typename", TV_ascii_string_type, ((PetscObject)mat)->type_name);
1353: return TV_format_OK;
1354: }
1355: #endif
1357: /*@
1358: MatLoad - Loads a matrix that has been stored in binary/HDF5 format
1359: with `MatView()`. The matrix format is determined from the options database.
1360: Generates a parallel MPI matrix if the communicator has more than one
1361: process. The default matrix type is `MATAIJ`.
1363: Collective
1365: Input Parameters:
1366: + mat - the newly loaded matrix, this needs to have been created with `MatCreate()`
1367: or some related function before a call to `MatLoad()`
1368: - viewer - `PETSCVIEWERBINARY`/`PETSCVIEWERHDF5` file viewer
1370: Options Database Key:
1371: . -matload_block_size bs - set block size
1373: Level: beginner
1375: Notes:
1376: If the `Mat` type has not yet been given then `MATAIJ` is used, call `MatSetFromOptions()` on the
1377: `Mat` before calling this routine if you wish to set it from the options database.
1379: `MatLoad()` automatically loads into the options database any options
1380: given in the file filename.info where filename is the name of the file
1381: that was passed to the `PetscViewerBinaryOpen()`. The options in the info
1382: file will be ignored if you use the `-viewer_binary_skip_info` option.
1384: If the type or size of mat is not set before a call to `MatLoad()`, PETSc
1385: sets the default matrix type AIJ and sets the local and global sizes.
1386: If type and/or size is already set, then the same are used.
1388: In parallel, each process can load a subset of rows (or the
1389: entire matrix). This routine is especially useful when a large
1390: matrix is stored on disk and only part of it is desired on each
1391: process. For example, a parallel solver may access only some of
1392: the rows from each process. The algorithm used here reads
1393: relatively small blocks of data rather than reading the entire
1394: matrix and then subsetting it.
1396: Viewer's `PetscViewerType` must be either `PETSCVIEWERBINARY` or `PETSCVIEWERHDF5`.
1397: Such viewer can be created using `PetscViewerBinaryOpen()` or `PetscViewerHDF5Open()`,
1398: or the sequence like
1399: .vb
1400: PetscViewer v;
1401: PetscViewerCreate(PETSC_COMM_WORLD, &v);
1402: PetscViewerSetType(v, PETSCVIEWERBINARY);
1403: PetscViewerSetFromOptions(v);
1404: PetscViewerFileSetMode(v, FILE_MODE_READ);
1405: PetscViewerFileSetName(v, "datafile");
1406: .ve
1407: The optional `PetscViewerSetFromOptions()` call allows overriding `PetscViewerSetType()` using the option
1408: .vb
1409: -viewer_type (binary|hdf5)
1410: .ve
1412: See the example src/ksp/ksp/tutorials/ex27.c with the first approach,
1413: and src/mat/tutorials/ex10.c with the second approach.
1415: In case of `PETSCVIEWERBINARY`, a native PETSc binary format is used. Each of the blocks
1416: is read onto MPI rank 0 and then shipped to its destination MPI rank, one after another.
1417: Multiple objects, both matrices and vectors, can be stored within the same file.
1418: Their `PetscObject` name is ignored; they are loaded in the order of their storage.
1420: Most users should not need to know the details of the binary storage
1421: format, since `MatLoad()` and `MatView()` completely hide these details.
1422: But for anyone who is interested, the standard binary matrix storage
1423: format is
1425: .vb
1426: PetscInt MAT_FILE_CLASSID
1427: PetscInt number of rows
1428: PetscInt number of columns
1429: PetscInt total number of nonzeros
1430: PetscInt *number nonzeros in each row
1431: PetscInt *column indices of all nonzeros (starting index is zero)
1432: PetscScalar *values of all nonzeros
1433: .ve
1434: If PETSc was not configured with `--with-64-bit-indices` then only `MATMPIAIJ` matrices with more than `PETSC_INT_MAX` non-zeros can be
1435: 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
1436: case will not fit in a (32-bit) `PetscInt` the value `PETSC_INT_MAX` is used for the header entry `total number of nonzeros`.
1438: PETSc automatically does the byte swapping for
1439: machines that store the bytes reversed. Thus if you write your own binary
1440: read/write routines you have to swap the bytes; see `PetscBinaryRead()`
1441: and `PetscBinaryWrite()` to see how this may be done.
1443: In case of `PETSCVIEWERHDF5`, a parallel HDF5 reader is used.
1444: Each process's chunk is loaded independently by its owning MPI process.
1445: Multiple objects, both matrices and vectors, can be stored within the same file.
1446: They are looked up by their PetscObject name.
1448: As the MATLAB MAT-File Version 7.3 format is also a HDF5 flavor, we decided to use
1449: by default the same structure and naming of the AIJ arrays and column count
1450: within the HDF5 file. This means that a MAT file saved with -v7.3 flag, e.g.
1451: .vb
1452: save example.mat A b -v7.3
1453: .ve
1454: can be directly read by this routine (see Reference 1 for details).
1456: Depending on your MATLAB version, this format might be a default,
1457: otherwise you can set it as default in Preferences.
1459: Unless `-nocompression` flag is used to save the file in MATLAB,
1460: PETSc must be configured with ZLIB package.
1462: See also examples `src/mat/tutorials/ex10.c` and `src/ksp/ksp/tutorials/ex27.c`
1464: This reader currently supports only real `MATSEQAIJ`, `MATMPIAIJ`, `MATSEQDENSE`, and `MATMPIDENSE` matrices for `PETSCVIEWERHDF5`
1466: Corresponding `MatView()` is not yet implemented.
1468: The loaded matrix is actually a transpose of the original one in MATLAB,
1469: unless you push `PETSC_VIEWER_HDF5_MAT` format (see examples above).
1470: With this format, matrix is automatically transposed by PETSc,
1471: unless the matrix is marked as SPD or symmetric
1472: (see `MatSetOption()`, `MAT_SPD`, `MAT_SYMMETRIC`).
1474: See MATLAB Documentation on `save()`, <https://www.mathworks.com/help/matlab/ref/save.html#btox10b-1-version>
1476: .seealso: [](ch_matrices), `Mat`, `PetscViewerBinaryOpen()`, `PetscViewerSetType()`, `MatView()`, `VecLoad()`
1477: @*/
1478: PetscErrorCode MatLoad(Mat mat, PetscViewer viewer)
1479: {
1480: PetscBool flg;
1482: PetscFunctionBegin;
1486: if (!((PetscObject)mat)->type_name) PetscCall(MatSetType(mat, MATAIJ));
1488: flg = PETSC_FALSE;
1489: PetscCall(PetscOptionsGetBool(((PetscObject)mat)->options, ((PetscObject)mat)->prefix, "-matload_symmetric", &flg, NULL));
1490: if (flg) {
1491: PetscCall(MatSetOption(mat, MAT_SYMMETRIC, PETSC_TRUE));
1492: PetscCall(MatSetOption(mat, MAT_SYMMETRY_ETERNAL, PETSC_TRUE));
1493: }
1494: flg = PETSC_FALSE;
1495: PetscCall(PetscOptionsGetBool(((PetscObject)mat)->options, ((PetscObject)mat)->prefix, "-matload_spd", &flg, NULL));
1496: if (flg) PetscCall(MatSetOption(mat, MAT_SPD, PETSC_TRUE));
1498: PetscCall(PetscLogEventBegin(MAT_Load, mat, viewer, 0, 0));
1499: PetscUseTypeMethod(mat, load, viewer);
1500: PetscCall(PetscLogEventEnd(MAT_Load, mat, viewer, 0, 0));
1501: PetscFunctionReturn(PETSC_SUCCESS);
1502: }
1504: static PetscErrorCode MatDestroy_Redundant(Mat_Redundant **redundant)
1505: {
1506: Mat_Redundant *redund = *redundant;
1508: PetscFunctionBegin;
1509: if (redund) {
1510: if (redund->matseq) { /* via MatCreateSubMatrices() */
1511: PetscCall(ISDestroy(&redund->isrow));
1512: PetscCall(ISDestroy(&redund->iscol));
1513: PetscCall(MatDestroySubMatrices(1, &redund->matseq));
1514: } else {
1515: PetscCall(PetscFree2(redund->send_rank, redund->recv_rank));
1516: PetscCall(PetscFree(redund->sbuf_j));
1517: PetscCall(PetscFree(redund->sbuf_a));
1518: for (PetscInt i = 0; i < redund->nrecvs; i++) {
1519: PetscCall(PetscFree(redund->rbuf_j[i]));
1520: PetscCall(PetscFree(redund->rbuf_a[i]));
1521: }
1522: PetscCall(PetscFree4(redund->sbuf_nz, redund->rbuf_nz, redund->rbuf_j, redund->rbuf_a));
1523: }
1525: PetscCall(PetscCommDestroy(&redund->subcomm));
1526: PetscCall(PetscFree(redund));
1527: }
1528: PetscFunctionReturn(PETSC_SUCCESS);
1529: }
1531: /*@
1532: MatDestroy - Frees space taken by a matrix.
1534: Collective
1536: Input Parameter:
1537: . A - the matrix
1539: Level: beginner
1541: Developer Note:
1542: Some special arrays of matrices are not destroyed in this routine but instead by the routines called by
1543: `MatDestroySubMatrices()`. Thus one must be sure that any changes here must also be made in those routines.
1544: `MatHeaderMerge()` and `MatHeaderReplace()` also manipulate the data in the `Mat` object and likely need changes
1545: if changes are needed here.
1547: .seealso: [](ch_matrices), `Mat`, `MatCreate()`
1548: @*/
1549: PetscErrorCode MatDestroy(Mat *A)
1550: {
1551: PetscFunctionBegin;
1552: if (!*A) PetscFunctionReturn(PETSC_SUCCESS);
1554: if (--((PetscObject)*A)->refct > 0) {
1555: *A = NULL;
1556: PetscFunctionReturn(PETSC_SUCCESS);
1557: }
1559: /* if memory was published with SAWs then destroy it */
1560: PetscCall(PetscObjectSAWsViewOff((PetscObject)*A));
1561: PetscTryTypeMethod(*A, destroy);
1563: PetscCall(PetscFree((*A)->factorprefix));
1564: PetscCall(PetscFree((*A)->defaultvectype));
1565: PetscCall(PetscFree((*A)->defaultrandtype));
1566: PetscCall(PetscFree((*A)->bsizes));
1567: PetscCall(PetscFree((*A)->solvertype));
1568: for (PetscInt i = 0; i < MAT_FACTOR_NUM_TYPES; i++) PetscCall(PetscFree((*A)->preferredordering[i]));
1569: if ((*A)->redundant && (*A)->redundant->matseq[0] == *A) (*A)->redundant->matseq[0] = NULL;
1570: PetscCall(MatDestroy_Redundant(&(*A)->redundant));
1571: PetscCall(MatProductClear(*A));
1572: PetscCall(MatNullSpaceDestroy(&(*A)->nullsp));
1573: PetscCall(MatNullSpaceDestroy(&(*A)->transnullsp));
1574: PetscCall(MatNullSpaceDestroy(&(*A)->nearnullsp));
1575: PetscCall(MatDestroy(&(*A)->schur));
1576: PetscCall(VecDestroy(&(*A)->dot_vec));
1577: PetscCall(PetscLayoutDestroy(&(*A)->rmap));
1578: PetscCall(PetscLayoutDestroy(&(*A)->cmap));
1579: PetscCall(PetscHeaderDestroy(A));
1580: PetscFunctionReturn(PETSC_SUCCESS);
1581: }
1583: // PetscClangLinter pragma disable: -fdoc-section-header-unknown
1584: /*@
1585: MatSetValues - Inserts or adds a block of values into a matrix.
1586: These values may be cached, so `MatAssemblyBegin()` and `MatAssemblyEnd()`
1587: MUST be called after all calls to `MatSetValues()` have been completed.
1589: Not Collective
1591: Input Parameters:
1592: + mat - the matrix
1593: . m - the number of rows
1594: . idxm - the global indices of the rows
1595: . n - the number of columns
1596: . idxn - the global indices of the columns
1597: . v - a one-dimensional array that contains the values implicitly stored as a two-dimensional array, by default in row-major order.
1598: See `MAT_ROW_ORIENTED` in `MatSetOption()` for how to use column-major order.
1599: - addv - either `ADD_VALUES` to add values to any existing entries, or `INSERT_VALUES` to replace existing entries with new values
1601: Level: beginner
1603: Notes:
1604: Calls to `MatSetValues()` with the `INSERT_VALUES` and `ADD_VALUES`
1605: options cannot be mixed without intervening calls to the assembly
1606: routines.
1608: `MatSetValues()` uses 0-based row and column numbers in Fortran
1609: as well as in C.
1611: Negative indices may be passed in `idxm` and `idxn`, these rows and columns are simply ignored. This allows easily inserting element stiffness matrices
1612: with homogeneous Dirichlet boundary conditions that you don't want represented
1613: in the matrix.
1615: Efficiency Alert:
1616: The routine `MatSetValuesBlocked()` may offer much better efficiency
1617: for users of block sparse formats (`MATSEQBAIJ` and `MATMPIBAIJ`).
1619: Fortran Notes:
1620: If any of `idxm`, `idxn`, and `v` are scalars pass them using, for example,
1621: .vb
1622: call MatSetValues(mat, one, [idxm], one, [idxn], [v], INSERT_VALUES, ierr)
1623: .ve
1625: If `v` is a two-dimensional array make sure to first call `MatSetOption(mat, MAT_ROW_ORIENTED, PETSC_FALSE, ierr)` before using this function,
1626: otherwise the transpose of `v` will seemingly be inserted in the matrix, since Fortran passes two-dimensional arrays with column orientation.
1628: .seealso: [](ch_matrices), `Mat`, `MatSetOption()`, `MatAssemblyBegin()`, `MatAssemblyEnd()`, `MatSetValuesBlocked()`, `MatSetValuesLocal()`,
1629: `InsertMode`, `INSERT_VALUES`, `ADD_VALUES`
1630: @*/
1631: PetscErrorCode MatSetValues(Mat mat, PetscInt m, const PetscInt idxm[], PetscInt n, const PetscInt idxn[], const PetscScalar v[], InsertMode addv)
1632: {
1633: PetscFunctionBeginHot;
1636: if (!m || !n) PetscFunctionReturn(PETSC_SUCCESS); /* no values to insert */
1637: PetscAssertPointer(idxm, 3);
1638: PetscAssertPointer(idxn, 5);
1639: MatCheckPreallocated(mat, 1);
1641: if (mat->insertmode == NOT_SET_VALUES) mat->insertmode = addv;
1642: else PetscCheck(mat->insertmode == addv, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Cannot mix add values and insert values");
1644: if (PetscDefined(USE_DEBUG)) {
1645: PetscInt i, j;
1647: PetscCheck(!mat->factortype, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
1648: if (v) {
1649: for (i = 0; i < m; i++) {
1650: for (j = 0; j < n; j++) {
1651: if (mat->erroriffailure && PetscIsInfOrNanScalar(v[i * n + j]))
1652: #if PetscDefined(USE_COMPLEX)
1653: 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]);
1654: #else
1655: 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]);
1656: #endif
1657: }
1658: }
1659: }
1660: 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);
1661: 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);
1662: }
1664: if (mat->assembled) {
1665: mat->was_assembled = PETSC_TRUE;
1666: mat->assembled = PETSC_FALSE;
1667: }
1668: PetscCall(PetscLogEventBegin(MAT_SetValues, mat, 0, 0, 0));
1669: PetscUseTypeMethod(mat, setvalues, m, idxm, n, idxn, v, addv);
1670: PetscCall(PetscLogEventEnd(MAT_SetValues, mat, 0, 0, 0));
1671: PetscFunctionReturn(PETSC_SUCCESS);
1672: }
1674: // PetscClangLinter pragma disable: -fdoc-section-header-unknown
1675: /*@
1676: MatSetValuesIS - Inserts or adds a block of values into a matrix using an `IS` to indicate the rows and columns
1677: These values may be cached, so `MatAssemblyBegin()` and `MatAssemblyEnd()`
1678: MUST be called after all calls to `MatSetValues()` have been completed.
1680: Not Collective
1682: Input Parameters:
1683: + mat - the matrix
1684: . ism - the rows to provide
1685: . isn - the columns to provide
1686: . v - a one-dimensional array that contains the values implicitly stored as a two-dimensional array, by default in row-major order.
1687: See `MAT_ROW_ORIENTED` in `MatSetOption()` for how to use column-major order.
1688: - addv - either `ADD_VALUES` to add values to any existing entries, or `INSERT_VALUES` to replace existing entries with new values
1690: Level: beginner
1692: Notes:
1693: By default, the values, `v`, are stored in row-major order. See `MAT_ROW_ORIENTED` in `MatSetOption()` for how to use column-major order.
1695: Calls to `MatSetValues()` with the `INSERT_VALUES` and `ADD_VALUES`
1696: options cannot be mixed without intervening calls to the assembly
1697: routines.
1699: `MatSetValues()` uses 0-based row and column numbers in Fortran
1700: as well as in C.
1702: Negative indices may be passed in `ism` and `isn`, these rows and columns are
1703: simply ignored. This allows easily inserting element stiffness matrices
1704: with homogeneous Dirichlet boundary conditions that you don't want represented
1705: in the matrix.
1707: Fortran Note:
1708: If `v` is a two-dimensional array make sure to first call `MatSetOption(mat, MAT_ROW_ORIENTED, PETSC_FALSE, ierr)` before using this function,
1709: otherwise the transpose of `v` will seemingly be inserted in the matrix, since Fortran passes two-dimensional arrays with column orientation.
1711: Efficiency Alert:
1712: The routine `MatSetValuesBlocked()` may offer much better efficiency
1713: for users of block sparse formats (`MATSEQBAIJ` and `MATMPIBAIJ`).
1715: This is currently not optimized for any particular `ISType`
1717: .seealso: [](ch_matrices), `Mat`, `MatSetOption()`, `MatSetValues()`, `MatAssemblyBegin()`, `MatAssemblyEnd()`, `MatSetValuesBlocked()`, `MatSetValuesLocal()`,
1718: `InsertMode`, `INSERT_VALUES`, `ADD_VALUES`
1719: @*/
1720: PetscErrorCode MatSetValuesIS(Mat mat, IS ism, IS isn, const PetscScalar v[], InsertMode addv)
1721: {
1722: PetscInt m, n;
1723: const PetscInt *rows, *cols;
1725: PetscFunctionBeginHot;
1727: PetscCall(ISGetIndices(ism, &rows));
1728: PetscCall(ISGetIndices(isn, &cols));
1729: PetscCall(ISGetLocalSize(ism, &m));
1730: PetscCall(ISGetLocalSize(isn, &n));
1731: PetscCall(MatSetValues(mat, m, rows, n, cols, v, addv));
1732: PetscCall(ISRestoreIndices(ism, &rows));
1733: PetscCall(ISRestoreIndices(isn, &cols));
1734: PetscFunctionReturn(PETSC_SUCCESS);
1735: }
1737: /*@
1738: MatSetValuesRowLocal - Inserts a row of nonzero values into a matrix
1740: Not Collective
1742: Input Parameters:
1743: + mat - the matrix
1744: . row - the row to set
1745: - v - a one-dimensional array that contains the values
1747: Level: intermediate
1749: Notes:
1750: Currently only supported for `MATAIJ`.
1752: All the nonzero values in `row` must be provided
1754: The matrix must have previously had its column indices set, likely by having been assembled.
1756: `row` must belong to this MPI process
1758: .seealso: [](ch_matrices), `Mat`, `MatSetOption()`, `MatAssemblyBegin()`, `MatAssemblyEnd()`, `MatSetValuesBlocked()`, `MatSetValuesLocal()`,
1759: `InsertMode`, `INSERT_VALUES`, `ADD_VALUES`, `MatSetValues()`, `MatSetValuesRow()`, `MatSetLocalToGlobalMapping()`, `MATAIJ`
1760: @*/
1761: PetscErrorCode MatSetValuesRowLocal(Mat mat, PetscInt row, const PetscScalar v[])
1762: {
1763: PetscInt globalrow;
1765: PetscFunctionBegin;
1768: PetscAssertPointer(v, 3);
1769: PetscCall(ISLocalToGlobalMappingApply(mat->rmap->mapping, 1, &row, &globalrow));
1770: PetscCall(MatSetValuesRow(mat, globalrow, v));
1771: PetscFunctionReturn(PETSC_SUCCESS);
1772: }
1774: /*@
1775: MatSetValuesRow - Inserts a row of nonzero values into a matrix
1777: Not Collective
1779: Input Parameters:
1780: + mat - the matrix
1781: . row - the row to set
1782: - v - a one dimensional array of values
1784: Level: advanced
1786: Notes:
1787: Currently only supported for `MATAIJ`.
1789: All the nonzeros in `row` must be provided
1791: The matrix must have previously had its column indices set, likely by having been assembled.
1793: `row` must belong to this process
1795: .seealso: [](ch_matrices), `Mat`, `MatSetValues()`, `MatSetOption()`, `MatAssemblyBegin()`, `MatAssemblyEnd()`, `MatSetValuesBlocked()`, `MatSetValuesLocal()`,
1796: `InsertMode`, `INSERT_VALUES`, `ADD_VALUES`, `MATAIJ`
1797: @*/
1798: PetscErrorCode MatSetValuesRow(Mat mat, PetscInt row, const PetscScalar v[])
1799: {
1800: PetscFunctionBeginHot;
1803: MatCheckPreallocated(mat, 1);
1804: PetscAssertPointer(v, 3);
1805: PetscCheck(mat->insertmode != ADD_VALUES, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Cannot mix add and insert values");
1806: PetscCheck(!mat->factortype, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
1807: mat->insertmode = INSERT_VALUES;
1809: if (mat->assembled) {
1810: mat->was_assembled = PETSC_TRUE;
1811: mat->assembled = PETSC_FALSE;
1812: }
1813: PetscCall(PetscLogEventBegin(MAT_SetValues, mat, 0, 0, 0));
1814: PetscUseTypeMethod(mat, setvaluesrow, row, v);
1815: PetscCall(PetscLogEventEnd(MAT_SetValues, mat, 0, 0, 0));
1816: PetscFunctionReturn(PETSC_SUCCESS);
1817: }
1819: // PetscClangLinter pragma disable: -fdoc-section-header-unknown
1820: /*@
1821: MatSetValuesStencil - Inserts or adds a block of values into a matrix.
1822: Using structured grid indexing
1824: Not Collective
1826: Input Parameters:
1827: + mat - the matrix
1828: . m - number of rows being entered
1829: . idxm - grid coordinates (and component number when dof > 1) for matrix rows being entered
1830: . n - number of columns being entered
1831: . idxn - grid coordinates (and component number when dof > 1) for matrix columns being entered
1832: . v - a one-dimensional array that contains the values implicitly stored as a two-dimensional array, by default in row-major order.
1833: See `MAT_ROW_ORIENTED` in `MatSetOption()` for how to use column-major order.
1834: - addv - either `ADD_VALUES` to add to existing entries at that location or `INSERT_VALUES` to replace existing entries with new values
1836: Level: beginner
1838: Notes:
1839: By default the values, `v`, are row-oriented. See `MatSetOption()` for other options.
1841: Calls to `MatSetValuesStencil()` with the `INSERT_VALUES` and `ADD_VALUES`
1842: options cannot be mixed without intervening calls to the assembly
1843: routines.
1845: The grid coordinates are across the entire grid, not just the local portion
1847: `MatSetValuesStencil()` uses 0-based row and column numbers in Fortran
1848: as well as in C.
1850: For setting/accessing vector values via array coordinates you can use the `DMDAVecGetArray()` routine
1852: In order to use this routine you must either obtain the matrix with `DMCreateMatrix()`
1853: or call `MatSetLocalToGlobalMapping()` and `MatSetStencil()` first.
1855: The columns and rows in the stencil passed in MUST be contained within the
1856: ghost region of the given process as set with DMDACreateXXX() or `MatSetStencil()`. For example,
1857: if you create a `DMDA` with an overlap of one grid level and on a particular process its first
1858: local nonghost x logical coordinate is 6 (so its first ghost x logical coordinate is 5) the
1859: first i index you can use in your column and row indices in `MatSetStencil()` is 5.
1861: For periodic boundary conditions use negative indices for values to the left (below 0; that are to be
1862: obtained by wrapping values from right edge). For values to the right of the last entry using that index plus one
1863: etc to obtain values that obtained by wrapping the values from the left edge. This does not work for anything but the
1864: `DM_BOUNDARY_PERIODIC` boundary type.
1866: 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
1867: a single value per point) you can skip filling those indices.
1869: Inspired by the structured grid interface to the HYPRE package
1870: (https://computation.llnl.gov/projects/hypre-scalable-linear-solvers-multigrid-methods)
1872: Fortran Notes:
1873: If any of `idxm`, `idxn`, and `v` are scalars pass them using, for example,
1874: .vb
1875: call MatSetValuesStencil(mat, one, [idxm], one, [idxn], [v], INSERT_VALUES, ierr)
1876: .ve
1878: If `v` is a two-dimensional array make sure to first call `MatSetOption(mat, MAT_ROW_ORIENTED, PETSC_FALSE, ierr)` before using this function,
1879: otherwise the transpose of `v` will seemingly be inserted in the matrix, since Fortran passes two-dimensional arrays with column orientation.
1881: Efficiency Alert:
1882: The routine `MatSetValuesBlockedStencil()` may offer much better efficiency
1883: for users of block sparse formats (`MATSEQBAIJ` and `MATMPIBAIJ`).
1885: .seealso: [](ch_matrices), `Mat`, `DMDA`, `MatSetOption()`, `MatAssemblyBegin()`, `MatAssemblyEnd()`, `MatSetValuesBlocked()`, `MatSetValuesLocal()`,
1886: `MatSetValues()`, `MatSetValuesBlockedStencil()`, `MatSetStencil()`, `DMCreateMatrix()`, `DMDAVecGetArray()`, `MatStencil`
1887: @*/
1888: PetscErrorCode MatSetValuesStencil(Mat mat, PetscInt m, const MatStencil idxm[], PetscInt n, const MatStencil idxn[], const PetscScalar v[], InsertMode addv)
1889: {
1890: PetscInt buf[8192], *bufm = NULL, *bufn = NULL, *jdxm, *jdxn;
1891: PetscInt j, i, dim = mat->stencil.dim, *dims = mat->stencil.dims + 1, tmp;
1892: PetscInt *starts = mat->stencil.starts, *dxm = (PetscInt *)idxm, *dxn = (PetscInt *)idxn, sdim = dim - (1 - (PetscInt)mat->stencil.noc);
1894: PetscFunctionBegin;
1895: if (!m || !n) PetscFunctionReturn(PETSC_SUCCESS); /* no values to insert */
1898: PetscAssertPointer(idxm, 3);
1899: PetscAssertPointer(idxn, 5);
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 < dim - 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: if (mat->stencil.noc) 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 < dim - 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: if (mat->stencil.noc) dxn++;
1927: jdxn[i] = tmp;
1928: }
1929: PetscCall(MatSetValuesLocal(mat, m, jdxm, n, jdxn, v, addv));
1930: PetscCall(PetscFree2(bufm, bufn));
1931: PetscFunctionReturn(PETSC_SUCCESS);
1932: }
1934: /*@
1935: MatSetValuesBlockedStencil - Inserts or adds a block of values into a matrix.
1936: Using structured grid indexing
1938: Not Collective
1940: Input Parameters:
1941: + mat - the matrix
1942: . m - number of rows being entered
1943: . idxm - grid coordinates for matrix rows being entered
1944: . n - number of columns being entered
1945: . idxn - grid coordinates for matrix columns being entered
1946: . v - a one-dimensional array that contains the values implicitly stored as a two-dimensional array, by default in row-major order.
1947: See `MAT_ROW_ORIENTED` in `MatSetOption()` for how to use column-major order.
1948: - addv - either `ADD_VALUES` to add to existing entries or `INSERT_VALUES` to replace existing entries with new values
1950: Level: beginner
1952: Notes:
1953: By default the values, `v`, are row-oriented and unsorted.
1954: See `MatSetOption()` for other options.
1956: Calls to `MatSetValuesBlockedStencil()` with the `INSERT_VALUES` and `ADD_VALUES`
1957: options cannot be mixed without intervening calls to the assembly
1958: routines.
1960: The grid coordinates are across the entire grid, not just the local portion
1962: `MatSetValuesBlockedStencil()` uses 0-based row and column numbers in Fortran
1963: as well as in C.
1965: For setting/accessing vector values via array coordinates you can use the `DMDAVecGetArray()` routine
1967: In order to use this routine you must either obtain the matrix with `DMCreateMatrix()`
1968: or call `MatSetBlockSize()`, `MatSetLocalToGlobalMapping()` and `MatSetStencil()` first.
1970: The columns and rows in the stencil passed in MUST be contained within the
1971: ghost region of the given process as set with DMDACreateXXX() or `MatSetStencil()`. For example,
1972: if you create a `DMDA` with an overlap of one grid level and on a particular process its first
1973: local nonghost x logical coordinate is 6 (so its first ghost x logical coordinate is 5) the
1974: first i index you can use in your column and row indices in `MatSetStencil()` is 5.
1976: Negative indices may be passed in `idxm` and `idxn`, these rows and columns are
1977: simply ignored. This allows easily inserting element stiffness matrices
1978: with homogeneous Dirichlet boundary conditions that you don't want represented
1979: in the matrix.
1981: Inspired by the structured grid interface to the HYPRE package
1982: (https://computation.llnl.gov/projects/hypre-scalable-linear-solvers-multigrid-methods)
1984: Fortran Notes:
1985: If any of `idxm`, `idxn`, and `v` are scalars pass them using, for example,
1986: .vb
1987: call MatSetValuesBlockedStencil(mat, one, [idxm], one, [idxn], [v], INSERT_VALUES, ierr)
1988: .ve
1990: If `v` is a two-dimensional array make sure to first call `MatSetOption(mat, MAT_ROW_ORIENTED, PETSC_FALSE, ierr)` before using this function,
1991: otherwise the transpose of `v` will seemingly be inserted in the matrix, since Fortran passes two-dimensional arrays with column orientation.
1993: .seealso: [](ch_matrices), `Mat`, `DMDA`, `MatSetOption()`, `MatAssemblyBegin()`, `MatAssemblyEnd()`, `MatSetValuesBlocked()`, `MatSetValuesLocal()`,
1994: `MatSetValues()`, `MatSetValuesStencil()`, `MatSetStencil()`, `DMCreateMatrix()`, `DMDAVecGetArray()`, `MatStencil`,
1995: `MatSetBlockSize()`, `MatSetLocalToGlobalMapping()`
1996: @*/
1997: PetscErrorCode MatSetValuesBlockedStencil(Mat mat, PetscInt m, const MatStencil idxm[], PetscInt n, const MatStencil idxn[], const PetscScalar v[], InsertMode addv)
1998: {
1999: PetscInt buf[8192], *bufm = NULL, *bufn = NULL, *jdxm, *jdxn;
2000: PetscInt j, i, dim = mat->stencil.dim, *dims = mat->stencil.dims + 1, tmp;
2001: PetscInt *starts = mat->stencil.starts, *dxm = (PetscInt *)idxm, *dxn = (PetscInt *)idxn, sdim = dim - (1 - (PetscInt)mat->stencil.noc);
2003: PetscFunctionBegin;
2004: if (!m || !n) PetscFunctionReturn(PETSC_SUCCESS); /* no values to insert */
2007: PetscAssertPointer(idxm, 3);
2008: PetscAssertPointer(idxn, 5);
2009: PetscAssertPointer(v, 6);
2011: if ((m + n) <= (PetscInt)PETSC_STATIC_ARRAY_LENGTH(buf)) {
2012: jdxm = buf;
2013: jdxn = buf + m;
2014: } else {
2015: PetscCall(PetscMalloc2(m, &bufm, n, &bufn));
2016: jdxm = bufm;
2017: jdxn = bufn;
2018: }
2019: for (i = 0; i < m; i++) {
2020: for (j = 0; j < 3 - sdim; j++) dxm++;
2021: tmp = *dxm++ - starts[0];
2022: for (j = 0; j < sdim - 1; j++) {
2023: if ((*dxm++ - starts[j + 1]) < 0 || tmp < 0) tmp = -1;
2024: else tmp = tmp * dims[j] + *(dxm - 1) - starts[j + 1];
2025: }
2026: dxm++;
2027: jdxm[i] = tmp;
2028: }
2029: for (i = 0; i < n; i++) {
2030: for (j = 0; j < 3 - sdim; j++) dxn++;
2031: tmp = *dxn++ - starts[0];
2032: for (j = 0; j < sdim - 1; j++) {
2033: if ((*dxn++ - starts[j + 1]) < 0 || tmp < 0) tmp = -1;
2034: else tmp = tmp * dims[j] + *(dxn - 1) - starts[j + 1];
2035: }
2036: dxn++;
2037: jdxn[i] = tmp;
2038: }
2039: PetscCall(MatSetValuesBlockedLocal(mat, m, jdxm, n, jdxn, v, addv));
2040: PetscCall(PetscFree2(bufm, bufn));
2041: PetscFunctionReturn(PETSC_SUCCESS);
2042: }
2044: /*@
2045: MatSetStencil - Sets the grid information for setting values into a matrix via
2046: `MatSetValuesStencil()`
2048: Not Collective
2050: Input Parameters:
2051: + mat - the matrix
2052: . dim - dimension of the grid 1, 2, or 3
2053: . dims - number of grid points in x, y, and z direction, including ghost points on your process
2054: . starts - starting point of ghost nodes on your process in x, y, and z direction
2055: - dof - number of degrees of freedom per node
2057: Level: beginner
2059: Notes:
2060: Inspired by the structured grid interface to the HYPRE package
2061: (www.llnl.gov/CASC/hyper)
2063: For matrices generated with `DMCreateMatrix()` this routine is automatically called and so not needed by the
2064: user.
2066: .seealso: [](ch_matrices), `Mat`, `MatStencil`, `MatSetOption()`, `MatAssemblyBegin()`, `MatAssemblyEnd()`, `MatSetValuesBlocked()`, `MatSetValuesLocal()`,
2067: `MatSetValues()`, `MatSetValuesBlockedStencil()`, `MatSetValuesStencil()`
2068: @*/
2069: PetscErrorCode MatSetStencil(Mat mat, PetscInt dim, const PetscInt dims[], const PetscInt starts[], PetscInt dof)
2070: {
2071: PetscFunctionBegin;
2073: PetscAssertPointer(dims, 3);
2074: PetscAssertPointer(starts, 4);
2076: mat->stencil.dim = dim + (dof > 1);
2077: for (PetscInt i = 0; i < dim; i++) {
2078: mat->stencil.dims[i] = dims[dim - i - 1]; /* copy the values in backwards */
2079: mat->stencil.starts[i] = starts[dim - i - 1];
2080: }
2081: mat->stencil.dims[dim] = dof;
2082: mat->stencil.starts[dim] = 0;
2083: mat->stencil.noc = (PetscBool)(dof == 1);
2084: PetscFunctionReturn(PETSC_SUCCESS);
2085: }
2087: /*@
2088: MatSetValuesBlocked - Inserts or adds a block of values into a matrix.
2090: Not Collective
2092: Input Parameters:
2093: + mat - the matrix
2094: . m - the number of block rows
2095: . idxm - the global block indices
2096: . n - the number of block columns
2097: . idxn - the global block indices
2098: . v - a one-dimensional array that contains the values implicitly stored as a two-dimensional array, by default in row-major order.
2099: See `MAT_ROW_ORIENTED` in `MatSetOption()` for how to use column-major order.
2100: - addv - either `ADD_VALUES` to add values to any existing entries, or `INSERT_VALUES` replaces existing entries with new values
2102: Level: intermediate
2104: Notes:
2105: If you create the matrix yourself (that is not with a call to `DMCreateMatrix()`) then you MUST call
2106: MatXXXXSetPreallocation() or `MatSetUp()` before using this routine.
2108: The `m` and `n` count the NUMBER of blocks in the row direction and column direction,
2109: NOT the total number of rows/columns; for example, if the block size is 2 and
2110: you are passing in values for rows 2,3,4,5 then `m` would be 2 (not 4).
2111: The values in `idxm` would be 1 2; that is the first index for each block divided by
2112: the block size.
2114: You must call `MatSetBlockSize()` when constructing this matrix (before
2115: preallocating it).
2117: By default, the values, `v`, are stored in row-major order. See `MAT_ROW_ORIENTED` in `MatSetOption()` for how to use column-major order.
2119: Calls to `MatSetValuesBlocked()` with the `INSERT_VALUES` and `ADD_VALUES`
2120: options cannot be mixed without intervening calls to the assembly
2121: routines.
2123: `MatSetValuesBlocked()` uses 0-based row and column numbers in Fortran
2124: as well as in C.
2126: Negative indices may be passed in `idxm` and `idxn`, these rows and columns are
2127: simply ignored. This allows easily inserting element stiffness matrices
2128: with homogeneous Dirichlet boundary conditions that you don't want represented
2129: in the matrix.
2131: Each time an entry is set within a sparse matrix via `MatSetValues()`,
2132: internal searching must be done to determine where to place the
2133: data in the matrix storage space. By instead inserting blocks of
2134: entries via `MatSetValuesBlocked()`, the overhead of matrix assembly is
2135: reduced.
2137: Example:
2138: .vb
2139: Suppose m=n=2 and block size(bs) = 2 The array is
2141: 1 2 | 3 4
2142: 5 6 | 7 8
2143: - - - | - - -
2144: 9 10 | 11 12
2145: 13 14 | 15 16
2147: v[] should be passed in like
2148: v[] = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]
2150: If you are not using row-oriented storage of v (that is you called MatSetOption(mat,MAT_ROW_ORIENTED,PETSC_FALSE)) then
2151: v[] = [1,5,9,13,2,6,10,14,3,7,11,15,4,8,12,16]
2152: .ve
2154: Fortran Notes:
2155: If any of `idmx`, `idxn`, and `v` are scalars pass them using, for example,
2156: .vb
2157: call MatSetValuesBlocked(mat, one, [idxm], one, [idxn], [v], INSERT_VALUES, ierr)
2158: .ve
2160: If `v` is a two-dimensional array make sure to first call `MatSetOption(mat, MAT_ROW_ORIENTED, PETSC_FALSE, ierr)` before using this function,
2161: otherwise the transpose of `v` will seemingly be inserted in the matrix, since Fortran passes two-dimensional arrays with column orientation.
2163: .seealso: [](ch_matrices), `Mat`, `MatSetBlockSize()`, `MatSetOption()`, `MatAssemblyBegin()`, `MatAssemblyEnd()`, `MatSetValues()`, `MatSetValuesBlockedLocal()`
2164: @*/
2165: PetscErrorCode MatSetValuesBlocked(Mat mat, PetscInt m, const PetscInt idxm[], PetscInt n, const PetscInt idxn[], const PetscScalar v[], InsertMode addv)
2166: {
2167: PetscFunctionBeginHot;
2170: if (!m || !n) PetscFunctionReturn(PETSC_SUCCESS); /* no values to insert */
2171: PetscAssertPointer(idxm, 3);
2172: PetscAssertPointer(idxn, 5);
2173: MatCheckPreallocated(mat, 1);
2174: if (mat->insertmode == NOT_SET_VALUES) mat->insertmode = addv;
2175: else PetscCheck(mat->insertmode == addv, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Cannot mix add values and insert values");
2176: if (PetscDefined(USE_DEBUG)) {
2177: PetscCheck(!mat->factortype, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
2178: PetscCheck(mat->ops->setvaluesblocked || mat->ops->setvalues, PETSC_COMM_SELF, PETSC_ERR_SUP, "Mat type %s", ((PetscObject)mat)->type_name);
2179: }
2180: if (PetscDefined(USE_DEBUG)) {
2181: PetscInt rbs, cbs, M, N, i;
2182: PetscCall(MatGetBlockSizes(mat, &rbs, &cbs));
2183: PetscCall(MatGetSize(mat, &M, &N));
2184: 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);
2185: for (i = 0; i < n; i++)
2186: 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);
2187: }
2188: if (mat->assembled) {
2189: mat->was_assembled = PETSC_TRUE;
2190: mat->assembled = PETSC_FALSE;
2191: }
2192: PetscCall(PetscLogEventBegin(MAT_SetValues, mat, 0, 0, 0));
2193: if (mat->ops->setvaluesblocked) PetscUseTypeMethod(mat, setvaluesblocked, m, idxm, n, idxn, v, addv);
2194: else {
2195: PetscInt buf[8192], *bufr = NULL, *bufc = NULL, *iidxm, *iidxn;
2196: PetscInt i, j, bs, cbs;
2198: PetscCall(MatGetBlockSizes(mat, &bs, &cbs));
2199: if ((m * bs + n * cbs) <= (PetscInt)PETSC_STATIC_ARRAY_LENGTH(buf)) {
2200: iidxm = buf;
2201: iidxn = buf + m * bs;
2202: } else {
2203: PetscCall(PetscMalloc2(m * bs, &bufr, n * cbs, &bufc));
2204: iidxm = bufr;
2205: iidxn = bufc;
2206: }
2207: for (i = 0; i < m; i++) {
2208: for (j = 0; j < bs; j++) iidxm[i * bs + j] = bs * idxm[i] + j;
2209: }
2210: if (m != n || bs != cbs || idxm != idxn) {
2211: for (i = 0; i < n; i++) {
2212: for (j = 0; j < cbs; j++) iidxn[i * cbs + j] = cbs * idxn[i] + j;
2213: }
2214: } else iidxn = iidxm;
2215: PetscCall(MatSetValues(mat, m * bs, iidxm, n * cbs, iidxn, v, addv));
2216: PetscCall(PetscFree2(bufr, bufc));
2217: }
2218: PetscCall(PetscLogEventEnd(MAT_SetValues, mat, 0, 0, 0));
2219: PetscFunctionReturn(PETSC_SUCCESS);
2220: }
2222: /*@
2223: MatGetValues - Gets a block of local values from a matrix.
2225: Not Collective; can only return values that are owned by the give process
2227: Input Parameters:
2228: + mat - the matrix
2229: . v - a logically two-dimensional array for storing the values
2230: . m - the number of rows
2231: . idxm - the global indices of the rows
2232: . n - the number of columns
2233: - idxn - the global indices of the columns
2235: Level: advanced
2237: Notes:
2238: The user must allocate space (m*n `PetscScalar`s) for the values, `v`.
2240: The values, `v`, are returned in a row-oriented format, analogous to that used by default in `MatSetValues()`,
2241: unless `MatSetOption(mat, MAT_ROW_ORIENTED, PETSC_FALSE)` is called in which case they are returned column oriented.
2243: `MatGetValues()` uses 0-based row and column numbers in
2244: Fortran as well as in C.
2246: For `MATSBAIJ` matrices only the block upper triangular entries will be set.
2248: `MatGetValues()` requires that the matrix has been assembled
2249: with `MatAssemblyBegin()`/`MatAssemblyEnd()`. Thus, calls to
2250: `MatSetValues()` and `MatGetValues()` CANNOT be made in succession
2251: without intermediate matrix assembly.
2253: Negative row or column indices will be ignored and those locations in `v` will be
2254: left unchanged.
2256: For the standard row-based matrix formats, `idxm` can only contain rows owned by the requesting MPI process.
2257: That is, rows with global index greater than or equal to `rstart` and less than `rend` where `rstart` and `rend` are obtainable
2258: from `MatGetOwnershipRange`(mat,&rstart,&rend).
2260: .seealso: [](ch_matrices), `Mat`, `MatGetRow()`, `MatCreateSubMatrices()`, `MatSetValues()`, `MatGetOwnershipRange()`, `MatGetValuesLocal()`, `MatGetValue()`
2261: @*/
2262: PetscErrorCode MatGetValues(Mat mat, PetscInt m, const PetscInt idxm[], PetscInt n, const PetscInt idxn[], PetscScalar v[])
2263: {
2264: PetscFunctionBegin;
2267: if (!m || !n) PetscFunctionReturn(PETSC_SUCCESS);
2268: PetscAssertPointer(idxm, 3);
2269: PetscAssertPointer(idxn, 5);
2270: PetscAssertPointer(v, 6);
2271: PetscCheck(mat->assembled, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
2272: PetscCheck(!mat->factortype, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
2273: MatCheckPreallocated(mat, 1);
2275: PetscCall(PetscLogEventBegin(MAT_GetValues, mat, 0, 0, 0));
2276: PetscUseTypeMethod(mat, getvalues, m, idxm, n, idxn, v);
2277: PetscCall(PetscLogEventEnd(MAT_GetValues, mat, 0, 0, 0));
2278: PetscFunctionReturn(PETSC_SUCCESS);
2279: }
2281: /*@
2282: MatGetValuesLocal - retrieves values from certain locations in a matrix using the local numbering of the indices
2283: defined previously by `MatSetLocalToGlobalMapping()`
2285: Not Collective
2287: Input Parameters:
2288: + mat - the matrix
2289: . nrow - number of rows
2290: . irow - the row local indices
2291: . ncol - number of columns
2292: - icol - the column local indices
2294: Output Parameter:
2295: . y - a one-dimensional array that contains the values implicitly stored as a two-dimensional array, by default in row-major order.
2296: See `MAT_ROW_ORIENTED` in `MatSetOption()` for how to use column-major order.
2298: Level: advanced
2300: Notes:
2301: If you create the matrix yourself (that is not with a call to `DMCreateMatrix()`) then you MUST call `MatSetLocalToGlobalMapping()` before using this routine.
2303: 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,
2304: are greater than or equal to rstart and less than rend where rstart and rend are obtainable from `MatGetOwnershipRange`(mat,&rstart,&rend). One can
2305: determine if the resulting global row associated with the local row r is owned by the requesting MPI process by applying the `ISLocalToGlobalMapping` set
2306: with `MatSetLocalToGlobalMapping()`.
2308: .seealso: [](ch_matrices), `Mat`, `MatAssemblyBegin()`, `MatAssemblyEnd()`, `MatSetValues()`, `MatSetLocalToGlobalMapping()`,
2309: `MatSetValuesLocal()`, `MatGetValues()`
2310: @*/
2311: PetscErrorCode MatGetValuesLocal(Mat mat, PetscInt nrow, const PetscInt irow[], PetscInt ncol, const PetscInt icol[], PetscScalar y[])
2312: {
2313: PetscFunctionBeginHot;
2316: MatCheckPreallocated(mat, 1);
2317: if (!nrow || !ncol) PetscFunctionReturn(PETSC_SUCCESS); /* no values to retrieve */
2318: PetscAssertPointer(irow, 3);
2319: PetscAssertPointer(icol, 5);
2320: if (PetscDefined(USE_DEBUG)) {
2321: PetscCheck(!mat->factortype, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
2322: PetscCheck(mat->ops->getvalueslocal || mat->ops->getvalues, PETSC_COMM_SELF, PETSC_ERR_SUP, "Mat type %s", ((PetscObject)mat)->type_name);
2323: }
2324: PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
2325: PetscCall(PetscLogEventBegin(MAT_GetValues, mat, 0, 0, 0));
2326: if (mat->ops->getvalueslocal) PetscUseTypeMethod(mat, getvalueslocal, nrow, irow, ncol, icol, y);
2327: else {
2328: PetscInt buf[8192], *bufr = NULL, *bufc = NULL, *irowm, *icolm;
2329: if ((nrow + ncol) <= (PetscInt)PETSC_STATIC_ARRAY_LENGTH(buf)) {
2330: irowm = buf;
2331: icolm = buf + nrow;
2332: } else {
2333: PetscCall(PetscMalloc2(nrow, &bufr, ncol, &bufc));
2334: irowm = bufr;
2335: icolm = bufc;
2336: }
2337: PetscCheck(mat->rmap->mapping, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "MatGetValuesLocal() cannot proceed without local-to-global row mapping (See MatSetLocalToGlobalMapping()).");
2338: PetscCheck(mat->cmap->mapping, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "MatGetValuesLocal() cannot proceed without local-to-global column mapping (See MatSetLocalToGlobalMapping()).");
2339: PetscCall(ISLocalToGlobalMappingApply(mat->rmap->mapping, nrow, irow, irowm));
2340: PetscCall(ISLocalToGlobalMappingApply(mat->cmap->mapping, ncol, icol, icolm));
2341: PetscCall(MatGetValues(mat, nrow, irowm, ncol, icolm, y));
2342: PetscCall(PetscFree2(bufr, bufc));
2343: }
2344: PetscCall(PetscLogEventEnd(MAT_GetValues, mat, 0, 0, 0));
2345: PetscFunctionReturn(PETSC_SUCCESS);
2346: }
2348: /*@
2349: MatSetValuesBatch - Adds (`ADD_VALUES`) many blocks of values into a matrix at once. The blocks must all be square and
2350: the same size. Currently, this can only be called once and creates the given matrix.
2352: Not Collective
2354: Input Parameters:
2355: + mat - the matrix
2356: . nb - the number of blocks
2357: . bs - the number of rows (and columns) in each block
2358: . rows - a concatenation of the rows for each block
2359: - v - a concatenation of logically two-dimensional arrays of values
2361: Level: advanced
2363: Notes:
2364: `MatSetPreallocationCOO()` and `MatSetValuesCOO()` may be a better way to provide the values
2366: In the future, we will extend this routine to handle rectangular blocks, and to allow multiple calls for a given matrix.
2368: .seealso: [](ch_matrices), `Mat`, `MatSetOption()`, `MatAssemblyBegin()`, `MatAssemblyEnd()`, `MatSetValuesBlocked()`, `MatSetValuesLocal()`,
2369: `InsertMode`, `INSERT_VALUES`, `ADD_VALUES`, `MatSetValues()`, `MatSetPreallocationCOO()`, `MatSetValuesCOO()`
2370: @*/
2371: PetscErrorCode MatSetValuesBatch(Mat mat, PetscInt nb, PetscInt bs, PetscInt rows[], const PetscScalar v[])
2372: {
2373: PetscFunctionBegin;
2376: PetscAssertPointer(rows, 4);
2377: PetscAssertPointer(v, 5);
2378: PetscAssert(!mat->factortype, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
2380: PetscCall(PetscLogEventBegin(MAT_SetValuesBatch, mat, 0, 0, 0));
2381: for (PetscInt b = 0; b < nb; ++b) PetscCall(MatSetValues(mat, bs, &rows[b * bs], bs, &rows[b * bs], &v[b * bs * bs], ADD_VALUES));
2382: PetscCall(PetscLogEventEnd(MAT_SetValuesBatch, mat, 0, 0, 0));
2383: PetscFunctionReturn(PETSC_SUCCESS);
2384: }
2386: /*@
2387: MatSetLocalToGlobalMapping - Sets a local-to-global numbering for use by
2388: the routine `MatSetValuesLocal()` to allow users to insert matrix entries
2389: using a local (per-process) numbering.
2391: Not Collective
2393: Input Parameters:
2394: + x - the matrix
2395: . rmapping - row mapping created with `ISLocalToGlobalMappingCreate()` or `ISLocalToGlobalMappingCreateIS()`
2396: - cmapping - column mapping
2398: Level: intermediate
2400: Note:
2401: If the matrix is obtained with `DMCreateMatrix()` then this may already have been called on the matrix
2403: .seealso: [](ch_matrices), `Mat`, `DM`, `DMCreateMatrix()`, `MatGetLocalToGlobalMapping()`, `MatAssemblyBegin()`, `MatAssemblyEnd()`, `MatSetValues()`, `MatSetValuesLocal()`, `MatGetValuesLocal()`
2404: @*/
2405: PetscErrorCode MatSetLocalToGlobalMapping(Mat x, ISLocalToGlobalMapping rmapping, ISLocalToGlobalMapping cmapping)
2406: {
2407: PetscFunctionBegin;
2412: if (x->ops->setlocaltoglobalmapping) PetscUseTypeMethod(x, setlocaltoglobalmapping, rmapping, cmapping);
2413: else {
2414: PetscCall(PetscLayoutSetISLocalToGlobalMapping(x->rmap, rmapping));
2415: PetscCall(PetscLayoutSetISLocalToGlobalMapping(x->cmap, cmapping));
2416: }
2417: PetscFunctionReturn(PETSC_SUCCESS);
2418: }
2420: /*@
2421: MatGetLocalToGlobalMapping - Gets the local-to-global numbering set by `MatSetLocalToGlobalMapping()`
2423: Not Collective
2425: Input Parameter:
2426: . A - the matrix
2428: Output Parameters:
2429: + rmapping - row mapping
2430: - cmapping - column mapping
2432: Level: advanced
2434: .seealso: [](ch_matrices), `Mat`, `MatSetLocalToGlobalMapping()`, `MatSetValuesLocal()`
2435: @*/
2436: PetscErrorCode MatGetLocalToGlobalMapping(Mat A, ISLocalToGlobalMapping *rmapping, ISLocalToGlobalMapping *cmapping)
2437: {
2438: PetscFunctionBegin;
2441: if (rmapping) {
2442: PetscAssertPointer(rmapping, 2);
2443: *rmapping = A->rmap->mapping;
2444: }
2445: if (cmapping) {
2446: PetscAssertPointer(cmapping, 3);
2447: *cmapping = A->cmap->mapping;
2448: }
2449: PetscFunctionReturn(PETSC_SUCCESS);
2450: }
2452: /*@
2453: MatSetLayouts - Sets the `PetscLayout` objects for rows and columns of a matrix
2455: Logically Collective
2457: Input Parameters:
2458: + A - the matrix
2459: . rmap - row layout
2460: - cmap - column layout
2462: Level: advanced
2464: Note:
2465: The `PetscLayout` objects are usually created automatically for the matrix so this routine rarely needs to be called.
2467: .seealso: [](ch_matrices), `Mat`, `PetscLayout`, `MatCreateVecs()`, `MatGetLocalToGlobalMapping()`, `MatGetLayouts()`
2468: @*/
2469: PetscErrorCode MatSetLayouts(Mat A, PetscLayout rmap, PetscLayout cmap)
2470: {
2471: PetscFunctionBegin;
2473: PetscCall(PetscLayoutReference(rmap, &A->rmap));
2474: PetscCall(PetscLayoutReference(cmap, &A->cmap));
2475: PetscFunctionReturn(PETSC_SUCCESS);
2476: }
2478: /*@
2479: MatGetLayouts - Gets the `PetscLayout` objects for rows and columns
2481: Not Collective
2483: Input Parameter:
2484: . A - the matrix
2486: Output Parameters:
2487: + rmap - row layout
2488: - cmap - column layout
2490: Level: advanced
2492: .seealso: [](ch_matrices), `Mat`, [Matrix Layouts](sec_matlayout), `PetscLayout`, `MatCreateVecs()`, `MatGetLocalToGlobalMapping()`, `MatSetLayouts()`
2493: @*/
2494: PetscErrorCode MatGetLayouts(Mat A, PetscLayout *rmap, PetscLayout *cmap)
2495: {
2496: PetscFunctionBegin;
2499: if (rmap) {
2500: PetscAssertPointer(rmap, 2);
2501: *rmap = A->rmap;
2502: }
2503: if (cmap) {
2504: PetscAssertPointer(cmap, 3);
2505: *cmap = A->cmap;
2506: }
2507: PetscFunctionReturn(PETSC_SUCCESS);
2508: }
2510: /*@
2511: MatSetValuesLocal - Inserts or adds values into certain locations of a matrix,
2512: using a local numbering of the rows and columns.
2514: Not Collective
2516: Input Parameters:
2517: + mat - the matrix
2518: . nrow - number of rows
2519: . irow - the row local indices
2520: . ncol - number of columns
2521: . icol - the column local indices
2522: . v - a one-dimensional array that contains the values implicitly stored as a two-dimensional array, by default in row-major order.
2523: See `MAT_ROW_ORIENTED` in `MatSetOption()` for how to use column-major order.
2524: - addv - either `ADD_VALUES` to add values to any existing entries, or `INSERT_VALUES` to replace existing entries with new values
2526: Level: intermediate
2528: Notes:
2529: If you create the matrix yourself (that is not with a call to `DMCreateMatrix()`) then you MUST call `MatSetLocalToGlobalMapping()` before using this routine
2531: Calls to `MatSetValuesLocal()` with the `INSERT_VALUES` and `ADD_VALUES`
2532: options cannot be mixed without intervening calls to the assembly
2533: routines.
2535: These values may be cached, so `MatAssemblyBegin()` and `MatAssemblyEnd()`
2536: MUST be called after all calls to `MatSetValuesLocal()` have been completed.
2538: Fortran Notes:
2539: If any of `irow`, `icol`, and `v` are scalars pass them using, for example,
2540: .vb
2541: call MatSetValuesLocal(mat, one, [irow], one, [icol], [v], INSERT_VALUES, ierr)
2542: .ve
2544: If `v` is a two-dimensional array make sure to first call `MatSetOption(mat, MAT_ROW_ORIENTED, PETSC_FALSE, ierr)` before using this function,
2545: otherwise the transpose of `v` will seemingly be inserted in the matrix, since Fortran passes two-dimensional arrays with column orientation.
2547: .seealso: [](ch_matrices), `Mat`, `MatAssemblyBegin()`, `MatAssemblyEnd()`, `MatSetValues()`, `MatSetLocalToGlobalMapping()`,
2548: `MatGetValuesLocal()`
2549: @*/
2550: PetscErrorCode MatSetValuesLocal(Mat mat, PetscInt nrow, const PetscInt irow[], PetscInt ncol, const PetscInt icol[], const PetscScalar v[], InsertMode addv)
2551: {
2552: PetscFunctionBeginHot;
2555: MatCheckPreallocated(mat, 1);
2556: if (!nrow || !ncol) PetscFunctionReturn(PETSC_SUCCESS); /* no values to insert */
2557: PetscAssertPointer(irow, 3);
2558: PetscAssertPointer(icol, 5);
2559: if (mat->insertmode == NOT_SET_VALUES) mat->insertmode = addv;
2560: else PetscCheck(mat->insertmode == addv, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Cannot mix add values and insert values");
2561: if (PetscDefined(USE_DEBUG)) {
2562: PetscCheck(!mat->factortype, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
2563: PetscCheck(mat->ops->setvalueslocal || mat->ops->setvalues, PETSC_COMM_SELF, PETSC_ERR_SUP, "Mat type %s", ((PetscObject)mat)->type_name);
2564: }
2566: if (mat->assembled) {
2567: mat->was_assembled = PETSC_TRUE;
2568: mat->assembled = PETSC_FALSE;
2569: }
2570: PetscCall(PetscLogEventBegin(MAT_SetValues, mat, 0, 0, 0));
2571: if (mat->ops->setvalueslocal) PetscUseTypeMethod(mat, setvalueslocal, nrow, irow, ncol, icol, v, addv);
2572: else {
2573: PetscInt buf[8192], *bufr = NULL, *bufc = NULL;
2574: const PetscInt *irowm, *icolm;
2576: if ((!mat->rmap->mapping && !mat->cmap->mapping) || (nrow + ncol) <= (PetscInt)PETSC_STATIC_ARRAY_LENGTH(buf)) {
2577: bufr = buf;
2578: bufc = buf + nrow;
2579: irowm = bufr;
2580: icolm = bufc;
2581: } else {
2582: PetscCall(PetscMalloc2(nrow, &bufr, ncol, &bufc));
2583: irowm = bufr;
2584: icolm = bufc;
2585: }
2586: if (mat->rmap->mapping) PetscCall(ISLocalToGlobalMappingApply(mat->rmap->mapping, nrow, irow, bufr));
2587: else irowm = irow;
2588: if (mat->cmap->mapping) {
2589: if (mat->cmap->mapping != mat->rmap->mapping || ncol != nrow || icol != irow) PetscCall(ISLocalToGlobalMappingApply(mat->cmap->mapping, ncol, icol, bufc));
2590: else icolm = irowm;
2591: } else icolm = icol;
2592: PetscCall(MatSetValues(mat, nrow, irowm, ncol, icolm, v, addv));
2593: if (bufr != buf) PetscCall(PetscFree2(bufr, bufc));
2594: }
2595: PetscCall(PetscLogEventEnd(MAT_SetValues, mat, 0, 0, 0));
2596: PetscFunctionReturn(PETSC_SUCCESS);
2597: }
2599: /*@
2600: MatSetValuesBlockedLocal - Inserts or adds values into certain locations of a matrix,
2601: using a local ordering of the nodes a block at a time.
2603: Not Collective
2605: Input Parameters:
2606: + mat - the matrix
2607: . nrow - number of rows
2608: . irow - the row local indices
2609: . ncol - number of columns
2610: . icol - the column local indices
2611: . v - a one-dimensional array that contains the values implicitly stored as a two-dimensional array, by default in row-major order.
2612: See `MAT_ROW_ORIENTED` in `MatSetOption()` for how to use column-major order.
2613: - addv - either `ADD_VALUES` to add values to any existing entries, or `INSERT_VALUES` to replace existing entries with new values
2615: Level: intermediate
2617: Notes:
2618: If you create the matrix yourself (that is not with a call to `DMCreateMatrix()`) then you MUST call `MatSetBlockSize()` and `MatSetLocalToGlobalMapping()`
2619: before using this routineBefore calling `MatSetValuesLocal()`, the user must first set the
2621: Calls to `MatSetValuesBlockedLocal()` with the `INSERT_VALUES` and `ADD_VALUES`
2622: options cannot be mixed without intervening calls to the assembly
2623: routines.
2625: These values may be cached, so `MatAssemblyBegin()` and `MatAssemblyEnd()`
2626: MUST be called after all calls to `MatSetValuesBlockedLocal()` have been completed.
2628: Fortran Notes:
2629: If any of `irow`, `icol`, and `v` are scalars pass them using, for example,
2630: .vb
2631: call MatSetValuesBlockedLocal(mat, one, [irow], one, [icol], [v], INSERT_VALUES, ierr)
2632: .ve
2634: If `v` is a two-dimensional array make sure to first call `MatSetOption(mat, MAT_ROW_ORIENTED, PETSC_FALSE, ierr)` before using this function,
2635: otherwise the transpose of `v` will seemingly be inserted in the matrix, since Fortran passes two-dimensional arrays with column orientation.
2637: .seealso: [](ch_matrices), `Mat`, `MatSetBlockSize()`, `MatSetLocalToGlobalMapping()`, `MatAssemblyBegin()`, `MatAssemblyEnd()`,
2638: `MatSetValuesLocal()`, `MatSetValuesBlocked()`
2639: @*/
2640: PetscErrorCode MatSetValuesBlockedLocal(Mat mat, PetscInt nrow, const PetscInt irow[], PetscInt ncol, const PetscInt icol[], const PetscScalar v[], InsertMode addv)
2641: {
2642: PetscFunctionBeginHot;
2645: MatCheckPreallocated(mat, 1);
2646: if (!nrow || !ncol) PetscFunctionReturn(PETSC_SUCCESS); /* no values to insert */
2647: PetscAssertPointer(irow, 3);
2648: PetscAssertPointer(icol, 5);
2649: if (mat->insertmode == NOT_SET_VALUES) mat->insertmode = addv;
2650: else PetscCheck(mat->insertmode == addv, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Cannot mix add values and insert values");
2651: if (PetscDefined(USE_DEBUG)) {
2652: PetscCheck(!mat->factortype, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
2653: 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);
2654: }
2656: if (mat->assembled) {
2657: mat->was_assembled = PETSC_TRUE;
2658: mat->assembled = PETSC_FALSE;
2659: }
2660: if (PetscUnlikelyDebug(mat->rmap->mapping)) { /* Condition on the mapping existing, because MatSetValuesBlockedLocal_IS does not require it to be set. */
2661: PetscInt irbs, rbs;
2662: PetscCall(MatGetBlockSizes(mat, &rbs, NULL));
2663: PetscCall(ISLocalToGlobalMappingGetBlockSize(mat->rmap->mapping, &irbs));
2664: PetscCheck(rbs == irbs, PetscObjectComm((PetscObject)mat), PETSC_ERR_SUP, "Different row block sizes! mat %" PetscInt_FMT ", row l2g map %" PetscInt_FMT, rbs, irbs);
2665: }
2666: if (PetscUnlikelyDebug(mat->cmap->mapping)) {
2667: PetscInt icbs, cbs;
2668: PetscCall(MatGetBlockSizes(mat, NULL, &cbs));
2669: PetscCall(ISLocalToGlobalMappingGetBlockSize(mat->cmap->mapping, &icbs));
2670: PetscCheck(cbs == icbs, PetscObjectComm((PetscObject)mat), PETSC_ERR_SUP, "Different col block sizes! mat %" PetscInt_FMT ", col l2g map %" PetscInt_FMT, cbs, icbs);
2671: }
2672: PetscCall(PetscLogEventBegin(MAT_SetValues, mat, 0, 0, 0));
2673: if (mat->ops->setvaluesblockedlocal) PetscUseTypeMethod(mat, setvaluesblockedlocal, nrow, irow, ncol, icol, v, addv);
2674: else {
2675: PetscInt buf[8192], *bufr = NULL, *bufc = NULL;
2676: const PetscInt *irowm, *icolm;
2678: if ((!mat->rmap->mapping && !mat->cmap->mapping) || (nrow + ncol) <= ((PetscInt)PETSC_STATIC_ARRAY_LENGTH(buf))) {
2679: bufr = buf;
2680: bufc = buf + nrow;
2681: irowm = bufr;
2682: icolm = bufc;
2683: } else {
2684: PetscCall(PetscMalloc2(nrow, &bufr, ncol, &bufc));
2685: irowm = bufr;
2686: icolm = bufc;
2687: }
2688: if (mat->rmap->mapping) PetscCall(ISLocalToGlobalMappingApplyBlock(mat->rmap->mapping, nrow, irow, bufr));
2689: else irowm = irow;
2690: if (mat->cmap->mapping) {
2691: if (mat->cmap->mapping != mat->rmap->mapping || ncol != nrow || icol != irow) PetscCall(ISLocalToGlobalMappingApplyBlock(mat->cmap->mapping, ncol, icol, bufc));
2692: else icolm = irowm;
2693: } else icolm = icol;
2694: PetscCall(MatSetValuesBlocked(mat, nrow, irowm, ncol, icolm, v, addv));
2695: if (bufr != buf) PetscCall(PetscFree2(bufr, bufc));
2696: }
2697: PetscCall(PetscLogEventEnd(MAT_SetValues, mat, 0, 0, 0));
2698: PetscFunctionReturn(PETSC_SUCCESS);
2699: }
2701: /*@
2702: MatMultDiagonalBlock - Computes the matrix-vector product, $y = Dx$. Where `D` is defined by the inode or block structure of the diagonal
2704: Collective
2706: Input Parameters:
2707: + mat - the matrix
2708: - x - the vector to be multiplied
2710: Output Parameter:
2711: . y - the result
2713: Level: developer
2715: Note:
2716: The vectors `x` and `y` cannot be the same. I.e., one cannot
2717: call `MatMultDiagonalBlock`(A,y,y).
2719: .seealso: [](ch_matrices), `Mat`, `MatMult()`, `MatMultTranspose()`, `MatMultAdd()`, `MatMultTransposeAdd()`
2720: @*/
2721: PetscErrorCode MatMultDiagonalBlock(Mat mat, Vec x, Vec y)
2722: {
2723: PetscFunctionBegin;
2729: PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
2730: PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
2731: PetscCheck(x != y, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "x and y must be different vectors");
2732: MatCheckPreallocated(mat, 1);
2734: PetscUseTypeMethod(mat, multdiagonalblock, x, y);
2735: PetscCall(PetscObjectStateIncrease((PetscObject)y));
2736: PetscFunctionReturn(PETSC_SUCCESS);
2737: }
2739: /*@
2740: MatMult - Computes the matrix-vector product, $y = Ax$.
2742: Neighbor-wise Collective
2744: Input Parameters:
2745: + mat - the matrix
2746: - x - the vector to be multiplied
2748: Output Parameter:
2749: . y - the result
2751: Level: beginner
2753: Note:
2754: The vectors `x` and `y` cannot be the same. I.e., one cannot
2755: call `MatMult`(A,y,y).
2757: .seealso: [](ch_matrices), `Mat`, `MatMultTranspose()`, `MatMultAdd()`, `MatMultTransposeAdd()`
2758: @*/
2759: PetscErrorCode MatMult(Mat mat, Vec x, Vec y)
2760: {
2761: PetscFunctionBegin;
2765: VecCheckAssembled(x);
2767: PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
2768: PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
2769: PetscCheck(x != y, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "x and y must be different vectors");
2770: PetscCheck(mat->cmap->N == 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);
2771: 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);
2772: 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);
2773: 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);
2774: PetscCall(VecSetErrorIfLocked(y, 3));
2775: if (mat->erroriffailure) PetscCall(VecValidValues_Internal(x, 2, PETSC_TRUE));
2776: MatCheckPreallocated(mat, 1);
2778: PetscCall(VecLockReadPush(x));
2779: PetscCall(PetscLogEventBegin(MAT_Mult, mat, x, y, 0));
2780: PetscUseTypeMethod(mat, mult, x, y);
2781: PetscCall(PetscLogEventEnd(MAT_Mult, mat, x, y, 0));
2782: if (mat->erroriffailure) PetscCall(VecValidValues_Internal(y, 3, PETSC_FALSE));
2783: PetscCall(VecLockReadPop(x));
2784: PetscFunctionReturn(PETSC_SUCCESS);
2785: }
2787: /*@
2788: MatMultTranspose - Computes matrix transpose times a vector $y = A^T x$.
2790: Neighbor-wise Collective
2792: Input Parameters:
2793: + mat - the matrix
2794: - x - the vector to be multiplied
2796: Output Parameter:
2797: . y - the result
2799: Level: beginner
2801: Notes:
2802: The vectors `x` and `y` cannot be the same. I.e., one cannot
2803: call `MatMultTranspose`(A,y,y).
2805: For complex numbers this does NOT compute the Hermitian (complex conjugate) transpose multiple,
2806: use `MatMultHermitianTranspose()`
2808: .seealso: [](ch_matrices), `Mat`, `MatMult()`, `MatMultAdd()`, `MatMultTransposeAdd()`, `MatMultHermitianTranspose()`, `MatTranspose()`
2809: @*/
2810: PetscErrorCode MatMultTranspose(Mat mat, Vec x, Vec y)
2811: {
2812: PetscErrorCode (*op)(Mat, Vec, Vec) = NULL;
2814: PetscFunctionBegin;
2818: VecCheckAssembled(x);
2821: PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
2822: PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
2823: PetscCheck(x != y, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "x and y must be different vectors");
2824: 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);
2825: 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);
2826: 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);
2827: 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);
2828: if (mat->erroriffailure) PetscCall(VecValidValues_Internal(x, 2, PETSC_TRUE));
2829: MatCheckPreallocated(mat, 1);
2831: if (!mat->ops->multtranspose) {
2832: if (mat->symmetric == PETSC_BOOL3_TRUE && mat->ops->mult) op = mat->ops->mult;
2833: 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);
2834: } else op = mat->ops->multtranspose;
2835: PetscCall(PetscLogEventBegin(MAT_MultTranspose, mat, x, y, 0));
2836: PetscCall(VecLockReadPush(x));
2837: PetscCall((*op)(mat, x, y));
2838: PetscCall(VecLockReadPop(x));
2839: PetscCall(PetscLogEventEnd(MAT_MultTranspose, mat, x, y, 0));
2840: PetscCall(PetscObjectStateIncrease((PetscObject)y));
2841: if (mat->erroriffailure) PetscCall(VecValidValues_Internal(y, 3, PETSC_FALSE));
2842: PetscFunctionReturn(PETSC_SUCCESS);
2843: }
2845: /*@
2846: MatMultHermitianTranspose - Computes matrix Hermitian-transpose times a vector $y = A^H x$.
2848: Neighbor-wise Collective
2850: Input Parameters:
2851: + mat - the matrix
2852: - x - the vector to be multiplied
2854: Output Parameter:
2855: . y - the result
2857: Level: beginner
2859: Notes:
2860: The vectors `x` and `y` cannot be the same. I.e., one cannot
2861: call `MatMultHermitianTranspose`(A,y,y).
2863: Also called the conjugate transpose, complex conjugate transpose, or adjoint.
2865: For real numbers `MatMultTranspose()` and `MatMultHermitianTranspose()` are identical.
2867: .seealso: [](ch_matrices), `Mat`, `MatMult()`, `MatMultAdd()`, `MatMultHermitianTransposeAdd()`, `MatMultTranspose()`
2868: @*/
2869: PetscErrorCode MatMultHermitianTranspose(Mat mat, Vec x, Vec y)
2870: {
2871: PetscFunctionBegin;
2877: PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
2878: PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
2879: PetscCheck(x != y, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "x and y must be different vectors");
2880: 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);
2881: 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);
2882: 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);
2883: 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);
2884: MatCheckPreallocated(mat, 1);
2886: PetscCall(PetscLogEventBegin(MAT_MultHermitianTranspose, mat, x, y, 0));
2887: if (PetscDefined(USE_COMPLEX)) {
2888: if (mat->ops->multhermitiantranspose || (mat->hermitian == PETSC_BOOL3_TRUE && mat->ops->mult)) {
2889: PetscCall(VecLockReadPush(x));
2890: if (mat->ops->multhermitiantranspose) PetscUseTypeMethod(mat, multhermitiantranspose, x, y);
2891: else PetscUseTypeMethod(mat, mult, x, y);
2892: PetscCall(VecLockReadPop(x));
2893: } else {
2894: Vec w;
2895: PetscCall(VecDuplicate(x, &w));
2896: PetscCall(VecCopy(x, w));
2897: PetscCall(VecConjugate(w));
2898: PetscCall(MatMultTranspose(mat, w, y));
2899: PetscCall(VecDestroy(&w));
2900: PetscCall(VecConjugate(y));
2901: }
2902: PetscCall(PetscObjectStateIncrease((PetscObject)y));
2903: } else PetscCall(MatMultTranspose(mat, x, y));
2904: PetscCall(PetscLogEventEnd(MAT_MultHermitianTranspose, mat, x, y, 0));
2905: PetscFunctionReturn(PETSC_SUCCESS);
2906: }
2908: /*@
2909: MatMultAdd - Computes $v3 = v2 + A v1$.
2911: Neighbor-wise Collective
2913: Input Parameters:
2914: + mat - the matrix
2915: . v1 - the vector to be multiplied by `mat`
2916: - v2 - the vector to be added to the result
2918: Output Parameter:
2919: . v3 - the result
2921: Level: beginner
2923: Note:
2924: The vectors `v1` and `v3` cannot be the same. I.e., one cannot
2925: call `MatMultAdd`(A,v1,v2,v1).
2927: .seealso: [](ch_matrices), `Mat`, `MatMultTranspose()`, `MatMult()`, `MatMultTransposeAdd()`
2928: @*/
2929: PetscErrorCode MatMultAdd(Mat mat, Vec v1, Vec v2, Vec v3)
2930: {
2931: PetscFunctionBegin;
2938: PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
2939: PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
2940: 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);
2941: /* 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);
2942: 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); */
2943: 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);
2944: 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);
2945: PetscCheck(v1 != v3, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_IDN, "v1 and v3 must be different vectors");
2946: MatCheckPreallocated(mat, 1);
2948: PetscCall(PetscLogEventBegin(MAT_MultAdd, mat, v1, v2, v3));
2949: PetscCall(VecLockReadPush(v1));
2950: PetscUseTypeMethod(mat, multadd, v1, v2, v3);
2951: PetscCall(VecLockReadPop(v1));
2952: PetscCall(PetscLogEventEnd(MAT_MultAdd, mat, v1, v2, v3));
2953: PetscCall(PetscObjectStateIncrease((PetscObject)v3));
2954: PetscFunctionReturn(PETSC_SUCCESS);
2955: }
2957: /*@
2958: MatMultTransposeAdd - Computes $v3 = v2 + A^T v1$.
2960: Neighbor-wise Collective
2962: Input Parameters:
2963: + mat - the matrix
2964: . v1 - the vector to be multiplied by the transpose of the matrix
2965: - v2 - the vector to be added to the result
2967: Output Parameter:
2968: . v3 - the result
2970: Level: beginner
2972: Note:
2973: The vectors `v1` and `v3` cannot be the same. I.e., one cannot
2974: call `MatMultTransposeAdd`(A,v1,v2,v1).
2976: .seealso: [](ch_matrices), `Mat`, `MatMultTranspose()`, `MatMultAdd()`, `MatMult()`
2977: @*/
2978: PetscErrorCode MatMultTransposeAdd(Mat mat, Vec v1, Vec v2, Vec v3)
2979: {
2980: PetscErrorCode (*op)(Mat, Vec, Vec, Vec) = (!mat->ops->multtransposeadd && mat->symmetric) ? mat->ops->multadd : mat->ops->multtransposeadd;
2982: PetscFunctionBegin;
2989: PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
2990: PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
2991: 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);
2992: 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);
2993: 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);
2994: PetscCheck(v1 != v3, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_IDN, "v1 and v3 must be different vectors");
2995: PetscCheck(op, PetscObjectComm((PetscObject)mat), PETSC_ERR_SUP, "Mat type %s", ((PetscObject)mat)->type_name);
2996: MatCheckPreallocated(mat, 1);
2998: PetscCall(PetscLogEventBegin(MAT_MultTransposeAdd, mat, v1, v2, v3));
2999: PetscCall(VecLockReadPush(v1));
3000: PetscCall((*op)(mat, v1, v2, v3));
3001: PetscCall(VecLockReadPop(v1));
3002: PetscCall(PetscLogEventEnd(MAT_MultTransposeAdd, mat, v1, v2, v3));
3003: PetscCall(PetscObjectStateIncrease((PetscObject)v3));
3004: PetscFunctionReturn(PETSC_SUCCESS);
3005: }
3007: /*@
3008: MatMultHermitianTransposeAdd - Computes $v3 = v2 + A^H v1$.
3010: Neighbor-wise Collective
3012: Input Parameters:
3013: + mat - the matrix
3014: . v1 - the vector to be multiplied by the Hermitian transpose
3015: - v2 - the vector to be added to the result
3017: Output Parameter:
3018: . v3 - the result
3020: Level: beginner
3022: Note:
3023: The vectors `v1` and `v3` cannot be the same. I.e., one cannot
3024: call `MatMultHermitianTransposeAdd`(A,v1,v2,v1).
3026: .seealso: [](ch_matrices), `Mat`, `MatMultHermitianTranspose()`, `MatMultTranspose()`, `MatMultAdd()`, `MatMult()`
3027: @*/
3028: PetscErrorCode MatMultHermitianTransposeAdd(Mat mat, Vec v1, Vec v2, Vec v3)
3029: {
3030: PetscFunctionBegin;
3037: PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
3038: PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
3039: PetscCheck(v1 != v3, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_IDN, "v1 and v3 must be different vectors");
3040: 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);
3041: 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);
3042: 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);
3043: MatCheckPreallocated(mat, 1);
3045: PetscCall(PetscLogEventBegin(MAT_MultHermitianTransposeAdd, mat, v1, v2, v3));
3046: PetscCall(VecLockReadPush(v1));
3047: if (mat->ops->multhermitiantransposeadd) PetscUseTypeMethod(mat, multhermitiantransposeadd, v1, v2, v3);
3048: else {
3049: Vec w, z;
3050: PetscCall(VecDuplicate(v1, &w));
3051: PetscCall(VecCopy(v1, w));
3052: PetscCall(VecConjugate(w));
3053: PetscCall(VecDuplicate(v3, &z));
3054: PetscCall(MatMultTranspose(mat, w, z));
3055: PetscCall(VecDestroy(&w));
3056: PetscCall(VecConjugate(z));
3057: if (v2 != v3) PetscCall(VecWAXPY(v3, 1.0, v2, z));
3058: else PetscCall(VecAXPY(v3, 1.0, z));
3059: PetscCall(VecDestroy(&z));
3060: }
3061: PetscCall(VecLockReadPop(v1));
3062: PetscCall(PetscLogEventEnd(MAT_MultHermitianTransposeAdd, mat, v1, v2, v3));
3063: PetscCall(PetscObjectStateIncrease((PetscObject)v3));
3064: PetscFunctionReturn(PETSC_SUCCESS);
3065: }
3067: static PetscErrorCode MatADot_Default(Mat mat, Vec x, Vec y, PetscScalar *val)
3068: {
3069: PetscFunctionBegin;
3070: if (!mat->dot_vec) PetscCall(MatCreateVecs(mat, NULL, &mat->dot_vec));
3071: PetscCall(MatMult(mat, x, mat->dot_vec));
3072: PetscCall(VecDot(mat->dot_vec, y, val));
3073: PetscFunctionReturn(PETSC_SUCCESS);
3074: }
3076: static PetscErrorCode MatANorm_Default(Mat mat, Vec x, PetscReal *val)
3077: {
3078: PetscScalar sval;
3080: PetscFunctionBegin;
3081: PetscCall(MatADot(mat, x, x, &sval));
3082: PetscCheck(PetscRealPart(sval) >= 0.0, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONG, "Matrix argument is not positive definite");
3083: PetscCheck(PetscAbsReal(PetscImaginaryPart(sval)) <= 100 * PETSC_MACHINE_EPSILON * PetscMax(1.0, PetscAbsScalar(sval)), PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONG, "Matrix argument is not Hermitian");
3084: *val = PetscSqrtReal(PetscRealPart(sval));
3085: PetscFunctionReturn(PETSC_SUCCESS);
3086: }
3088: /*@
3089: 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)
3090: positive definite.
3092: Collective
3094: Input Parameters:
3095: + mat - matrix used to define the inner product
3096: . x - first vector
3097: - y - second vector
3099: Output Parameter:
3100: . val - the dot product with respect to `A`
3102: Level: intermediate
3104: Note:
3105: For complex vectors, `MatADot()` computes
3106: $$
3107: val = (x,y)_A = y^H A x,
3108: $$
3109: where $y^H$ denotes the conjugate transpose of `y`. Note that this corresponds to the "mathematicians" complex
3110: inner product where the SECOND argument gets the complex conjugate.
3112: .seealso: [](ch_matrices), `Mat`, `MatANorm()`, `VecDot()`, `VecNorm()`, `MatMult()`, `MatMultAdd()`, `MatMultTransposeAdd()`
3113: @*/
3114: PetscErrorCode MatADot(Mat mat, Vec x, Vec y, PetscScalar *val)
3115: {
3116: PetscFunctionBegin;
3120: VecCheckAssembled(x);
3122: VecCheckAssembled(y);
3125: PetscAssertPointer(val, 4);
3126: PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
3127: PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
3128: 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);
3129: 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);
3130: 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);
3131: 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);
3132: if (mat->erroriffailure) PetscCall(VecValidValues_Internal(x, 2, PETSC_TRUE));
3133: if (mat->erroriffailure) PetscCall(VecValidValues_Internal(y, 3, PETSC_TRUE));
3134: MatCheckPreallocated(mat, 1);
3136: PetscCall(VecLockReadPush(x));
3137: PetscCall(VecLockReadPush(y));
3138: PetscCall(PetscLogEventBegin(MAT_ADot, mat, x, y, 0));
3139: if (mat->ops->adot) PetscUseTypeMethod(mat, adot, x, y, val);
3140: else PetscCall(MatADot_Default(mat, x, y, val));
3141: PetscCall(PetscLogEventEnd(MAT_ADot, mat, x, y, 0));
3142: PetscCall(VecLockReadPop(y));
3143: PetscCall(VecLockReadPop(x));
3144: PetscFunctionReturn(PETSC_SUCCESS);
3145: }
3147: /*@
3148: 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)
3149: positive definite.
3151: Collective
3153: Input Parameters:
3154: + mat - matrix used to define norm
3155: - x - the vector to compute the norm of
3157: Output Parameter:
3158: . val - the norm with respect to `A`
3160: Level: intermediate
3162: Note:
3163: For complex vectors, `MatANorm()` computes
3164: $$
3165: val = (x,x)_A^{1/2} = (x^H A x)^{1/2},
3166: $$
3167: where $x^H$ denotes the conjugate transpose of `x`.
3169: .seealso: [](ch_matrices), `Mat`, `MatADot()`, `VecDot()`, `VecNorm()`, `MatMult()`, `MatMultAdd()`, `MatMultTransposeAdd()`
3170: @*/
3171: PetscErrorCode MatANorm(Mat mat, Vec x, PetscReal *val)
3172: {
3173: PetscFunctionBegin;
3177: VecCheckAssembled(x);
3179: PetscAssertPointer(val, 3);
3180: PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
3181: PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
3182: 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);
3183: 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);
3184: 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);
3185: 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);
3186: if (mat->erroriffailure) PetscCall(VecValidValues_Internal(x, 2, PETSC_TRUE));
3187: MatCheckPreallocated(mat, 1);
3189: PetscCall(VecLockReadPush(x));
3190: PetscCall(PetscLogEventBegin(MAT_ANorm, mat, x, 0, 0));
3191: if (mat->ops->anorm) PetscUseTypeMethod(mat, anorm, x, val);
3192: else PetscCall(MatANorm_Default(mat, x, val));
3193: PetscCall(PetscLogEventEnd(MAT_ANorm, mat, x, 0, 0));
3194: PetscCall(VecLockReadPop(x));
3195: PetscFunctionReturn(PETSC_SUCCESS);
3196: }
3198: /*@
3199: MatGetFactorType - gets the type of factorization a matrix is
3201: Not Collective
3203: Input Parameter:
3204: . mat - the matrix
3206: Output Parameter:
3207: . 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`
3209: Level: intermediate
3211: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatFactorType`, `MatGetFactor()`, `MatSetFactorType()`, `MAT_FACTOR_NONE`, `MAT_FACTOR_LU`, `MAT_FACTOR_CHOLESKY`, `MAT_FACTOR_ILU`,
3212: `MAT_FACTOR_ICC`, `MAT_FACTOR_ILUDT`, `MAT_FACTOR_QR`
3213: @*/
3214: PetscErrorCode MatGetFactorType(Mat mat, MatFactorType *t)
3215: {
3216: PetscFunctionBegin;
3219: PetscAssertPointer(t, 2);
3220: *t = mat->factortype;
3221: PetscFunctionReturn(PETSC_SUCCESS);
3222: }
3224: /*@
3225: MatSetFactorType - sets the type of factorization a matrix is
3227: Logically Collective
3229: Input Parameters:
3230: + mat - the matrix
3231: - 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`
3233: Level: intermediate
3235: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatFactorType`, `MatGetFactor()`, `MatGetFactorType()`, `MAT_FACTOR_NONE`, `MAT_FACTOR_LU`, `MAT_FACTOR_CHOLESKY`, `MAT_FACTOR_ILU`,
3236: `MAT_FACTOR_ICC`, `MAT_FACTOR_ILUDT`, `MAT_FACTOR_QR`
3237: @*/
3238: PetscErrorCode MatSetFactorType(Mat mat, MatFactorType t)
3239: {
3240: PetscFunctionBegin;
3243: mat->factortype = t;
3244: PetscFunctionReturn(PETSC_SUCCESS);
3245: }
3247: /*@
3248: MatGetInfo - Returns information about matrix storage (number of
3249: nonzeros, memory, etc.).
3251: Collective if `MAT_GLOBAL_MAX` or `MAT_GLOBAL_SUM` is used as the flag
3253: Input Parameters:
3254: + mat - the matrix
3255: - flag - flag indicating the type of parameters to be returned (`MAT_LOCAL` - local matrix, `MAT_GLOBAL_MAX` - maximum over all processes, `MAT_GLOBAL_SUM` - sum over all processes)
3257: Output Parameter:
3258: . info - matrix information context
3260: Options Database Key:
3261: . -mat_view :[filename]:ascii_info - print the matrix information to `filename` or `stdout`, see `MatView()`
3263: Level: intermediate
3265: Notes:
3266: The `MatInfo` context contains a variety of matrix data, including
3267: number of nonzeros allocated and used, number of mallocs during
3268: matrix assembly, etc. Additional information for factored matrices
3269: is provided (such as the fill ratio, number of mallocs during
3270: factorization, etc.).
3272: Example:
3273: See the file `${PETSC_DIR}/include/petscmat.h` for a complete list of
3274: data within the `MatInfo` context. For example,
3275: .vb
3276: MatInfo info;
3277: Mat A;
3278: double mal, nz_a, nz_u;
3280: MatGetInfo(A, MAT_LOCAL, &info);
3281: mal = info.mallocs;
3282: nz_a = info.nz_allocated;
3283: .ve
3285: .seealso: [](ch_matrices), `Mat`, `MatInfo`, `MatStashGetInfo()`
3286: @*/
3287: PetscErrorCode MatGetInfo(Mat mat, MatInfoType flag, MatInfo *info)
3288: {
3289: PetscFunctionBegin;
3292: PetscAssertPointer(info, 3);
3293: MatCheckPreallocated(mat, 1);
3294: PetscUseTypeMethod(mat, getinfo, flag, info);
3295: PetscFunctionReturn(PETSC_SUCCESS);
3296: }
3298: /*
3299: This is used by external packages where it is not easy to get the info from the actual
3300: matrix factorization.
3301: */
3302: PetscErrorCode MatGetInfo_External(Mat A, MatInfoType flag, MatInfo *info)
3303: {
3304: PetscFunctionBegin;
3305: PetscCall(PetscMemzero(info, sizeof(MatInfo)));
3306: PetscFunctionReturn(PETSC_SUCCESS);
3307: }
3309: /*@
3310: MatLUFactor - Performs in-place LU factorization of matrix.
3312: Collective
3314: Input Parameters:
3315: + mat - the matrix
3316: . row - row permutation
3317: . col - column permutation
3318: - info - options for factorization, includes
3319: .vb
3320: fill - expected fill as ratio of original fill.
3321: dtcol - pivot tolerance (0 no pivot, 1 full column pivoting)
3322: Run with the option -info to determine an optimal value to use
3323: .ve
3325: Level: developer
3327: Notes:
3328: Most users should employ the `KSP` interface for linear solvers
3329: instead of working directly with matrix algebra routines such as this.
3330: See, e.g., `KSPCreate()`.
3332: This changes the state of the matrix to a factored matrix; it cannot be used
3333: for example with `MatSetValues()` unless one first calls `MatSetUnfactored()`.
3335: This is really in-place only for dense matrices, the preferred approach is to use `MatGetFactor()`, `MatLUFactorSymbolic()`, and `MatLUFactorNumeric()`
3336: when not using `KSP`.
3338: Fortran Note:
3339: A valid (non-null) `info` argument must be provided
3341: .seealso: [](ch_matrices), [Matrix Factorization](sec_matfactor), `Mat`, `MatFactorType`, `MatLUFactorSymbolic()`, `MatLUFactorNumeric()`, `MatCholeskyFactor()`,
3342: `MatGetOrdering()`, `MatSetUnfactored()`, `MatFactorInfo`, `MatGetFactor()`
3343: @*/
3344: PetscErrorCode MatLUFactor(Mat mat, IS row, IS col, const MatFactorInfo *info)
3345: {
3346: MatFactorInfo tinfo;
3348: PetscFunctionBegin;
3352: if (info) PetscAssertPointer(info, 4);
3354: PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
3355: PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
3356: MatCheckPreallocated(mat, 1);
3357: if (!info) {
3358: PetscCall(MatFactorInfoInitialize(&tinfo));
3359: info = &tinfo;
3360: }
3362: PetscCall(PetscLogEventBegin(MAT_LUFactor, mat, row, col, 0));
3363: PetscUseTypeMethod(mat, lufactor, row, col, info);
3364: PetscCall(PetscLogEventEnd(MAT_LUFactor, mat, row, col, 0));
3365: PetscCall(PetscObjectStateIncrease((PetscObject)mat));
3366: PetscFunctionReturn(PETSC_SUCCESS);
3367: }
3369: /*@
3370: MatILUFactor - Performs in-place ILU factorization of matrix.
3372: Collective
3374: Input Parameters:
3375: + mat - the matrix
3376: . row - row permutation
3377: . col - column permutation
3378: - info - structure containing
3379: .vb
3380: levels - number of levels of fill.
3381: expected fill - as ratio of original fill.
3382: 1 or 0 - indicating force fill on diagonal (improves robustness for matrices
3383: missing diagonal entries)
3384: .ve
3386: Level: developer
3388: Notes:
3389: Most users should employ the `KSP` interface for linear solvers
3390: instead of working directly with matrix algebra routines such as this.
3391: See, e.g., `KSPCreate()`.
3393: Probably really in-place only when level of fill is zero, otherwise allocates
3394: new space to store factored matrix and deletes previous memory. The preferred approach is to use `MatGetFactor()`, `MatILUFactorSymbolic()`, and `MatLUFactorNumeric()`
3395: when not using `KSP`.
3397: Fortran Note:
3398: A valid (non-null) `info` argument must be provided
3400: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatILUFactorSymbolic()`, `MatLUFactorNumeric()`, `MatCholeskyFactor()`, `MatFactorInfo`
3401: @*/
3402: PetscErrorCode MatILUFactor(Mat mat, IS row, IS col, const MatFactorInfo *info)
3403: {
3404: PetscFunctionBegin;
3408: PetscAssertPointer(info, 4);
3410: PetscCheck(mat->rmap->N == mat->cmap->N, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONG, "matrix must be square");
3411: PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
3412: PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
3413: MatCheckPreallocated(mat, 1);
3415: PetscCall(PetscLogEventBegin(MAT_ILUFactor, mat, row, col, 0));
3416: PetscUseTypeMethod(mat, ilufactor, row, col, info);
3417: PetscCall(PetscLogEventEnd(MAT_ILUFactor, mat, row, col, 0));
3418: PetscCall(PetscObjectStateIncrease((PetscObject)mat));
3419: PetscFunctionReturn(PETSC_SUCCESS);
3420: }
3422: /*@
3423: MatLUFactorSymbolic - Performs symbolic LU factorization of matrix.
3424: Call this routine before calling `MatLUFactorNumeric()` and after `MatGetFactor()`.
3426: Collective
3428: Input Parameters:
3429: + fact - the factor matrix obtained with `MatGetFactor()`
3430: . mat - the matrix
3431: . row - the row permutation
3432: . col - the column permutation
3433: - info - options for factorization, includes
3434: .vb
3435: fill - expected fill as ratio of original fill. Run with the option -info to determine an optimal value to use
3436: dtcol - pivot tolerance (0 no pivot, 1 full column pivoting)
3437: .ve
3439: Level: developer
3441: Notes:
3442: See [Matrix Factorization](sec_matfactor) for additional information about factorizations
3444: Most users should employ the simplified `KSP` interface for linear solvers
3445: instead of working directly with matrix algebra routines such as this.
3446: See, e.g., `KSPCreate()`.
3448: Fortran Note:
3449: A valid (non-null) `info` argument must be provided
3451: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatGetFactor()`, `MatLUFactor()`, `MatLUFactorNumeric()`, `MatCholeskyFactor()`, `MatFactorInfo`, `MatFactorInfoInitialize()`
3452: @*/
3453: PetscErrorCode MatLUFactorSymbolic(Mat fact, Mat mat, IS row, IS col, const MatFactorInfo *info)
3454: {
3455: MatFactorInfo tinfo;
3457: PetscFunctionBegin;
3462: if (info) PetscAssertPointer(info, 5);
3465: PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
3466: PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
3467: MatCheckPreallocated(mat, 2);
3468: if (!info) {
3469: PetscCall(MatFactorInfoInitialize(&tinfo));
3470: info = &tinfo;
3471: }
3473: if (!fact->trivialsymbolic) PetscCall(PetscLogEventBegin(MAT_LUFactorSymbolic, mat, row, col, 0));
3474: PetscUseTypeMethod(fact, lufactorsymbolic, mat, row, col, info);
3475: if (!fact->trivialsymbolic) PetscCall(PetscLogEventEnd(MAT_LUFactorSymbolic, mat, row, col, 0));
3476: PetscCall(PetscObjectStateIncrease((PetscObject)fact));
3477: PetscFunctionReturn(PETSC_SUCCESS);
3478: }
3480: /*@
3481: MatLUFactorNumeric - Performs numeric LU factorization of a matrix.
3482: Call this routine after first calling `MatLUFactorSymbolic()` and `MatGetFactor()`.
3484: Collective
3486: Input Parameters:
3487: + fact - the factor matrix obtained with `MatGetFactor()`
3488: . mat - the matrix
3489: - info - options for factorization
3491: Level: developer
3493: Notes:
3494: See `MatLUFactor()` for in-place factorization. See
3495: `MatCholeskyFactorNumeric()` for the symmetric, positive definite case.
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), `MatGetFactor()`, `MatFactorInfo`, `MatLUFactorSymbolic()`, `MatLUFactor()`, `MatCholeskyFactor()`
3505: @*/
3506: PetscErrorCode MatLUFactorNumeric(Mat fact, Mat mat, const MatFactorInfo *info)
3507: {
3508: MatFactorInfo tinfo;
3510: PetscFunctionBegin;
3515: PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
3516: 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,
3517: mat->rmap->N, (fact)->rmap->N, mat->cmap->N, (fact)->cmap->N);
3519: MatCheckPreallocated(mat, 2);
3520: if (!info) {
3521: PetscCall(MatFactorInfoInitialize(&tinfo));
3522: info = &tinfo;
3523: }
3525: if (!fact->trivialsymbolic) PetscCall(PetscLogEventBegin(MAT_LUFactorNumeric, mat, fact, 0, 0));
3526: else PetscCall(PetscLogEventBegin(MAT_LUFactor, mat, fact, 0, 0));
3527: PetscUseTypeMethod(fact, lufactornumeric, mat, info);
3528: if (!fact->trivialsymbolic) PetscCall(PetscLogEventEnd(MAT_LUFactorNumeric, mat, fact, 0, 0));
3529: else PetscCall(PetscLogEventEnd(MAT_LUFactor, mat, fact, 0, 0));
3530: PetscCall(MatViewFromOptions(fact, NULL, "-mat_factor_view"));
3531: PetscCall(PetscObjectStateIncrease((PetscObject)fact));
3532: PetscFunctionReturn(PETSC_SUCCESS);
3533: }
3535: /*@
3536: MatCholeskyFactor - Performs in-place Cholesky factorization of a
3537: symmetric matrix.
3539: Collective
3541: Input Parameters:
3542: + mat - the matrix
3543: . perm - row and column permutations
3544: - info - expected fill as ratio of original fill
3546: Level: developer
3548: Notes:
3549: See `MatLUFactor()` for the nonsymmetric case. See also `MatGetFactor()`,
3550: `MatCholeskyFactorSymbolic()`, and `MatCholeskyFactorNumeric()`.
3552: Most users should employ the `KSP` interface for linear solvers
3553: instead of working directly with matrix algebra routines such as this.
3554: See, e.g., `KSPCreate()`.
3556: Fortran Note:
3557: A valid (non-null) `info` argument must be provided
3559: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatGetFactor()`, `MatFactorInfo`, `MatLUFactor()`, `MatCholeskyFactorSymbolic()`, `MatCholeskyFactorNumeric()`,
3560: `MatGetOrdering()`
3561: @*/
3562: PetscErrorCode MatCholeskyFactor(Mat mat, IS perm, const MatFactorInfo *info)
3563: {
3564: MatFactorInfo tinfo;
3566: PetscFunctionBegin;
3569: if (info) PetscAssertPointer(info, 3);
3571: PetscCheck(mat->rmap->N == mat->cmap->N, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONG, "Matrix must be square");
3572: PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
3573: PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
3574: MatCheckPreallocated(mat, 1);
3575: if (!info) {
3576: PetscCall(MatFactorInfoInitialize(&tinfo));
3577: info = &tinfo;
3578: }
3580: PetscCall(PetscLogEventBegin(MAT_CholeskyFactor, mat, perm, 0, 0));
3581: PetscUseTypeMethod(mat, choleskyfactor, perm, info);
3582: PetscCall(PetscLogEventEnd(MAT_CholeskyFactor, mat, perm, 0, 0));
3583: PetscCall(PetscObjectStateIncrease((PetscObject)mat));
3584: PetscFunctionReturn(PETSC_SUCCESS);
3585: }
3587: /*@
3588: MatCholeskyFactorSymbolic - Performs symbolic Cholesky factorization
3589: of a symmetric matrix.
3591: Collective
3593: Input Parameters:
3594: + fact - the factor matrix obtained with `MatGetFactor()`
3595: . mat - the matrix
3596: . perm - row and column permutations
3597: - info - options for factorization, includes
3598: .vb
3599: fill - expected fill as ratio of original fill.
3600: dtcol - pivot tolerance (0 no pivot, 1 full column pivoting)
3601: Run with the option -info to determine an optimal value to use
3602: .ve
3604: Level: developer
3606: Notes:
3607: See `MatLUFactorSymbolic()` for the nonsymmetric case. See also
3608: `MatCholeskyFactor()` and `MatCholeskyFactorNumeric()`.
3610: Most users should employ the `KSP` interface for linear solvers
3611: instead of working directly with matrix algebra routines such as this.
3612: See, e.g., `KSPCreate()`.
3614: Fortran Note:
3615: A valid (non-null) `info` argument must be provided
3617: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatFactorInfo`, `MatGetFactor()`, `MatLUFactorSymbolic()`, `MatCholeskyFactor()`, `MatCholeskyFactorNumeric()`,
3618: `MatGetOrdering()`
3619: @*/
3620: PetscErrorCode MatCholeskyFactorSymbolic(Mat fact, Mat mat, IS perm, const MatFactorInfo *info)
3621: {
3622: MatFactorInfo tinfo;
3624: PetscFunctionBegin;
3628: if (info) PetscAssertPointer(info, 4);
3631: PetscCheck(mat->rmap->N == mat->cmap->N, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONG, "Matrix must be square");
3632: PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
3633: PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
3634: MatCheckPreallocated(mat, 2);
3635: if (!info) {
3636: PetscCall(MatFactorInfoInitialize(&tinfo));
3637: info = &tinfo;
3638: }
3640: if (!fact->trivialsymbolic) PetscCall(PetscLogEventBegin(MAT_CholeskyFactorSymbolic, mat, perm, 0, 0));
3641: PetscUseTypeMethod(fact, choleskyfactorsymbolic, mat, perm, info);
3642: if (!fact->trivialsymbolic) PetscCall(PetscLogEventEnd(MAT_CholeskyFactorSymbolic, mat, perm, 0, 0));
3643: PetscCall(PetscObjectStateIncrease((PetscObject)fact));
3644: PetscFunctionReturn(PETSC_SUCCESS);
3645: }
3647: /*@
3648: MatCholeskyFactorNumeric - Performs numeric Cholesky factorization
3649: of a symmetric matrix. Call this routine after first calling `MatGetFactor()` and
3650: `MatCholeskyFactorSymbolic()`.
3652: Collective
3654: Input Parameters:
3655: + fact - the factor matrix obtained with `MatGetFactor()`, where the factored values are stored
3656: . mat - the initial matrix that is to be factored
3657: - info - options for factorization
3659: Level: developer
3661: Note:
3662: Most users should employ the `KSP` interface for linear solvers
3663: instead of working directly with matrix algebra routines such as this.
3664: See, e.g., `KSPCreate()`.
3666: Fortran Note:
3667: A valid (non-null) `info` argument must be provided
3669: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatFactorInfo`, `MatGetFactor()`, `MatCholeskyFactorSymbolic()`, `MatCholeskyFactor()`, `MatLUFactorNumeric()`
3670: @*/
3671: PetscErrorCode MatCholeskyFactorNumeric(Mat fact, Mat mat, const MatFactorInfo *info)
3672: {
3673: MatFactorInfo tinfo;
3675: PetscFunctionBegin;
3680: PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
3681: 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,
3682: mat->rmap->N, (fact)->rmap->N, mat->cmap->N, (fact)->cmap->N);
3683: MatCheckPreallocated(mat, 2);
3684: if (!info) {
3685: PetscCall(MatFactorInfoInitialize(&tinfo));
3686: info = &tinfo;
3687: }
3689: if (!fact->trivialsymbolic) PetscCall(PetscLogEventBegin(MAT_CholeskyFactorNumeric, mat, fact, 0, 0));
3690: else PetscCall(PetscLogEventBegin(MAT_CholeskyFactor, mat, fact, 0, 0));
3691: PetscUseTypeMethod(fact, choleskyfactornumeric, mat, info);
3692: if (!fact->trivialsymbolic) PetscCall(PetscLogEventEnd(MAT_CholeskyFactorNumeric, mat, fact, 0, 0));
3693: else PetscCall(PetscLogEventEnd(MAT_CholeskyFactor, mat, fact, 0, 0));
3694: PetscCall(MatViewFromOptions(fact, NULL, "-mat_factor_view"));
3695: PetscCall(PetscObjectStateIncrease((PetscObject)fact));
3696: PetscFunctionReturn(PETSC_SUCCESS);
3697: }
3699: /*@
3700: MatQRFactor - Performs in-place QR factorization of matrix.
3702: Collective
3704: Input Parameters:
3705: + mat - the matrix
3706: . col - column permutation
3707: - info - options for factorization, includes
3708: .vb
3709: fill - expected fill as ratio of original fill.
3710: dtcol - pivot tolerance (0 no pivot, 1 full column pivoting)
3711: Run with the option -info to determine an optimal value to use
3712: .ve
3714: Level: developer
3716: Notes:
3717: Most users should employ the `KSP` interface for linear solvers
3718: instead of working directly with matrix algebra routines such as this.
3719: See, e.g., `KSPCreate()`.
3721: This changes the state of the matrix to a factored matrix; it cannot be used
3722: for example with `MatSetValues()` unless one first calls `MatSetUnfactored()`.
3724: Fortran Note:
3725: A valid (non-null) `info` argument must be provided
3727: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatFactorInfo`, `MatGetFactor()`, `MatQRFactorSymbolic()`, `MatQRFactorNumeric()`, `MatLUFactor()`,
3728: `MatSetUnfactored()`
3729: @*/
3730: PetscErrorCode MatQRFactor(Mat mat, IS col, const MatFactorInfo *info)
3731: {
3732: PetscFunctionBegin;
3735: if (info) PetscAssertPointer(info, 3);
3737: PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
3738: PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
3739: MatCheckPreallocated(mat, 1);
3740: PetscCall(PetscLogEventBegin(MAT_QRFactor, mat, col, 0, 0));
3741: PetscUseMethod(mat, "MatQRFactor_C", (Mat, IS, const MatFactorInfo *), (mat, col, info));
3742: PetscCall(PetscLogEventEnd(MAT_QRFactor, mat, col, 0, 0));
3743: PetscCall(PetscObjectStateIncrease((PetscObject)mat));
3744: PetscFunctionReturn(PETSC_SUCCESS);
3745: }
3747: /*@
3748: MatQRFactorSymbolic - Performs symbolic QR factorization of matrix.
3749: Call this routine after `MatGetFactor()` but before calling `MatQRFactorNumeric()`.
3751: Collective
3753: Input Parameters:
3754: + fact - the factor matrix obtained with `MatGetFactor()`
3755: . mat - the matrix
3756: . col - column permutation
3757: - info - options for factorization, includes
3758: .vb
3759: fill - expected fill as ratio of original fill.
3760: dtcol - pivot tolerance (0 no pivot, 1 full column pivoting)
3761: Run with the option -info to determine an optimal value to use
3762: .ve
3764: Level: developer
3766: Note:
3767: Most users should employ the `KSP` interface for linear solvers
3768: instead of working directly with matrix algebra routines such as this.
3769: See, e.g., `KSPCreate()`.
3771: Fortran Note:
3772: A valid (non-null) `info` argument must be provided
3774: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatGetFactor()`, `MatFactorInfo`, `MatQRFactor()`, `MatQRFactorNumeric()`, `MatLUFactor()`, `MatFactorInfoInitialize()`
3775: @*/
3776: PetscErrorCode MatQRFactorSymbolic(Mat fact, Mat mat, IS col, const MatFactorInfo *info)
3777: {
3778: MatFactorInfo tinfo;
3780: PetscFunctionBegin;
3784: if (info) PetscAssertPointer(info, 4);
3787: PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
3788: PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
3789: MatCheckPreallocated(mat, 2);
3790: if (!info) {
3791: PetscCall(MatFactorInfoInitialize(&tinfo));
3792: info = &tinfo;
3793: }
3795: if (!fact->trivialsymbolic) PetscCall(PetscLogEventBegin(MAT_QRFactorSymbolic, fact, mat, col, 0));
3796: PetscUseMethod(fact, "MatQRFactorSymbolic_C", (Mat, Mat, IS, const MatFactorInfo *), (fact, mat, col, info));
3797: if (!fact->trivialsymbolic) PetscCall(PetscLogEventEnd(MAT_QRFactorSymbolic, fact, mat, col, 0));
3798: PetscCall(PetscObjectStateIncrease((PetscObject)fact));
3799: PetscFunctionReturn(PETSC_SUCCESS);
3800: }
3802: /*@
3803: MatQRFactorNumeric - Performs numeric QR factorization of a matrix.
3804: Call this routine after first calling `MatGetFactor()`, and `MatQRFactorSymbolic()`.
3806: Collective
3808: Input Parameters:
3809: + fact - the factor matrix obtained with `MatGetFactor()`
3810: . mat - the matrix
3811: - info - options for factorization
3813: Level: developer
3815: Notes:
3816: See `MatQRFactor()` for in-place factorization.
3818: Most users should employ the `KSP` interface for linear solvers
3819: instead of working directly with matrix algebra routines such as this.
3820: See, e.g., `KSPCreate()`.
3822: Fortran Note:
3823: A valid (non-null) `info` argument must be provided
3825: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatFactorInfo`, `MatGetFactor()`, `MatQRFactor()`, `MatQRFactorSymbolic()`, `MatLUFactor()`
3826: @*/
3827: PetscErrorCode MatQRFactorNumeric(Mat fact, Mat mat, const MatFactorInfo *info)
3828: {
3829: MatFactorInfo tinfo;
3831: PetscFunctionBegin;
3836: PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
3837: 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,
3838: mat->rmap->N, (fact)->rmap->N, mat->cmap->N, (fact)->cmap->N);
3840: MatCheckPreallocated(mat, 2);
3841: if (!info) {
3842: PetscCall(MatFactorInfoInitialize(&tinfo));
3843: info = &tinfo;
3844: }
3846: if (!fact->trivialsymbolic) PetscCall(PetscLogEventBegin(MAT_QRFactorNumeric, mat, fact, 0, 0));
3847: else PetscCall(PetscLogEventBegin(MAT_QRFactor, mat, fact, 0, 0));
3848: PetscUseMethod(fact, "MatQRFactorNumeric_C", (Mat, Mat, const MatFactorInfo *), (fact, mat, info));
3849: if (!fact->trivialsymbolic) PetscCall(PetscLogEventEnd(MAT_QRFactorNumeric, mat, fact, 0, 0));
3850: else PetscCall(PetscLogEventEnd(MAT_QRFactor, mat, fact, 0, 0));
3851: PetscCall(MatViewFromOptions(fact, NULL, "-mat_factor_view"));
3852: PetscCall(PetscObjectStateIncrease((PetscObject)fact));
3853: PetscFunctionReturn(PETSC_SUCCESS);
3854: }
3856: /*@
3857: MatSolve - Solves $A x = b$, given a factored matrix.
3859: Neighbor-wise Collective
3861: Input Parameters:
3862: + mat - the factored matrix
3863: - b - the right-hand-side vector
3865: Output Parameter:
3866: . x - the result vector
3868: Level: developer
3870: Notes:
3871: The vectors `b` and `x` cannot be the same. I.e., one cannot
3872: call `MatSolve`(A,x,x).
3874: Most users should employ the `KSP` interface for linear solvers
3875: instead of working directly with matrix algebra routines such as this.
3876: See, e.g., `KSPCreate()`.
3878: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatGetFactor()`, `MatLUFactor()`, `MatSolveAdd()`, `MatSolveTranspose()`, `MatSolveTransposeAdd()`
3879: @*/
3880: PetscErrorCode MatSolve(Mat mat, Vec b, Vec x)
3881: {
3882: PetscFunctionBegin;
3887: PetscCheckSameComm(mat, 1, b, 2);
3888: PetscCheckSameComm(mat, 1, x, 3);
3889: PetscCheck(x != b, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_IDN, "x and b must be different vectors");
3890: 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);
3891: 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);
3892: 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);
3893: if (!mat->rmap->N && !mat->cmap->N) PetscFunctionReturn(PETSC_SUCCESS);
3894: MatCheckPreallocated(mat, 1);
3896: PetscCall(PetscLogEventBegin(MAT_Solve, mat, b, x, 0));
3897: PetscCall(VecFlag(x, mat->factorerrortype));
3898: if (mat->factorerrortype) PetscCall(PetscInfo(mat, "MatFactorError %d\n", mat->factorerrortype));
3899: else PetscUseTypeMethod(mat, solve, b, x);
3900: PetscCall(PetscLogEventEnd(MAT_Solve, mat, b, x, 0));
3901: PetscCall(PetscObjectStateIncrease((PetscObject)x));
3902: PetscFunctionReturn(PETSC_SUCCESS);
3903: }
3905: static PetscErrorCode MatMatSolve_Basic(Mat A, Mat B, Mat X, PetscBool trans)
3906: {
3907: Vec b, x;
3908: PetscInt N;
3909: PetscErrorCode (*f)(Mat, Vec, Vec);
3910: PetscBool Abound, Bneedconv = PETSC_FALSE, Xneedconv = PETSC_FALSE;
3912: PetscFunctionBegin;
3913: f = (!trans || (!A->ops->solvetranspose && A->symmetric)) ? A->ops->solve : A->ops->solvetranspose;
3914: PetscCheck(f, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "Mat type %s", ((PetscObject)A)->type_name);
3915: PetscCall(MatBoundToCPU(A, &Abound));
3916: if (!Abound) {
3917: PetscCall(PetscObjectTypeCompareAny((PetscObject)B, &Bneedconv, MATSEQDENSE, MATMPIDENSE, ""));
3918: PetscCall(PetscObjectTypeCompareAny((PetscObject)X, &Xneedconv, MATSEQDENSE, MATMPIDENSE, ""));
3919: }
3920: #if PetscDefined(HAVE_CUDA)
3921: if (Bneedconv) PetscCall(MatConvert(B, MATDENSECUDA, MAT_INPLACE_MATRIX, &B));
3922: if (Xneedconv) PetscCall(MatConvert(X, MATDENSECUDA, MAT_INPLACE_MATRIX, &X));
3923: #elif PetscDefined(HAVE_HIP)
3924: if (Bneedconv) PetscCall(MatConvert(B, MATDENSEHIP, MAT_INPLACE_MATRIX, &B));
3925: if (Xneedconv) PetscCall(MatConvert(X, MATDENSEHIP, MAT_INPLACE_MATRIX, &X));
3926: #endif
3927: PetscCall(MatGetSize(B, NULL, &N));
3928: for (PetscInt i = 0; i < N; i++) {
3929: PetscCall(MatDenseGetColumnVecRead(B, i, &b));
3930: PetscCall(MatDenseGetColumnVecWrite(X, i, &x));
3931: PetscCall((*f)(A, b, x));
3932: PetscCall(MatDenseRestoreColumnVecWrite(X, i, &x));
3933: PetscCall(MatDenseRestoreColumnVecRead(B, i, &b));
3934: }
3935: if (Bneedconv) PetscCall(MatConvert(B, MATDENSE, MAT_INPLACE_MATRIX, &B));
3936: if (Xneedconv) PetscCall(MatConvert(X, MATDENSE, MAT_INPLACE_MATRIX, &X));
3937: PetscFunctionReturn(PETSC_SUCCESS);
3938: }
3940: /*@
3941: MatMatSolve - Solves $A X = B$, given a factored matrix.
3943: Neighbor-wise Collective
3945: Input Parameters:
3946: + A - the factored matrix
3947: - B - the right-hand-side matrix `MATDENSE` (or sparse `MATAIJ`-- when using MUMPS)
3949: Output Parameter:
3950: . X - the result matrix (dense matrix)
3952: Level: developer
3954: Note:
3955: If `B` is a `MATDENSE` matrix then one can call `MatMatSolve`(A,B,B) except with `MATSOLVERMKL_CPARDISO`;
3956: otherwise, `B` and `X` cannot be the same.
3958: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatGetFactor()`, `MatSolve()`, `MatMatSolveTranspose()`, `MatLUFactor()`, `MatCholeskyFactor()`
3959: @*/
3960: PetscErrorCode MatMatSolve(Mat A, Mat B, Mat X)
3961: {
3962: PetscFunctionBegin;
3967: PetscCheckSameComm(A, 1, B, 2);
3968: PetscCheckSameComm(A, 1, X, 3);
3969: 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);
3970: 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);
3971: 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");
3972: if (!A->rmap->N && !A->cmap->N) PetscFunctionReturn(PETSC_SUCCESS);
3973: MatCheckPreallocated(A, 1);
3975: PetscCall(PetscLogEventBegin(MAT_MatSolve, A, B, X, 0));
3976: if (A->factorerrortype) {
3977: PetscCall(PetscInfo(A, "MatFactorError %d\n", A->factorerrortype));
3978: PetscCall(MatFlag(X, 1));
3979: } else if (!A->ops->matsolve) {
3980: PetscCall(PetscInfo(A, "Mat type %s using basic MatMatSolve\n", ((PetscObject)A)->type_name));
3981: PetscCall(MatMatSolve_Basic(A, B, X, PETSC_FALSE));
3982: } else PetscUseTypeMethod(A, matsolve, B, X);
3983: PetscCall(PetscLogEventEnd(MAT_MatSolve, A, B, X, 0));
3984: PetscCall(PetscObjectStateIncrease((PetscObject)X));
3985: PetscFunctionReturn(PETSC_SUCCESS);
3986: }
3988: /*@
3989: MatMatSolveTranspose - Solves $A^T X = B$, given a factored matrix.
3991: Neighbor-wise Collective
3993: Input Parameters:
3994: + A - the factored matrix
3995: - B - the right-hand-side matrix (`MATDENSE` matrix)
3997: Output Parameter:
3998: . X - the result matrix (dense matrix)
4000: Level: developer
4002: Note:
4003: The matrices `B` and `X` cannot be the same. I.e., one cannot
4004: call `MatMatSolveTranspose`(A,X,X).
4006: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatGetFactor()`, `MatSolveTranspose()`, `MatMatSolve()`, `MatLUFactor()`, `MatCholeskyFactor()`
4007: @*/
4008: PetscErrorCode MatMatSolveTranspose(Mat A, Mat B, Mat X)
4009: {
4010: PetscFunctionBegin;
4015: PetscCheckSameComm(A, 1, B, 2);
4016: PetscCheckSameComm(A, 1, X, 3);
4017: PetscCheck(X != B, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_IDN, "X and B must be different matrices");
4018: 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);
4019: 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);
4020: 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);
4021: 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");
4022: if (!A->rmap->N && !A->cmap->N) PetscFunctionReturn(PETSC_SUCCESS);
4023: MatCheckPreallocated(A, 1);
4025: PetscCall(PetscLogEventBegin(MAT_MatSolve, A, B, X, 0));
4026: if (A->factorerrortype) {
4027: PetscCall(PetscInfo(A, "MatFactorError %d\n", A->factorerrortype));
4028: PetscCall(MatFlag(X, 1));
4029: } else if (!A->ops->matsolvetranspose) {
4030: PetscCall(PetscInfo(A, "Mat type %s using basic MatMatSolveTranspose\n", ((PetscObject)A)->type_name));
4031: PetscCall(MatMatSolve_Basic(A, B, X, PETSC_TRUE));
4032: } else PetscUseTypeMethod(A, matsolvetranspose, B, X);
4033: PetscCall(PetscLogEventEnd(MAT_MatSolve, A, B, X, 0));
4034: PetscCall(PetscObjectStateIncrease((PetscObject)X));
4035: PetscFunctionReturn(PETSC_SUCCESS);
4036: }
4038: /*@
4039: MatMatTransposeSolve - Solves $A X = B^T$, given a factored matrix.
4041: Neighbor-wise Collective
4043: Input Parameters:
4044: + A - the factored matrix
4045: - Bt - the transpose of right-hand-side matrix as a `MATDENSE`
4047: Output Parameter:
4048: . X - the result matrix (dense matrix)
4050: Level: developer
4052: Note:
4053: For MUMPS, it only supports centralized sparse compressed column format on the host process for right-hand side matrix. User must create `Bt` in sparse compressed row
4054: format on the host process and call `MatMatTransposeSolve()` to implement MUMPS' `MatMatSolve()`.
4056: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatMatSolve()`, `MatMatSolveTranspose()`, `MatLUFactor()`, `MatCholeskyFactor()`
4057: @*/
4058: PetscErrorCode MatMatTransposeSolve(Mat A, Mat Bt, Mat X)
4059: {
4060: PetscFunctionBegin;
4065: PetscCheckSameComm(A, 1, Bt, 2);
4066: PetscCheckSameComm(A, 1, X, 3);
4068: PetscCheck(X != Bt, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_IDN, "X and B must be different matrices");
4069: 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);
4070: 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);
4071: 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");
4072: if (!A->rmap->N && !A->cmap->N) PetscFunctionReturn(PETSC_SUCCESS);
4073: PetscCheck(A->factortype, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_WRONGSTATE, "Unfactored matrix");
4074: MatCheckPreallocated(A, 1);
4076: PetscCall(PetscLogEventBegin(MAT_MatTrSolve, A, Bt, X, 0));
4077: if (A->factorerrortype) {
4078: PetscCall(PetscInfo(A, "MatFactorError %d\n", A->factorerrortype));
4079: PetscCall(MatFlag(X, 1));
4080: } else PetscUseTypeMethod(A, mattransposesolve, Bt, X);
4081: PetscCall(PetscLogEventEnd(MAT_MatTrSolve, A, Bt, X, 0));
4082: PetscCall(PetscObjectStateIncrease((PetscObject)X));
4083: PetscFunctionReturn(PETSC_SUCCESS);
4084: }
4086: /*@
4087: MatForwardSolve - Solves $L x = b$, given a factored matrix, $A = LU$, or
4088: $U^T D^{1/2} x = b$, given a factored symmetric matrix, $A = U^T D U$,
4090: Neighbor-wise Collective
4092: Input Parameters:
4093: + mat - the factored matrix
4094: - b - the right-hand-side vector
4096: Output Parameter:
4097: . x - the result vector
4099: Level: developer
4101: Notes:
4102: `MatSolve()` should be used for most applications, as it performs
4103: a forward solve followed by a backward solve.
4105: The vectors `b` and `x` cannot be the same, i.e., one cannot
4106: call `MatForwardSolve`(A,x,x).
4108: For matrix in `MATSEQBAIJ` format with block size larger than 1,
4109: the diagonal blocks are not implemented as $D = D^{1/2} D^{1/2}$ yet.
4110: `MatForwardSolve()` solves $U^T D y = b$, and
4111: `MatBackwardSolve()` solves $U x = y$.
4112: Thus they do not provide a symmetric preconditioner.
4114: .seealso: [](ch_matrices), `Mat`, `MatBackwardSolve()`, `MatGetFactor()`, `MatSolve()`
4115: @*/
4116: PetscErrorCode MatForwardSolve(Mat mat, Vec b, Vec x)
4117: {
4118: PetscFunctionBegin;
4123: PetscCheckSameComm(mat, 1, b, 2);
4124: PetscCheckSameComm(mat, 1, x, 3);
4125: PetscCheck(x != b, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_IDN, "x and b must be different vectors");
4126: 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);
4127: 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);
4128: 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);
4129: if (!mat->rmap->N && !mat->cmap->N) PetscFunctionReturn(PETSC_SUCCESS);
4130: MatCheckPreallocated(mat, 1);
4132: PetscCall(PetscLogEventBegin(MAT_ForwardSolve, mat, b, x, 0));
4133: PetscUseTypeMethod(mat, forwardsolve, b, x);
4134: PetscCall(PetscLogEventEnd(MAT_ForwardSolve, mat, b, x, 0));
4135: PetscCall(PetscObjectStateIncrease((PetscObject)x));
4136: PetscFunctionReturn(PETSC_SUCCESS);
4137: }
4139: /*@
4140: MatBackwardSolve - Solves $U x = b$, given a factored matrix, $A = LU$.
4141: $D^{1/2} U x = b$, given a factored symmetric matrix, $A = U^T D U$,
4143: Neighbor-wise Collective
4145: Input Parameters:
4146: + mat - the factored matrix
4147: - b - the right-hand-side vector
4149: Output Parameter:
4150: . x - the result vector
4152: Level: developer
4154: Notes:
4155: `MatSolve()` should be used for most applications, as it performs
4156: a forward solve followed by a backward solve.
4158: The vectors `b` and `x` cannot be the same. I.e., one cannot
4159: call `MatBackwardSolve`(A,x,x).
4161: For matrix in `MATSEQBAIJ` format with block size larger than 1,
4162: the diagonal blocks are not implemented as $D = D^{1/2} D^{1/2}$ yet.
4163: `MatForwardSolve()` solves $U^T D y = b$, and
4164: `MatBackwardSolve()` solves $U x = y$.
4165: Thus they do not provide a symmetric preconditioner.
4167: .seealso: [](ch_matrices), `Mat`, `MatForwardSolve()`, `MatGetFactor()`, `MatSolve()`
4168: @*/
4169: PetscErrorCode MatBackwardSolve(Mat mat, Vec b, Vec x)
4170: {
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->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);
4180: 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);
4181: 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);
4182: if (!mat->rmap->N && !mat->cmap->N) PetscFunctionReturn(PETSC_SUCCESS);
4183: MatCheckPreallocated(mat, 1);
4185: PetscCall(PetscLogEventBegin(MAT_BackwardSolve, mat, b, x, 0));
4186: PetscUseTypeMethod(mat, backwardsolve, b, x);
4187: PetscCall(PetscLogEventEnd(MAT_BackwardSolve, mat, b, x, 0));
4188: PetscCall(PetscObjectStateIncrease((PetscObject)x));
4189: PetscFunctionReturn(PETSC_SUCCESS);
4190: }
4192: /*@
4193: MatSolveAdd - Computes $x = y + A^{-1} b$, given a factored matrix.
4195: Neighbor-wise Collective
4197: Input Parameters:
4198: + mat - the factored matrix
4199: . b - the right-hand-side vector
4200: - y - the vector to be added to
4202: Output Parameter:
4203: . x - the result vector
4205: Level: developer
4207: Note:
4208: The vectors `b` and `x` cannot be the same. I.e., one cannot
4209: call `MatSolveAdd`(A,x,y,x).
4211: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatSolve()`, `MatGetFactor()`, `MatSolveTranspose()`, `MatSolveTransposeAdd()`
4212: @*/
4213: PetscErrorCode MatSolveAdd(Mat mat, Vec b, Vec y, Vec x)
4214: {
4215: PetscScalar one = 1.0;
4216: Vec tmp;
4218: PetscFunctionBegin;
4224: PetscCheckSameComm(mat, 1, b, 2);
4225: PetscCheckSameComm(mat, 1, y, 3);
4226: PetscCheckSameComm(mat, 1, x, 4);
4227: PetscCheck(x != b, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_IDN, "x and b must be different vectors");
4228: 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);
4229: 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);
4230: 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);
4231: 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);
4232: 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);
4233: if (!mat->rmap->N && !mat->cmap->N) PetscFunctionReturn(PETSC_SUCCESS);
4234: MatCheckPreallocated(mat, 1);
4236: PetscCall(PetscLogEventBegin(MAT_SolveAdd, mat, b, x, y));
4237: PetscCall(VecFlag(x, mat->factorerrortype));
4238: if (mat->factorerrortype) {
4239: PetscCall(PetscInfo(mat, "MatFactorError %d\n", mat->factorerrortype));
4240: } else if (mat->ops->solveadd) {
4241: PetscUseTypeMethod(mat, solveadd, b, y, x);
4242: } else {
4243: /* do the solve then the add manually */
4244: if (x != y) {
4245: PetscCall(MatSolve(mat, b, x));
4246: PetscCall(VecAXPY(x, one, y));
4247: } else {
4248: PetscCall(VecDuplicate(x, &tmp));
4249: PetscCall(VecCopy(x, tmp));
4250: PetscCall(MatSolve(mat, b, x));
4251: PetscCall(VecAXPY(x, one, tmp));
4252: PetscCall(VecDestroy(&tmp));
4253: }
4254: }
4255: PetscCall(PetscLogEventEnd(MAT_SolveAdd, mat, b, x, y));
4256: PetscCall(PetscObjectStateIncrease((PetscObject)x));
4257: PetscFunctionReturn(PETSC_SUCCESS);
4258: }
4260: /*@
4261: MatSolveTranspose - Solves $A^T x = b$, given a factored matrix.
4263: Neighbor-wise Collective
4265: Input Parameters:
4266: + mat - the factored matrix
4267: - b - the right-hand-side vector
4269: Output Parameter:
4270: . x - the result vector
4272: Level: developer
4274: Notes:
4275: The vectors `b` and `x` cannot be the same. I.e., one cannot
4276: call `MatSolveTranspose`(A,x,x).
4278: Most users should employ the `KSP` interface for linear solvers
4279: instead of working directly with matrix algebra routines such as this.
4280: See, e.g., `KSPCreate()`.
4282: .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `KSP`, `MatSolve()`, `MatSolveAdd()`, `MatSolveTransposeAdd()`
4283: @*/
4284: PetscErrorCode MatSolveTranspose(Mat mat, Vec b, Vec x)
4285: {
4286: PetscErrorCode (*f)(Mat, Vec, Vec) = (!mat->ops->solvetranspose && mat->symmetric) ? mat->ops->solve : mat->ops->solvetranspose;
4288: PetscFunctionBegin;
4293: PetscCheckSameComm(mat, 1, b, 2);
4294: PetscCheckSameComm(mat, 1, x, 3);
4295: PetscCheck(x != b, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_IDN, "x and b must be different vectors");
4296: 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);
4297: 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);
4298: if (!mat->rmap->N && !mat->cmap->N) PetscFunctionReturn(PETSC_SUCCESS);
4299: MatCheckPreallocated(mat, 1);
4300: PetscCall(PetscLogEventBegin(MAT_SolveTranspose, mat, b, x, 0));
4301: PetscCall(VecFlag(x, mat->factorerrortype));
4302: if (mat->factorerrortype) {
4303: PetscCall(PetscInfo(mat, "MatFactorError %d\n", mat->factorerrortype));
4304: } else {
4305: PetscCheck(f, PetscObjectComm((PetscObject)mat), PETSC_ERR_SUP, "Matrix type %s", ((PetscObject)mat)->type_name);
4306: PetscCall((*f)(mat, b, x));
4307: }
4308: PetscCall(PetscLogEventEnd(MAT_SolveTranspose, mat, b, x, 0));
4309: PetscCall(PetscObjectStateIncrease((PetscObject)x));
4310: PetscFunctionReturn(PETSC_SUCCESS);
4311: }
4313: /*@
4314: MatSolveTransposeAdd - Computes $x = y + A^{-T} b$
4315: factored matrix.
4317: Neighbor-wise Collective
4319: Input Parameters:
4320: + mat - the factored matrix
4321: . b - the right-hand-side vector
4322: - y - the vector to be added to
4324: Output Parameter:
4325: . x - the result vector
4327: Level: developer
4329: Note:
4330: The vectors `b` and `x` cannot be the same. I.e., one cannot
4331: call `MatSolveTransposeAdd`(A,x,y,x).
4333: .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatSolve()`, `MatSolveAdd()`, `MatSolveTranspose()`
4334: @*/
4335: PetscErrorCode MatSolveTransposeAdd(Mat mat, Vec b, Vec y, Vec x)
4336: {
4337: PetscScalar one = 1.0;
4338: Vec tmp;
4339: PetscErrorCode (*f)(Mat, Vec, Vec, Vec) = (!mat->ops->solvetransposeadd && mat->symmetric) ? mat->ops->solveadd : mat->ops->solvetransposeadd;
4341: PetscFunctionBegin;
4347: PetscCheckSameComm(mat, 1, b, 2);
4348: PetscCheckSameComm(mat, 1, y, 3);
4349: PetscCheckSameComm(mat, 1, x, 4);
4350: PetscCheck(x != b, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_IDN, "x and b must be different vectors");
4351: 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);
4352: 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);
4353: 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);
4354: 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);
4355: if (!mat->rmap->N && !mat->cmap->N) PetscFunctionReturn(PETSC_SUCCESS);
4356: MatCheckPreallocated(mat, 1);
4358: PetscCall(PetscLogEventBegin(MAT_SolveTransposeAdd, mat, b, x, y));
4359: PetscCall(VecFlag(x, mat->factorerrortype));
4360: if (mat->factorerrortype) {
4361: PetscCall(PetscInfo(mat, "MatFactorError %d\n", mat->factorerrortype));
4362: } else if (f) {
4363: PetscCall((*f)(mat, b, y, x));
4364: } else {
4365: /* do the solve then the add manually */
4366: if (x != y) {
4367: PetscCall(MatSolveTranspose(mat, b, x));
4368: PetscCall(VecAXPY(x, one, y));
4369: } else {
4370: PetscCall(VecDuplicate(x, &tmp));
4371: PetscCall(VecCopy(x, tmp));
4372: PetscCall(MatSolveTranspose(mat, b, x));
4373: PetscCall(VecAXPY(x, one, tmp));
4374: PetscCall(VecDestroy(&tmp));
4375: }
4376: }
4377: PetscCall(PetscLogEventEnd(MAT_SolveTransposeAdd, mat, b, x, y));
4378: PetscCall(PetscObjectStateIncrease((PetscObject)x));
4379: PetscFunctionReturn(PETSC_SUCCESS);
4380: }
4382: // PetscClangLinter pragma disable: -fdoc-section-header-unknown
4383: /*@
4384: MatSOR - Computes relaxation (SOR, Gauss-Seidel) sweeps.
4386: Neighbor-wise Collective
4388: Input Parameters:
4389: + mat - the matrix
4390: . b - the right-hand side
4391: . omega - the relaxation factor
4392: . flag - flag indicating the type of SOR (see below)
4393: . shift - diagonal shift
4394: . its - the number of iterations
4395: - lits - the number of local iterations
4397: Output Parameter:
4398: . x - the solution (can contain an initial guess, use option `SOR_ZERO_INITIAL_GUESS` to indicate no guess)
4400: SOR Flags:
4401: + `SOR_FORWARD_SWEEP` - forward SOR
4402: . `SOR_BACKWARD_SWEEP` - backward SOR
4403: . `SOR_SYMMETRIC_SWEEP` - SSOR (symmetric SOR)
4404: . `SOR_LOCAL_FORWARD_SWEEP` - local forward SOR
4405: . `SOR_LOCAL_BACKWARD_SWEEP` - local forward SOR
4406: . `SOR_LOCAL_SYMMETRIC_SWEEP` - local SSOR
4407: . `SOR_EISENSTAT` - SOR with Eisenstat trick
4408: . `SOR_APPLY_UPPER`, `SOR_APPLY_LOWER` - applies upper/lower triangular part of matrix to vector (with `omega`)
4409: - `SOR_ZERO_INITIAL_GUESS` - zero initial guess
4411: Level: developer
4413: Notes:
4414: `SOR_LOCAL_FORWARD_SWEEP`, `SOR_LOCAL_BACKWARD_SWEEP`, and
4415: `SOR_LOCAL_SYMMETRIC_SWEEP` perform separate independent smoothings
4416: on each process.
4418: Application programmers will not generally use `MatSOR()` directly,
4419: but instead will employ `PCSOR` or `PCEISENSTAT`
4421: For `MATBAIJ`, `MATSBAIJ`, and `MATAIJ` matrices with inodes, this does a block SOR smoothing, otherwise it does a pointwise smoothing.
4422: For `MATAIJ` matrices with inodes, the block sizes are determined by the inode sizes, not the block size set with `MatSetBlockSize()`
4424: Vectors `x` and `b` CANNOT be the same
4426: The flags are implemented as bitwise inclusive or operations.
4427: For example, use (`SOR_ZERO_INITIAL_GUESS` | `SOR_SYMMETRIC_SWEEP`)
4428: to specify a zero initial guess for SSOR.
4430: Developer Note:
4431: We should add block SOR support for `MATAIJ` matrices with block size set to greater than one and no inodes
4433: .seealso: [](ch_matrices), `Mat`, `MatMult()`, `KSP`, `PC`, `MatGetFactor()`
4434: @*/
4435: PetscErrorCode MatSOR(Mat mat, Vec b, PetscReal omega, MatSORType flag, PetscReal shift, PetscInt its, PetscInt lits, Vec x)
4436: {
4437: PetscFunctionBegin;
4442: PetscCheckSameComm(mat, 1, b, 2);
4443: PetscCheckSameComm(mat, 1, x, 8);
4444: PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
4445: PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
4446: 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);
4447: 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);
4448: 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);
4449: PetscCheck(its > 0, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Relaxation requires global its %" PetscInt_FMT " positive", its);
4450: PetscCheck(lits > 0, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Relaxation requires local its %" PetscInt_FMT " positive", lits);
4451: PetscCheck(b != x, PETSC_COMM_SELF, PETSC_ERR_ARG_IDN, "b and x vector cannot be the same");
4453: MatCheckPreallocated(mat, 1);
4454: PetscCall(PetscLogEventBegin(MAT_SOR, mat, b, x, 0));
4455: PetscUseTypeMethod(mat, sor, b, omega, flag, shift, its, lits, x);
4456: PetscCall(PetscLogEventEnd(MAT_SOR, mat, b, x, 0));
4457: PetscCall(PetscObjectStateIncrease((PetscObject)x));
4458: PetscFunctionReturn(PETSC_SUCCESS);
4459: }
4461: /*
4462: Default matrix copy routine.
4463: */
4464: PetscErrorCode MatCopy_Basic(Mat A, Mat B, MatStructure str)
4465: {
4466: PetscInt i, rstart = 0, rend = 0, nz;
4467: const PetscInt *cwork;
4468: const PetscScalar *vwork;
4470: PetscFunctionBegin;
4471: if (B->assembled) PetscCall(MatZeroEntries(B));
4472: if (str == SAME_NONZERO_PATTERN) {
4473: PetscCall(MatGetOwnershipRange(A, &rstart, &rend));
4474: for (i = rstart; i < rend; i++) {
4475: PetscCall(MatGetRow(A, i, &nz, &cwork, &vwork));
4476: PetscCall(MatSetValues(B, 1, &i, nz, cwork, vwork, INSERT_VALUES));
4477: PetscCall(MatRestoreRow(A, i, &nz, &cwork, &vwork));
4478: }
4479: } else {
4480: PetscCall(MatAYPX(B, 0.0, A, str));
4481: }
4482: PetscCall(MatAssemblyBegin(B, MAT_FINAL_ASSEMBLY));
4483: PetscCall(MatAssemblyEnd(B, MAT_FINAL_ASSEMBLY));
4484: PetscFunctionReturn(PETSC_SUCCESS);
4485: }
4487: /*@
4488: MatCopy - Copies a matrix to another matrix.
4490: Collective
4492: Input Parameters:
4493: + A - the matrix
4494: - str - `SAME_NONZERO_PATTERN` or `DIFFERENT_NONZERO_PATTERN`
4496: Output Parameter:
4497: . B - where the copy is put
4499: Level: intermediate
4501: Notes:
4502: If you use `SAME_NONZERO_PATTERN`, then the two matrices must have the same nonzero pattern or the routine will crash.
4504: `MatCopy()` copies the matrix entries of a matrix to another existing
4505: matrix (after first zeroing the second matrix). A related routine is
4506: `MatConvert()`, which first creates a new matrix and then copies the data.
4508: .seealso: [](ch_matrices), `Mat`, `MatConvert()`, `MatDuplicate()`
4509: @*/
4510: PetscErrorCode MatCopy(Mat A, Mat B, MatStructure str)
4511: {
4512: PetscInt i;
4514: PetscFunctionBegin;
4519: PetscCheckSameComm(A, 1, B, 2);
4520: MatCheckPreallocated(B, 2);
4521: PetscCheck(A->assembled, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
4522: PetscCheck(!A->factortype, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
4523: 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,
4524: A->cmap->N, B->cmap->N);
4525: MatCheckPreallocated(A, 1);
4526: if (A == B) PetscFunctionReturn(PETSC_SUCCESS);
4528: PetscCall(PetscLogEventBegin(MAT_Copy, A, B, 0, 0));
4529: if (A->ops->copy) PetscUseTypeMethod(A, copy, B, str);
4530: else PetscCall(MatCopy_Basic(A, B, str));
4532: B->stencil.dim = A->stencil.dim;
4533: B->stencil.noc = A->stencil.noc;
4534: for (i = 0; i <= A->stencil.dim + (A->stencil.noc ? 0 : -1); i++) {
4535: B->stencil.dims[i] = A->stencil.dims[i];
4536: B->stencil.starts[i] = A->stencil.starts[i];
4537: }
4539: PetscCall(PetscLogEventEnd(MAT_Copy, A, B, 0, 0));
4540: PetscCall(PetscObjectStateIncrease((PetscObject)B));
4541: PetscFunctionReturn(PETSC_SUCCESS);
4542: }
4544: /*@
4545: MatConvert - Converts a matrix to another matrix, either of the same
4546: or different type.
4548: Collective
4550: Input Parameters:
4551: + mat - the matrix
4552: . newtype - new matrix type. Use `MATSAME` to create a new matrix of the
4553: same type as the original matrix.
4554: - reuse - denotes if the destination matrix is to be created or reused.
4555: 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
4556: `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).
4558: Output Parameter:
4559: . M - pointer to place new matrix
4561: Level: intermediate
4563: Notes:
4564: `MatConvert()` first creates a new matrix and then copies the data from
4565: the first matrix. A related routine is `MatCopy()`, which copies the matrix
4566: entries of one matrix to another already existing matrix context.
4568: Cannot be used to convert a sequential matrix to parallel or parallel to sequential,
4569: the MPI communicator of the generated matrix is always the same as the communicator
4570: of the input matrix.
4572: .seealso: [](ch_matrices), `Mat`, `MatCopy()`, `MatDuplicate()`, `MAT_INITIAL_MATRIX`, `MAT_REUSE_MATRIX`, `MAT_INPLACE_MATRIX`
4573: @*/
4574: PetscErrorCode MatConvert(Mat mat, MatType newtype, MatReuse reuse, Mat *M)
4575: {
4576: PetscBool sametype, issame, flg;
4577: PetscBool3 issymmetric, ishermitian, isspd;
4578: char convname[256], mtype[256];
4579: Mat B;
4581: PetscFunctionBegin;
4584: PetscAssertPointer(M, 4);
4585: PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
4586: PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
4587: MatCheckPreallocated(mat, 1);
4589: PetscCall(PetscOptionsGetString(((PetscObject)mat)->options, ((PetscObject)mat)->prefix, "-matconvert_type", mtype, sizeof(mtype), &flg));
4590: if (flg) newtype = mtype;
4592: PetscCall(PetscObjectTypeCompare((PetscObject)mat, newtype, &sametype));
4593: PetscCall(PetscStrcmp(newtype, "same", &issame));
4594: PetscCheck(!(reuse == MAT_INPLACE_MATRIX) || !(mat != *M), PetscObjectComm((PetscObject)mat), PETSC_ERR_SUP, "MAT_INPLACE_MATRIX requires same input and output matrix");
4595: if (reuse == MAT_REUSE_MATRIX) {
4597: PetscCheck(mat != *M, PetscObjectComm((PetscObject)mat), PETSC_ERR_SUP, "MAT_REUSE_MATRIX means reuse matrix in final argument, perhaps you mean MAT_INPLACE_MATRIX");
4598: }
4600: if ((reuse == MAT_INPLACE_MATRIX) && (issame || sametype)) {
4601: PetscCall(PetscInfo(mat, "Early return for inplace %s %d %d\n", ((PetscObject)mat)->type_name, sametype, issame));
4602: PetscFunctionReturn(PETSC_SUCCESS);
4603: }
4605: /* Cache Mat options because some converters use MatHeaderReplace() */
4606: issymmetric = mat->symmetric;
4607: ishermitian = mat->hermitian;
4608: isspd = mat->spd;
4610: if ((sametype || issame) && (reuse == MAT_INITIAL_MATRIX) && mat->ops->duplicate) {
4611: PetscCall(PetscInfo(mat, "Calling MatDuplicate() for initial matrix %s %d %d\n", ((PetscObject)mat)->type_name, sametype, issame));
4612: PetscUseTypeMethod(mat, duplicate, MAT_COPY_VALUES, M);
4613: (*M)->nonzerostate = mat->nonzerostate;
4614: } else {
4615: PetscErrorCode (*conv)(Mat, MatType, MatReuse, Mat *) = NULL;
4616: const char *prefix[3] = {"seq", "mpi", ""};
4617: PetscInt i;
4618: /*
4619: Order of precedence:
4620: 0) See if newtype is a superclass of the current matrix.
4621: 1) See if a specialized converter is known to the current matrix.
4622: 2) See if a specialized converter is known to the desired matrix class.
4623: 3) See if a good general converter is registered for the desired class
4624: (as of 6/27/03 only MATMPIADJ falls into this category).
4625: 4) See if a good general converter is known for the current matrix.
4626: 5) Use a really basic converter.
4627: */
4629: /* 0) See if newtype is a superclass of the current matrix.
4630: i.e mat is mpiaij and newtype is aij */
4631: for (i = 0; i < (PetscInt)PETSC_STATIC_ARRAY_LENGTH(prefix); i++) {
4632: PetscCall(PetscStrncpy(convname, prefix[i], sizeof(convname)));
4633: PetscCall(PetscStrlcat(convname, newtype, sizeof(convname)));
4634: PetscCall(PetscStrcmp(convname, ((PetscObject)mat)->type_name, &flg));
4635: PetscCall(PetscInfo(mat, "Check superclass %s %s -> %d\n", convname, ((PetscObject)mat)->type_name, flg));
4636: if (flg) {
4637: if (reuse == MAT_INPLACE_MATRIX) {
4638: PetscCall(PetscInfo(mat, "Early return\n"));
4639: PetscFunctionReturn(PETSC_SUCCESS);
4640: } else if (reuse == MAT_INITIAL_MATRIX && mat->ops->duplicate) {
4641: PetscCall(PetscInfo(mat, "Calling MatDuplicate()\n"));
4642: PetscUseTypeMethod(mat, duplicate, MAT_COPY_VALUES, M);
4643: (*M)->nonzerostate = mat->nonzerostate;
4644: PetscFunctionReturn(PETSC_SUCCESS);
4645: } else if (reuse == MAT_REUSE_MATRIX && mat->ops->copy) {
4646: PetscCall(PetscInfo(mat, "Calling MatCopy()\n"));
4647: PetscCall(MatCopy(mat, *M, SAME_NONZERO_PATTERN));
4648: PetscFunctionReturn(PETSC_SUCCESS);
4649: }
4650: }
4651: }
4652: /* 1) See if a specialized converter is known to the current matrix and the desired class */
4653: for (i = 0; i < (PetscInt)PETSC_STATIC_ARRAY_LENGTH(prefix); i++) {
4654: PetscCall(PetscStrncpy(convname, "MatConvert_", sizeof(convname)));
4655: PetscCall(PetscStrlcat(convname, ((PetscObject)mat)->type_name, sizeof(convname)));
4656: PetscCall(PetscStrlcat(convname, "_", sizeof(convname)));
4657: PetscCall(PetscStrlcat(convname, prefix[i], sizeof(convname)));
4658: PetscCall(PetscStrlcat(convname, issame ? ((PetscObject)mat)->type_name : newtype, sizeof(convname)));
4659: PetscCall(PetscStrlcat(convname, "_C", sizeof(convname)));
4660: PetscCall(PetscObjectQueryFunction((PetscObject)mat, convname, &conv));
4661: PetscCall(PetscInfo(mat, "Check specialized (1) %s (%s) -> %d\n", convname, ((PetscObject)mat)->type_name, !!conv));
4662: if (conv) goto foundconv;
4663: }
4665: /* 2) See if a specialized converter is known to the desired matrix class. */
4666: PetscCall(MatCreate(PetscObjectComm((PetscObject)mat), &B));
4667: PetscCall(MatSetSizes(B, mat->rmap->n, mat->cmap->n, mat->rmap->N, mat->cmap->N));
4668: PetscCall(MatSetType(B, newtype));
4669: for (i = 0; i < (PetscInt)PETSC_STATIC_ARRAY_LENGTH(prefix); i++) {
4670: PetscCall(PetscStrncpy(convname, "MatConvert_", sizeof(convname)));
4671: PetscCall(PetscStrlcat(convname, ((PetscObject)mat)->type_name, sizeof(convname)));
4672: PetscCall(PetscStrlcat(convname, "_", sizeof(convname)));
4673: PetscCall(PetscStrlcat(convname, prefix[i], sizeof(convname)));
4674: PetscCall(PetscStrlcat(convname, newtype, sizeof(convname)));
4675: PetscCall(PetscStrlcat(convname, "_C", sizeof(convname)));
4676: PetscCall(PetscObjectQueryFunction((PetscObject)B, convname, &conv));
4677: PetscCall(PetscInfo(mat, "Check specialized (2) %s (%s) -> %d\n", convname, ((PetscObject)B)->type_name, !!conv));
4678: if (conv) {
4679: PetscCall(MatDestroy(&B));
4680: goto foundconv;
4681: }
4682: }
4684: /* 3) See if a good general converter is registered for the desired class */
4685: conv = B->ops->convertfrom;
4686: PetscCall(PetscInfo(mat, "Check convertfrom (%s) -> %d\n", ((PetscObject)B)->type_name, !!conv));
4687: PetscCall(MatDestroy(&B));
4688: if (conv) goto foundconv;
4690: /* 4) See if a good general converter is known for the current matrix */
4691: if (mat->ops->convert) conv = mat->ops->convert;
4692: PetscCall(PetscInfo(mat, "Check general convert (%s) -> %d\n", ((PetscObject)mat)->type_name, !!conv));
4693: if (conv) goto foundconv;
4695: /* 5) Use a really basic converter. */
4696: PetscCall(PetscInfo(mat, "Using MatConvert_Basic()\n"));
4697: conv = MatConvert_Basic;
4699: foundconv:
4700: PetscCall(PetscLogEventBegin(MAT_Convert, mat, 0, 0, 0));
4701: PetscCall((*conv)(mat, newtype, reuse, M));
4702: if (mat->rmap->mapping && mat->cmap->mapping && !(*M)->rmap->mapping && !(*M)->cmap->mapping) {
4703: /* the block sizes must be same if the mappings are copied over */
4704: (*M)->rmap->bs = mat->rmap->bs;
4705: (*M)->cmap->bs = mat->cmap->bs;
4706: PetscCall(PetscObjectReference((PetscObject)mat->rmap->mapping));
4707: PetscCall(PetscObjectReference((PetscObject)mat->cmap->mapping));
4708: (*M)->rmap->mapping = mat->rmap->mapping;
4709: (*M)->cmap->mapping = mat->cmap->mapping;
4710: }
4711: (*M)->stencil.dim = mat->stencil.dim;
4712: (*M)->stencil.noc = mat->stencil.noc;
4713: for (i = 0; i <= mat->stencil.dim + (mat->stencil.noc ? 0 : -1); i++) {
4714: (*M)->stencil.dims[i] = mat->stencil.dims[i];
4715: (*M)->stencil.starts[i] = mat->stencil.starts[i];
4716: }
4717: PetscCall(PetscLogEventEnd(MAT_Convert, mat, 0, 0, 0));
4718: }
4719: PetscCall(PetscObjectStateIncrease((PetscObject)*M));
4721: /* Reset Mat options */
4722: if (issymmetric != PETSC_BOOL3_UNKNOWN) PetscCall(MatSetOption(*M, MAT_SYMMETRIC, PetscBool3ToBool(issymmetric)));
4723: if (ishermitian != PETSC_BOOL3_UNKNOWN) PetscCall(MatSetOption(*M, MAT_HERMITIAN, PetscBool3ToBool(ishermitian)));
4724: if (isspd != PETSC_BOOL3_UNKNOWN) PetscCall(MatSetOption(*M, MAT_SPD, PetscBool3ToBool(isspd)));
4725: PetscFunctionReturn(PETSC_SUCCESS);
4726: }
4728: /*@
4729: MatFactorGetSolverType - Returns name of the package providing the factorization routines
4731: Not Collective
4733: Input Parameter:
4734: . mat - the matrix, must be a factored matrix
4736: Output Parameter:
4737: . type - the string name of the package (do not free this string)
4739: Level: intermediate
4741: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatGetFactor()`, `MatSolverType`, `MatCopy()`, `MatDuplicate()`, `MatGetFactorAvailable()`
4742: @*/
4743: PetscErrorCode MatFactorGetSolverType(Mat mat, MatSolverType *type)
4744: {
4745: PetscErrorCode (*conv)(Mat, MatSolverType *);
4747: PetscFunctionBegin;
4750: PetscAssertPointer(type, 2);
4751: PetscCheck(mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Only for factored matrix");
4752: PetscCall(PetscObjectQueryFunction((PetscObject)mat, "MatFactorGetSolverType_C", &conv));
4753: if (conv) PetscCall((*conv)(mat, type));
4754: else *type = MATSOLVERPETSC;
4755: PetscFunctionReturn(PETSC_SUCCESS);
4756: }
4758: typedef struct _MatSolverTypeForSpecifcType *MatSolverTypeForSpecifcType;
4759: struct _MatSolverTypeForSpecifcType {
4760: MatType mtype;
4761: /* no entry for MAT_FACTOR_NONE */
4762: PetscErrorCode (*createfactor[MAT_FACTOR_NUM_TYPES - 1])(Mat, MatFactorType, Mat *);
4763: MatSolverTypeForSpecifcType next;
4764: };
4766: typedef struct _MatSolverTypeHolder *MatSolverTypeHolder;
4767: struct _MatSolverTypeHolder {
4768: char *name;
4769: MatSolverTypeForSpecifcType handlers;
4770: MatSolverTypeHolder next;
4771: };
4773: static MatSolverTypeHolder MatSolverTypeHolders = NULL;
4775: /*@
4776: MatSolverTypeRegister - Registers a `MatSolverType` that works for a particular matrix type
4778: Logically Collective, No Fortran Support
4780: Input Parameters:
4781: + package - name of the package, for example `petsc` or `superlu`
4782: . mtype - the matrix type that works with this package
4783: . ftype - the type of factorization supported by the package
4784: - createfactor - routine that will create the factored matrix ready to be used
4786: Level: developer
4788: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatFactorGetSolverType()`, `MatCopy()`, `MatDuplicate()`, `MatGetFactorAvailable()`,
4789: `MatGetFactor()`
4790: @*/
4791: PetscErrorCode MatSolverTypeRegister(MatSolverType package, MatType mtype, MatFactorType ftype, PetscErrorCode (*createfactor)(Mat, MatFactorType, Mat *))
4792: {
4793: MatSolverTypeHolder next = MatSolverTypeHolders, prev = NULL;
4794: PetscBool flg;
4795: MatSolverTypeForSpecifcType inext, iprev = NULL;
4797: PetscFunctionBegin;
4798: PetscCall(MatInitializePackage());
4799: if (!next) {
4800: PetscCall(PetscNew(&MatSolverTypeHolders));
4801: PetscCall(PetscStrallocpy(package, &MatSolverTypeHolders->name));
4802: PetscCall(PetscNew(&MatSolverTypeHolders->handlers));
4803: PetscCall(PetscStrallocpy(mtype, (char **)&MatSolverTypeHolders->handlers->mtype));
4804: MatSolverTypeHolders->handlers->createfactor[(int)ftype - 1] = createfactor;
4805: PetscFunctionReturn(PETSC_SUCCESS);
4806: }
4807: while (next) {
4808: PetscCall(PetscStrcasecmp(package, next->name, &flg));
4809: if (flg) {
4810: PetscCheck(next->handlers, PETSC_COMM_SELF, PETSC_ERR_PLIB, "MatSolverTypeHolder is missing handlers");
4811: inext = next->handlers;
4812: while (inext) {
4813: PetscCall(PetscStrcasecmp(mtype, inext->mtype, &flg));
4814: if (flg) {
4815: inext->createfactor[(int)ftype - 1] = createfactor;
4816: PetscFunctionReturn(PETSC_SUCCESS);
4817: }
4818: iprev = inext;
4819: inext = inext->next;
4820: }
4821: PetscCall(PetscNew(&iprev->next));
4822: PetscCall(PetscStrallocpy(mtype, (char **)&iprev->next->mtype));
4823: iprev->next->createfactor[(int)ftype - 1] = createfactor;
4824: PetscFunctionReturn(PETSC_SUCCESS);
4825: }
4826: prev = next;
4827: next = next->next;
4828: }
4829: PetscCall(PetscNew(&prev->next));
4830: PetscCall(PetscStrallocpy(package, &prev->next->name));
4831: PetscCall(PetscNew(&prev->next->handlers));
4832: PetscCall(PetscStrallocpy(mtype, (char **)&prev->next->handlers->mtype));
4833: prev->next->handlers->createfactor[(int)ftype - 1] = createfactor;
4834: PetscFunctionReturn(PETSC_SUCCESS);
4835: }
4837: /*@
4838: MatSolverTypeGet - Gets the function that creates the factor matrix if it exist
4840: Input Parameters:
4841: + 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
4842: . ftype - the type of factorization supported by the type
4843: - mtype - the matrix type that works with this type
4845: Output Parameters:
4846: + foundtype - `PETSC_TRUE` if the type was registered
4847: . foundmtype - `PETSC_TRUE` if the type supports the requested mtype
4848: - createfactor - routine that will create the factored matrix ready to be used or `NULL` if not found
4850: Calling sequence of `createfactor`:
4851: + A - the matrix providing the factor matrix
4852: . ftype - the `MatFactorType` of the factor requested
4853: - B - the new factor matrix that responds to MatXXFactorSymbolic,Numeric() functions, such as `MatLUFactorSymbolic()`
4855: Level: developer
4857: Note:
4858: When `type` is `NULL` the available functions are searched for based on the order of the calls to `MatSolverTypeRegister()` in `MatInitializePackage()`.
4859: Since different PETSc configurations may have different external solvers, seemingly identical runs with different PETSc configurations may use a different solver.
4860: For example if one configuration had `--download-mumps` while a different one had `--download-superlu_dist`.
4862: .seealso: [](ch_matrices), `Mat`, `MatFactorType`, `MatType`, `MatCopy()`, `MatDuplicate()`, `MatGetFactorAvailable()`, `MatSolverTypeRegister()`, `MatGetFactor()`,
4863: `MatInitializePackage()`
4864: @*/
4865: PetscErrorCode MatSolverTypeGet(MatSolverType type, MatType mtype, MatFactorType ftype, PetscBool *foundtype, PetscBool *foundmtype, PetscErrorCode (**createfactor)(Mat A, MatFactorType ftype, Mat *B))
4866: {
4867: MatSolverTypeHolder next = MatSolverTypeHolders;
4868: PetscBool flg;
4869: MatSolverTypeForSpecifcType inext;
4871: PetscFunctionBegin;
4872: if (foundtype) *foundtype = PETSC_FALSE;
4873: if (foundmtype) *foundmtype = PETSC_FALSE;
4874: if (createfactor) *createfactor = NULL;
4876: if (type) {
4877: while (next) {
4878: PetscCall(PetscStrcasecmp(type, next->name, &flg));
4879: if (flg) {
4880: if (foundtype) *foundtype = PETSC_TRUE;
4881: inext = next->handlers;
4882: while (inext) {
4883: PetscCall(PetscStrbeginswith(mtype, inext->mtype, &flg));
4884: if (flg) {
4885: if (foundmtype) *foundmtype = PETSC_TRUE;
4886: if (createfactor) *createfactor = inext->createfactor[(int)ftype - 1];
4887: PetscFunctionReturn(PETSC_SUCCESS);
4888: }
4889: inext = inext->next;
4890: }
4891: }
4892: next = next->next;
4893: }
4894: } else {
4895: while (next) {
4896: inext = next->handlers;
4897: while (inext) {
4898: PetscCall(PetscStrcmp(mtype, inext->mtype, &flg));
4899: if (flg && inext->createfactor[(int)ftype - 1]) {
4900: if (foundtype) *foundtype = PETSC_TRUE;
4901: if (foundmtype) *foundmtype = PETSC_TRUE;
4902: if (createfactor) *createfactor = inext->createfactor[(int)ftype - 1];
4903: PetscFunctionReturn(PETSC_SUCCESS);
4904: }
4905: inext = inext->next;
4906: }
4907: next = next->next;
4908: }
4909: /* try with base classes inext->mtype */
4910: next = MatSolverTypeHolders;
4911: while (next) {
4912: inext = next->handlers;
4913: while (inext) {
4914: PetscCall(PetscStrbeginswith(mtype, inext->mtype, &flg));
4915: if (flg && inext->createfactor[(int)ftype - 1]) {
4916: if (foundtype) *foundtype = PETSC_TRUE;
4917: if (foundmtype) *foundmtype = PETSC_TRUE;
4918: if (createfactor) *createfactor = inext->createfactor[(int)ftype - 1];
4919: PetscFunctionReturn(PETSC_SUCCESS);
4920: }
4921: inext = inext->next;
4922: }
4923: next = next->next;
4924: }
4925: }
4926: PetscFunctionReturn(PETSC_SUCCESS);
4927: }
4929: PetscErrorCode MatSolverTypeDestroy(void)
4930: {
4931: MatSolverTypeHolder next = MatSolverTypeHolders, prev;
4932: MatSolverTypeForSpecifcType inext, iprev;
4934: PetscFunctionBegin;
4935: while (next) {
4936: PetscCall(PetscFree(next->name));
4937: inext = next->handlers;
4938: while (inext) {
4939: PetscCall(PetscFree(inext->mtype));
4940: iprev = inext;
4941: inext = inext->next;
4942: PetscCall(PetscFree(iprev));
4943: }
4944: prev = next;
4945: next = next->next;
4946: PetscCall(PetscFree(prev));
4947: }
4948: MatSolverTypeHolders = NULL;
4949: PetscFunctionReturn(PETSC_SUCCESS);
4950: }
4952: static PetscErrorCode MatGetFactor_Private(Mat mat, MatFactorType ftype, PetscBool exact, PetscBool *found, Mat *f)
4953: {
4954: MatSolverTypeHolder next = MatSolverTypeHolders;
4955: MatSolverTypeForSpecifcType inext;
4956: PetscBool flg, same;
4958: PetscFunctionBegin;
4959: *found = PETSC_FALSE;
4960: *f = NULL;
4961: /* When no solver type is requested, MatGetFactor() must honor registration order, but a registered
4962: MatSolverType may only be able to reject a particular MatType at runtime by returning NULL in *f.
4963: Keep walking the registry until a matching backend actually creates a factor. */
4964: while (next) {
4965: inext = next->handlers;
4966: while (inext) {
4967: PetscCall(PetscStrcmp(((PetscObject)mat)->type_name, inext->mtype, &same));
4968: if (exact) flg = same;
4969: else {
4970: /* Do the base-type pass separately from the exact pass so exact registrations for the MatType
4971: are all tried before broader registrations such as implementation base classes. */
4972: PetscCall(PetscStrbeginswith(((PetscObject)mat)->type_name, inext->mtype, &flg));
4973: flg = (PetscBool)(flg && !same);
4974: }
4975: if (flg && inext->createfactor[(int)ftype - 1]) {
4976: *found = PETSC_TRUE;
4977: PetscCall((*inext->createfactor[(int)ftype - 1])(mat, ftype, f));
4978: if (*f) PetscFunctionReturn(PETSC_SUCCESS);
4979: }
4980: inext = inext->next;
4981: }
4982: next = next->next;
4983: }
4984: PetscFunctionReturn(PETSC_SUCCESS);
4985: }
4987: /*@
4988: MatFactorGetCanUseOrdering - Indicates if the factorization can use the ordering provided in `MatLUFactorSymbolic()`, `MatCholeskyFactorSymbolic()`
4990: Logically Collective
4992: Input Parameter:
4993: . mat - the matrix
4995: Output Parameter:
4996: . flg - `PETSC_TRUE` if uses the ordering
4998: Level: developer
5000: Note:
5001: Most internal PETSc factorizations use the ordering passed to the factorization routine but external
5002: packages do not, thus we want to skip generating the ordering when it is not needed or used.
5004: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatCopy()`, `MatDuplicate()`, `MatGetFactorAvailable()`, `MatGetFactor()`, `MatLUFactorSymbolic()`, `MatCholeskyFactorSymbolic()`
5005: @*/
5006: PetscErrorCode MatFactorGetCanUseOrdering(Mat mat, PetscBool *flg)
5007: {
5008: PetscFunctionBegin;
5009: *flg = mat->canuseordering;
5010: PetscFunctionReturn(PETSC_SUCCESS);
5011: }
5013: /*@
5014: MatFactorGetPreferredOrdering - The preferred ordering for a particular matrix factor object
5016: Logically Collective
5018: Input Parameters:
5019: + mat - the matrix obtained with `MatGetFactor()`
5020: - ftype - the factorization type to be used
5022: Output Parameter:
5023: . otype - the preferred ordering type
5025: Level: developer
5027: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatFactorType`, `MatOrderingType`, `MatCopy()`, `MatDuplicate()`, `MatGetFactorAvailable()`, `MatGetFactor()`, `MatLUFactorSymbolic()`, `MatCholeskyFactorSymbolic()`
5028: @*/
5029: PetscErrorCode MatFactorGetPreferredOrdering(Mat mat, MatFactorType ftype, MatOrderingType *otype)
5030: {
5031: PetscFunctionBegin;
5032: *otype = mat->preferredordering[ftype];
5033: PetscCheck(*otype, PETSC_COMM_SELF, PETSC_ERR_PLIB, "MatFactor did not have a preferred ordering");
5034: PetscFunctionReturn(PETSC_SUCCESS);
5035: }
5037: /*@
5038: MatGetFactor - Returns a matrix suitable to calls to routines such as `MatLUFactorSymbolic()`, `MatCholeskyFactorSymbolic()`, `MatILUFactorSymbolic()`,
5039: `MatICCFactorSymbolic()`, `MatLUFactorNumeric()`, and `MatCholeskyFactorNumeric()`
5041: Collective
5043: Input Parameters:
5044: + mat - the matrix
5045: . 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
5046: the other criteria is returned
5047: - ftype - factor type, `MAT_FACTOR_LU`, `MAT_FACTOR_CHOLESKY`, `MAT_FACTOR_ICC`, `MAT_FACTOR_ILU`, `MAT_FACTOR_QR`
5049: Output Parameter:
5050: . f - the factor matrix used with MatXXFactorSymbolic,Numeric() calls. Can be `NULL` in some cases, see notes below.
5052: Options Database Keys:
5053: + -pc_factor_mat_solver_type type - choose the type at run time. When using `KSP` solvers
5054: . -pc_factor_mat_factor_on_host (true|false) - do matrix factorization on host (with device matrices). Default is doing it on device
5055: - -pc_factor_mat_solve_on_host (true|false) - do matrix solve on host (with device matrices). Default is doing it on device
5057: Level: intermediate
5059: Notes:
5060: Some of the packages, such as MUMPS, have options for controlling the factorization, these are in the form `-prefix_mat_packagename_packageoption`
5061: (for example, `-mat_mumps_icntl_6 1`) where `prefix` is normally set automatically from the calling `KSP`/`PC`. If `MatGetFactor()` is called directly,
5062: without using a `PC`, one can set the prefix by
5063: calling `MatSetOptionsPrefixFactor()` on the originating matrix or `MatSetOptionsPrefix()` on the resulting factor matrix.
5065: Some PETSc matrix formats have alternative solvers available that are provided by alternative packages
5066: such as PaStiX, SuperLU_DIST, MUMPS etc. PETSc must have been configured to use the external solver,
5067: using the corresponding `./configure` option such as `--download-package` or `--with-package-dir`.
5069: When `type` is `NULL` the available results are searched for based on the order of the calls to `MatSolverTypeRegister()` in `MatInitializePackage()`.
5070: Since different PETSc configurations may have different external solvers, seemingly identical runs with different PETSc configurations may use a different solver.
5071: For example if one configuration had `--download-mumps` while a different one had `--download-superlu_dist`.
5073: The return matrix can be `NULL` if the requested factorization is not available, since some combinations of matrix types and factorization
5074: types registered with `MatSolverTypeRegister()` cannot be fully tested if not at runtime.
5076: Developer Note:
5077: This should actually be called `MatCreateFactor()` since it creates a new factor object
5079: The `MatGetFactor()` implementations should not be accessing the PETSc options database or making other decisions about solver options,
5080: that should be delayed until the later operations. This is to ensure the correct options prefix has been set in the factor matrix.
5082: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `KSP`, `MatSolverType`, `MatFactorType`, `MatCopy()`, `MatDuplicate()`,
5083: `MatGetFactorAvailable()`, `MatFactorGetCanUseOrdering()`, `MatSolverTypeRegister()`, `MatSolverTypeGet()`,
5084: `MAT_FACTOR_LU`, `MAT_FACTOR_CHOLESKY`, `MAT_FACTOR_ICC`, `MAT_FACTOR_ILU`, `MAT_FACTOR_QR`, `MatInitializePackage()`,
5085: `MatLUFactorSymbolic()`, `MatCholeskyFactorSymbolic()`, `MatILUFactorSymbolic()`,
5086: `MatICCFactorSymbolic()`, `MatLUFactorNumeric()`, `MatCholeskyFactorNumeric()`
5087: @*/
5088: PetscErrorCode MatGetFactor(Mat mat, MatSolverType type, MatFactorType ftype, Mat *f)
5089: {
5090: PetscBool foundtype, foundmtype, shell, hasop = PETSC_FALSE;
5091: PetscErrorCode (*conv)(Mat, MatFactorType, Mat *);
5093: PetscFunctionBegin;
5097: PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
5098: MatCheckPreallocated(mat, 1);
5100: PetscCall(MatIsShell(mat, &shell));
5101: if (shell) PetscCall(MatHasOperation(mat, MATOP_GET_FACTOR, &hasop));
5102: if (hasop) {
5103: PetscUseTypeMethod(mat, getfactor, type, ftype, f);
5104: PetscFunctionReturn(PETSC_SUCCESS);
5105: }
5107: if (!type) {
5108: PetscBool foundbase;
5110: /* First try exact MatType registrations in solver registration order. If all matching backends
5111: decline this matrix instance by returning NULL, then try base-type registrations. */
5112: PetscCall(MatGetFactor_Private(mat, ftype, PETSC_TRUE, &foundtype, f));
5113: if (!*f) {
5114: PetscCall(MatGetFactor_Private(mat, ftype, PETSC_FALSE, &foundbase, f));
5115: foundtype = (PetscBool)(foundtype || foundbase);
5116: }
5117: 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);
5118: if (mat->factorprefix) PetscCall(MatSetOptionsPrefix(*f, mat->factorprefix));
5119: PetscFunctionReturn(PETSC_SUCCESS);
5120: }
5122: PetscCall(MatSolverTypeGet(type, ((PetscObject)mat)->type_name, ftype, &foundtype, &foundmtype, &conv));
5123: 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],
5124: ((PetscObject)mat)->type_name, type ? " Perhaps you must ./configure with --download-" : "", type ? type : "");
5125: PetscCheck(foundmtype, PetscObjectComm((PetscObject)mat), PETSC_ERR_MISSING_FACTOR, "MatSolverType %s does not support matrix type %s", type, ((PetscObject)mat)->type_name);
5126: 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);
5128: PetscCall((*conv)(mat, ftype, f));
5129: if (mat->factorprefix) PetscCall(MatSetOptionsPrefix(*f, mat->factorprefix));
5130: PetscFunctionReturn(PETSC_SUCCESS);
5131: }
5133: /*@
5134: MatGetFactorAvailable - Returns a flag if matrix supports particular type and factor type
5136: Not Collective
5138: Input Parameters:
5139: + mat - the matrix
5140: . type - name of solver type, for example, `superlu`, `petsc` (to use PETSc's default)
5141: - ftype - factor type, `MAT_FACTOR_LU`, `MAT_FACTOR_CHOLESKY`, `MAT_FACTOR_ICC`, `MAT_FACTOR_ILU`, `MAT_FACTOR_QR`
5143: Output Parameter:
5144: . flg - `PETSC_TRUE` if the factorization is available
5146: Level: intermediate
5148: Notes:
5149: Some PETSc matrix formats have alternative solvers available that are contained in alternative packages
5150: such as `pastix`, `superlu`, `mumps`, etc.
5152: PETSc must have been configured with `./configure` to use the external solver using the option `--download-package` where package is the name of the package
5154: Developer Note:
5155: This should actually be called `MatCreateFactorAvailable()` since `MatGetFactor()` creates a new factor object
5157: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatSolverType`, `MatFactorType`, `MatGetFactor()`, `MatCopy()`, `MatDuplicate()`, `MatSolverTypeRegister()`,
5158: `MAT_FACTOR_LU`, `MAT_FACTOR_CHOLESKY`, `MAT_FACTOR_ICC`, `MAT_FACTOR_ILU`, `MAT_FACTOR_QR`, `MatSolverTypeGet()`
5159: @*/
5160: PetscErrorCode MatGetFactorAvailable(Mat mat, MatSolverType type, MatFactorType ftype, PetscBool *flg)
5161: {
5162: PetscErrorCode (*gconv)(Mat, MatFactorType, Mat *);
5164: PetscFunctionBegin;
5166: PetscAssertPointer(flg, 4);
5168: *flg = PETSC_FALSE;
5169: if (!((PetscObject)mat)->type_name) PetscFunctionReturn(PETSC_SUCCESS);
5171: PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
5172: MatCheckPreallocated(mat, 1);
5174: PetscCall(MatSolverTypeGet(type, ((PetscObject)mat)->type_name, ftype, NULL, NULL, &gconv));
5175: *flg = gconv ? PETSC_TRUE : PETSC_FALSE;
5176: PetscFunctionReturn(PETSC_SUCCESS);
5177: }
5179: /*@
5180: MatDuplicate - Duplicates a matrix including the non-zero structure.
5182: Collective
5184: Input Parameters:
5185: + mat - the matrix
5186: - op - One of `MAT_DO_NOT_COPY_VALUES`, `MAT_COPY_VALUES`, or `MAT_SHARE_NONZERO_PATTERN`.
5187: See the manual page for `MatDuplicateOption()` for an explanation of these options.
5189: Output Parameter:
5190: . M - pointer to place new matrix
5192: Level: intermediate
5194: Notes:
5195: You cannot change the nonzero pattern for the parent or child matrix later if you use `MAT_SHARE_NONZERO_PATTERN`.
5197: If `op` is not `MAT_COPY_VALUES` the numerical values in the new matrix are zeroed.
5199: 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.
5201: When original mat is a product of matrix operation, e.g., an output of `MatMatMult()` or `MatCreateSubMatrix()`, only the matrix data structure of `mat`
5202: is duplicated and the internal data structures created for the reuse of previous matrix operations are not duplicated.
5203: User should not use `MatDuplicate()` to create new matrix `M` if `M` is intended to be reused as the product of matrix operation.
5205: .seealso: [](ch_matrices), `Mat`, `MatCopy()`, `MatConvert()`, `MatDuplicateOption`
5206: @*/
5207: PetscErrorCode MatDuplicate(Mat mat, MatDuplicateOption op, Mat *M)
5208: {
5209: Mat B;
5210: VecType vtype;
5211: PetscInt i;
5212: PetscObject dm, container_h, container_d;
5213: PetscErrorCodeFn *viewf;
5215: PetscFunctionBegin;
5218: PetscAssertPointer(M, 3);
5219: PetscCheck(op != MAT_COPY_VALUES || mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "MAT_COPY_VALUES not allowed for unassembled matrix");
5220: PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
5221: MatCheckPreallocated(mat, 1);
5223: PetscCall(PetscLogEventBegin(MAT_Convert, mat, 0, 0, 0));
5224: PetscUseTypeMethod(mat, duplicate, op, M);
5225: PetscCall(PetscLogEventEnd(MAT_Convert, mat, 0, 0, 0));
5226: B = *M;
5228: PetscCall(MatGetOperation(mat, MATOP_VIEW, &viewf));
5229: if (viewf) PetscCall(MatSetOperation(B, MATOP_VIEW, viewf));
5230: PetscCall(MatGetVecType(mat, &vtype));
5231: PetscCall(MatSetVecType(B, vtype));
5233: B->stencil.dim = mat->stencil.dim;
5234: B->stencil.noc = mat->stencil.noc;
5235: for (i = 0; i <= mat->stencil.dim + (mat->stencil.noc ? 0 : -1); i++) {
5236: B->stencil.dims[i] = mat->stencil.dims[i];
5237: B->stencil.starts[i] = mat->stencil.starts[i];
5238: }
5240: B->nooffproczerorows = mat->nooffproczerorows;
5241: B->nooffprocentries = mat->nooffprocentries;
5242: B->nonzerostate = mat->nonzerostate;
5244: PetscCall(PetscObjectQuery((PetscObject)mat, "__PETSc_dm", &dm));
5245: if (dm) PetscCall(PetscObjectCompose((PetscObject)B, "__PETSc_dm", dm));
5246: PetscCall(PetscObjectQuery((PetscObject)mat, "__PETSc_MatCOOStruct_Host", &container_h));
5247: if (container_h) PetscCall(PetscObjectCompose((PetscObject)B, "__PETSc_MatCOOStruct_Host", container_h));
5248: PetscCall(PetscObjectQuery((PetscObject)mat, "__PETSc_MatCOOStruct_Device", &container_d));
5249: if (container_d) PetscCall(PetscObjectCompose((PetscObject)B, "__PETSc_MatCOOStruct_Device", container_d));
5250: if (op == MAT_COPY_VALUES) PetscCall(MatPropagateSymmetryOptions(mat, B));
5251: PetscCall(PetscObjectStateIncrease((PetscObject)B));
5252: PetscFunctionReturn(PETSC_SUCCESS);
5253: }
5255: /*@
5256: MatGetDiagonal - Gets the diagonal of a matrix as a `Vec`
5258: Logically Collective
5260: Input Parameter:
5261: . mat - the matrix
5263: Output Parameter:
5264: . v - the diagonal of the matrix
5266: Level: intermediate
5268: Note:
5269: If `mat` has local sizes `n` x `m`, this routine fills the first `ndiag = min(n, m)` entries
5270: of `v` with the diagonal values. Thus `v` must have local size of at least `ndiag`. If `v`
5271: is larger than `ndiag`, the values of the remaining entries are unspecified.
5273: Currently only correct in parallel for square matrices.
5275: .seealso: [](ch_matrices), `Mat`, `Vec`, `MatGetRow()`, `MatCreateSubMatrices()`, `MatCreateSubMatrix()`, `MatGetRowMaxAbs()`
5276: @*/
5277: PetscErrorCode MatGetDiagonal(Mat mat, Vec v)
5278: {
5279: PetscFunctionBegin;
5283: PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
5284: MatCheckPreallocated(mat, 1);
5285: if (PetscDefined(USE_DEBUG)) {
5286: PetscInt nv, row, col, ndiag;
5288: PetscCall(VecGetLocalSize(v, &nv));
5289: PetscCall(MatGetLocalSize(mat, &row, &col));
5290: ndiag = PetscMin(row, col);
5291: 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);
5292: }
5294: PetscUseTypeMethod(mat, getdiagonal, v);
5295: PetscCall(PetscObjectStateIncrease((PetscObject)v));
5296: PetscFunctionReturn(PETSC_SUCCESS);
5297: }
5299: /*@
5300: MatGetRowMin - Gets the minimum value (of the real part) of each
5301: row of the matrix
5303: Logically Collective
5305: Input Parameter:
5306: . mat - the matrix
5308: Output Parameters:
5309: + v - the vector for storing the maximums
5310: - idx - the indices of the column found for each row (optional, pass `NULL` if not needed)
5312: Level: intermediate
5314: Note:
5315: The result of this call are the same as if one converted the matrix to dense format
5316: and found the minimum value in each row (i.e. the implicit zeros are counted as zeros).
5318: This code is only implemented for a couple of matrix formats.
5320: .seealso: [](ch_matrices), `Mat`, `MatGetDiagonal()`, `MatCreateSubMatrices()`, `MatCreateSubMatrix()`, `MatGetRowMaxAbs()`, `MatGetRowMinAbs()`,
5321: `MatGetRowMax()`
5322: @*/
5323: PetscErrorCode MatGetRowMin(Mat mat, Vec v, PetscInt idx[])
5324: {
5325: PetscFunctionBegin;
5329: PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
5331: if (!mat->cmap->N) {
5332: PetscCall(VecSet(v, PETSC_MAX_REAL));
5333: if (idx) {
5334: PetscInt i, m = mat->rmap->n;
5335: for (i = 0; i < m; i++) idx[i] = -1;
5336: }
5337: } else {
5338: MatCheckPreallocated(mat, 1);
5339: }
5340: PetscUseTypeMethod(mat, getrowmin, v, idx);
5341: PetscCall(PetscObjectStateIncrease((PetscObject)v));
5342: PetscFunctionReturn(PETSC_SUCCESS);
5343: }
5345: /*@
5346: MatGetRowMinAbs - Gets the minimum value (in absolute value) of each
5347: row of the matrix
5349: Logically Collective
5351: Input Parameter:
5352: . mat - the matrix
5354: Output Parameters:
5355: + v - the vector for storing the minimums
5356: - idx - the indices of the column found for each row (or `NULL` if not needed)
5358: Level: intermediate
5360: Notes:
5361: if a row is completely empty or has only 0.0 values, then the `idx` value for that
5362: row is 0 (the first column).
5364: This code is only implemented for a couple of matrix formats.
5366: .seealso: [](ch_matrices), `Mat`, `MatGetDiagonal()`, `MatCreateSubMatrices()`, `MatCreateSubMatrix()`, `MatGetRowMax()`, `MatGetRowMaxAbs()`, `MatGetRowMin()`
5367: @*/
5368: PetscErrorCode MatGetRowMinAbs(Mat mat, Vec v, PetscInt idx[])
5369: {
5370: PetscFunctionBegin;
5374: PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
5375: PetscCheck(!mat->factortype, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
5377: if (!mat->cmap->N) {
5378: PetscCall(VecSet(v, 0.0));
5379: if (idx) {
5380: PetscInt i, m = mat->rmap->n;
5381: for (i = 0; i < m; i++) idx[i] = -1;
5382: }
5383: } else {
5384: MatCheckPreallocated(mat, 1);
5385: if (idx) PetscCall(PetscArrayzero(idx, mat->rmap->n));
5386: PetscUseTypeMethod(mat, getrowminabs, v, idx);
5387: }
5388: PetscCall(PetscObjectStateIncrease((PetscObject)v));
5389: PetscFunctionReturn(PETSC_SUCCESS);
5390: }
5392: /*@
5393: MatGetRowMax - Gets the maximum value (of the real part) of each
5394: row of the matrix
5396: Logically Collective
5398: Input Parameter:
5399: . mat - the matrix
5401: Output Parameters:
5402: + v - the vector for storing the maximums
5403: - idx - the indices of the column found for each row (optional, otherwise pass `NULL`)
5405: Level: intermediate
5407: Notes:
5408: The result of this call are the same as if one converted the matrix to dense format
5409: and found the minimum value in each row (i.e. the implicit zeros are counted as zeros).
5411: This code is only implemented for a couple of matrix formats.
5413: .seealso: [](ch_matrices), `Mat`, `MatGetDiagonal()`, `MatCreateSubMatrices()`, `MatCreateSubMatrix()`, `MatGetRowMaxAbs()`, `MatGetRowMin()`, `MatGetRowMinAbs()`
5414: @*/
5415: PetscErrorCode MatGetRowMax(Mat mat, Vec v, PetscInt idx[])
5416: {
5417: PetscFunctionBegin;
5421: PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
5423: if (!mat->cmap->N) {
5424: PetscCall(VecSet(v, PETSC_MIN_REAL));
5425: if (idx) {
5426: PetscInt i, m = mat->rmap->n;
5427: for (i = 0; i < m; i++) idx[i] = -1;
5428: }
5429: } else {
5430: MatCheckPreallocated(mat, 1);
5431: PetscUseTypeMethod(mat, getrowmax, v, idx);
5432: }
5433: PetscCall(PetscObjectStateIncrease((PetscObject)v));
5434: PetscFunctionReturn(PETSC_SUCCESS);
5435: }
5437: /*@
5438: MatGetRowMaxAbs - Gets the maximum value (in absolute value) of each
5439: row of the matrix
5441: Logically Collective
5443: Input Parameter:
5444: . mat - the matrix
5446: Output Parameters:
5447: + v - the vector for storing the maximums
5448: - idx - the indices of the column found for each row (or `NULL` if not needed)
5450: Level: intermediate
5452: Notes:
5453: if a row is completely empty or has only 0.0 values, then the `idx` value for that
5454: row is 0 (the first column).
5456: This code is only implemented for a couple of matrix formats.
5458: .seealso: [](ch_matrices), `Mat`, `MatGetDiagonal()`, `MatCreateSubMatrices()`, `MatCreateSubMatrix()`, `MatGetRowSum()`, `MatGetRowMin()`, `MatGetRowMinAbs()`
5459: @*/
5460: PetscErrorCode MatGetRowMaxAbs(Mat mat, Vec v, PetscInt idx[])
5461: {
5462: PetscFunctionBegin;
5466: PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
5468: if (!mat->cmap->N) {
5469: PetscCall(VecSet(v, 0.0));
5470: if (idx) {
5471: PetscInt i, m = mat->rmap->n;
5472: for (i = 0; i < m; i++) idx[i] = -1;
5473: }
5474: } else {
5475: MatCheckPreallocated(mat, 1);
5476: if (idx) PetscCall(PetscArrayzero(idx, mat->rmap->n));
5477: PetscUseTypeMethod(mat, getrowmaxabs, v, idx);
5478: }
5479: PetscCall(PetscObjectStateIncrease((PetscObject)v));
5480: PetscFunctionReturn(PETSC_SUCCESS);
5481: }
5483: /*@
5484: MatGetRowSumAbs - Gets the sum value (in absolute value) of each row of the matrix
5486: Logically Collective
5488: Input Parameter:
5489: . mat - the matrix
5491: Output Parameter:
5492: . v - the vector for storing the sum
5494: Level: intermediate
5496: This code is only implemented for a couple of matrix formats.
5498: .seealso: [](ch_matrices), `Mat`, `MatGetDiagonal()`, `MatCreateSubMatrices()`, `MatCreateSubMatrix()`, `MatGetRowMax()`, `MatGetRowMin()`, `MatGetRowMinAbs()`
5499: @*/
5500: PetscErrorCode MatGetRowSumAbs(Mat mat, Vec v)
5501: {
5502: PetscFunctionBegin;
5506: PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
5508: if (!mat->cmap->N) PetscCall(VecSet(v, 0.0));
5509: else {
5510: MatCheckPreallocated(mat, 1);
5511: PetscUseTypeMethod(mat, getrowsumabs, v);
5512: }
5513: PetscCall(PetscObjectStateIncrease((PetscObject)v));
5514: PetscFunctionReturn(PETSC_SUCCESS);
5515: }
5517: /*@
5518: MatGetRowSum - Gets the sum of each row of the matrix
5520: Logically or Neighborhood Collective
5522: Input Parameter:
5523: . mat - the matrix
5525: Output Parameter:
5526: . v - the vector for storing the sum of rows
5528: Level: intermediate
5530: Note:
5531: This code is slow since it is not currently specialized for different formats
5533: .seealso: [](ch_matrices), `Mat`, `MatGetDiagonal()`, `MatCreateSubMatrices()`, `MatCreateSubMatrix()`, `MatGetRowMax()`, `MatGetRowMin()`, `MatGetRowMaxAbs()`, `MatGetRowMinAbs()`, `MatGetRowSumAbs()`
5534: @*/
5535: PetscErrorCode MatGetRowSum(Mat mat, Vec v)
5536: {
5537: Vec ones;
5539: PetscFunctionBegin;
5543: PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
5544: MatCheckPreallocated(mat, 1);
5545: PetscCall(MatCreateVecs(mat, &ones, NULL));
5546: PetscCall(VecSet(ones, 1.));
5547: PetscCall(MatMult(mat, ones, v));
5548: PetscCall(VecDestroy(&ones));
5549: PetscFunctionReturn(PETSC_SUCCESS);
5550: }
5552: /*@
5553: MatTransposeSetPrecursor - Set the matrix from which the second matrix will receive numerical transpose data with a call to `MatTranspose`(A,`MAT_REUSE_MATRIX`,&B)
5554: when B was not obtained with `MatTranspose`(A,`MAT_INITIAL_MATRIX`,&B)
5556: Collective
5558: Input Parameter:
5559: . mat - the matrix to provide the transpose
5561: Output Parameter:
5562: . 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
5564: Level: advanced
5566: Note:
5567: 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
5568: routine allows bypassing that call.
5570: .seealso: [](ch_matrices), `Mat`, `MatTransposeSymbolic()`, `MatTranspose()`, `MatMultTranspose()`, `MatMultTransposeAdd()`, `MatIsTranspose()`, `MatReuse`, `MAT_INITIAL_MATRIX`, `MAT_REUSE_MATRIX`, `MAT_INPLACE_MATRIX`
5571: @*/
5572: PetscErrorCode MatTransposeSetPrecursor(Mat mat, Mat B)
5573: {
5574: MatState *rb = NULL;
5576: PetscFunctionBegin;
5577: PetscCall(PetscNew(&rb));
5578: rb->id = ((PetscObject)mat)->id;
5579: rb->state = 0;
5580: PetscCall(MatGetNonzeroState(mat, &rb->nonzerostate));
5581: PetscCall(PetscObjectContainerCompose((PetscObject)B, "MatTransposeParent", rb, PetscCtxDestroyDefault));
5582: PetscFunctionReturn(PETSC_SUCCESS);
5583: }
5585: static PetscErrorCode MatTranspose_Private(Mat mat, MatReuse reuse, Mat *B, PetscBool conjugate)
5586: {
5587: PetscContainer rB = NULL;
5588: MatState *rb = NULL;
5589: PetscErrorCode (*f)(Mat, MatReuse, Mat *) = NULL;
5591: PetscFunctionBegin;
5594: PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
5595: PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
5596: PetscCheck(reuse != MAT_INPLACE_MATRIX || mat == *B, PetscObjectComm((PetscObject)mat), PETSC_ERR_SUP, "MAT_INPLACE_MATRIX requires last matrix to match first");
5597: PetscCheck(reuse != MAT_REUSE_MATRIX || mat != *B, PetscObjectComm((PetscObject)mat), PETSC_ERR_SUP, "Perhaps you mean MAT_INPLACE_MATRIX");
5598: MatCheckPreallocated(mat, 1);
5599: if (reuse == MAT_REUSE_MATRIX) {
5600: PetscCall(PetscObjectQuery((PetscObject)*B, "MatTransposeParent", (PetscObject *)&rB));
5601: PetscCheck(rB, PetscObjectComm((PetscObject)*B), PETSC_ERR_ARG_WRONG, "Reuse matrix used was not generated from call to MatTranspose(). Suggest MatTransposeSetPrecursor().");
5602: PetscCall(PetscContainerGetPointer(rB, &rb));
5603: PetscCheck(rb->id == ((PetscObject)mat)->id, PetscObjectComm((PetscObject)*B), PETSC_ERR_ARG_WRONG, "Reuse matrix used was not generated from input matrix");
5604: if (rb->state == ((PetscObject)mat)->state) PetscFunctionReturn(PETSC_SUCCESS);
5605: }
5607: if (conjugate) {
5608: f = mat->ops->hermitiantranspose;
5609: if (f) PetscCall((*f)(mat, reuse, B));
5610: }
5611: if (!f && !(reuse == MAT_INPLACE_MATRIX && mat->hermitian == PETSC_BOOL3_TRUE && conjugate)) {
5612: PetscCall(PetscLogEventBegin(MAT_Transpose, mat, 0, 0, 0));
5613: if (reuse != MAT_INPLACE_MATRIX || mat->symmetric != PETSC_BOOL3_TRUE) {
5614: PetscUseTypeMethod(mat, transpose, reuse, B);
5615: PetscCall(PetscObjectStateIncrease((PetscObject)*B));
5616: }
5617: PetscCall(PetscLogEventEnd(MAT_Transpose, mat, 0, 0, 0));
5618: if (conjugate) PetscCall(MatConjugate(*B));
5619: }
5621: if (reuse == MAT_INITIAL_MATRIX) PetscCall(MatTransposeSetPrecursor(mat, *B));
5622: if (reuse != MAT_INPLACE_MATRIX) {
5623: PetscCall(PetscObjectQuery((PetscObject)*B, "MatTransposeParent", (PetscObject *)&rB));
5624: PetscCall(PetscContainerGetPointer(rB, &rb));
5625: rb->state = ((PetscObject)mat)->state;
5626: rb->nonzerostate = mat->nonzerostate;
5627: }
5628: PetscFunctionReturn(PETSC_SUCCESS);
5629: }
5631: /*@
5632: MatTranspose - Computes the transpose of a matrix, either in-place or out-of-place.
5634: Collective
5636: Input Parameters:
5637: + mat - the matrix to transpose
5638: - reuse - either `MAT_INITIAL_MATRIX`, `MAT_REUSE_MATRIX`, or `MAT_INPLACE_MATRIX`
5640: Output Parameter:
5641: . B - the transpose of the matrix
5643: Level: intermediate
5645: Notes:
5646: If you use `MAT_INPLACE_MATRIX` then you must pass in `&mat` for `B`
5648: `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
5649: transpose, call `MatTransposeSetPrecursor(mat, B)` before calling this routine.
5651: 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.
5653: Consider using `MatCreateTranspose()` instead if you only need a matrix that behaves like the transpose but don't need the storage to be changed.
5654: For example, the result of `MatCreateTranspose()` will compute the transpose of the given matrix times a vector for matrix-vector products computed with `MatMult()`.
5656: If `mat` is unchanged from the last call this function returns immediately without recomputing the result
5658: If you only need the symbolic transpose of a matrix, and not the numerical values, use `MatTransposeSymbolic()`
5660: .seealso: [](ch_matrices), `Mat`, `MatTransposeSetPrecursor()`, `MatMultTranspose()`, `MatMultTransposeAdd()`, `MatIsTranspose()`, `MatReuse`, `MAT_INITIAL_MATRIX`, `MAT_REUSE_MATRIX`, `MAT_INPLACE_MATRIX`,
5661: `MatTransposeSymbolic()`, `MatCreateTranspose()`
5662: @*/
5663: PetscErrorCode MatTranspose(Mat mat, MatReuse reuse, Mat *B)
5664: {
5665: PetscFunctionBegin;
5666: PetscCall(MatTranspose_Private(mat, reuse, B, PETSC_FALSE));
5667: PetscFunctionReturn(PETSC_SUCCESS);
5668: }
5670: /*@
5671: MatTransposeSymbolic - Computes the symbolic part of the transpose of a matrix.
5673: Collective
5675: Input Parameter:
5676: . A - the matrix to transpose
5678: Output Parameter:
5679: . 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
5680: numerical portion.
5682: Level: intermediate
5684: Note:
5685: This is not supported for many matrix types, use `MatTranspose()` in those cases
5687: .seealso: [](ch_matrices), `Mat`, `MatTransposeSetPrecursor()`, `MatTranspose()`, `MatMultTranspose()`, `MatMultTransposeAdd()`, `MatIsTranspose()`, `MatReuse`, `MAT_INITIAL_MATRIX`, `MAT_REUSE_MATRIX`, `MAT_INPLACE_MATRIX`
5688: @*/
5689: PetscErrorCode MatTransposeSymbolic(Mat A, Mat *B)
5690: {
5691: PetscFunctionBegin;
5694: PetscCheck(A->assembled, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
5695: PetscCheck(!A->factortype, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
5696: PetscCall(PetscLogEventBegin(MAT_Transpose, A, 0, 0, 0));
5697: PetscUseTypeMethod(A, transposesymbolic, B);
5698: PetscCall(PetscLogEventEnd(MAT_Transpose, A, 0, 0, 0));
5700: PetscCall(MatTransposeSetPrecursor(A, *B));
5701: PetscFunctionReturn(PETSC_SUCCESS);
5702: }
5704: PetscErrorCode MatTransposeCheckNonzeroState_Private(Mat A, Mat B)
5705: {
5706: PetscContainer rB;
5707: MatState *rb;
5709: PetscFunctionBegin;
5712: PetscCheck(A->assembled, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
5713: PetscCheck(!A->factortype, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
5714: PetscCall(PetscObjectQuery((PetscObject)B, "MatTransposeParent", (PetscObject *)&rB));
5715: PetscCheck(rB, PetscObjectComm((PetscObject)B), PETSC_ERR_ARG_WRONG, "Reuse matrix used was not generated from call to MatTranspose()");
5716: PetscCall(PetscContainerGetPointer(rB, &rb));
5717: PetscCheck(rb->id == ((PetscObject)A)->id, PetscObjectComm((PetscObject)B), PETSC_ERR_ARG_WRONG, "Reuse matrix used was not generated from input matrix");
5718: PetscCheck(rb->nonzerostate == A->nonzerostate, PetscObjectComm((PetscObject)B), PETSC_ERR_ARG_WRONGSTATE, "Reuse matrix has changed nonzero structure");
5719: PetscFunctionReturn(PETSC_SUCCESS);
5720: }
5722: /*@
5723: MatIsTranspose - Test whether a matrix is another one's transpose,
5724: or its own, in which case it tests symmetry.
5726: Collective
5728: Input Parameters:
5729: + A - the matrix to test
5730: . B - the matrix to test against, this can equal the first parameter
5731: - tol - tolerance, differences between entries smaller than this are counted as zero
5733: Output Parameter:
5734: . flg - the result
5736: Level: intermediate
5738: Notes:
5739: The sequential algorithm has a running time of the order of the number of nonzeros; the parallel
5740: test involves parallel copies of the block off-diagonal parts of the matrix.
5742: .seealso: [](ch_matrices), `Mat`, `MatTranspose()`, `MatIsSymmetric()`, `MatIsHermitian()`
5743: @*/
5744: PetscErrorCode MatIsTranspose(Mat A, Mat B, PetscReal tol, PetscBool *flg)
5745: {
5746: PetscErrorCode (*f)(Mat, Mat, PetscReal, PetscBool *), (*g)(Mat, Mat, PetscReal, PetscBool *);
5748: PetscFunctionBegin;
5751: PetscAssertPointer(flg, 4);
5752: PetscCall(PetscObjectQueryFunction((PetscObject)A, "MatIsTranspose_C", &f));
5753: PetscCall(PetscObjectQueryFunction((PetscObject)B, "MatIsTranspose_C", &g));
5754: *flg = PETSC_FALSE;
5755: if (f && g) {
5756: PetscCheck(f == g, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_NOTSAMETYPE, "Matrices do not have the same comparator for symmetry test");
5757: PetscCall((*f)(A, B, tol, flg));
5758: } else {
5759: MatType mattype;
5761: PetscCall(MatGetType(f ? B : A, &mattype));
5762: SETERRQ(PETSC_COMM_SELF, PETSC_ERR_SUP, "Matrix of type %s does not support checking for transpose", mattype);
5763: }
5764: PetscFunctionReturn(PETSC_SUCCESS);
5765: }
5767: /*@
5768: MatHermitianTranspose - Computes an in-place or out-of-place Hermitian transpose of a matrix in complex conjugate.
5770: Collective
5772: Input Parameters:
5773: + mat - the matrix to transpose and complex conjugate
5774: - reuse - either `MAT_INITIAL_MATRIX`, `MAT_REUSE_MATRIX`, or `MAT_INPLACE_MATRIX`
5776: Output Parameter:
5777: . B - the Hermitian transpose
5779: Level: intermediate
5781: .seealso: [](ch_matrices), `Mat`, `MatTranspose()`, `MatMultTranspose()`, `MatMultTransposeAdd()`, `MatIsTranspose()`, `MatReuse`
5782: @*/
5783: PetscErrorCode MatHermitianTranspose(Mat mat, MatReuse reuse, Mat *B)
5784: {
5785: PetscFunctionBegin;
5786: PetscCall(MatTranspose_Private(mat, reuse, B, PetscDefined(USE_COMPLEX) ? PETSC_TRUE : PETSC_FALSE));
5787: PetscFunctionReturn(PETSC_SUCCESS);
5788: }
5790: /*@
5791: MatIsHermitianTranspose - Test whether a matrix is another one's Hermitian transpose,
5793: Collective
5795: Input Parameters:
5796: + A - the matrix to test
5797: . B - the matrix to test against, this can equal the first parameter
5798: - tol - tolerance, differences between entries smaller than this are counted as zero
5800: Output Parameter:
5801: . flg - the result
5803: Level: intermediate
5805: Notes:
5806: Only available for `MATAIJ` matrices.
5808: The sequential algorithm
5809: has a running time of the order of the number of nonzeros; the parallel
5810: test involves parallel copies of the block off-diagonal parts of the matrix.
5812: .seealso: [](ch_matrices), `Mat`, `MatTranspose()`, `MatIsSymmetric()`, `MatIsHermitian()`, `MatIsTranspose()`
5813: @*/
5814: PetscErrorCode MatIsHermitianTranspose(Mat A, Mat B, PetscReal tol, PetscBool *flg)
5815: {
5816: PetscErrorCode (*f)(Mat, Mat, PetscReal, PetscBool *), (*g)(Mat, Mat, PetscReal, PetscBool *);
5818: PetscFunctionBegin;
5821: PetscAssertPointer(flg, 4);
5822: PetscCall(PetscObjectQueryFunction((PetscObject)A, "MatIsHermitianTranspose_C", &f));
5823: PetscCall(PetscObjectQueryFunction((PetscObject)B, "MatIsHermitianTranspose_C", &g));
5824: if (f && g) {
5825: PetscCheck(f == g, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_NOTSAMETYPE, "Matrices do not have the same comparator for Hermitian test");
5826: PetscCall((*f)(A, B, tol, flg));
5827: } else {
5828: MatType mattype;
5830: PetscCall(MatGetType(f ? B : A, &mattype));
5831: SETERRQ(PETSC_COMM_SELF, PETSC_ERR_SUP, "Matrix of type %s does not support checking for Hermitian transpose", mattype);
5832: }
5833: PetscFunctionReturn(PETSC_SUCCESS);
5834: }
5836: /*@
5837: MatPermute - Creates a new matrix with rows and columns permuted from the
5838: original.
5840: Collective
5842: Input Parameters:
5843: + mat - the matrix to permute
5844: . row - row permutation, each process supplies only the permutation for its rows
5845: - col - column permutation, each process supplies only the permutation for its columns
5847: Output Parameter:
5848: . B - the permuted matrix
5850: Level: advanced
5852: Note:
5853: The index sets map from `row`/`col` of permuted matrix to `row`/`col` of original matrix.
5854: The index sets should be on the same communicator as mat and have the same local sizes.
5855: `MATSEQSBAIJ` inputs may produce a `MATSEQBAIJ` matrix when the permutation does not preserve symmetry.
5857: Developer Note:
5858: If you want to implement `MatPermute()` for a matrix type, and your approach doesn't
5859: exploit the fact that `row` and `col` are permutations, consider implementing the
5860: more general `MatCreateSubMatrix()` instead.
5862: .seealso: [](ch_matrices), `Mat`, `MatGetOrdering()`, `ISAllGather()`, `MatCreateSubMatrix()`
5863: @*/
5864: PetscErrorCode MatPermute(Mat mat, IS row, IS col, Mat *B)
5865: {
5866: PetscFunctionBegin;
5871: PetscAssertPointer(B, 4);
5872: PetscCheckSameComm(mat, 1, row, 2);
5873: if (row != col) PetscCheckSameComm(row, 2, col, 3);
5874: PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
5875: PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
5876: PetscCheck(mat->ops->permute || mat->ops->createsubmatrix, PETSC_COMM_SELF, PETSC_ERR_SUP, "MatPermute not available for Mat type %s", ((PetscObject)mat)->type_name);
5877: MatCheckPreallocated(mat, 1);
5879: if (mat->ops->permute) {
5880: PetscUseTypeMethod(mat, permute, row, col, B);
5881: PetscCall(PetscObjectStateIncrease((PetscObject)*B));
5882: } else {
5883: PetscCall(MatCreateSubMatrix(mat, row, col, MAT_INITIAL_MATRIX, B));
5884: }
5885: PetscFunctionReturn(PETSC_SUCCESS);
5886: }
5888: /*@
5889: MatEqual - Compares two matrices.
5891: Collective
5893: Input Parameters:
5894: + A - the first matrix
5895: - B - the second matrix
5897: Output Parameter:
5898: . flg - `PETSC_TRUE` if the matrices are equal; `PETSC_FALSE` otherwise.
5900: Level: intermediate
5902: Note:
5903: If either of the matrix is "matrix-free", meaning the matrix entries are not stored explicitly then equality is determined by comparing
5904: the results of several matrix-vector product using randomly created vectors, see `MatMultEqual()`.
5906: .seealso: [](ch_matrices), `Mat`, `MatMultEqual()`
5907: @*/
5908: PetscErrorCode MatEqual(Mat A, Mat B, PetscBool *flg)
5909: {
5910: PetscFunctionBegin;
5915: PetscAssertPointer(flg, 3);
5916: PetscCheckSameComm(A, 1, B, 2);
5917: MatCheckPreallocated(A, 1);
5918: MatCheckPreallocated(B, 2);
5919: PetscCheck(A->assembled, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
5920: PetscCheck(B->assembled, PetscObjectComm((PetscObject)B), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
5921: 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,
5922: B->cmap->N);
5923: if (A->ops->equal && A->ops->equal == B->ops->equal) PetscUseTypeMethod(A, equal, B, flg);
5924: else PetscCall(MatMultEqual(A, B, 10, flg));
5925: PetscFunctionReturn(PETSC_SUCCESS);
5926: }
5928: /*@
5929: MatDiagonalScale - Scales a matrix on the left and right by diagonal
5930: matrices that are stored as vectors. Either of the two scaling
5931: matrices can be `NULL`.
5933: Collective
5935: Input Parameters:
5936: + mat - the matrix to be scaled
5937: . l - the left scaling vector (or `NULL`)
5938: - r - the right scaling vector (or `NULL`)
5940: Level: intermediate
5942: Note:
5943: `MatDiagonalScale()` computes $A = LAR$, where
5944: L = a diagonal matrix (stored as a vector), R = a diagonal matrix (stored as a vector)
5945: The L scales the rows of the matrix, the R scales the columns of the matrix.
5946: For `MATSEQSBAIJ`, if `l` and `r` are different `Vec` objects, `mat` changes to type `MATSEQBAIJ` because the result is not necessarily symmetric.
5948: .seealso: [](ch_matrices), `Mat`, `MatScale()`, `MatShift()`, `MatDiagonalSet()`
5949: @*/
5950: PetscErrorCode MatDiagonalScale(Mat mat, Vec l, Vec r)
5951: {
5952: PetscBool flg = PETSC_FALSE;
5954: PetscFunctionBegin;
5957: if (l) {
5959: PetscCheckSameComm(mat, 1, l, 2);
5960: }
5961: if (r) {
5963: PetscCheckSameComm(mat, 1, r, 3);
5964: }
5965: PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
5966: PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
5967: MatCheckPreallocated(mat, 1);
5968: if (!l && !r) PetscFunctionReturn(PETSC_SUCCESS);
5970: PetscCall(PetscLogEventBegin(MAT_Scale, mat, 0, 0, 0));
5971: PetscUseTypeMethod(mat, diagonalscale, l, r);
5972: PetscCall(PetscLogEventEnd(MAT_Scale, mat, 0, 0, 0));
5973: PetscCall(PetscObjectStateIncrease((PetscObject)mat));
5974: if (l != r && (PetscBool3ToBool(mat->symmetric) || PetscBool3ToBool(mat->hermitian))) {
5975: if (!PetscDefined(USE_COMPLEX) || PetscBool3ToBool(mat->symmetric)) {
5976: if (l && r) PetscCall(VecEqual(l, r, &flg));
5977: if (!flg) {
5978: PetscCall(PetscObjectTypeCompare((PetscObject)mat, MATMPISBAIJ, &flg));
5979: PetscCheck(!flg, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_OUTOFRANGE, "For MATMPISBAIJ, left and right scaling vectors must be the same");
5980: mat->symmetric = mat->spd = PETSC_BOOL3_FALSE;
5981: if (!PetscDefined(USE_COMPLEX)) mat->hermitian = PETSC_BOOL3_FALSE;
5982: else mat->hermitian = PETSC_BOOL3_UNKNOWN;
5983: }
5984: }
5985: if (PetscDefined(USE_COMPLEX) && PetscBool3ToBool(mat->hermitian)) {
5986: flg = PETSC_FALSE;
5987: if (l && r) {
5988: Vec conjugate;
5990: PetscCall(VecDuplicate(l, &conjugate));
5991: PetscCall(VecCopy(l, conjugate));
5992: PetscCall(VecConjugate(conjugate));
5993: PetscCall(VecEqual(conjugate, r, &flg));
5994: PetscCall(VecDestroy(&conjugate));
5995: }
5996: if (!flg) {
5997: PetscCall(PetscObjectTypeCompare((PetscObject)mat, MATMPISBAIJ, &flg));
5998: PetscCheck(!flg, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_OUTOFRANGE, "For Hermitian MATMPISBAIJ, left and right scaling vectors must be conjugate one of the other");
5999: mat->hermitian = PETSC_BOOL3_FALSE;
6000: mat->symmetric = mat->spd = PETSC_BOOL3_UNKNOWN;
6001: }
6002: }
6003: }
6004: PetscFunctionReturn(PETSC_SUCCESS);
6005: }
6007: /*@
6008: MatScale - Scales all elements of a matrix by a given number.
6010: Logically Collective
6012: Input Parameters:
6013: + mat - the matrix to be scaled
6014: - a - the scaling value
6016: Level: intermediate
6018: .seealso: [](ch_matrices), `Mat`, `MatDiagonalScale()`
6019: @*/
6020: PetscErrorCode MatScale(Mat mat, PetscScalar a)
6021: {
6022: PetscFunctionBegin;
6025: PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
6026: PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
6028: MatCheckPreallocated(mat, 1);
6030: PetscCall(PetscLogEventBegin(MAT_Scale, mat, 0, 0, 0));
6031: if (a != (PetscScalar)1.0) {
6032: PetscUseTypeMethod(mat, scale, a);
6033: PetscCall(PetscObjectStateIncrease((PetscObject)mat));
6034: }
6035: PetscCall(PetscLogEventEnd(MAT_Scale, mat, 0, 0, 0));
6036: PetscFunctionReturn(PETSC_SUCCESS);
6037: }
6039: /*@
6040: MatNorm - Calculates various norms of a matrix.
6042: Collective
6044: Input Parameters:
6045: + mat - the matrix
6046: - type - the type of norm, `NORM_1`, `NORM_FROBENIUS`, `NORM_INFINITY`
6048: Output Parameter:
6049: . nrm - the resulting norm
6051: Level: intermediate
6053: .seealso: [](ch_matrices), `Mat`, `MatNormApproximate()`
6054: @*/
6055: PetscErrorCode MatNorm(Mat mat, NormType type, PetscReal *nrm)
6056: {
6057: PetscFunctionBegin;
6061: PetscAssertPointer(nrm, 3);
6063: PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
6064: PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
6065: MatCheckPreallocated(mat, 1);
6067: PetscUseTypeMethod(mat, norm, type, nrm);
6068: PetscFunctionReturn(PETSC_SUCCESS);
6069: }
6071: static PetscErrorCode VecSetFinalNormApp_Private(Vec x)
6072: {
6073: PetscScalar *ax, nm1;
6074: PetscInt st, en, n;
6076: PetscFunctionBegin;
6077: PetscCall(VecGetSize(x, &n));
6078: if (n < 2) PetscFunctionReturn(PETSC_SUCCESS);
6079: nm1 = n - 1;
6080: PetscCall(VecGetOwnershipRange(x, &st, &en));
6081: PetscCall(VecGetArrayWrite(x, &ax));
6082: for (PetscInt i = st; i < en; i++) {
6083: const PetscInt ii = i - st;
6084: const PetscScalar s = i % 2 ? -1.0 : 1.0;
6086: ax[ii] = s * (1.0 + i / nm1);
6087: }
6088: PetscCall(VecRestoreArrayWrite(x, &ax));
6089: PetscFunctionReturn(PETSC_SUCCESS);
6090: }
6092: static PetscErrorCode MatNormApproximateForwardOnly_Private(Mat A, NormType normtype, PetscInt maxit, PetscBool boundtocpu, PetscReal *n)
6093: {
6094: Vec x, y;
6095: PetscReal normx, normy;
6096: PetscInt i, N;
6097: PetscRandom rnd;
6099: PetscFunctionBegin;
6100: if (maxit < 0) maxit = 1;
6101: PetscCall(PetscRandomCreate(PetscObjectComm((PetscObject)A), &rnd));
6102: PetscCall(PetscRandomSetFromOptions(rnd));
6103: PetscCall(MatCreateVecs(A, &x, &y));
6104: PetscCall(VecBindToCPU(x, boundtocpu));
6105: PetscCall(VecBindToCPU(y, boundtocpu));
6106: PetscCall(VecGetSize(x, &N));
6107: *n = 0.0;
6108: for (i = 0; i < maxit; i++) {
6109: PetscCall(VecSetRandom(x, rnd));
6110: switch (normtype) {
6111: case NORM_1:
6112: PetscCall(VecNorm(x, NORM_1, &normx));
6113: if (normx > 0.0) PetscCall(VecScale(x, 1.0 / normx));
6114: break;
6115: case NORM_INFINITY:
6116: PetscCall(VecShift(x, -0.5));
6117: PetscCall(VecPointwiseSign(x, x, VEC_SIGN_ZERO_TO_SIGNED_UNIT));
6118: break;
6119: case NORM_2:
6120: PetscCall(VecNormalize(x, NULL));
6121: break;
6122: default:
6123: PetscUnreachable();
6124: }
6125: PetscCall(MatMult(A, x, y));
6126: PetscCall(VecNorm(y, normtype, &normy));
6127: *n = PetscMax(*n, normy);
6128: PetscCall(PetscInfo(A, "%s norm forward-only sample %" PetscInt_FMT " -> %g\n", NormTypes[normtype], i, (double)normy));
6129: }
6130: PetscCall(VecDestroy(&x));
6131: PetscCall(VecDestroy(&y));
6132: PetscCall(PetscRandomDestroy(&rnd));
6133: PetscFunctionReturn(PETSC_SUCCESS);
6134: }
6136: /*@
6137: MatNormApproximate - Approximate the norm of a matrix.
6139: Collective
6141: Input Parameters:
6142: + A - the matrix
6143: . normtype - the `NormType`
6144: - maxit - maximum number of iterations to use
6146: Output Parameter:
6147: . n - the norm estimate
6149: Level: intermediate
6151: Notes:
6152: 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`.
6154: If `maxit` is negative, a default number of iterations (10 for `NORM_1` and `NORM_INFINITY` and 20 for `NORM_2`) is performed.
6156: .seealso: [](ch_matrices), `Mat`, `MatNorm()`
6157: @*/
6158: PetscErrorCode MatNormApproximate(Mat A, NormType normtype, PetscInt maxit, PetscReal *n)
6159: {
6160: Vec x, y, w, z;
6161: PetscReal normz, adot;
6162: PetscScalar dot;
6163: PetscInt i, j, N, jold = -1;
6164: PetscBool boundtocpu = PETSC_TRUE, setherm, isherm, hasop;
6166: PetscFunctionBegin;
6171: PetscAssertPointer(n, 4);
6172: #if PetscDefined(HAVE_DEVICE)
6173: boundtocpu = A->boundtocpu;
6174: #endif
6175: PetscCall(MatHasOperation(A, MATOP_MULT_HERMITIAN_TRANSPOSE, &hasop));
6176: switch (normtype) {
6177: case NORM_INFINITY:
6178: case NORM_1:
6179: if (!hasop) {
6180: PetscCall(MatNormApproximateForwardOnly_Private(A, normtype, maxit, boundtocpu, n));
6181: i = maxit;
6182: break;
6183: } else {
6184: PetscCall(MatIsHermitianKnown(A, &setherm, &isherm));
6185: if ((setherm && isherm) || normtype == NORM_1) PetscCall(PetscObjectReference((PetscObject)A));
6186: else {
6187: Mat B;
6189: PetscCall(MatCreateHermitianTranspose(A, &B));
6190: A = B;
6191: }
6192: }
6193: if (maxit < 0) maxit = 10; /* pure guess */
6194: PetscCall(MatCreateVecs(A, &x, &y));
6195: PetscCall(MatCreateVecs(A, &z, &w));
6196: PetscCall(VecBindToCPU(x, boundtocpu));
6197: PetscCall(VecBindToCPU(y, boundtocpu));
6198: PetscCall(VecBindToCPU(z, boundtocpu));
6199: PetscCall(VecBindToCPU(w, boundtocpu));
6200: PetscCall(VecGetSize(x, &N));
6201: PetscCall(VecSet(x, 1. / N));
6202: *n = 0.0;
6203: for (i = 0; i < maxit; i++) {
6204: PetscCall(MatMult(A, x, y));
6205: PetscCall(VecNorm(y, NORM_1, n));
6206: if (PetscDefined(USE_COMPLEX)) {
6207: PetscCall(VecCopy(y, w));
6208: PetscCall(VecAbs(w));
6209: PetscCall(VecPointwiseDivide(w, y, w));
6210: } else PetscCall(VecPointwiseSign(w, y, VEC_SIGN_ZERO_TO_SIGNED_UNIT));
6211: PetscCall(MatMultHermitianTranspose(A, w, z));
6212: PetscCall(VecRealPart(z));
6213: PetscCall(VecNorm(z, NORM_INFINITY, &normz));
6214: PetscCall(VecDot(x, z, &dot));
6215: adot = PetscAbsScalar(dot);
6216: PetscCall(PetscInfo(A, "%s norm it %" PetscInt_FMT " -> %g (%g %g)\n", NormTypes[normtype], i, (double)*n, (double)normz, (double)adot));
6217: if (normz <= adot && i > 0) {
6218: PetscCall(PetscInfo(A, "%s norm converged\n", NormTypes[normtype]));
6219: break;
6220: }
6221: PetscCall(VecAbs(z));
6222: PetscCall(VecMax(z, &j, &normz));
6223: if (j == jold) {
6224: PetscCall(PetscInfo(A, "%s norm it %" PetscInt_FMT " -> breakdown (j==jold)\n", NormTypes[normtype], i));
6225: break;
6226: }
6227: jold = j;
6228: if (i < maxit - 1) PetscCall(VecSetStdBasis(x, j));
6229: }
6230: /* last check */
6231: if (N > 1) {
6232: PetscReal ny;
6234: PetscCall(VecSetFinalNormApp_Private(x));
6235: PetscCall(MatMult(A, x, y));
6236: PetscCall(VecNorm(y, NORM_1, &ny));
6237: ny = 2 * ny / (3 * N);
6238: PetscCall(PetscInfo(A, "%s norm final check: current %g test %g\n", NormTypes[normtype], (double)*n, (double)ny));
6239: *n = PetscMax(*n, ny);
6240: }
6241: PetscCall(MatDestroy(&A));
6242: PetscCall(VecDestroy(&x));
6243: PetscCall(VecDestroy(&w));
6244: PetscCall(VecDestroy(&y));
6245: PetscCall(VecDestroy(&z));
6246: break;
6247: case NORM_2:
6248: if (!hasop) {
6249: PetscCall(MatNormApproximateForwardOnly_Private(A, normtype, maxit, boundtocpu, n));
6250: i = maxit;
6251: break;
6252: }
6253: if (maxit < 0) maxit = 20; /* pure guess */
6254: PetscCall(MatCreateVecs(A, &x, &y));
6255: PetscCall(MatCreateVecs(A, &z, NULL));
6256: PetscCall(VecBindToCPU(x, boundtocpu));
6257: PetscCall(VecBindToCPU(y, boundtocpu));
6258: PetscCall(VecBindToCPU(z, boundtocpu));
6259: PetscCall(VecSetRandom(x, NULL));
6260: PetscCall(VecNormalize(x, NULL));
6261: *n = 0.0;
6262: for (i = 0; i < maxit; i++) {
6263: PetscCall(MatMult(A, x, y));
6264: PetscCall(VecNormalize(y, n));
6265: PetscCall(MatMultHermitianTranspose(A, y, z));
6266: PetscCall(VecNorm(z, NORM_2, &normz));
6267: PetscCall(VecDot(x, z, &dot));
6268: adot = PetscAbsScalar(dot);
6269: PetscCall(PetscInfo(A, "%s norm it %" PetscInt_FMT " -> %g (%g %g)\n", NormTypes[normtype], i, (double)*n, (double)normz, (double)adot));
6270: if (normz <= adot) {
6271: PetscCall(PetscInfo(A, "%s norm converged\n", NormTypes[normtype]));
6272: break;
6273: }
6274: if (i < maxit - 1) {
6275: Vec t;
6277: PetscCall(VecNormalize(z, NULL));
6278: t = x;
6279: x = z;
6280: z = t;
6281: }
6282: }
6283: PetscCall(VecDestroy(&x));
6284: PetscCall(VecDestroy(&y));
6285: PetscCall(VecDestroy(&z));
6286: break;
6287: default:
6288: SETERRQ(PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "%s norm not supported", NormTypes[normtype]);
6289: }
6290: PetscCall(PetscInfo(A, "%s norm %g computed in %" PetscInt_FMT " iterations\n", NormTypes[normtype], (double)*n, i));
6291: PetscFunctionReturn(PETSC_SUCCESS);
6292: }
6294: /*
6295: This variable is used to prevent counting of MatAssemblyBegin() that
6296: are called from within a MatAssemblyEnd().
6297: */
6298: static PetscInt MatAssemblyEnd_InUse = 0;
6299: /*@
6300: MatAssemblyBegin - Begins assembling the matrix. This routine should
6301: be called after completing all calls to `MatSetValues()`.
6303: Collective
6305: Input Parameters:
6306: + mat - the matrix
6307: - type - type of assembly, either `MAT_FLUSH_ASSEMBLY` or `MAT_FINAL_ASSEMBLY`
6309: Level: beginner
6311: Notes:
6312: `MatSetValues()` generally caches the values that belong to other MPI processes. The matrix is ready to
6313: use only after `MatAssemblyBegin()` and `MatAssemblyEnd()` have been called.
6315: Use `MAT_FLUSH_ASSEMBLY` when switching between `ADD_VALUES` and `INSERT_VALUES`
6316: in `MatSetValues()`; use `MAT_FINAL_ASSEMBLY` for the final assembly before
6317: using the matrix.
6319: ALL processes that share a matrix MUST call `MatAssemblyBegin()` and `MatAssemblyEnd()` the SAME NUMBER of times, and each time with the
6320: 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
6321: a global collective operation requiring all processes that share the matrix.
6323: Space for preallocated nonzeros that is not filled by a call to `MatSetValues()` or a related routine are compressed
6324: out by assembly. If you intend to use that extra space on a subsequent assembly, be sure to insert explicit zeros
6325: before `MAT_FINAL_ASSEMBLY` so the space is not compressed out.
6327: .seealso: [](ch_matrices), `Mat`, `MatAssemblyEnd()`, `MatSetValues()`, `MatAssembled()`
6328: @*/
6329: PetscErrorCode MatAssemblyBegin(Mat mat, MatAssemblyType type)
6330: {
6331: PetscFunctionBegin;
6334: MatCheckPreallocated(mat, 1);
6335: PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix. Did you forget to call MatSetUnfactored()?");
6336: if (mat->assembled) {
6337: mat->was_assembled = PETSC_TRUE;
6338: mat->assembled = PETSC_FALSE;
6339: }
6341: if (!MatAssemblyEnd_InUse) {
6342: PetscCall(PetscLogEventBegin(MAT_AssemblyBegin, mat, 0, 0, 0));
6343: PetscTryTypeMethod(mat, assemblybegin, type);
6344: PetscCall(PetscLogEventEnd(MAT_AssemblyBegin, mat, 0, 0, 0));
6345: } else PetscTryTypeMethod(mat, assemblybegin, type);
6346: PetscFunctionReturn(PETSC_SUCCESS);
6347: }
6349: /*@
6350: MatAssembled - Indicates if a matrix has been assembled and is ready for
6351: use; for example, in matrix-vector product.
6353: Not Collective
6355: Input Parameter:
6356: . mat - the matrix
6358: Output Parameter:
6359: . assembled - `PETSC_TRUE` or `PETSC_FALSE`
6361: Level: advanced
6363: .seealso: [](ch_matrices), `Mat`, `MatAssemblyEnd()`, `MatSetValues()`, `MatAssemblyBegin()`
6364: @*/
6365: PetscErrorCode MatAssembled(Mat mat, PetscBool *assembled)
6366: {
6367: PetscFunctionBegin;
6369: PetscAssertPointer(assembled, 2);
6370: *assembled = mat->assembled;
6371: PetscFunctionReturn(PETSC_SUCCESS);
6372: }
6374: /*@
6375: MatAssemblyEnd - Completes assembling the matrix. This routine should
6376: be called after `MatAssemblyBegin()`.
6378: Collective
6380: Input Parameters:
6381: + mat - the matrix
6382: - type - type of assembly, either `MAT_FLUSH_ASSEMBLY` or `MAT_FINAL_ASSEMBLY`
6384: Options Database Key:
6385: . -mat_view viewer_specification - Displays the matrix during this function call. See `PetscOptionsCreateViewer()` for the values of `viewer_specification`
6387: Level: beginner
6389: .seealso: [](ch_matrices), `Mat`, `MatAssemblyBegin()`, `MatSetValues()`, `PetscDrawOpenX()`, `PetscDrawCreate()`, `MatView()`, `MatAssembled()`, `PetscViewerSocketOpen()`,
6390: `MatViewFromOptions()`, `PetscObjectViewFromOptions()`, `PetscOptionsCreateViewer()`
6391: @*/
6392: PetscErrorCode MatAssemblyEnd(Mat mat, MatAssemblyType type)
6393: {
6394: static PetscInt inassm = 0;
6395: PetscBool flg = PETSC_FALSE;
6397: PetscFunctionBegin;
6401: inassm++;
6402: MatAssemblyEnd_InUse++;
6403: if (MatAssemblyEnd_InUse == 1) { /* Do the logging only the first time through */
6404: PetscCall(PetscLogEventBegin(MAT_AssemblyEnd, mat, 0, 0, 0));
6405: PetscTryTypeMethod(mat, assemblyend, type);
6406: PetscCall(PetscLogEventEnd(MAT_AssemblyEnd, mat, 0, 0, 0));
6407: } else PetscTryTypeMethod(mat, assemblyend, type);
6409: /* Flush assembly is not a true assembly */
6410: if (type != MAT_FLUSH_ASSEMBLY) {
6411: if (mat->num_ass) {
6412: if (!mat->symmetry_eternal) {
6413: mat->symmetric = PETSC_BOOL3_UNKNOWN;
6414: mat->hermitian = PETSC_BOOL3_UNKNOWN;
6415: }
6416: if (!mat->structural_symmetry_eternal && mat->ass_nonzerostate != mat->nonzerostate) mat->structurally_symmetric = PETSC_BOOL3_UNKNOWN;
6417: if (!mat->spd_eternal) mat->spd = PETSC_BOOL3_UNKNOWN;
6418: }
6419: mat->num_ass++;
6420: mat->assembled = PETSC_TRUE;
6421: mat->ass_nonzerostate = mat->nonzerostate;
6422: }
6424: mat->insertmode = NOT_SET_VALUES;
6425: MatAssemblyEnd_InUse--;
6426: PetscCall(PetscObjectStateIncrease((PetscObject)mat));
6427: if (inassm == 1 && type != MAT_FLUSH_ASSEMBLY) {
6428: PetscCall(MatViewFromOptions(mat, NULL, "-mat_view"));
6430: if (mat->checksymmetryonassembly) {
6431: PetscCall(MatIsSymmetric(mat, mat->checksymmetrytol, &flg));
6432: if (flg) {
6433: PetscCall(PetscPrintf(PetscObjectComm((PetscObject)mat), "Matrix is symmetric (tolerance %g)\n", (double)mat->checksymmetrytol));
6434: } else {
6435: PetscCall(PetscPrintf(PetscObjectComm((PetscObject)mat), "Matrix is not symmetric (tolerance %g)\n", (double)mat->checksymmetrytol));
6436: }
6437: }
6438: if (mat->nullsp && mat->checknullspaceonassembly) PetscCall(MatNullSpaceTest(mat->nullsp, mat, NULL));
6439: }
6440: inassm--;
6441: PetscFunctionReturn(PETSC_SUCCESS);
6442: }
6444: // PetscClangLinter pragma disable: -fdoc-section-header-unknown
6445: /*@
6446: MatSetOption - Sets a parameter option for a matrix. Some options
6447: may be specific to certain storage formats. Some options
6448: determine how values will be inserted (or added). Sorted,
6449: row-oriented input will generally assemble the fastest. The default
6450: is row-oriented.
6452: Logically Collective for certain operations, such as `MAT_SPD`, not collective for `MAT_ROW_ORIENTED`, see `MatOption`
6454: Input Parameters:
6455: + mat - the matrix
6456: . op - the option, one of those listed below (and possibly others),
6457: - flg - turn the option on (`PETSC_TRUE`) or off (`PETSC_FALSE`)
6459: Options Describing Matrix Structure:
6460: + `MAT_SPD` - symmetric positive definite
6461: . `MAT_SYMMETRIC` - symmetric in terms of both structure and value
6462: . `MAT_HERMITIAN` - transpose is the complex conjugation
6463: . `MAT_STRUCTURALLY_SYMMETRIC` - symmetric nonzero structure
6464: . `MAT_SYMMETRY_ETERNAL` - indicates the symmetry (or Hermitian structure) or its absence will persist through any changes to the matrix
6465: . `MAT_STRUCTURAL_SYMMETRY_ETERNAL` - indicates the structural symmetry or its absence will persist through any changes to the matrix
6466: . `MAT_SPD_ETERNAL` - indicates the value of `MAT_SPD` (true or false) will persist through any changes to the matrix
6468: These are not really options of the matrix, they are knowledge about the structure of the matrix that users may provide so that they
6469: do not need to be computed (usually at a high cost)
6471: Options For Use with `MatSetValues()` and `MatGetValues()`:
6472: Insert a logically dense subblock, which can be
6473: . `MAT_ROW_ORIENTED` - row-oriented (default)
6475: These options reflect the data you pass in with `MatSetValues()` or receive with `MatGetValues()`; it has
6476: nothing to do with how the data is stored internally in the matrix
6477: data structure.
6479: When (re)assembling a matrix, we can restrict the input for
6480: efficiency/debugging purposes. These options include
6481: . `MAT_NEW_NONZERO_LOCATIONS` - additional insertions will be allowed if they generate a new nonzero (slow)
6482: . `MAT_FORCE_DIAGONAL_ENTRIES` - forces diagonal entries to be allocated
6483: . `MAT_IGNORE_OFF_PROC_ENTRIES` - drops off-process entries
6484: . `MAT_NEW_NONZERO_LOCATION_ERR` - generates an error for new matrix entry
6485: . `MAT_USE_HASH_TABLE` - uses a hash table to speed up matrix assembly
6486: . `MAT_NO_OFF_PROC_ENTRIES` - you know each process will only set values for its own rows, will generate an error if
6487: any process sets values for another process. This avoids all reductions in the MatAssembly routines and thus improves
6488: performance for very large process counts.
6489: - `MAT_SUBSET_OFF_PROC_ENTRIES` - you know that the first assembly after setting this flag will set a superset
6490: of the off-process entries required for all subsequent assemblies. This avoids a rendezvous step in the MatAssembly
6491: functions, instead sending only neighbor messages.
6493: Level: intermediate
6495: Notes:
6496: Except for `MAT_UNUSED_NONZERO_LOCATION_ERR` and `MAT_ROW_ORIENTED` all processes that share the matrix must pass the same value in flg!
6498: Some options are relevant only for particular matrix types and
6499: are thus ignored by others. Other options are not supported by
6500: certain matrix types and will generate an error message if set.
6502: Once `MAT_STRUCTURE_ONLY` has been set to `PETSC_TRUE`, it cannot be set back to `PETSC_FALSE`.
6504: The matrix properties must be consistent with one another. With real scalars, `MAT_SPD` implies `MAT_SYMMETRIC`, and
6505: both `MAT_SYMMETRIC` and `MAT_HERMITIAN` imply `MAT_STRUCTURALLY_SYMMETRIC`. Setting a property that contradicts
6506: another known property generates an error. Still with real scalars, setting either `MAT_SYMMETRIC` or `MAT_HERMITIAN`
6507: also sets the other to the same value.
6509: If using Fortran to compute a matrix, one may need to use the column-oriented
6510: option (or convert to the row-oriented format).
6512: `MAT_NEW_NONZERO_LOCATIONS` set to `PETSC_FALSE` indicates that any add or insertion
6513: that would generate a new entry in the nonzero structure is instead
6514: ignored. Thus, if memory has not already been allocated for this particular
6515: data, then the insertion is ignored. For dense matrices, in which
6516: the entire array is allocated, no entries are ever ignored.
6517: Set after the first `MatAssemblyEnd()`. If this option is set, then the `MatAssemblyBegin()`/`MatAssemblyEnd()` processes has one less global reduction
6519: `MAT_NEW_NONZERO_LOCATION_ERR` set to `PETSC_TRUE` indicates that any add or insertion
6520: that would generate a new entry in the nonzero structure instead produces
6521: 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
6523: `MAT_NEW_NONZERO_ALLOCATION_ERR` set to `PETSC_TRUE` indicates that any add or insertion
6524: that would generate a new entry that has not been preallocated will
6525: instead produce an error. (Currently supported for `MATAIJ` and `MATBAIJ` formats
6526: only.) This is a useful flag when debugging matrix memory preallocation.
6527: If this option is set, then the `MatAssemblyBegin()`/`MatAssemblyEnd()` processes has one less global reduction
6529: `MAT_IGNORE_OFF_PROC_ENTRIES` set to `PETSC_TRUE` indicates entries destined for
6530: other processes should be dropped, rather than stashed.
6531: This is useful if you know that the "owning" process is also
6532: always generating the correct matrix entries, so that PETSc need
6533: not transfer duplicate entries generated on another process.
6535: `MAT_USE_HASH_TABLE` indicates that a hash table be used to improve the
6536: searches during matrix assembly. When this flag is set, the hash table
6537: is created during the first matrix assembly. This hash table is
6538: used the next time through, during `MatSetValues()`/`MatSetValuesBlocked()`
6539: to improve the searching of indices. `MAT_NEW_NONZERO_LOCATIONS` flag
6540: should be used with `MAT_USE_HASH_TABLE` flag. This option is currently
6541: supported by `MATMPIBAIJ` format only.
6543: `MAT_KEEP_NONZERO_PATTERN` indicates when `MatZeroRows()` is called the zeroed entries
6544: are kept in the nonzero structure. This flag is not used for `MatZeroRowsColumns()`
6546: `MAT_IGNORE_ZERO_ENTRIES` - for `MATAIJ`, `MATSELL`, and `MATIS` matrices this will stop zero values
6547: from creating a zero location in the matrix. A zero on the diagonal is exempt and still creates its
6548: location, so that operations needing a full diagonal, such as `MatSOR()`, keep working. The exemption
6549: covers the diagonal portion of the owning process's rows; a zero added with `ADD_VALUES` to a row owned
6550: by another process is dropped as it is stashed and never reaches that test. A matrix assembled without
6551: preallocation, through `MatSetUp()`, decides the exemption from process-local indices, so it does not
6552: hold there when the row and column layouts differ
6554: `MAT_USE_INODES` - indicates using inode version of the code - works with `MATAIJ` matrix types
6556: `MAT_NO_OFF_PROC_ZERO_ROWS` - you know each process will only zero its own rows. This avoids all reductions in the
6557: zero row routines and thus improves performance for very large process counts.
6559: `MAT_IGNORE_LOWER_TRIANGULAR` - For `MATSBAIJ` matrices will ignore any insertions you make in the lower triangular
6560: part of the matrix (since they should match the upper triangular part).
6562: `MAT_SORTED_FULL` - each process provides exactly its local rows; all column indices for a given row are passed in a
6563: single call to `MatSetValues()`, preallocation is perfect, row-oriented, `INSERT_VALUES` is used. Common
6564: with finite difference schemes with non-periodic boundary conditions.
6566: Developer Note:
6567: `MAT_SYMMETRY_ETERNAL`, `MAT_STRUCTURAL_SYMMETRY_ETERNAL`, and `MAT_SPD_ETERNAL` are used by `MatAssemblyEnd()` and in other
6568: places where otherwise the value of `MAT_SYMMETRIC`, `MAT_STRUCTURALLY_SYMMETRIC` or `MAT_SPD` would need to be changed back
6569: to `PETSC_BOOL3_UNKNOWN` because the matrix values had changed so the code cannot be certain that the related property had
6570: not changed.
6572: .seealso: [](ch_matrices), `MatOption`, `Mat`, `MatGetOption()`
6573: @*/
6574: PetscErrorCode MatSetOption(Mat mat, MatOption op, PetscBool flg)
6575: {
6576: PetscFunctionBegin;
6578: if (op > 0) {
6581: }
6583: 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);
6585: switch (op) {
6586: case MAT_FORCE_DIAGONAL_ENTRIES:
6587: mat->force_diagonals = flg;
6588: PetscFunctionReturn(PETSC_SUCCESS);
6589: case MAT_NO_OFF_PROC_ENTRIES:
6590: mat->nooffprocentries = flg;
6591: PetscFunctionReturn(PETSC_SUCCESS);
6592: case MAT_SUBSET_OFF_PROC_ENTRIES:
6593: mat->assembly_subset = flg;
6594: if (!mat->assembly_subset) { /* See the same logic in VecAssembly wrt VEC_SUBSET_OFF_PROC_ENTRIES */
6595: #if !PetscDefined(HAVE_MPIUNI)
6596: PetscCall(MatStashScatterDestroy_BTS(&mat->stash));
6597: #endif
6598: mat->stash.first_assembly_done = PETSC_FALSE;
6599: }
6600: PetscFunctionReturn(PETSC_SUCCESS);
6601: case MAT_NO_OFF_PROC_ZERO_ROWS:
6602: mat->nooffproczerorows = flg;
6603: PetscFunctionReturn(PETSC_SUCCESS);
6604: case MAT_SPD:
6605: PetscCheck(PetscDefined(USE_COMPLEX) || !flg || mat->symmetric != PETSC_BOOL3_FALSE, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_INCOMP, "Cannot set MAT_SPD to PETSC_TRUE when MAT_SYMMETRIC is PETSC_FALSE");
6606: PetscCheck(!flg || mat->structurally_symmetric != PETSC_BOOL3_FALSE, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_INCOMP, "Cannot set MAT_SPD to PETSC_TRUE when MAT_STRUCTURALLY_SYMMETRIC is PETSC_FALSE");
6607: if (flg) {
6608: mat->spd = PETSC_BOOL3_TRUE;
6609: mat->symmetric = PETSC_BOOL3_TRUE;
6610: mat->structurally_symmetric = PETSC_BOOL3_TRUE;
6611: if (!PetscDefined(USE_COMPLEX)) mat->hermitian = PETSC_BOOL3_TRUE;
6612: } else mat->spd = PETSC_BOOL3_FALSE;
6613: break;
6614: case MAT_SYMMETRIC:
6615: PetscCheck(PetscDefined(USE_COMPLEX) || flg || mat->spd != PETSC_BOOL3_TRUE, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_INCOMP, "Cannot set MAT_SYMMETRIC to PETSC_FALSE when MAT_SPD is PETSC_TRUE");
6616: PetscCheck(!flg || mat->structurally_symmetric != PETSC_BOOL3_FALSE, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_INCOMP, "Cannot set MAT_SYMMETRIC to PETSC_TRUE when MAT_STRUCTURALLY_SYMMETRIC is PETSC_FALSE");
6617: mat->symmetric = PetscBoolToBool3(flg);
6618: if (flg) mat->structurally_symmetric = PETSC_BOOL3_TRUE;
6619: if (!PetscDefined(USE_COMPLEX)) mat->hermitian = PetscBoolToBool3(flg);
6620: break;
6621: case MAT_HERMITIAN:
6622: PetscCheck(PetscDefined(USE_COMPLEX) || flg || mat->spd != PETSC_BOOL3_TRUE, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_INCOMP, "Cannot set MAT_HERMITIAN to PETSC_FALSE when MAT_SPD is PETSC_TRUE");
6623: PetscCheck(!flg || mat->structurally_symmetric != PETSC_BOOL3_FALSE, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_INCOMP, "Cannot set MAT_HERMITIAN to PETSC_TRUE when MAT_STRUCTURALLY_SYMMETRIC is PETSC_FALSE");
6624: mat->hermitian = PetscBoolToBool3(flg);
6625: if (flg) mat->structurally_symmetric = PETSC_BOOL3_TRUE;
6626: if (!PetscDefined(USE_COMPLEX)) mat->symmetric = PetscBoolToBool3(flg);
6627: break;
6628: case MAT_STRUCTURALLY_SYMMETRIC:
6629: PetscCheck(flg || mat->spd != PETSC_BOOL3_TRUE, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_INCOMP, "Cannot set MAT_STRUCTURALLY_SYMMETRIC to PETSC_FALSE when MAT_SPD is PETSC_TRUE");
6630: PetscCheck(flg || mat->symmetric != PETSC_BOOL3_TRUE, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_INCOMP, "Cannot set MAT_STRUCTURALLY_SYMMETRIC to PETSC_FALSE when MAT_SYMMETRIC is PETSC_TRUE");
6631: PetscCheck(flg || mat->hermitian != PETSC_BOOL3_TRUE, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_INCOMP, "Cannot set MAT_STRUCTURALLY_SYMMETRIC to PETSC_FALSE when MAT_HERMITIAN is PETSC_TRUE");
6632: mat->structurally_symmetric = PetscBoolToBool3(flg);
6633: break;
6634: case MAT_SYMMETRY_ETERNAL:
6635: PetscCheck(mat->symmetric != PETSC_BOOL3_UNKNOWN, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Cannot set MAT_SYMMETRY_ETERNAL without first setting MAT_SYMMETRIC to PETSC_TRUE or PETSC_FALSE");
6636: mat->symmetry_eternal = flg;
6637: if (flg) mat->structural_symmetry_eternal = PETSC_TRUE;
6638: break;
6639: case MAT_STRUCTURAL_SYMMETRY_ETERNAL:
6640: 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 PETSC_TRUE or PETSC_FALSE");
6641: mat->structural_symmetry_eternal = flg;
6642: break;
6643: case MAT_SPD_ETERNAL:
6644: PetscCheck(mat->spd != PETSC_BOOL3_UNKNOWN, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Cannot set MAT_SPD_ETERNAL without first setting MAT_SPD to PETSC_TRUE or PETSC_FALSE");
6645: mat->spd_eternal = flg;
6646: if (flg) {
6647: mat->structural_symmetry_eternal = PETSC_TRUE;
6648: mat->symmetry_eternal = PETSC_TRUE;
6649: }
6650: break;
6651: case MAT_STRUCTURE_ONLY:
6652: PetscCheck(flg || !mat->structure_only, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Cannot set MAT_STRUCTURE_ONLY to PETSC_FALSE after it has been set to PETSC_TRUE");
6653: mat->structure_only = flg;
6654: break;
6655: case MAT_SORTED_FULL:
6656: mat->sortedfull = flg;
6657: break;
6658: default:
6659: break;
6660: }
6661: PetscCheck((op != MAT_ROW_ORIENTED) || ((PetscObject)mat)->type_name, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "The matrix type must be set (MatSetType()) before setting this option");
6662: PetscTryTypeMethod(mat, setoption, op, flg);
6663: PetscFunctionReturn(PETSC_SUCCESS);
6664: }
6666: /*@
6667: MatGetOption - Gets a parameter option that has been set for a matrix.
6669: Logically Collective
6671: Input Parameters:
6672: + mat - the matrix
6673: - op - the option, this only responds to certain options, check the code for which ones
6675: Output Parameter:
6676: . flg - turn the option on (`PETSC_TRUE`) or off (`PETSC_FALSE`)
6678: Level: intermediate
6680: Notes:
6681: Can only be called after `MatSetSizes()` and `MatSetType()` have been set.
6683: Certain option values may be unknown, for those use the routines `MatIsSymmetric()`, `MatIsHermitian()`, `MatIsStructurallySymmetric()`, or
6684: `MatIsSymmetricKnown()`, `MatIsHermitianKnown()`, `MatIsStructurallySymmetricKnown()`
6686: .seealso: [](ch_matrices), `Mat`, `MatOption`, `MatSetOption()`, `MatIsSymmetric()`, `MatIsHermitian()`, `MatIsStructurallySymmetric()`,
6687: `MatIsSymmetricKnown()`, `MatIsHermitianKnown()`, `MatIsStructurallySymmetricKnown()`
6688: @*/
6689: PetscErrorCode MatGetOption(Mat mat, MatOption op, PetscBool *flg)
6690: {
6691: PetscFunctionBegin;
6695: 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);
6696: 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()");
6698: switch (op) {
6699: case MAT_NO_OFF_PROC_ENTRIES:
6700: *flg = mat->nooffprocentries;
6701: break;
6702: case MAT_NO_OFF_PROC_ZERO_ROWS:
6703: *flg = mat->nooffproczerorows;
6704: break;
6705: case MAT_SYMMETRIC:
6706: SETERRQ(PetscObjectComm((PetscObject)mat), PETSC_ERR_SUP, "Use MatIsSymmetric() or MatIsSymmetricKnown()");
6707: break;
6708: case MAT_HERMITIAN:
6709: SETERRQ(PetscObjectComm((PetscObject)mat), PETSC_ERR_SUP, "Use MatIsHermitian() or MatIsHermitianKnown()");
6710: break;
6711: case MAT_STRUCTURALLY_SYMMETRIC:
6712: SETERRQ(PetscObjectComm((PetscObject)mat), PETSC_ERR_SUP, "Use MatIsStructurallySymmetric() or MatIsStructurallySymmetricKnown()");
6713: break;
6714: case MAT_SPD:
6715: SETERRQ(PetscObjectComm((PetscObject)mat), PETSC_ERR_SUP, "Use MatIsSPDKnown()");
6716: break;
6717: case MAT_SYMMETRY_ETERNAL:
6718: *flg = mat->symmetry_eternal;
6719: break;
6720: case MAT_STRUCTURAL_SYMMETRY_ETERNAL:
6721: *flg = mat->symmetry_eternal;
6722: break;
6723: default:
6724: break;
6725: }
6726: PetscFunctionReturn(PETSC_SUCCESS);
6727: }
6729: /*@
6730: MatZeroEntries - Zeros all entries of a matrix. For sparse matrices
6731: this routine retains the old nonzero structure.
6733: Logically Collective
6735: Input Parameter:
6736: . mat - the matrix
6738: Level: intermediate
6740: Note:
6741: 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.
6742: See the Performance chapter of the users manual for information on preallocating matrices.
6743: For matrices with the `MAT_STRUCTURE_ONLY` option set to true, this routine leaves the structure and object state unchanged because no numerical values are stored.
6745: .seealso: [](ch_matrices), `Mat`, `MatZeroRows()`, `MatZeroRowsColumns()`
6746: @*/
6747: PetscErrorCode MatZeroEntries(Mat mat)
6748: {
6749: PetscFunctionBegin;
6752: PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
6753: 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");
6754: MatCheckPreallocated(mat, 1);
6756: if (mat->structure_only == PETSC_FALSE) {
6757: PetscCall(PetscLogEventBegin(MAT_ZeroEntries, mat, 0, 0, 0));
6758: PetscUseTypeMethod(mat, zeroentries);
6759: PetscCall(PetscLogEventEnd(MAT_ZeroEntries, mat, 0, 0, 0));
6760: PetscCall(PetscObjectStateIncrease((PetscObject)mat));
6761: }
6762: PetscFunctionReturn(PETSC_SUCCESS);
6763: }
6765: /*@
6766: MatZeroRowsColumns - Zeros all entries (except possibly the main diagonal)
6767: of a set of rows and columns of a matrix.
6769: Collective
6771: Input Parameters:
6772: + mat - the matrix
6773: . numRows - the number of rows/columns to zero
6774: . rows - the global row indices
6775: . diag - value put in the diagonal of the eliminated rows
6776: . x - optional vector of the solution for zeroed rows (other entries in vector are not used), these must be set before this call
6777: - b - optional vector of the right-hand side, that will be adjusted by provided solution entries
6779: Level: intermediate
6781: Notes:
6782: This routine, along with `MatZeroRows()`, is typically used to eliminate known Dirichlet boundary conditions from a linear system.
6784: For each zeroed row, the value of the corresponding `b` is set to diag times the value of the corresponding `x`.
6785: 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
6787: If the resulting linear system is to be solved with `KSP` then one can (but does not have to) call `KSPSetInitialGuessNonzero()` to allow the
6788: Krylov method to take advantage of the known solution on the zeroed rows.
6790: For the parallel case, all processes that share the matrix (i.e.,
6791: those in the communicator used for matrix creation) MUST call this
6792: routine, regardless of whether any rows being zeroed are owned by
6793: them.
6795: Unlike `MatZeroRows()`, this ignores the `MAT_KEEP_NONZERO_PATTERN` option value set with `MatSetOption()`, it merely zeros those entries in the matrix, but never
6796: 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
6797: missing.
6799: Each process can indicate any rows in the entire matrix to be zeroed (i.e. each process does NOT have to
6800: list only rows local to itself).
6802: The option `MAT_NO_OFF_PROC_ZERO_ROWS` does not apply to this routine.
6804: .seealso: [](ch_matrices), `Mat`, `MatZeroRowsIS()`, `MatZeroRows()`, `MatZeroRowsLocalIS()`, `MatZeroRowsStencil()`, `MatZeroEntries()`, `MatZeroRowsLocal()`, `MatSetOption()`,
6805: `MatZeroRowsColumnsLocal()`, `MatZeroRowsColumnsLocalIS()`, `MatZeroRowsColumnsIS()`, `MatZeroRowsColumnsStencil()`
6806: @*/
6807: PetscErrorCode MatZeroRowsColumns(Mat mat, PetscInt numRows, const PetscInt rows[], PetscScalar diag, Vec x, Vec b)
6808: {
6809: PetscFunctionBegin;
6812: if (numRows) PetscAssertPointer(rows, 3);
6813: PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
6814: PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
6815: MatCheckPreallocated(mat, 1);
6817: PetscUseTypeMethod(mat, zerorowscolumns, numRows, rows, diag, x, b);
6818: PetscCall(MatViewFromOptions(mat, NULL, "-mat_view"));
6819: PetscCall(PetscObjectStateIncrease((PetscObject)mat));
6820: PetscFunctionReturn(PETSC_SUCCESS);
6821: }
6823: /*@
6824: MatZeroRowsColumnsIS - Zeros all entries (except possibly the main diagonal)
6825: of a set of rows and columns of a matrix.
6827: Collective
6829: Input Parameters:
6830: + mat - the matrix
6831: . is - the rows to zero
6832: . diag - value put in all diagonals of eliminated rows (0.0 will even eliminate diagonal entry)
6833: . x - optional vector of solutions for zeroed rows (other entries in vector are not used)
6834: - b - optional vector of right-hand side, that will be adjusted by provided solution
6836: Level: intermediate
6838: Note:
6839: See `MatZeroRowsColumns()` for details on how this routine operates.
6841: .seealso: [](ch_matrices), `Mat`, `MatZeroRowsIS()`, `MatZeroRowsColumns()`, `MatZeroRowsLocalIS()`, `MatZeroRowsStencil()`, `MatZeroEntries()`, `MatZeroRowsLocal()`, `MatSetOption()`,
6842: `MatZeroRowsColumnsLocal()`, `MatZeroRowsColumnsLocalIS()`, `MatZeroRows()`, `MatZeroRowsColumnsStencil()`
6843: @*/
6844: PetscErrorCode MatZeroRowsColumnsIS(Mat mat, IS is, PetscScalar diag, Vec x, Vec b)
6845: {
6846: PetscInt numRows;
6847: const PetscInt *rows;
6849: PetscFunctionBegin;
6854: PetscCall(ISGetLocalSize(is, &numRows));
6855: PetscCall(ISGetIndices(is, &rows));
6856: PetscCall(MatZeroRowsColumns(mat, numRows, rows, diag, x, b));
6857: PetscCall(ISRestoreIndices(is, &rows));
6858: PetscFunctionReturn(PETSC_SUCCESS);
6859: }
6861: /*@
6862: MatZeroRows - Zeros all entries (except possibly the main diagonal)
6863: of a set of rows of a matrix.
6865: Collective
6867: Input Parameters:
6868: + mat - the matrix
6869: . numRows - the number of rows to zero
6870: . rows - the global row indices
6871: . diag - value put in the diagonal of the zeroed rows
6872: . x - optional vector of solutions for zeroed rows (other entries in vector are not used), these must be set before this call
6873: - b - optional vector of right-hand side, that will be adjusted by provided solution entries
6875: Level: intermediate
6877: Notes:
6878: This routine, along with `MatZeroRowsColumns()`, is typically used to eliminate known Dirichlet boundary conditions from a linear system.
6880: For each zeroed row, the value of the corresponding `b` is set to `diag` times the value of the corresponding `x`.
6882: If the resulting linear system is to be solved with `KSP` then one can (but does not have to) call `KSPSetInitialGuessNonzero()` to allow the
6883: Krylov method to take advantage of the known solution on the zeroed rows.
6885: 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)
6886: from the matrix.
6888: Unlike `MatZeroRowsColumns()` for the `MATAIJ` and `MATBAIJ` matrix formats this removes the old nonzero structure, from the eliminated rows of the matrix
6889: but does not release memory. Because of this removal matrix-vector products with the adjusted matrix will be a bit faster. For the dense
6890: formats this does not alter the nonzero structure.
6892: If the option `MatSetOption`(mat,`MAT_KEEP_NONZERO_PATTERN`,`PETSC_TRUE`) the nonzero structure
6893: of the matrix is not changed the values are
6894: merely zeroed.
6896: The user can set a value in the diagonal entry (or for the `MATAIJ` format
6897: formats can optionally remove the main diagonal entry from the
6898: nonzero structure as well, by passing 0.0 as the final argument).
6900: For the parallel case, all processes that share the matrix (i.e.,
6901: those in the communicator used for matrix creation) MUST call this
6902: routine, regardless of whether any rows being zeroed are owned by
6903: them.
6905: Each process can indicate any rows in the entire matrix to be zeroed (i.e. each process does NOT have to
6906: list only rows local to itself).
6908: You can call `MatSetOption`(mat,`MAT_NO_OFF_PROC_ZERO_ROWS`,`PETSC_TRUE`) if each process indicates only rows it
6909: owns that are to be zeroed. This saves a global synchronization in the implementation.
6911: .seealso: [](ch_matrices), `Mat`, `MatZeroRowsIS()`, `MatZeroRowsColumns()`, `MatZeroRowsLocalIS()`, `MatZeroRowsStencil()`, `MatZeroEntries()`, `MatZeroRowsLocal()`, `MatSetOption()`,
6912: `MatZeroRowsColumnsLocal()`, `MatZeroRowsColumnsLocalIS()`, `MatZeroRowsColumnsIS()`, `MatZeroRowsColumnsStencil()`, `PCREDISTRIBUTE`, `MAT_KEEP_NONZERO_PATTERN`
6913: @*/
6914: PetscErrorCode MatZeroRows(Mat mat, PetscInt numRows, const PetscInt rows[], PetscScalar diag, Vec x, Vec b)
6915: {
6916: PetscFunctionBegin;
6919: if (numRows) PetscAssertPointer(rows, 3);
6920: PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
6921: PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
6922: MatCheckPreallocated(mat, 1);
6924: PetscUseTypeMethod(mat, zerorows, numRows, rows, diag, x, b);
6925: PetscCall(MatViewFromOptions(mat, NULL, "-mat_view"));
6926: PetscCall(PetscObjectStateIncrease((PetscObject)mat));
6927: PetscFunctionReturn(PETSC_SUCCESS);
6928: }
6930: /*@
6931: MatZeroRowsIS - Zeros all entries (except possibly the main diagonal)
6932: of a set of rows of a matrix indicated by an `IS`
6934: Collective
6936: Input Parameters:
6937: + mat - the matrix
6938: . is - index set, `IS`, of rows to remove (if `NULL` then no row is removed)
6939: . diag - value put in all diagonals of eliminated rows
6940: . x - optional vector of solutions for zeroed rows (other entries in vector are not used)
6941: - b - optional vector of right-hand side, that will be adjusted by provided solution
6943: Level: intermediate
6945: Note:
6946: See `MatZeroRows()` for details on how this routine operates.
6948: .seealso: [](ch_matrices), `Mat`, `MatZeroRows()`, `MatZeroRowsColumns()`, `MatZeroRowsLocalIS()`, `MatZeroRowsStencil()`, `MatZeroEntries()`, `MatZeroRowsLocal()`, `MatSetOption()`,
6949: `MatZeroRowsColumnsLocal()`, `MatZeroRowsColumnsLocalIS()`, `MatZeroRowsColumnsIS()`, `MatZeroRowsColumnsStencil()`, `IS`
6950: @*/
6951: PetscErrorCode MatZeroRowsIS(Mat mat, IS is, PetscScalar diag, Vec x, Vec b)
6952: {
6953: PetscInt numRows = 0;
6954: const PetscInt *rows = NULL;
6956: PetscFunctionBegin;
6959: if (is) {
6961: PetscCall(ISGetLocalSize(is, &numRows));
6962: PetscCall(ISGetIndices(is, &rows));
6963: }
6964: PetscCall(MatZeroRows(mat, numRows, rows, diag, x, b));
6965: if (is) PetscCall(ISRestoreIndices(is, &rows));
6966: PetscFunctionReturn(PETSC_SUCCESS);
6967: }
6969: /*@
6970: MatZeroRowsStencil - Zeros all entries (except possibly the main diagonal)
6971: of a set of rows of a matrix indicated by a `MatStencil`. These rows must be local to the process.
6973: Collective
6975: Input Parameters:
6976: + mat - the matrix
6977: . numRows - the number of rows to remove
6978: . rows - the grid coordinates (and component number when dof > 1) for matrix rows indicated by an array of `MatStencil`
6979: . diag - value put in all diagonals of eliminated rows (0.0 will even eliminate diagonal entry)
6980: . x - optional vector of solutions for zeroed rows (other entries in vector are not used)
6981: - b - optional vector of right-hand side, that will be adjusted by provided solution
6983: Level: intermediate
6985: Notes:
6986: See `MatZeroRows()` for details on how this routine operates.
6988: The grid coordinates are across the entire grid, not just the local portion
6990: For periodic boundary conditions use negative indices for values to the left (below 0; that are to be
6991: obtained by wrapping values from right edge). For values to the right of the last entry using that index plus one
6992: etc to obtain values that obtained by wrapping the values from the left edge. This does not work for anything but the
6993: `DM_BOUNDARY_PERIODIC` boundary type.
6995: 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
6996: a single value per point) you can skip filling those indices.
6998: Fortran Note:
6999: `idxm` and `idxn` should be declared as
7000: .vb
7001: MatStencil idxm(4, m)
7002: .ve
7003: and the values inserted using
7004: .vb
7005: idxm(MatStencil_i, 1) = i
7006: idxm(MatStencil_j, 1) = j
7007: idxm(MatStencil_k, 1) = k
7008: idxm(MatStencil_c, 1) = c
7009: etc
7010: .ve
7012: .seealso: [](ch_matrices), `Mat`, `MatStencil`, `MatZeroRowsIS()`, `MatZeroRowsColumns()`, `MatZeroRowsLocalIS()`, `MatZeroRows()`, `MatZeroEntries()`, `MatZeroRowsLocal()`, `MatSetOption()`,
7013: `MatZeroRowsColumnsLocal()`, `MatZeroRowsColumnsLocalIS()`, `MatZeroRowsColumnsIS()`, `MatZeroRowsColumnsStencil()`
7014: @*/
7015: PetscErrorCode MatZeroRowsStencil(Mat mat, PetscInt numRows, const MatStencil rows[], PetscScalar diag, Vec x, Vec b)
7016: {
7017: PetscInt dim = mat->stencil.dim;
7018: PetscInt sdim = dim - (1 - (PetscInt)mat->stencil.noc);
7019: PetscInt *dims = mat->stencil.dims + 1;
7020: PetscInt *starts = mat->stencil.starts;
7021: PetscInt *dxm = (PetscInt *)rows;
7022: PetscInt *jdxm, i, j, tmp, numNewRows = 0;
7024: PetscFunctionBegin;
7027: if (numRows) PetscAssertPointer(rows, 3);
7029: PetscCall(PetscMalloc1(numRows, &jdxm));
7030: for (i = 0; i < numRows; ++i) {
7031: /* Skip unused dimensions (they are ordered k, j, i, c) */
7032: for (j = 0; j < 3 - sdim; ++j) dxm++;
7033: /* Local index in X dir */
7034: tmp = *dxm++ - starts[0];
7035: /* Loop over remaining dimensions */
7036: for (j = 0; j < dim - 1; ++j) {
7037: /* If nonlocal, set index to be negative */
7038: if ((*dxm++ - starts[j + 1]) < 0 || tmp < 0) tmp = PETSC_INT_MIN;
7039: /* Update local index */
7040: else tmp = tmp * dims[j] + *(dxm - 1) - starts[j + 1];
7041: }
7042: /* Skip component slot if necessary */
7043: if (mat->stencil.noc) dxm++;
7044: /* Local row number */
7045: if (tmp >= 0) jdxm[numNewRows++] = tmp;
7046: }
7047: PetscCall(MatZeroRowsLocal(mat, numNewRows, jdxm, diag, x, b));
7048: PetscCall(PetscFree(jdxm));
7049: PetscFunctionReturn(PETSC_SUCCESS);
7050: }
7052: /*@
7053: MatZeroRowsColumnsStencil - Zeros all row and column entries (except possibly the main diagonal)
7054: of a set of rows and columns of a matrix.
7056: Collective
7058: Input Parameters:
7059: + mat - the matrix
7060: . numRows - the number of rows/columns to remove
7061: . rows - the grid coordinates (and component number when dof > 1) for matrix rows
7062: . diag - value put in all diagonals of eliminated rows (0.0 will even eliminate diagonal entry)
7063: . x - optional vector of solutions for zeroed rows (other entries in vector are not used)
7064: - b - optional vector of right-hand side, that will be adjusted by provided solution
7066: Level: intermediate
7068: Notes:
7069: See `MatZeroRowsColumns()` for details on how this routine operates.
7071: The grid coordinates are across the entire grid, not just the local portion
7073: For periodic boundary conditions use negative indices for values to the left (below 0; that are to be
7074: obtained by wrapping values from right edge). For values to the right of the last entry using that index plus one
7075: etc to obtain values that obtained by wrapping the values from the left edge. This does not work for anything but the
7076: `DM_BOUNDARY_PERIODIC` boundary type.
7078: 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
7079: a single value per point) you can skip filling those indices.
7081: Fortran Note:
7082: `idxm` and `idxn` should be declared as
7083: .vb
7084: MatStencil idxm(4, m)
7085: .ve
7086: and the values inserted using
7087: .vb
7088: idxm(MatStencil_i, 1) = i
7089: idxm(MatStencil_j, 1) = j
7090: idxm(MatStencil_k, 1) = k
7091: idxm(MatStencil_c, 1) = c
7092: etc
7093: .ve
7095: .seealso: [](ch_matrices), `Mat`, `MatZeroRowsIS()`, `MatZeroRowsColumns()`, `MatZeroRowsLocalIS()`, `MatZeroRowsStencil()`, `MatZeroEntries()`, `MatZeroRowsLocal()`, `MatSetOption()`,
7096: `MatZeroRowsColumnsLocal()`, `MatZeroRowsColumnsLocalIS()`, `MatZeroRowsColumnsIS()`, `MatZeroRows()`
7097: @*/
7098: PetscErrorCode MatZeroRowsColumnsStencil(Mat mat, PetscInt numRows, const MatStencil rows[], PetscScalar diag, Vec x, Vec b)
7099: {
7100: PetscInt dim = mat->stencil.dim;
7101: PetscInt sdim = dim - (1 - (PetscInt)mat->stencil.noc);
7102: PetscInt *dims = mat->stencil.dims + 1;
7103: PetscInt *starts = mat->stencil.starts;
7104: PetscInt *dxm = (PetscInt *)rows;
7105: PetscInt *jdxm, i, j, tmp, numNewRows = 0;
7107: PetscFunctionBegin;
7110: if (numRows) PetscAssertPointer(rows, 3);
7112: PetscCall(PetscMalloc1(numRows, &jdxm));
7113: for (i = 0; i < numRows; ++i) {
7114: /* Skip unused dimensions (they are ordered k, j, i, c) */
7115: for (j = 0; j < 3 - sdim; ++j) dxm++;
7116: /* Local index in X dir */
7117: tmp = *dxm++ - starts[0];
7118: /* Loop over remaining dimensions */
7119: for (j = 0; j < dim - 1; ++j) {
7120: /* If nonlocal, set index to be negative */
7121: if ((*dxm++ - starts[j + 1]) < 0 || tmp < 0) tmp = PETSC_INT_MIN;
7122: /* Update local index */
7123: else tmp = tmp * dims[j] + *(dxm - 1) - starts[j + 1];
7124: }
7125: /* Skip component slot if necessary */
7126: if (mat->stencil.noc) dxm++;
7127: /* Local row number */
7128: if (tmp >= 0) jdxm[numNewRows++] = tmp;
7129: }
7130: PetscCall(MatZeroRowsColumnsLocal(mat, numNewRows, jdxm, diag, x, b));
7131: PetscCall(PetscFree(jdxm));
7132: PetscFunctionReturn(PETSC_SUCCESS);
7133: }
7135: /*@
7136: MatZeroRowsLocal - Zeros all entries (except possibly the main diagonal)
7137: of a set of rows of a matrix; using local numbering of rows.
7139: Collective
7141: Input Parameters:
7142: + mat - the matrix
7143: . numRows - the number of rows to remove
7144: . rows - the local row indices
7145: . diag - value put in all diagonals of eliminated rows
7146: . x - optional vector of solutions for zeroed rows (other entries in vector are not used)
7147: - b - optional vector of right-hand side, that will be adjusted by provided solution
7149: Level: intermediate
7151: Notes:
7152: Before calling `MatZeroRowsLocal()`, the user must first set the
7153: local-to-global mapping by calling MatSetLocalToGlobalMapping(), this is often already set for matrices obtained with `DMCreateMatrix()`.
7155: See `MatZeroRows()` for details on how this routine operates.
7157: .seealso: [](ch_matrices), `Mat`, `MatZeroRowsIS()`, `MatZeroRowsColumns()`, `MatZeroRowsLocalIS()`, `MatZeroRowsStencil()`, `MatZeroEntries()`, `MatZeroRows()`, `MatSetOption()`,
7158: `MatZeroRowsColumnsLocal()`, `MatZeroRowsColumnsLocalIS()`, `MatZeroRowsColumnsIS()`, `MatZeroRowsColumnsStencil()`
7159: @*/
7160: PetscErrorCode MatZeroRowsLocal(Mat mat, PetscInt numRows, const PetscInt rows[], PetscScalar diag, Vec x, Vec b)
7161: {
7162: PetscFunctionBegin;
7165: if (numRows) PetscAssertPointer(rows, 3);
7166: PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
7167: PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
7168: MatCheckPreallocated(mat, 1);
7170: if (mat->ops->zerorowslocal) {
7171: PetscUseTypeMethod(mat, zerorowslocal, numRows, rows, diag, x, b);
7172: } else {
7173: IS is, newis;
7174: PetscInt *newRows, nl = 0;
7176: PetscCheck(mat->rmap->mapping, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Need to provide local to global mapping to matrix first");
7177: PetscCall(ISCreateGeneral(PETSC_COMM_SELF, numRows, rows, PETSC_USE_POINTER, &is));
7178: PetscCall(ISLocalToGlobalMappingApplyIS(mat->rmap->mapping, is, &newis));
7179: PetscCall(ISGetIndices(newis, (const PetscInt **)&newRows));
7180: for (PetscInt i = 0; i < numRows; i++)
7181: if (newRows[i] > -1) newRows[nl++] = newRows[i];
7182: PetscUseTypeMethod(mat, zerorows, nl, newRows, diag, x, b);
7183: PetscCall(ISRestoreIndices(newis, (const PetscInt **)&newRows));
7184: PetscCall(ISDestroy(&newis));
7185: PetscCall(ISDestroy(&is));
7186: }
7187: PetscCall(PetscObjectStateIncrease((PetscObject)mat));
7188: PetscFunctionReturn(PETSC_SUCCESS);
7189: }
7191: /*@
7192: MatZeroRowsLocalIS - Zeros all entries (except possibly the main diagonal)
7193: of a set of rows of a matrix; using local numbering of rows.
7195: Collective
7197: Input Parameters:
7198: + mat - the matrix
7199: . is - index set of rows to remove
7200: . diag - value put in all diagonals of eliminated rows
7201: . x - optional vector of solutions for zeroed rows (other entries in vector are not used)
7202: - b - optional vector of right-hand side, that will be adjusted by provided solution
7204: Level: intermediate
7206: Notes:
7207: Before calling `MatZeroRowsLocalIS()`, the user must first set the
7208: local-to-global mapping by calling `MatSetLocalToGlobalMapping()`, this is often already set for matrices obtained with `DMCreateMatrix()`.
7210: See `MatZeroRows()` for details on how this routine operates.
7212: .seealso: [](ch_matrices), `Mat`, `MatZeroRowsIS()`, `MatZeroRowsColumns()`, `MatZeroRows()`, `MatZeroRowsStencil()`, `MatZeroEntries()`, `MatZeroRowsLocal()`, `MatSetOption()`,
7213: `MatZeroRowsColumnsLocal()`, `MatZeroRowsColumnsLocalIS()`, `MatZeroRowsColumnsIS()`, `MatZeroRowsColumnsStencil()`
7214: @*/
7215: PetscErrorCode MatZeroRowsLocalIS(Mat mat, IS is, PetscScalar diag, Vec x, Vec b)
7216: {
7217: PetscInt numRows;
7218: const PetscInt *rows;
7220: PetscFunctionBegin;
7224: PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
7225: PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
7226: MatCheckPreallocated(mat, 1);
7228: PetscCall(ISGetLocalSize(is, &numRows));
7229: PetscCall(ISGetIndices(is, &rows));
7230: PetscCall(MatZeroRowsLocal(mat, numRows, rows, diag, x, b));
7231: PetscCall(ISRestoreIndices(is, &rows));
7232: PetscFunctionReturn(PETSC_SUCCESS);
7233: }
7235: /*@
7236: MatZeroRowsColumnsLocal - Zeros all entries (except possibly the main diagonal)
7237: of a set of rows and columns of a matrix; using local numbering of rows.
7239: Collective
7241: Input Parameters:
7242: + mat - the matrix
7243: . numRows - the number of rows to remove
7244: . rows - the global row indices
7245: . diag - value put in all diagonals of eliminated rows
7246: . x - optional vector of solutions for zeroed rows (other entries in vector are not used)
7247: - b - optional vector of right-hand side, that will be adjusted by provided solution
7249: Level: intermediate
7251: Notes:
7252: Before calling `MatZeroRowsColumnsLocal()`, the user must first set the
7253: local-to-global mapping by calling `MatSetLocalToGlobalMapping()`, this is often already set for matrices obtained with `DMCreateMatrix()`.
7255: See `MatZeroRowsColumns()` for details on how this routine operates.
7257: .seealso: [](ch_matrices), `Mat`, `MatZeroRowsIS()`, `MatZeroRowsColumns()`, `MatZeroRowsLocalIS()`, `MatZeroRowsStencil()`, `MatZeroEntries()`, `MatZeroRowsLocal()`, `MatSetOption()`,
7258: `MatZeroRows()`, `MatZeroRowsColumnsLocalIS()`, `MatZeroRowsColumnsIS()`, `MatZeroRowsColumnsStencil()`
7259: @*/
7260: PetscErrorCode MatZeroRowsColumnsLocal(Mat mat, PetscInt numRows, const PetscInt rows[], PetscScalar diag, Vec x, Vec b)
7261: {
7262: PetscFunctionBegin;
7265: if (numRows) PetscAssertPointer(rows, 3);
7266: PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
7267: PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
7268: MatCheckPreallocated(mat, 1);
7270: if (mat->ops->zerorowscolumnslocal) {
7271: PetscUseTypeMethod(mat, zerorowscolumnslocal, numRows, rows, diag, x, b);
7272: } else {
7273: IS is, newis;
7274: PetscInt *newRows, nl = 0;
7276: PetscCheck(mat->rmap->mapping, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Need to provide local to global mapping to matrix first");
7277: PetscCall(ISCreateGeneral(PETSC_COMM_SELF, numRows, rows, PETSC_USE_POINTER, &is));
7278: PetscCall(ISLocalToGlobalMappingApplyIS(mat->rmap->mapping, is, &newis));
7279: PetscCall(ISGetIndices(newis, (const PetscInt **)&newRows));
7280: for (PetscInt i = 0; i < numRows; i++)
7281: if (newRows[i] > -1) newRows[nl++] = newRows[i];
7282: PetscUseTypeMethod(mat, zerorowscolumns, nl, newRows, diag, x, b);
7283: PetscCall(ISRestoreIndices(newis, (const PetscInt **)&newRows));
7284: PetscCall(ISDestroy(&newis));
7285: PetscCall(ISDestroy(&is));
7286: }
7287: PetscCall(PetscObjectStateIncrease((PetscObject)mat));
7288: PetscFunctionReturn(PETSC_SUCCESS);
7289: }
7291: /*@
7292: MatZeroRowsColumnsLocalIS - Zeros all entries (except possibly the main diagonal)
7293: of a set of rows and columns of a matrix; using local numbering of rows.
7295: Collective
7297: Input Parameters:
7298: + mat - the matrix
7299: . is - index set of rows to remove
7300: . diag - value put in all diagonals of eliminated rows
7301: . x - optional vector of solutions for zeroed rows (other entries in vector are not used)
7302: - b - optional vector of right-hand side, that will be adjusted by provided solution
7304: Level: intermediate
7306: Notes:
7307: Before calling `MatZeroRowsColumnsLocalIS()`, the user must first set the
7308: local-to-global mapping by calling `MatSetLocalToGlobalMapping()`, this is often already set for matrices obtained with `DMCreateMatrix()`.
7310: See `MatZeroRowsColumns()` for details on how this routine operates.
7312: .seealso: [](ch_matrices), `Mat`, `MatZeroRowsIS()`, `MatZeroRowsColumns()`, `MatZeroRowsLocalIS()`, `MatZeroRowsStencil()`, `MatZeroEntries()`, `MatZeroRowsLocal()`, `MatSetOption()`,
7313: `MatZeroRowsColumnsLocal()`, `MatZeroRows()`, `MatZeroRowsColumnsIS()`, `MatZeroRowsColumnsStencil()`
7314: @*/
7315: PetscErrorCode MatZeroRowsColumnsLocalIS(Mat mat, IS is, PetscScalar diag, Vec x, Vec b)
7316: {
7317: PetscInt numRows;
7318: const PetscInt *rows;
7320: PetscFunctionBegin;
7324: PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
7325: PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
7326: MatCheckPreallocated(mat, 1);
7328: PetscCall(ISGetLocalSize(is, &numRows));
7329: PetscCall(ISGetIndices(is, &rows));
7330: PetscCall(MatZeroRowsColumnsLocal(mat, numRows, rows, diag, x, b));
7331: PetscCall(ISRestoreIndices(is, &rows));
7332: PetscFunctionReturn(PETSC_SUCCESS);
7333: }
7335: /*@
7336: MatGetSize - Returns the numbers of rows and columns in a matrix.
7338: Not Collective
7340: Input Parameter:
7341: . mat - the matrix
7343: Output Parameters:
7344: + m - the number of global rows
7345: - n - the number of global columns
7347: Level: beginner
7349: Note:
7350: Both output parameters can be `NULL` on input.
7352: .seealso: [](ch_matrices), `Mat`, `MatSetSizes()`, `MatGetLocalSize()`
7353: @*/
7354: PetscErrorCode MatGetSize(Mat mat, PetscInt *m, PetscInt *n)
7355: {
7356: PetscFunctionBegin;
7358: if (m) *m = mat->rmap->N;
7359: if (n) *n = mat->cmap->N;
7360: PetscFunctionReturn(PETSC_SUCCESS);
7361: }
7363: /*@
7364: MatGetLocalSize - For most matrix formats, excluding `MATELEMENTAL` and `MATSCALAPACK`, Returns the number of local rows and local columns
7365: of a matrix. For all matrices this is the local size of the left and right vectors as returned by `MatCreateVecs()`.
7367: Not Collective
7369: Input Parameter:
7370: . mat - the matrix
7372: Output Parameters:
7373: + m - the number of local rows, use `NULL` to not obtain this value
7374: - n - the number of local columns, use `NULL` to not obtain this value
7376: Level: beginner
7378: .seealso: [](ch_matrices), `Mat`, `MatSetSizes()`, `MatGetSize()`
7379: @*/
7380: PetscErrorCode MatGetLocalSize(Mat mat, PetscInt *m, PetscInt *n)
7381: {
7382: PetscFunctionBegin;
7384: if (m) PetscAssertPointer(m, 2);
7385: if (n) PetscAssertPointer(n, 3);
7386: if (m) *m = mat->rmap->n;
7387: if (n) *n = mat->cmap->n;
7388: PetscFunctionReturn(PETSC_SUCCESS);
7389: }
7391: /*@
7392: MatGetOwnershipRangeColumn - Returns the range of matrix columns associated with rows of a
7393: vector one multiplies this matrix by that are owned by this process.
7395: Not Collective, unless matrix has not been allocated, then collective
7397: Input Parameter:
7398: . mat - the matrix
7400: Output Parameters:
7401: + m - the global index of the first local column, use `NULL` to not obtain this value
7402: - n - one more than the global index of the last local column, use `NULL` to not obtain this value
7404: Level: developer
7406: Notes:
7407: If the `Mat` was obtained from a `DM` with `DMCreateMatrix()`, then the range values are determined by the specific `DM`.
7409: If the `Mat` was created directly the range values are determined by the local size passed to `MatSetSizes()` or `MatCreateAIJ()`.
7410: If `PETSC_DECIDE` was passed as the local size, then the vector uses default values for the range using `PetscSplitOwnership()`.
7412: For certain `DM`, such as `DMDA`, it is better to use `DM` specific routines, such as `DMDAGetGhostCorners()`, to determine
7413: the local values in the matrix.
7415: Returns the columns of the "diagonal block" for most sparse matrix formats. See [Matrix
7416: Layouts](sec_matlayout) for details on matrix layouts.
7418: .seealso: [](ch_matrices), `Mat`, `MatGetOwnershipRange()`, `MatGetOwnershipRanges()`, `MatGetOwnershipRangesColumn()`, `PetscLayout`,
7419: `MatSetSizes()`, `MatCreateAIJ()`, `DMDAGetGhostCorners()`, `DM`
7420: @*/
7421: PetscErrorCode MatGetOwnershipRangeColumn(Mat mat, PetscInt *m, PetscInt *n)
7422: {
7423: PetscFunctionBegin;
7426: if (m) PetscAssertPointer(m, 2);
7427: if (n) PetscAssertPointer(n, 3);
7428: MatCheckPreallocated(mat, 1);
7429: if (m) *m = mat->cmap->rstart;
7430: if (n) *n = mat->cmap->rend;
7431: PetscFunctionReturn(PETSC_SUCCESS);
7432: }
7434: /*@
7435: MatGetOwnershipRange - For matrices that own values by row, excludes `MATELEMENTAL` and `MATSCALAPACK`, returns the range of matrix rows owned by
7436: this MPI process.
7438: Not Collective
7440: Input Parameter:
7441: . mat - the matrix
7443: Output Parameters:
7444: + m - the global index of the first local row, use `NULL` to not obtain this value
7445: - n - one more than the global index of the last local row, use `NULL` to not obtain this value
7447: Level: beginner
7449: Notes:
7450: If the `Mat` was obtained from a `DM` with `DMCreateMatrix()`, then the range values are determined by the specific `DM`.
7452: If the `Mat` was created directly the range values are determined by the local size passed to `MatSetSizes()` or `MatCreateAIJ()`.
7453: If `PETSC_DECIDE` was passed as the local size, then the vector uses default values for the range using `PetscSplitOwnership()`.
7455: For certain `DM`, such as `DMDA`, it is better to use `DM` specific routines, such as `DMDAGetGhostCorners()`, to determine
7456: the local values in the matrix.
7458: The high argument is one more than the last element stored locally.
7460: For all matrices it returns the range of matrix rows associated with rows of a vector that
7461: would contain the result of a matrix vector product with this matrix. See [Matrix
7462: Layouts](sec_matlayout) for details on matrix layouts.
7464: .seealso: [](ch_matrices), `Mat`, `MatGetOwnershipRanges()`, `MatGetOwnershipRangeColumn()`, `MatGetOwnershipRangesColumn()`, `PetscSplitOwnership()`,
7465: `PetscSplitOwnershipBlock()`, `PetscLayout`, `MatSetSizes()`, `MatCreateAIJ()`, `DMDAGetGhostCorners()`, `DM`
7466: @*/
7467: PetscErrorCode MatGetOwnershipRange(Mat mat, PetscInt *m, PetscInt *n)
7468: {
7469: PetscFunctionBegin;
7472: if (m) PetscAssertPointer(m, 2);
7473: if (n) PetscAssertPointer(n, 3);
7474: MatCheckPreallocated(mat, 1);
7475: if (m) *m = mat->rmap->rstart;
7476: if (n) *n = mat->rmap->rend;
7477: PetscFunctionReturn(PETSC_SUCCESS);
7478: }
7480: /*@
7481: MatGetOwnershipRanges - For matrices that own values by row, excludes `MATELEMENTAL` and
7482: `MATSCALAPACK`, returns the range of matrix rows owned by each process.
7484: Not Collective, unless matrix has not been allocated
7486: Input Parameter:
7487: . mat - the matrix
7489: Output Parameter:
7490: . ranges - start of each process's portion plus one more than the total length at the end, of length `size` + 1
7491: where `size` is the number of MPI processes used by `mat`
7493: Level: beginner
7495: Notes:
7496: If the `Mat` was obtained from a `DM` with `DMCreateMatrix()`, then the range values are determined by the specific `DM`.
7498: If the `Mat` was created directly the range values are determined by the local size passed to `MatSetSizes()` or `MatCreateAIJ()`.
7499: If `PETSC_DECIDE` was passed as the local size, then the vector uses default values for the range using `PetscSplitOwnership()`.
7501: For certain `DM`, such as `DMDA`, it is better to use `DM` specific routines, such as `DMDAGetGhostCorners()`, to determine
7502: the local values in the matrix.
7504: For all matrices it returns the ranges of matrix rows associated with rows of a vector that
7505: would contain the result of a matrix vector product with this matrix. See [Matrix
7506: Layouts](sec_matlayout) for details on matrix layouts.
7508: .seealso: [](ch_matrices), `Mat`, `MatGetOwnershipRange()`, `MatGetOwnershipRangeColumn()`, `MatGetOwnershipRangesColumn()`, `PetscLayout`,
7509: `PetscSplitOwnership()`, `PetscSplitOwnershipBlock()`, `MatSetSizes()`, `MatCreateAIJ()`,
7510: `DMDAGetGhostCorners()`, `DM`
7511: @*/
7512: PetscErrorCode MatGetOwnershipRanges(Mat mat, const PetscInt *ranges[])
7513: {
7514: PetscFunctionBegin;
7517: MatCheckPreallocated(mat, 1);
7518: PetscCall(PetscLayoutGetRanges(mat->rmap, ranges));
7519: PetscFunctionReturn(PETSC_SUCCESS);
7520: }
7522: /*@
7523: MatGetOwnershipRangesColumn - Returns the ranges of matrix columns associated with rows of a
7524: vector one multiplies this vector by that are owned by each process.
7526: Not Collective, unless matrix has not been allocated
7528: Input Parameter:
7529: . mat - the matrix
7531: Output Parameter:
7532: . ranges - start of each process's portion plus one more than the total length at the end
7534: Level: beginner
7536: Notes:
7537: If the `Mat` was obtained from a `DM` with `DMCreateMatrix()`, then the range values are determined by the specific `DM`.
7539: If the `Mat` was created directly the range values are determined by the local size passed to `MatSetSizes()` or `MatCreateAIJ()`.
7540: If `PETSC_DECIDE` was passed as the local size, then the vector uses default values for the range using `PetscSplitOwnership()`.
7542: For certain `DM`, such as `DMDA`, it is better to use `DM` specific routines, such as `DMDAGetGhostCorners()`, to determine
7543: the local values in the matrix.
7545: Returns the columns of the "diagonal blocks", for most sparse matrix formats. See [Matrix
7546: Layouts](sec_matlayout) for details on matrix layouts.
7548: .seealso: [](ch_matrices), `Mat`, `MatGetOwnershipRange()`, `MatGetOwnershipRangeColumn()`, `MatGetOwnershipRanges()`,
7549: `PetscSplitOwnership()`, `PetscSplitOwnershipBlock()`, `PetscLayout`, `MatSetSizes()`, `MatCreateAIJ()`,
7550: `DMDAGetGhostCorners()`, `DM`
7551: @*/
7552: PetscErrorCode MatGetOwnershipRangesColumn(Mat mat, const PetscInt *ranges[])
7553: {
7554: PetscFunctionBegin;
7557: MatCheckPreallocated(mat, 1);
7558: PetscCall(PetscLayoutGetRanges(mat->cmap, ranges));
7559: PetscFunctionReturn(PETSC_SUCCESS);
7560: }
7562: /*@
7563: MatGetOwnershipIS - Get row and column ownership of a matrices' values as index sets.
7565: Not Collective
7567: Input Parameter:
7568: . A - matrix
7570: Output Parameters:
7571: + rows - rows in which this process owns elements, , use `NULL` to not obtain this value
7572: - cols - columns in which this process owns elements, use `NULL` to not obtain this value
7574: Level: intermediate
7576: Note:
7577: You should call `ISDestroy()` on the returned `IS`
7579: For most matrices, excluding `MATELEMENTAL` and `MATSCALAPACK`, this corresponds to values
7580: returned by `MatGetOwnershipRange()`, `MatGetOwnershipRangeColumn()`. For `MATELEMENTAL` and
7581: `MATSCALAPACK` the ownership is more complicated. See [Matrix Layouts](sec_matlayout) for
7582: details on matrix layouts.
7584: .seealso: [](ch_matrices), `IS`, `Mat`, `MatGetOwnershipRanges()`, `MatSetValues()`, `MATELEMENTAL`, `MATSCALAPACK`
7585: @*/
7586: PetscErrorCode MatGetOwnershipIS(Mat A, IS *rows, IS *cols)
7587: {
7588: PetscErrorCode (*f)(Mat, IS *, IS *);
7590: PetscFunctionBegin;
7593: MatCheckPreallocated(A, 1);
7594: PetscCall(PetscObjectQueryFunction((PetscObject)A, "MatGetOwnershipIS_C", &f));
7595: if (f) {
7596: PetscCall((*f)(A, rows, cols));
7597: } else { /* Create a standard row-based partition, each process is responsible for ALL columns in their row block */
7598: if (rows) PetscCall(ISCreateStride(PETSC_COMM_SELF, A->rmap->n, A->rmap->rstart, 1, rows));
7599: if (cols) PetscCall(ISCreateStride(PETSC_COMM_SELF, A->cmap->N, 0, 1, cols));
7600: }
7601: PetscFunctionReturn(PETSC_SUCCESS);
7602: }
7604: /*@
7605: MatILUFactorSymbolic - Performs symbolic ILU factorization of a matrix obtained with `MatGetFactor()`
7606: Uses levels of fill only, not drop tolerance. Use `MatLUFactorNumeric()`
7607: to complete the factorization.
7609: Collective
7611: Input Parameters:
7612: + fact - the factorized matrix obtained with `MatGetFactor()`
7613: . mat - the matrix
7614: . row - row permutation
7615: . col - column permutation
7616: - info - structure containing
7617: .vb
7618: levels - number of levels of fill.
7619: expected fill - as ratio of original fill.
7620: 1 or 0 - indicating force fill on diagonal (improves robustness for matrices
7621: missing diagonal entries)
7622: .ve
7624: Level: developer
7626: Notes:
7627: See [Matrix Factorization](sec_matfactor) for additional information.
7629: Most users should employ the `KSP` interface for linear solvers
7630: instead of working directly with matrix algebra routines such as this.
7631: See, e.g., `KSPCreate()`.
7633: Uses the definition of level of fill as in Y. Saad, {cite}`saad2003`
7635: Fortran Note:
7636: A valid (non-null) `info` argument must be provided
7638: .seealso: [](ch_matrices), `Mat`, [Matrix Factorization](sec_matfactor), `MatGetFactor()`, `MatLUFactorSymbolic()`, `MatLUFactorNumeric()`, `MatCholeskyFactor()`,
7639: `MatGetOrdering()`, `MatFactorInfo`
7640: @*/
7641: PetscErrorCode MatILUFactorSymbolic(Mat fact, Mat mat, IS row, IS col, const MatFactorInfo *info)
7642: {
7643: PetscFunctionBegin;
7648: PetscAssertPointer(info, 5);
7649: PetscAssertPointer(fact, 1);
7650: PetscCheck(info->levels >= 0, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_OUTOFRANGE, "Levels of fill negative %" PetscInt_FMT, (PetscInt)info->levels);
7651: PetscCheck(info->fill >= 1.0, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_OUTOFRANGE, "Expected fill less than 1.0 %g", (double)info->fill);
7652: PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
7653: PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
7654: MatCheckPreallocated(mat, 2);
7656: if (!fact->trivialsymbolic) PetscCall(PetscLogEventBegin(MAT_ILUFactorSymbolic, mat, row, col, 0));
7657: PetscUseTypeMethod(fact, ilufactorsymbolic, mat, row, col, info);
7658: if (!fact->trivialsymbolic) PetscCall(PetscLogEventEnd(MAT_ILUFactorSymbolic, mat, row, col, 0));
7659: PetscFunctionReturn(PETSC_SUCCESS);
7660: }
7662: /*@
7663: MatICCFactorSymbolic - Performs symbolic incomplete
7664: Cholesky factorization for a symmetric matrix. Use
7665: `MatCholeskyFactorNumeric()` to complete the factorization.
7667: Collective
7669: Input Parameters:
7670: + fact - the factorized matrix obtained with `MatGetFactor()`
7671: . mat - the matrix to be factored
7672: . perm - row and column permutation
7673: - info - structure containing
7674: .vb
7675: levels - number of levels of fill.
7676: expected fill - as ratio of original fill.
7677: .ve
7679: Level: developer
7681: Notes:
7682: Most users should employ the `KSP` interface for linear solvers
7683: instead of working directly with matrix algebra routines such as this.
7684: See, e.g., `KSPCreate()`.
7686: This uses the definition of level of fill as in Y. Saad {cite}`saad2003`
7688: Fortran Note:
7689: A valid (non-null) `info` argument must be provided
7691: .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatCholeskyFactorNumeric()`, `MatCholeskyFactor()`, `MatFactorInfo`
7692: @*/
7693: PetscErrorCode MatICCFactorSymbolic(Mat fact, Mat mat, IS perm, const MatFactorInfo *info)
7694: {
7695: PetscFunctionBegin;
7699: PetscAssertPointer(info, 4);
7700: PetscAssertPointer(fact, 1);
7701: PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
7702: PetscCheck(info->levels >= 0, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_OUTOFRANGE, "Levels negative %" PetscInt_FMT, (PetscInt)info->levels);
7703: PetscCheck(info->fill >= 1.0, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_OUTOFRANGE, "Expected fill less than 1.0 %g", (double)info->fill);
7704: PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
7705: MatCheckPreallocated(mat, 2);
7707: if (!fact->trivialsymbolic) PetscCall(PetscLogEventBegin(MAT_ICCFactorSymbolic, mat, perm, 0, 0));
7708: PetscUseTypeMethod(fact, iccfactorsymbolic, mat, perm, info);
7709: if (!fact->trivialsymbolic) PetscCall(PetscLogEventEnd(MAT_ICCFactorSymbolic, mat, perm, 0, 0));
7710: PetscFunctionReturn(PETSC_SUCCESS);
7711: }
7713: /*@
7714: MatCreateSubMatrices - Extracts several submatrices from a matrix. If submat
7715: points to an array of valid matrices, they may be reused to store the new
7716: submatrices.
7718: Collective
7720: Input Parameters:
7721: + mat - the matrix
7722: . n - the number of submatrixes to be extracted (on this process, may be zero)
7723: . irow - index set of rows to extract
7724: . icol - index set of columns to extract
7725: - scall - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`
7727: Output Parameter:
7728: . submat - the array of submatrices
7730: Level: advanced
7732: Notes:
7733: `MatCreateSubMatrices()` can extract ONLY sequential submatrices
7734: (from both sequential and parallel matrices). Use `MatCreateSubMatrix()`
7735: to extract a parallel submatrix.
7737: Some matrix types place restrictions on the row and column
7738: indices, such as that they be sorted or that they be equal to each other.
7739: `MATSEQSBAIJ` inputs may produce `MATSEQBAIJ` submatrices when the row and column index sets do not preserve symmetry.
7741: The index sets may not have duplicate entries.
7743: When extracting submatrices from a parallel matrix, each process can
7744: form a different submatrix by setting the rows and columns of its
7745: individual index sets according to the local submatrix desired.
7747: When finished using the submatrices, the user should destroy
7748: them with `MatDestroySubMatrices()`.
7750: `MAT_REUSE_MATRIX` can only be used when the nonzero structure of the
7751: original matrix has not changed from that last call to `MatCreateSubMatrices()`.
7753: This routine creates the matrices in submat; you should NOT create them before
7754: calling it. It also allocates the array of matrix pointers submat.
7756: For `MATBAIJ` matrices the index sets must respect the block structure, that is if they
7757: request one row/column in a block, they must request all rows/columns that are in
7758: that block. For example, if the block size is 2 you cannot request just row 0 and
7759: column 0.
7761: Fortran Note:
7762: .vb
7763: Mat, pointer :: submat(:)
7764: .ve
7766: .seealso: [](ch_matrices), `Mat`, `MatDestroySubMatrices()`, `MatCreateSubMatrix()`, `MatGetRow()`, `MatGetDiagonal()`, `MatReuse`
7767: @*/
7768: PetscErrorCode MatCreateSubMatrices(Mat mat, PetscInt n, const IS irow[], const IS icol[], MatReuse scall, Mat *submat[])
7769: {
7770: PetscInt i;
7771: PetscBool eq;
7773: PetscFunctionBegin;
7776: if (n) {
7777: PetscAssertPointer(irow, 3);
7779: PetscAssertPointer(icol, 4);
7781: }
7782: PetscAssertPointer(submat, 6);
7783: if (n && scall == MAT_REUSE_MATRIX) {
7784: PetscAssertPointer(*submat, 6);
7786: }
7787: PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
7788: PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
7789: MatCheckPreallocated(mat, 1);
7790: PetscCall(PetscLogEventBegin(MAT_CreateSubMats, mat, 0, 0, 0));
7791: PetscUseTypeMethod(mat, createsubmatrices, n, irow, icol, scall, submat);
7792: PetscCall(PetscLogEventEnd(MAT_CreateSubMats, mat, 0, 0, 0));
7793: for (i = 0; i < n; i++) {
7794: (*submat)[i]->factortype = MAT_FACTOR_NONE; /* in case in place factorization was previously done on submatrix */
7795: PetscCall(ISEqualUnsorted(irow[i], icol[i], &eq));
7796: if (eq) PetscCall(MatPropagateSymmetryOptions(mat, (*submat)[i]));
7797: #if PetscDefined(HAVE_VIENNACL) || PetscDefined(HAVE_CUDA) || PetscDefined(HAVE_HIP)
7798: if (mat->boundtocpu && mat->bindingpropagates) {
7799: PetscCall(MatBindToCPU((*submat)[i], PETSC_TRUE));
7800: PetscCall(MatSetBindingPropagates((*submat)[i], PETSC_TRUE));
7801: }
7802: #endif
7803: }
7804: PetscFunctionReturn(PETSC_SUCCESS);
7805: }
7807: /*@
7808: MatCreateSubMatricesMPI - Extracts MPI submatrices across a sub communicator of `mat` (by pairs of `IS` that may live on subcomms).
7810: Collective
7812: Input Parameters:
7813: + mat - the matrix
7814: . n - the number of submatrixes to be extracted
7815: . irow - index set of rows to extract
7816: . icol - index set of columns to extract
7817: - scall - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`
7819: Output Parameter:
7820: . submat - the array of submatrices
7822: Level: advanced
7824: Note:
7825: This is used by `PCGASM`
7827: .seealso: [](ch_matrices), `Mat`, `PCGASM`, `MatCreateSubMatrices()`, `MatCreateSubMatrix()`, `MatGetRow()`, `MatGetDiagonal()`, `MatReuse`
7828: @*/
7829: PetscErrorCode MatCreateSubMatricesMPI(Mat mat, PetscInt n, const IS irow[], const IS icol[], MatReuse scall, Mat *submat[])
7830: {
7831: PetscInt i;
7832: PetscBool eq;
7834: PetscFunctionBegin;
7837: if (n) {
7838: PetscAssertPointer(irow, 3);
7840: PetscAssertPointer(icol, 4);
7842: }
7843: PetscAssertPointer(submat, 6);
7844: if (n && scall == MAT_REUSE_MATRIX) {
7845: PetscAssertPointer(*submat, 6);
7847: }
7848: PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
7849: PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
7850: MatCheckPreallocated(mat, 1);
7852: PetscCall(PetscLogEventBegin(MAT_CreateSubMats, mat, 0, 0, 0));
7853: PetscUseTypeMethod(mat, createsubmatricesmpi, n, irow, icol, scall, submat);
7854: PetscCall(PetscLogEventEnd(MAT_CreateSubMats, mat, 0, 0, 0));
7855: for (i = 0; i < n; i++) {
7856: PetscCall(ISEqualUnsorted(irow[i], icol[i], &eq));
7857: if (eq) PetscCall(MatPropagateSymmetryOptions(mat, (*submat)[i]));
7858: }
7859: PetscFunctionReturn(PETSC_SUCCESS);
7860: }
7862: /*@
7863: MatDestroyMatrices - Destroys an array of matrices
7865: Collective
7867: Input Parameters:
7868: + n - the number of local matrices
7869: - mat - the matrices (this is a pointer to the array of matrices)
7871: Level: advanced
7873: Notes:
7874: Frees not only the matrices, but also the array that contains the matrices
7876: For matrices obtained with `MatCreateSubMatrices()` use `MatDestroySubMatrices()`
7878: .seealso: [](ch_matrices), `Mat`, `MatCreateSubMatrices()`, `MatDestroySubMatrices()`
7879: @*/
7880: PetscErrorCode MatDestroyMatrices(PetscInt n, Mat *mat[])
7881: {
7882: PetscInt i;
7884: PetscFunctionBegin;
7885: if (!*mat) PetscFunctionReturn(PETSC_SUCCESS);
7886: PetscCheck(n >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Trying to destroy negative number of matrices %" PetscInt_FMT, n);
7887: PetscAssertPointer(mat, 2);
7889: for (i = 0; i < n; i++) PetscCall(MatDestroy(&(*mat)[i]));
7891: /* memory is allocated even if n = 0 */
7892: PetscCall(PetscFree(*mat));
7893: PetscFunctionReturn(PETSC_SUCCESS);
7894: }
7896: /*@
7897: MatDestroySubMatrices - Destroys a set of matrices obtained with `MatCreateSubMatrices()`.
7899: Collective
7901: Input Parameters:
7902: + n - the number of local matrices
7903: - mat - the matrices (this is a pointer to the array of matrices, to match the calling sequence of `MatCreateSubMatrices()`)
7905: Level: advanced
7907: Note:
7908: Frees not only the matrices, but also the array that contains the matrices
7910: .seealso: [](ch_matrices), `Mat`, `MatCreateSubMatrices()`, `MatDestroyMatrices()`
7911: @*/
7912: PetscErrorCode MatDestroySubMatrices(PetscInt n, Mat *mat[])
7913: {
7914: Mat mat0;
7916: PetscFunctionBegin;
7917: if (!*mat) PetscFunctionReturn(PETSC_SUCCESS);
7918: /* mat[] is an array of length n+1, see MatCreateSubMatrices_xxx() */
7919: PetscCheck(n >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Trying to destroy negative number of matrices %" PetscInt_FMT, n);
7920: PetscAssertPointer(mat, 2);
7922: mat0 = (*mat)[0];
7923: if (mat0 && mat0->ops->destroysubmatrices) {
7924: PetscCall((*mat0->ops->destroysubmatrices)(n, mat));
7925: } else {
7926: PetscCall(MatDestroyMatrices(n, mat));
7927: }
7928: PetscFunctionReturn(PETSC_SUCCESS);
7929: }
7931: /*@
7932: MatGetSeqNonzeroStructure - Extracts the nonzero structure from a matrix and stores it, in its entirety, on each process
7934: Collective
7936: Input Parameter:
7937: . mat - the matrix
7939: Output Parameter:
7940: . matstruct - the sequential matrix with the nonzero structure of `mat`
7942: Level: developer
7944: .seealso: [](ch_matrices), `Mat`, `MatDestroySeqNonzeroStructure()`, `MatCreateSubMatrices()`, `MatDestroyMatrices()`
7945: @*/
7946: PetscErrorCode MatGetSeqNonzeroStructure(Mat mat, Mat *matstruct)
7947: {
7948: PetscFunctionBegin;
7950: PetscAssertPointer(matstruct, 2);
7953: PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
7954: MatCheckPreallocated(mat, 1);
7956: PetscCall(PetscLogEventBegin(MAT_GetSeqNonzeroStructure, mat, 0, 0, 0));
7957: PetscUseTypeMethod(mat, getseqnonzerostructure, matstruct);
7958: PetscCall(PetscLogEventEnd(MAT_GetSeqNonzeroStructure, mat, 0, 0, 0));
7959: PetscFunctionReturn(PETSC_SUCCESS);
7960: }
7962: /*@
7963: MatDestroySeqNonzeroStructure - Destroys matrix obtained with `MatGetSeqNonzeroStructure()`.
7965: Collective
7967: Input Parameter:
7968: . mat - the matrix
7970: Level: advanced
7972: Note:
7973: This is not needed, one can just call `MatDestroy()`
7975: .seealso: [](ch_matrices), `Mat`, `MatGetSeqNonzeroStructure()`
7976: @*/
7977: PetscErrorCode MatDestroySeqNonzeroStructure(Mat *mat)
7978: {
7979: PetscFunctionBegin;
7980: PetscAssertPointer(mat, 1);
7981: PetscCall(MatDestroy(mat));
7982: PetscFunctionReturn(PETSC_SUCCESS);
7983: }
7985: /*@
7986: MatIncreaseOverlap - Given a set of submatrices indicated by index sets,
7987: replaces the index sets by larger ones that represent submatrices with
7988: additional overlap.
7990: Collective
7992: Input Parameters:
7993: + mat - the matrix
7994: . n - the number of index sets
7995: . is - the array of index sets (these index sets will changed during the call)
7996: - ov - the additional overlap requested
7998: Options Database Key:
7999: . -mat_increase_overlap_scalable - use a scalable algorithm to compute the overlap (supported by MPIAIJ matrix)
8001: Level: developer
8003: Note:
8004: The computed overlap preserves the matrix block sizes when the blocks are square.
8005: That is: if a matrix nonzero for a given block would increase the overlap all columns associated with
8006: that block are included in the overlap regardless of whether each specific column would increase the overlap.
8008: .seealso: [](ch_matrices), `Mat`, `PCASM`, `MatSetBlockSize()`, `MatIncreaseOverlapSplit()`, `MatCreateSubMatrices()`
8009: @*/
8010: PetscErrorCode MatIncreaseOverlap(Mat mat, PetscInt n, IS is[], PetscInt ov)
8011: {
8012: PetscInt i, bs, cbs;
8014: PetscFunctionBegin;
8018: PetscCheck(n >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Must have one or more domains, you have %" PetscInt_FMT, n);
8019: if (n) {
8020: PetscAssertPointer(is, 3);
8022: }
8023: PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
8024: PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
8025: MatCheckPreallocated(mat, 1);
8027: if (!ov || !n) PetscFunctionReturn(PETSC_SUCCESS);
8028: PetscCall(PetscLogEventBegin(MAT_IncreaseOverlap, mat, 0, 0, 0));
8029: PetscUseTypeMethod(mat, increaseoverlap, n, is, ov);
8030: PetscCall(PetscLogEventEnd(MAT_IncreaseOverlap, mat, 0, 0, 0));
8031: PetscCall(MatGetBlockSizes(mat, &bs, &cbs));
8032: if (bs == cbs) {
8033: for (i = 0; i < n; i++) PetscCall(ISSetBlockSize(is[i], bs));
8034: }
8035: PetscFunctionReturn(PETSC_SUCCESS);
8036: }
8038: PetscErrorCode MatIncreaseOverlapSplit_Single(Mat, IS *, PetscInt);
8040: /*@
8041: MatIncreaseOverlapSplit - Given a set of submatrices indicated by index sets across
8042: a sub communicator, replaces the index sets by larger ones that represent submatrices with
8043: additional overlap.
8045: Collective
8047: Input Parameters:
8048: + mat - the matrix
8049: . n - the number of index sets
8050: . is - the array of index sets (these index sets will changed during the call)
8051: - ov - the additional overlap requested
8053: ` Options Database Key:
8054: . -mat_increase_overlap_scalable - use a scalable algorithm to compute the overlap (supported by MPIAIJ matrix)
8056: Level: developer
8058: .seealso: [](ch_matrices), `Mat`, `MatCreateSubMatrices()`, `MatIncreaseOverlap()`
8059: @*/
8060: PetscErrorCode MatIncreaseOverlapSplit(Mat mat, PetscInt n, IS is[], PetscInt ov)
8061: {
8062: PetscInt i;
8064: PetscFunctionBegin;
8067: PetscCheck(n >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Must have one or more domains, you have %" PetscInt_FMT, n);
8068: if (n) {
8069: PetscAssertPointer(is, 3);
8071: }
8072: PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
8073: PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
8074: MatCheckPreallocated(mat, 1);
8075: if (!ov) PetscFunctionReturn(PETSC_SUCCESS);
8076: PetscCall(PetscLogEventBegin(MAT_IncreaseOverlap, mat, 0, 0, 0));
8077: for (i = 0; i < n; i++) PetscCall(MatIncreaseOverlapSplit_Single(mat, &is[i], ov));
8078: PetscCall(PetscLogEventEnd(MAT_IncreaseOverlap, mat, 0, 0, 0));
8079: PetscFunctionReturn(PETSC_SUCCESS);
8080: }
8082: /*@
8083: MatGetBlockSize - Returns the matrix block size.
8085: Not Collective
8087: Input Parameter:
8088: . mat - the matrix
8090: Output Parameter:
8091: . bs - block size
8093: Level: intermediate
8095: Notes:
8096: Block row formats are `MATBAIJ` and `MATSBAIJ` ALWAYS have square block storage in the matrix.
8098: If the block size has not been set yet this routine returns 1.
8100: .seealso: [](ch_matrices), `Mat`, `MATBAIJ`, `MATSBAIJ`, `MatCreateSeqBAIJ()`, `MatCreateBAIJ()`, `MatGetBlockSizes()`
8101: @*/
8102: PetscErrorCode MatGetBlockSize(Mat mat, PetscInt *bs)
8103: {
8104: PetscFunctionBegin;
8106: PetscAssertPointer(bs, 2);
8107: *bs = mat->rmap->bs;
8108: PetscFunctionReturn(PETSC_SUCCESS);
8109: }
8111: /*@
8112: MatGetBlockSizes - Returns the matrix block row and column sizes.
8114: Not Collective
8116: Input Parameter:
8117: . mat - the matrix
8119: Output Parameters:
8120: + rbs - row block size
8121: - cbs - column block size
8123: Level: intermediate
8125: Notes:
8126: Block row formats are `MATBAIJ` and `MATSBAIJ` ALWAYS have square block storage in the matrix.
8127: If you pass a different block size for the columns than the rows, the row block size determines the square block storage.
8129: If a block size has not been set yet this routine returns 1.
8131: .seealso: [](ch_matrices), `Mat`, `MATBAIJ`, `MATSBAIJ`, `MatCreateSeqBAIJ()`, `MatCreateBAIJ()`, `MatGetBlockSize()`, `MatSetBlockSize()`, `MatSetBlockSizes()`
8132: @*/
8133: PetscErrorCode MatGetBlockSizes(Mat mat, PetscInt *rbs, PetscInt *cbs)
8134: {
8135: PetscFunctionBegin;
8137: if (rbs) PetscAssertPointer(rbs, 2);
8138: if (cbs) PetscAssertPointer(cbs, 3);
8139: if (rbs) *rbs = mat->rmap->bs;
8140: if (cbs) *cbs = mat->cmap->bs;
8141: PetscFunctionReturn(PETSC_SUCCESS);
8142: }
8144: /*@
8145: MatSetBlockSize - Sets the matrix block size.
8147: Logically Collective
8149: Input Parameters:
8150: + mat - the matrix
8151: - bs - block size
8153: Level: intermediate
8155: Notes:
8156: Block row formats are `MATBAIJ` and `MATSBAIJ` formats ALWAYS have square block storage in the matrix.
8157: This must be called before `MatSetUp()` or MatXXXSetPreallocation() (or will default to 1) and the block size cannot be changed later.
8159: For `MATAIJ` matrix format, this function can be called at a later stage, provided that the specified block size
8160: is compatible with the matrix local sizes.
8162: .seealso: [](ch_matrices), `Mat`, `MATBAIJ`, `MATSBAIJ`, `MATAIJ`, `MatCreateSeqBAIJ()`, `MatCreateBAIJ()`, `MatGetBlockSize()`, `MatSetBlockSizes()`, `MatGetBlockSizes()`
8163: @*/
8164: PetscErrorCode MatSetBlockSize(Mat mat, PetscInt bs)
8165: {
8166: PetscFunctionBegin;
8169: PetscCall(MatSetBlockSizes(mat, bs, bs));
8170: PetscFunctionReturn(PETSC_SUCCESS);
8171: }
8173: typedef struct {
8174: PetscInt n;
8175: IS *is;
8176: Mat *mat;
8177: PetscObjectState nonzerostate;
8178: Mat C;
8179: } EnvelopeData;
8181: static PetscErrorCode EnvelopeDataDestroy(PetscCtxRt ptr)
8182: {
8183: EnvelopeData *edata = *(EnvelopeData **)ptr;
8185: PetscFunctionBegin;
8186: for (PetscInt i = 0; i < edata->n; i++) PetscCall(ISDestroy(&edata->is[i]));
8187: PetscCall(PetscFree(edata->is));
8188: PetscCall(PetscFree(edata));
8189: PetscFunctionReturn(PETSC_SUCCESS);
8190: }
8192: /*@
8193: MatComputeVariableBlockEnvelope - Given a matrix whose nonzeros are in blocks along the diagonal this computes and stores
8194: the sizes of these blocks in the matrix. An individual block may lie over several processes.
8196: Collective
8198: Input Parameter:
8199: . mat - the matrix
8201: Level: intermediate
8203: Notes:
8204: There can be zeros within the blocks
8206: The blocks can overlap between processes, including laying on more than two processes
8208: .seealso: [](ch_matrices), `Mat`, `MatInvertVariableBlockEnvelope()`, `MatSetVariableBlockSizes()`
8209: @*/
8210: PetscErrorCode MatComputeVariableBlockEnvelope(Mat mat)
8211: {
8212: PetscInt n, *sizes, *starts, i = 0, env = 0, tbs = 0, lblocks = 0, rstart, II, ln = 0, cnt = 0, cstart, cend;
8213: PetscInt *diag, *odiag, sc;
8214: PetscInt *seqv, *parv, *gidx;
8215: const PetscInt *ia, *ja;
8216: PetscBool set, flag, done;
8217: Mat AA = mat, A;
8218: MPI_Comm comm;
8219: PetscMPIInt rank, size, tag;
8220: MPI_Status status;
8221: PetscContainer container;
8222: EnvelopeData *edata;
8223: PetscSF sf;
8224: PetscLayout layout;
8226: PetscFunctionBegin;
8228: PetscCall(MatIsSymmetricKnown(mat, &set, &flag));
8229: if (!set || !flag) {
8230: /* TODO: only needs nonzero structure of transpose */
8231: PetscCall(MatTranspose(mat, MAT_INITIAL_MATRIX, &AA));
8232: PetscCall(MatAXPY(AA, 1.0, mat, DIFFERENT_NONZERO_PATTERN));
8233: }
8234: PetscCall(MatAIJGetLocalMat(AA, &A));
8235: PetscCall(MatGetRowIJ(A, 0, PETSC_FALSE, PETSC_FALSE, &n, &ia, &ja, &done));
8236: PetscCheck(done, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "Unable to get IJ structure from matrix");
8238: PetscCall(MatGetLocalSize(mat, &n, NULL));
8239: PetscCall(PetscObjectGetNewTag((PetscObject)mat, &tag));
8240: PetscCall(PetscObjectGetComm((PetscObject)mat, &comm));
8241: PetscCallMPI(MPI_Comm_size(comm, &size));
8242: PetscCallMPI(MPI_Comm_rank(comm, &rank));
8244: PetscCall(PetscMalloc2(n, &sizes, n, &starts));
8246: if (rank > 0) {
8247: PetscCallMPI(MPI_Recv(&env, 1, MPIU_INT, rank - 1, tag, comm, &status));
8248: PetscCallMPI(MPI_Recv(&tbs, 1, MPIU_INT, rank - 1, tag, comm, &status));
8249: }
8250: PetscCall(MatGetOwnershipRange(mat, &rstart, NULL));
8251: for (i = 0; i < n; i++) {
8252: env = PetscMax(env, ja[ia[i + 1] - 1]);
8253: II = rstart + i;
8254: if (env == II) {
8255: starts[lblocks] = tbs;
8256: sizes[lblocks++] = 1 + II - tbs;
8257: tbs = 1 + II;
8258: }
8259: }
8260: if (rank < size - 1) {
8261: PetscCallMPI(MPI_Send(&env, 1, MPIU_INT, rank + 1, tag, comm));
8262: PetscCallMPI(MPI_Send(&tbs, 1, MPIU_INT, rank + 1, tag, comm));
8263: }
8265: PetscCall(MatRestoreRowIJ(A, 0, PETSC_FALSE, PETSC_FALSE, &n, &ia, &ja, &done));
8266: if (!set || !flag) PetscCall(MatDestroy(&AA));
8267: PetscCall(MatDestroy(&A));
8269: PetscCall(PetscNew(&edata));
8270: PetscCall(MatGetNonzeroState(mat, &edata->nonzerostate));
8271: edata->n = lblocks;
8272: /* create IS needed for extracting blocks from the original matrix */
8273: PetscCall(PetscMalloc1(lblocks, &edata->is));
8274: for (PetscInt i = 0; i < lblocks; i++) PetscCall(ISCreateStride(PETSC_COMM_SELF, sizes[i], starts[i], 1, &edata->is[i]));
8276: /* Create the resulting inverse matrix nonzero structure with preallocation information */
8277: PetscCall(MatCreate(PetscObjectComm((PetscObject)mat), &edata->C));
8278: PetscCall(MatSetSizes(edata->C, mat->rmap->n, mat->cmap->n, mat->rmap->N, mat->cmap->N));
8279: PetscCall(MatSetBlockSizesFromMats(edata->C, mat, mat));
8280: PetscCall(MatSetType(edata->C, MATAIJ));
8282: /* Communicate the start and end of each row, from each block to the correct rank */
8283: for (PetscInt i = 0; i < lblocks; i++) ln += sizes[i];
8284: PetscCall(PetscCalloc3(2 * ln, &seqv, 2 * mat->rmap->n, &parv, 2 * ln, &gidx));
8285: for (PetscInt i = 0; i < lblocks; i++) {
8286: for (PetscInt j = 0; j < sizes[i]; j++) {
8287: seqv[cnt] = starts[i];
8288: seqv[cnt + 1] = starts[i] + sizes[i];
8289: cnt += 2;
8290: }
8291: }
8292: PetscCallMPI(MPI_Scan(&cnt, &sc, 1, MPIU_INT, MPI_SUM, PetscObjectComm((PetscObject)mat)));
8293: sc -= cnt;
8294: for (PetscInt i = 0; i < cnt; i++) gidx[i] = sc + i;
8295: PetscCall(PetscLayoutCreateFromSizes(PetscObjectComm((PetscObject)mat), 2 * mat->rmap->n, 2 * mat->rmap->N, 1, &layout));
8296: PetscCall(PetscSFCreate(PetscObjectComm((PetscObject)mat), &sf));
8297: PetscCall(PetscSFSetGraphLayout(sf, layout, cnt, NULL, PETSC_COPY_VALUES, gidx));
8298: PetscCall(PetscLayoutDestroy(&layout));
8299: PetscCall(PetscSFReduceBegin(sf, MPIU_INT, seqv, parv, MPI_REPLACE));
8300: PetscCall(PetscSFReduceEnd(sf, MPIU_INT, seqv, parv, MPI_REPLACE));
8301: PetscCall(PetscSFDestroy(&sf));
8302: PetscCall(MatGetOwnershipRangeColumn(mat, &cstart, &cend));
8303: PetscCall(PetscMalloc2(mat->rmap->n, &diag, mat->rmap->n, &odiag));
8304: cnt = 0;
8305: PetscCall(MatGetSize(mat, NULL, &n));
8306: for (PetscInt i = 0; i < mat->rmap->n; i++) {
8307: PetscInt start, end, d = 0, od = 0;
8309: start = parv[cnt];
8310: end = parv[cnt + 1];
8311: cnt += 2;
8313: if (start < cstart) {
8314: od += cstart - start + n - cend;
8315: d += cend - cstart;
8316: } else if (start < cend) {
8317: od += n - cend;
8318: d += cend - start;
8319: } else od += n - start;
8320: if (end <= cstart) {
8321: od -= cstart - end + n - cend;
8322: d -= cend - cstart;
8323: } else if (end < cend) {
8324: od -= n - cend;
8325: d -= cend - end;
8326: } else od -= n - end;
8328: odiag[i] = od;
8329: diag[i] = d;
8330: }
8331: PetscCall(PetscFree3(seqv, parv, gidx));
8332: PetscCall(MatXAIJSetPreallocation(edata->C, mat->rmap->bs, diag, odiag, NULL, NULL));
8333: PetscCall(PetscFree2(diag, odiag));
8334: PetscCall(PetscFree2(sizes, starts));
8336: PetscCall(PetscContainerCreate(PETSC_COMM_SELF, &container));
8337: PetscCall(PetscContainerSetPointer(container, edata));
8338: PetscCall(PetscContainerSetCtxDestroy(container, EnvelopeDataDestroy));
8339: PetscCall(PetscObjectCompose((PetscObject)mat, "EnvelopeData", (PetscObject)container));
8340: PetscCall(PetscObjectDereference((PetscObject)container));
8341: PetscFunctionReturn(PETSC_SUCCESS);
8342: }
8344: /*@
8345: MatInvertVariableBlockEnvelope - set matrix C to be the inverted block diagonal of matrix A
8347: Collective
8349: Input Parameters:
8350: + A - the matrix
8351: - reuse - indicates if the `C` matrix was obtained from a previous call to this routine
8353: Output Parameter:
8354: . C - matrix with inverted block diagonal of `A`
8356: Level: advanced
8358: Note:
8359: For efficiency the matrix `A` should have all the nonzero entries clustered in smallish blocks along the diagonal.
8361: .seealso: [](ch_matrices), `Mat`, `MatInvertBlockDiagonal()`, `MatComputeBlockDiagonal()`
8362: @*/
8363: PetscErrorCode MatInvertVariableBlockEnvelope(Mat A, MatReuse reuse, Mat *C)
8364: {
8365: PetscContainer container;
8366: EnvelopeData *edata;
8367: PetscObjectState nonzerostate;
8369: PetscFunctionBegin;
8370: PetscCall(PetscObjectQuery((PetscObject)A, "EnvelopeData", (PetscObject *)&container));
8371: if (!container) {
8372: PetscCall(MatComputeVariableBlockEnvelope(A));
8373: PetscCall(PetscObjectQuery((PetscObject)A, "EnvelopeData", (PetscObject *)&container));
8374: }
8375: PetscCall(PetscContainerGetPointer(container, &edata));
8376: PetscCall(MatGetNonzeroState(A, &nonzerostate));
8377: PetscCheck(nonzerostate <= edata->nonzerostate, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "Cannot handle changes to matrix nonzero structure");
8378: PetscCheck(reuse != MAT_REUSE_MATRIX || *C == edata->C, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "C matrix must be the same as previously output");
8380: PetscCall(MatCreateSubMatrices(A, edata->n, edata->is, edata->is, MAT_INITIAL_MATRIX, &edata->mat));
8381: *C = edata->C;
8383: for (PetscInt i = 0; i < edata->n; i++) {
8384: Mat D;
8385: PetscScalar *dvalues;
8387: PetscCall(MatConvert(edata->mat[i], MATSEQDENSE, MAT_INITIAL_MATRIX, &D));
8388: PetscCall(MatSetOption(*C, MAT_ROW_ORIENTED, PETSC_FALSE));
8389: PetscCall(MatSeqDenseInvert(D));
8390: PetscCall(MatDenseGetArray(D, &dvalues));
8391: PetscCall(MatSetValuesIS(*C, edata->is[i], edata->is[i], dvalues, INSERT_VALUES));
8392: PetscCall(MatDestroy(&D));
8393: }
8394: PetscCall(MatDestroySubMatrices(edata->n, &edata->mat));
8395: PetscCall(MatAssemblyBegin(*C, MAT_FINAL_ASSEMBLY));
8396: PetscCall(MatAssemblyEnd(*C, MAT_FINAL_ASSEMBLY));
8397: PetscFunctionReturn(PETSC_SUCCESS);
8398: }
8400: /*@
8401: MatSetVariableBlockSizes - Sets diagonal point-blocks of the matrix that need not be of the same size
8403: Not Collective
8405: Input Parameters:
8406: + mat - the matrix
8407: . nblocks - the number of blocks on this process, each block can only exist on a single MPI process
8408: - bsizes - the block sizes
8410: Level: intermediate
8412: Note:
8413: Currently used by `PCVPBJACOBI` for `MATAIJ` matrices
8415: .seealso: [](ch_matrices), `Mat`, `MatCreateSeqBAIJ()`, `MatCreateBAIJ()`, `MatGetBlockSize()`, `MatSetBlockSizes()`, `MatGetBlockSizes()`, `MatGetVariableBlockSizes()`,
8416: `MatComputeVariableBlockEnvelope()`, `PCVPBJACOBI`
8417: @*/
8418: PetscErrorCode MatSetVariableBlockSizes(Mat mat, PetscInt nblocks, const PetscInt bsizes[])
8419: {
8420: PetscInt ncnt = 0, nlocal;
8422: PetscFunctionBegin;
8424: PetscCall(MatGetLocalSize(mat, &nlocal, NULL));
8425: 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);
8426: for (PetscInt i = 0; i < nblocks; i++) ncnt += bsizes[i];
8427: 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);
8428: PetscCall(PetscFree(mat->bsizes));
8429: mat->nblocks = nblocks;
8430: PetscCall(PetscMalloc1(nblocks, &mat->bsizes));
8431: PetscCall(PetscArraycpy(mat->bsizes, bsizes, nblocks));
8432: PetscFunctionReturn(PETSC_SUCCESS);
8433: }
8435: /*@
8436: MatGetVariableBlockSizes - Gets a diagonal blocks of the matrix that need not be of the same size
8438: Not Collective; No Fortran Support
8440: Input Parameter:
8441: . mat - the matrix
8443: Output Parameters:
8444: + nblocks - the number of blocks on this process
8445: - bsizes - the block sizes
8447: Level: intermediate
8449: .seealso: [](ch_matrices), `Mat`, `MatCreateSeqBAIJ()`, `MatCreateBAIJ()`, `MatGetBlockSize()`, `MatSetBlockSizes()`, `MatGetBlockSizes()`, `MatSetVariableBlockSizes()`, `MatComputeVariableBlockEnvelope()`
8450: @*/
8451: PetscErrorCode MatGetVariableBlockSizes(Mat mat, PetscInt *nblocks, const PetscInt *bsizes[])
8452: {
8453: PetscFunctionBegin;
8455: if (nblocks) *nblocks = mat->nblocks;
8456: if (bsizes) *bsizes = mat->bsizes;
8457: PetscFunctionReturn(PETSC_SUCCESS);
8458: }
8460: /*@
8461: MatSelectVariableBlockSizes - When creating a submatrix, pass on the variable block sizes
8463: Not Collective
8465: Input Parameters:
8466: + subA - the submatrix
8467: . A - the original matrix
8468: - isrow - The `IS` of selected rows for the submatrix, must be sorted
8470: Level: developer
8472: Note:
8473: If the index set is not sorted or contains off-process entries, this function will do nothing.
8475: .seealso: [](ch_matrices), `Mat`, `MatSetVariableBlockSizes()`, `MatComputeVariableBlockEnvelope()`
8476: @*/
8477: PetscErrorCode MatSelectVariableBlockSizes(Mat subA, Mat A, IS isrow)
8478: {
8479: const PetscInt *rows;
8480: PetscInt n, rStart, rEnd, Nb = 0;
8481: PetscBool flg = A->bsizes ? PETSC_TRUE : PETSC_FALSE;
8483: PetscFunctionBegin;
8484: // The code for block size extraction does not support an unsorted IS
8485: if (flg) PetscCall(ISSorted(isrow, &flg));
8486: // We don't support originally off-diagonal blocks
8487: if (flg) {
8488: PetscCall(MatGetOwnershipRange(A, &rStart, &rEnd));
8489: PetscCall(ISGetLocalSize(isrow, &n));
8490: PetscCall(ISGetIndices(isrow, &rows));
8491: for (PetscInt i = 0; i < n && flg; ++i) {
8492: if (rows[i] < rStart || rows[i] >= rEnd) flg = PETSC_FALSE;
8493: }
8494: PetscCall(ISRestoreIndices(isrow, &rows));
8495: }
8496: // quiet return if we can't extract block size
8497: PetscCallMPI(MPIU_Allreduce(MPI_IN_PLACE, &flg, 1, MPI_C_BOOL, MPI_LAND, PetscObjectComm((PetscObject)subA)));
8498: if (!flg) PetscFunctionReturn(PETSC_SUCCESS);
8500: // extract block sizes
8501: PetscCall(ISGetIndices(isrow, &rows));
8502: for (PetscInt b = 0, gr = rStart, i = 0; b < A->nblocks; ++b) {
8503: PetscBool occupied = PETSC_FALSE;
8505: for (PetscInt br = 0; br < A->bsizes[b]; ++br) {
8506: const PetscInt row = gr + br;
8508: if (i == n) break;
8509: if (rows[i] == row) {
8510: occupied = PETSC_TRUE;
8511: ++i;
8512: }
8513: while (i < n && rows[i] < row) ++i;
8514: }
8515: gr += A->bsizes[b];
8516: if (occupied) ++Nb;
8517: }
8518: subA->nblocks = Nb;
8519: PetscCall(PetscFree(subA->bsizes));
8520: PetscCall(PetscMalloc1(subA->nblocks, &subA->bsizes));
8521: PetscInt sb = 0;
8522: for (PetscInt b = 0, gr = rStart, i = 0; b < A->nblocks; ++b) {
8523: if (sb < subA->nblocks) subA->bsizes[sb] = 0;
8524: for (PetscInt br = 0; br < A->bsizes[b]; ++br) {
8525: const PetscInt row = gr + br;
8527: if (i == n) break;
8528: if (rows[i] == row) {
8529: ++subA->bsizes[sb];
8530: ++i;
8531: }
8532: while (i < n && rows[i] < row) ++i;
8533: }
8534: gr += A->bsizes[b];
8535: if (sb < subA->nblocks && subA->bsizes[sb]) ++sb;
8536: }
8537: PetscCheck(sb == subA->nblocks, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Invalid number of blocks %" PetscInt_FMT " != %" PetscInt_FMT, sb, subA->nblocks);
8538: PetscInt nlocal, ncnt = 0;
8539: PetscCall(MatGetLocalSize(subA, &nlocal, NULL));
8540: 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);
8541: for (PetscInt i = 0; i < subA->nblocks; i++) ncnt += subA->bsizes[i];
8542: 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);
8543: PetscCall(ISRestoreIndices(isrow, &rows));
8544: PetscFunctionReturn(PETSC_SUCCESS);
8545: }
8547: /*@
8548: MatSetBlockSizes - Sets the matrix block row and column sizes.
8550: Logically Collective
8552: Input Parameters:
8553: + mat - the matrix
8554: . rbs - row block size
8555: - cbs - column block size
8557: Level: intermediate
8559: Notes:
8560: Block row formats are `MATBAIJ` and `MATSBAIJ`. These formats ALWAYS have square block storage in the matrix.
8561: If you pass a different block size for the columns than the rows, the row block size determines the square block storage.
8562: This must be called before `MatSetUp()` or MatXXXSetPreallocation() (or will default to 1) and the block size cannot be changed later.
8564: For `MATAIJ` matrix this function can be called at a later stage, provided that the specified block sizes
8565: are compatible with the matrix local sizes.
8567: The row and column block size determine the blocksize of the "row" and "column" vectors returned by `MatCreateVecs()`.
8569: .seealso: [](ch_matrices), `Mat`, `MatCreateSeqBAIJ()`, `MatCreateBAIJ()`, `MatGetBlockSize()`, `MatSetBlockSize()`, `MatGetBlockSizes()`
8570: @*/
8571: PetscErrorCode MatSetBlockSizes(Mat mat, PetscInt rbs, PetscInt cbs)
8572: {
8573: PetscFunctionBegin;
8577: PetscTryTypeMethod(mat, setblocksizes, rbs, cbs);
8578: if (mat->rmap->refcnt) {
8579: ISLocalToGlobalMapping l2g = NULL;
8580: PetscLayout nmap = NULL;
8582: PetscCall(PetscLayoutDuplicate(mat->rmap, &nmap));
8583: if (mat->rmap->mapping) PetscCall(ISLocalToGlobalMappingDuplicate(mat->rmap->mapping, &l2g));
8584: PetscCall(PetscLayoutDestroy(&mat->rmap));
8585: mat->rmap = nmap;
8586: mat->rmap->mapping = l2g;
8587: }
8588: if (mat->cmap->refcnt) {
8589: ISLocalToGlobalMapping l2g = NULL;
8590: PetscLayout nmap = NULL;
8592: PetscCall(PetscLayoutDuplicate(mat->cmap, &nmap));
8593: if (mat->cmap->mapping) PetscCall(ISLocalToGlobalMappingDuplicate(mat->cmap->mapping, &l2g));
8594: PetscCall(PetscLayoutDestroy(&mat->cmap));
8595: mat->cmap = nmap;
8596: mat->cmap->mapping = l2g;
8597: }
8598: PetscCall(PetscLayoutSetBlockSize(mat->rmap, rbs));
8599: PetscCall(PetscLayoutSetBlockSize(mat->cmap, cbs));
8600: PetscFunctionReturn(PETSC_SUCCESS);
8601: }
8603: /*@
8604: MatSetBlockSizesFromMats - Sets the matrix block row and column sizes to match a pair of matrices
8606: Logically Collective
8608: Input Parameters:
8609: + mat - the matrix
8610: . fromRow - matrix from which to copy row block size
8611: - fromCol - matrix from which to copy column block size (can be same as `fromRow`)
8613: Level: developer
8615: .seealso: [](ch_matrices), `Mat`, `MatCreateSeqBAIJ()`, `MatCreateBAIJ()`, `MatGetBlockSize()`, `MatSetBlockSizes()`
8616: @*/
8617: PetscErrorCode MatSetBlockSizesFromMats(Mat mat, Mat fromRow, Mat fromCol)
8618: {
8619: PetscFunctionBegin;
8623: PetscTryTypeMethod(mat, setblocksizes, fromRow->rmap->bs, fromCol->cmap->bs);
8624: PetscCall(PetscLayoutSetBlockSize(mat->rmap, fromRow->rmap->bs));
8625: PetscCall(PetscLayoutSetBlockSize(mat->cmap, fromCol->cmap->bs));
8626: PetscFunctionReturn(PETSC_SUCCESS);
8627: }
8629: /*@
8630: MatResidual - Default routine to calculate the residual $r = b - Ax$
8632: Collective
8634: Input Parameters:
8635: + mat - the matrix
8636: . b - the right-hand-side
8637: - x - the approximate solution
8639: Output Parameter:
8640: . r - location to store the residual
8642: Level: developer
8644: .seealso: [](ch_matrices), `Mat`, `MatMult()`, `MatMultAdd()`, `PCMGSetResidual()`
8645: @*/
8646: PetscErrorCode MatResidual(Mat mat, Vec b, Vec x, Vec r)
8647: {
8648: PetscFunctionBegin;
8654: MatCheckPreallocated(mat, 1);
8655: PetscCall(PetscLogEventBegin(MAT_Residual, mat, 0, 0, 0));
8656: if (!mat->ops->residual) {
8657: PetscCall(MatMult(mat, x, r));
8658: PetscCall(VecAYPX(r, -1.0, b));
8659: } else {
8660: PetscUseTypeMethod(mat, residual, b, x, r);
8661: }
8662: PetscCall(PetscLogEventEnd(MAT_Residual, mat, 0, 0, 0));
8663: PetscFunctionReturn(PETSC_SUCCESS);
8664: }
8666: /*@
8667: MatGetRowIJ - Returns the compressed row storage i and j indices for the local rows of a sparse matrix
8669: Collective
8671: Input Parameters:
8672: + mat - the matrix
8673: . shift - 0 or 1 indicating we want the indices starting at 0 or 1
8674: . symmetric - `PETSC_TRUE` or `PETSC_FALSE` indicating the matrix data structure should be symmetrized
8675: - inodecompressed - `PETSC_TRUE` or `PETSC_FALSE` indicating if the nonzero structure of the
8676: inodes or the nonzero elements is wanted. For `MATBAIJ` matrices the compressed version is
8677: always used.
8679: Output Parameters:
8680: + n - number of local rows in the (possibly compressed) matrix, use `NULL` if not needed
8681: . 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
8682: . ja - the column indices, use `NULL` if not needed
8683: - done - indicates if the routine actually worked and returned appropriate `ia` and `ja` arrays; callers
8684: are responsible for handling the case when done is `PETSC_FALSE` and `ia` and `ja` are not provided
8686: Level: developer
8688: Notes:
8689: You CANNOT change any of the `ia` or `ja` values.
8691: Use `MatRestoreRowIJ()` when you are finished accessing the `ia` and `ja` values.
8693: Fortran Notes:
8694: Use
8695: .vb
8696: PetscInt, pointer :: ia(:),ja(:)
8697: call MatGetRowIJ(mat,shift,symmetric,inodecompressed,n,ia,ja,done,ierr)
8698: ! Access the ith and jth entries via ia(i) and ja(j)
8699: .ve
8701: .seealso: [](ch_matrices), `Mat`, `MATAIJ`, `MatGetColumnIJ()`, `MatRestoreRowIJ()`, `MatSeqAIJGetArray()`
8702: @*/
8703: PetscErrorCode MatGetRowIJ(Mat mat, PetscInt shift, PetscBool symmetric, PetscBool inodecompressed, PetscInt *n, const PetscInt *ia[], const PetscInt *ja[], PetscBool *done)
8704: {
8705: PetscFunctionBegin;
8708: if (n) PetscAssertPointer(n, 5);
8709: if (ia) PetscAssertPointer(ia, 6);
8710: if (ja) PetscAssertPointer(ja, 7);
8711: if (done) PetscAssertPointer(done, 8);
8712: MatCheckPreallocated(mat, 1);
8713: if (!mat->ops->getrowij && done) *done = PETSC_FALSE;
8714: else {
8715: if (done) *done = PETSC_TRUE;
8716: PetscCall(PetscLogEventBegin(MAT_GetRowIJ, mat, 0, 0, 0));
8717: PetscUseTypeMethod(mat, getrowij, shift, symmetric, inodecompressed, n, ia, ja, done);
8718: PetscCall(PetscLogEventEnd(MAT_GetRowIJ, mat, 0, 0, 0));
8719: }
8720: PetscFunctionReturn(PETSC_SUCCESS);
8721: }
8723: /*@
8724: MatGetColumnIJ - Returns the compressed column storage i and j indices for sequential matrices.
8726: Collective
8728: Input Parameters:
8729: + mat - the matrix
8730: . shift - 1 or zero indicating we want the indices starting at 0 or 1
8731: . symmetric - `PETSC_TRUE` or `PETSC_FALSE` indicating the matrix data structure should be
8732: symmetrized
8733: - inodecompressed - `PETSC_TRUE` or `PETSC_FALSE` indicating if the nonzero structure of the
8734: inodes or the nonzero elements is wanted. For `MATBAIJ` matrices the compressed version is
8735: always used.
8737: Output Parameters:
8738: + n - number of columns in the (possibly compressed) matrix
8739: . ia - the column pointers; that is ia[0] = 0, ia[col] = i[col-1] + number of elements in that col of the matrix
8740: . ja - the row indices
8741: - done - `PETSC_TRUE` or `PETSC_FALSE`, indicating whether the values have been returned
8743: Level: developer
8745: .seealso: [](ch_matrices), `Mat`, `MatGetRowIJ()`, `MatRestoreColumnIJ()`
8746: @*/
8747: PetscErrorCode MatGetColumnIJ(Mat mat, PetscInt shift, PetscBool symmetric, PetscBool inodecompressed, PetscInt *n, const PetscInt *ia[], const PetscInt *ja[], PetscBool *done)
8748: {
8749: PetscFunctionBegin;
8752: PetscAssertPointer(n, 5);
8753: if (ia) PetscAssertPointer(ia, 6);
8754: if (ja) PetscAssertPointer(ja, 7);
8755: PetscAssertPointer(done, 8);
8756: MatCheckPreallocated(mat, 1);
8757: if (!mat->ops->getcolumnij) *done = PETSC_FALSE;
8758: else {
8759: *done = PETSC_TRUE;
8760: PetscUseTypeMethod(mat, getcolumnij, shift, symmetric, inodecompressed, n, ia, ja, done);
8761: }
8762: PetscFunctionReturn(PETSC_SUCCESS);
8763: }
8765: /*@
8766: MatRestoreRowIJ - Call after you are completed with the ia,ja indices obtained with `MatGetRowIJ()`.
8768: Collective
8770: Input Parameters:
8771: + mat - the matrix
8772: . shift - 1 or zero indicating we want the indices starting at 0 or 1
8773: . symmetric - `PETSC_TRUE` or `PETSC_FALSE` indicating the matrix data structure should be symmetrized
8774: . inodecompressed - `PETSC_TRUE` or `PETSC_FALSE` indicating if the nonzero structure of the
8775: inodes or the nonzero elements is wanted. For `MATBAIJ` matrices the compressed version is
8776: always used.
8777: . n - size of (possibly compressed) matrix, or `NULL`
8778: . ia - the row pointers, or `NULL`
8779: - ja - the column indices, or `NULL`
8781: Output Parameter:
8782: . done - `PETSC_TRUE` or `PETSC_FALSE` indicated that the values have been returned
8784: Level: developer
8786: Note:
8787: This routine zeros out `n`, `ia`, and `ja` if they are provided. Use of `ia` or `ja` after `MatRestoreRowIJ()` is always invalid.
8789: .seealso: [](ch_matrices), `Mat`, `MatGetRowIJ()`, `MatRestoreColumnIJ()`
8790: @*/
8791: PetscErrorCode MatRestoreRowIJ(Mat mat, PetscInt shift, PetscBool symmetric, PetscBool inodecompressed, PetscInt *n, const PetscInt *ia[], const PetscInt *ja[], PetscBool *done)
8792: {
8793: PetscFunctionBegin;
8796: if (ia) PetscAssertPointer(ia, 6);
8797: if (ja) PetscAssertPointer(ja, 7);
8798: if (done) PetscAssertPointer(done, 8);
8799: MatCheckPreallocated(mat, 1);
8801: if (!mat->ops->restorerowij && done) *done = PETSC_FALSE;
8802: else {
8803: if (done) *done = PETSC_TRUE;
8804: PetscUseTypeMethod(mat, restorerowij, shift, symmetric, inodecompressed, n, ia, ja, done);
8805: if (n) *n = 0;
8806: if (ia) *ia = NULL;
8807: if (ja) *ja = NULL;
8808: }
8809: PetscFunctionReturn(PETSC_SUCCESS);
8810: }
8812: /*@
8813: MatRestoreColumnIJ - Call after you are completed with the ia,ja indices obtained with `MatGetColumnIJ()`.
8815: Collective
8817: Input Parameters:
8818: + mat - the matrix
8819: . shift - 1 or zero indicating we want the indices starting at 0 or 1
8820: . symmetric - `PETSC_TRUE` or `PETSC_FALSE` indicating the matrix data structure should be symmetrized
8821: - inodecompressed - `PETSC_TRUE` or `PETSC_FALSE` indicating if the nonzero structure of the
8822: inodes or the nonzero elements is wanted. For `MATBAIJ` matrices the compressed version is
8823: always used.
8825: Output Parameters:
8826: + n - size of (possibly compressed) matrix
8827: . ia - the column pointers
8828: . ja - the row indices
8829: - done - `PETSC_TRUE` or `PETSC_FALSE` indicated that the values have been returned
8831: Level: developer
8833: .seealso: [](ch_matrices), `Mat`, `MatGetColumnIJ()`, `MatRestoreRowIJ()`
8834: @*/
8835: PetscErrorCode MatRestoreColumnIJ(Mat mat, PetscInt shift, PetscBool symmetric, PetscBool inodecompressed, PetscInt *n, const PetscInt *ia[], const PetscInt *ja[], PetscBool *done)
8836: {
8837: PetscFunctionBegin;
8840: if (ia) PetscAssertPointer(ia, 6);
8841: if (ja) PetscAssertPointer(ja, 7);
8842: PetscAssertPointer(done, 8);
8843: MatCheckPreallocated(mat, 1);
8845: if (!mat->ops->restorecolumnij) *done = PETSC_FALSE;
8846: else {
8847: *done = PETSC_TRUE;
8848: PetscUseTypeMethod(mat, restorecolumnij, shift, symmetric, inodecompressed, n, ia, ja, done);
8849: if (n) *n = 0;
8850: if (ia) *ia = NULL;
8851: if (ja) *ja = NULL;
8852: }
8853: PetscFunctionReturn(PETSC_SUCCESS);
8854: }
8856: /*@
8857: MatColoringPatch - Utility routine used inside matrix coloring routines that use `MatGetRowIJ()` and/or
8858: `MatGetColumnIJ()`.
8860: Collective
8862: Input Parameters:
8863: + mat - the matrix
8864: . ncolors - maximum color value
8865: . n - number of entries in `colorarray`
8866: - colorarray - array indicating color for each column
8868: Output Parameter:
8869: . iscoloring - coloring generated using `colorarray` information
8871: Level: developer
8873: .seealso: [](ch_matrices), `Mat`, `MatGetRowIJ()`, `MatGetColumnIJ()`
8874: @*/
8875: PetscErrorCode MatColoringPatch(Mat mat, PetscInt ncolors, PetscInt n, ISColoringValue colorarray[], ISColoring *iscoloring)
8876: {
8877: PetscFunctionBegin;
8880: PetscAssertPointer(colorarray, 4);
8881: PetscAssertPointer(iscoloring, 5);
8882: MatCheckPreallocated(mat, 1);
8884: if (!mat->ops->coloringpatch) {
8885: PetscCall(ISColoringCreate(PetscObjectComm((PetscObject)mat), ncolors, n, colorarray, PETSC_OWN_POINTER, iscoloring));
8886: } else {
8887: PetscUseTypeMethod(mat, coloringpatch, ncolors, n, colorarray, iscoloring);
8888: }
8889: PetscFunctionReturn(PETSC_SUCCESS);
8890: }
8892: /*@
8893: MatSetUnfactored - Resets a factored matrix to be treated as unfactored.
8895: Logically Collective
8897: Input Parameter:
8898: . mat - the factored matrix to be reset
8900: Level: developer
8902: Notes:
8903: This routine should be used only with factored matrices formed by in-place
8904: factorization via ILU(0) (or by in-place LU factorization for the `MATSEQDENSE`
8905: format). This option can save memory, for example, when solving nonlinear
8906: systems with a matrix-free Newton-Krylov method and a matrix-based, in-place
8907: ILU(0) preconditioner.
8909: One can specify in-place ILU(0) factorization by calling
8910: .vb
8911: PCType(pc,PCILU);
8912: PCFactorSeUseInPlace(pc);
8913: .ve
8914: or by using the options -pc_type ilu -pc_factor_in_place
8916: In-place factorization ILU(0) can also be used as a local
8917: solver for the blocks within the block Jacobi or additive Schwarz
8918: methods (runtime option: -sub_pc_factor_in_place). See Users-Manual: ch_pc
8919: for details on setting local solver options.
8921: Most users should employ the `KSP` interface for linear solvers
8922: instead of working directly with matrix algebra routines such as this.
8923: See, e.g., `KSPCreate()`.
8925: .seealso: [](ch_matrices), `Mat`, `PCFactorSetUseInPlace()`, `PCFactorGetUseInPlace()`
8926: @*/
8927: PetscErrorCode MatSetUnfactored(Mat mat)
8928: {
8929: PetscFunctionBegin;
8932: MatCheckPreallocated(mat, 1);
8933: mat->factortype = MAT_FACTOR_NONE;
8934: if (!mat->ops->setunfactored) PetscFunctionReturn(PETSC_SUCCESS);
8935: PetscUseTypeMethod(mat, setunfactored);
8936: PetscFunctionReturn(PETSC_SUCCESS);
8937: }
8939: /*@
8940: MatCreateSubMatrix - Gets a single submatrix on the same number of processes
8941: as the original matrix.
8943: Collective
8945: Input Parameters:
8946: + mat - the original matrix
8947: . isrow - parallel `IS` containing the rows this process should obtain
8948: . 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.
8949: - cll - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`
8951: Output Parameter:
8952: . newmat - the new submatrix, of the same type as the original matrix (except potentially for `MATSEQSBAIJ`)
8954: Level: advanced
8956: Notes:
8957: The submatrix will be able to be multiplied with vectors using the same layout as `iscol`.
8959: Some matrix types place restrictions on the row and column indices, such
8960: 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;
8961: for example, if the block size is 3 one cannot select the 0 and 2 rows without selecting the 1 row.
8962: `MATSEQSBAIJ` inputs may produce a `MATSEQBAIJ` matrix when the row and column index sets do not preserve symmetry.
8964: The index sets may not have duplicate entries.
8966: The first time this is called you should use a `cll` of `MAT_INITIAL_MATRIX`,
8967: the `MatCreateSubMatrix()` routine will create the newmat for you. Any additional calls
8968: to this routine with a mat of the same nonzero structure and with a call of `MAT_REUSE_MATRIX`
8969: will reuse the matrix generated the first time. You should call `MatDestroy()` on `newmat` when
8970: you are finished using it.
8972: The communicator of the newly obtained matrix is ALWAYS the same as the communicator of
8973: the input matrix.
8975: If `iscol` is `NULL` then all columns are obtained (not supported in Fortran).
8977: If `isrow` and `iscol` have a nontrivial block-size, then the resulting matrix has this block-size as well. This feature
8978: is used by `PCFIELDSPLIT` to allow easy nesting of its use.
8980: Example usage:
8981: Consider the following 8x8 matrix with 34 non-zero values, that is
8982: assembled across 3 processes. Let's assume that proc0 owns 3 rows,
8983: proc1 owns 3 rows, proc2 owns 2 rows. This division can be shown
8984: as follows
8985: .vb
8986: 1 2 0 | 0 3 0 | 0 4
8987: Proc0 0 5 6 | 7 0 0 | 8 0
8988: 9 0 10 | 11 0 0 | 12 0
8989: -------------------------------------
8990: 13 0 14 | 15 16 17 | 0 0
8991: Proc1 0 18 0 | 19 20 21 | 0 0
8992: 0 0 0 | 22 23 0 | 24 0
8993: -------------------------------------
8994: Proc2 25 26 27 | 0 0 28 | 29 0
8995: 30 0 0 | 31 32 33 | 0 34
8996: .ve
8998: Suppose `isrow` = [0 1 | 4 | 6 7] and `iscol` = [1 2 | 3 4 5 | 6]. The resulting submatrix is
9000: .vb
9001: 2 0 | 0 3 0 | 0
9002: Proc0 5 6 | 7 0 0 | 8
9003: -------------------------------
9004: Proc1 18 0 | 19 20 21 | 0
9005: -------------------------------
9006: Proc2 26 27 | 0 0 28 | 29
9007: 0 0 | 31 32 33 | 0
9008: .ve
9010: .seealso: [](ch_matrices), `Mat`, `MatCreateSubMatrices()`, `MatCreateSubMatricesMPI()`, `MatCreateSubMatrixVirtual()`, `MatSubMatrixVirtualUpdate()`
9011: @*/
9012: PetscErrorCode MatCreateSubMatrix(Mat mat, IS isrow, IS iscol, MatReuse cll, Mat *newmat)
9013: {
9014: PetscMPIInt size;
9015: Mat *local;
9016: IS iscoltmp;
9017: PetscBool flg;
9019: PetscFunctionBegin;
9023: PetscAssertPointer(newmat, 5);
9026: PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
9027: PetscCheck(cll != MAT_IGNORE_MATRIX, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Cannot use MAT_IGNORE_MATRIX");
9028: PetscCheck(cll != MAT_INPLACE_MATRIX, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Cannot use MAT_INPLACE_MATRIX");
9030: MatCheckPreallocated(mat, 1);
9031: PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)mat), &size));
9033: if (!iscol || isrow == iscol) {
9034: PetscBool stride;
9035: PetscMPIInt grab = 0;
9036: PetscCall(PetscObjectTypeCompare((PetscObject)isrow, ISSTRIDE, &stride));
9037: if (stride) {
9038: PetscInt first, step, n, rstart, rend;
9039: PetscCall(ISStrideGetInfo(isrow, &first, &step));
9040: if (step == 1) {
9041: PetscCall(MatGetOwnershipRange(mat, &rstart, &rend));
9042: if (rstart == first) {
9043: PetscCall(ISGetLocalSize(isrow, &n));
9044: if (n == rend - rstart) grab = 1;
9045: }
9046: }
9047: }
9048: PetscCallMPI(MPIU_Allreduce(MPI_IN_PLACE, &grab, 1, MPI_INT, MPI_MIN, PetscObjectComm((PetscObject)mat)));
9049: if (grab) {
9050: PetscCall(PetscInfo(mat, "Getting entire matrix as submatrix\n"));
9051: if (cll == MAT_INITIAL_MATRIX) {
9052: *newmat = mat;
9053: PetscCall(PetscObjectReference((PetscObject)mat));
9054: }
9055: PetscFunctionReturn(PETSC_SUCCESS);
9056: }
9057: }
9059: if (!iscol) {
9060: PetscCall(ISCreateStride(PetscObjectComm((PetscObject)mat), mat->cmap->n, mat->cmap->rstart, 1, &iscoltmp));
9061: } else {
9062: iscoltmp = iscol;
9063: }
9065: /* if original matrix is on just one process then use submatrix generated */
9066: if (mat->ops->createsubmatrices && !mat->ops->createsubmatrix && size == 1 && cll == MAT_REUSE_MATRIX) {
9067: PetscCall(MatCreateSubMatrices(mat, 1, &isrow, &iscoltmp, MAT_REUSE_MATRIX, &newmat));
9068: goto setproperties;
9069: } else if (mat->ops->createsubmatrices && !mat->ops->createsubmatrix && size == 1) {
9070: PetscCall(MatCreateSubMatrices(mat, 1, &isrow, &iscoltmp, MAT_INITIAL_MATRIX, &local));
9071: *newmat = *local;
9072: PetscCall(PetscFree(local));
9073: goto setproperties;
9074: } else if (!mat->ops->createsubmatrix) {
9075: /* Create a new matrix type that implements the operation using the full matrix */
9076: PetscCall(PetscLogEventBegin(MAT_CreateSubMat, mat, 0, 0, 0));
9077: switch (cll) {
9078: case MAT_INITIAL_MATRIX:
9079: PetscCall(MatCreateSubMatrixVirtual(mat, isrow, iscoltmp, newmat));
9080: break;
9081: case MAT_REUSE_MATRIX:
9082: PetscCall(MatSubMatrixVirtualUpdate(*newmat, mat, isrow, iscoltmp));
9083: break;
9084: default:
9085: SETERRQ(PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_OUTOFRANGE, "Invalid MatReuse, must be either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX");
9086: }
9087: PetscCall(PetscLogEventEnd(MAT_CreateSubMat, mat, 0, 0, 0));
9088: goto setproperties;
9089: }
9091: PetscCall(PetscLogEventBegin(MAT_CreateSubMat, mat, 0, 0, 0));
9092: PetscUseTypeMethod(mat, createsubmatrix, isrow, iscoltmp, cll, newmat);
9093: PetscCall(PetscLogEventEnd(MAT_CreateSubMat, mat, 0, 0, 0));
9095: setproperties:
9096: if ((*newmat)->symmetric == PETSC_BOOL3_UNKNOWN && (*newmat)->structurally_symmetric == PETSC_BOOL3_UNKNOWN && (*newmat)->spd == PETSC_BOOL3_UNKNOWN && (*newmat)->hermitian == PETSC_BOOL3_UNKNOWN) {
9097: PetscCall(ISEqualUnsorted(isrow, iscoltmp, &flg));
9098: if (flg) PetscCall(MatPropagateSymmetryOptions(mat, *newmat));
9099: }
9100: if (!iscol) PetscCall(ISDestroy(&iscoltmp));
9101: if (*newmat && cll == MAT_INITIAL_MATRIX) PetscCall(PetscObjectStateIncrease((PetscObject)*newmat));
9102: if (!iscol || isrow == iscol) PetscCall(MatSelectVariableBlockSizes(*newmat, mat, isrow));
9103: PetscFunctionReturn(PETSC_SUCCESS);
9104: }
9106: /*@
9107: MatPropagateSymmetryOptions - Propagates symmetry properties set on a matrix to another matrix
9109: Not Collective
9111: Input Parameters:
9112: + A - the matrix we wish to propagate properties from
9113: - B - the matrix we wish to propagate properties to
9115: Level: beginner
9117: Note:
9118: Propagates the properties associated to `MAT_SYMMETRY_ETERNAL`, `MAT_STRUCTURALLY_SYMMETRIC`, `MAT_HERMITIAN`, `MAT_SPD`, `MAT_SYMMETRIC`, and `MAT_STRUCTURAL_SYMMETRY_ETERNAL`
9120: .seealso: [](ch_matrices), `Mat`, `MatSetOption()`, `MatIsSymmetricKnown()`, `MatIsSPDKnown()`, `MatIsHermitianKnown()`, `MatIsStructurallySymmetricKnown()`
9121: @*/
9122: PetscErrorCode MatPropagateSymmetryOptions(Mat A, Mat B)
9123: {
9124: PetscFunctionBegin;
9127: B->symmetry_eternal = A->symmetry_eternal;
9128: B->structural_symmetry_eternal = A->structural_symmetry_eternal;
9129: B->symmetric = A->symmetric;
9130: B->structurally_symmetric = A->structurally_symmetric;
9131: B->spd = A->spd;
9132: B->hermitian = A->hermitian;
9133: PetscFunctionReturn(PETSC_SUCCESS);
9134: }
9136: /*@
9137: MatStashSetInitialSize - sets the sizes of the matrix stash, that is
9138: used during the assembly process to store values that belong to
9139: other processes.
9141: Not Collective
9143: Input Parameters:
9144: + mat - the matrix
9145: . size - the initial size of the stash.
9146: - bsize - the initial size of the block-stash(if used).
9148: Options Database Key:
9149: . -matstash_initial_size (size|size0,size1,...,sizep-1) - set initial size of stash for all or each of the MPI processes, sets both block and non-block stash sizes
9151: Level: intermediate
9153: Notes:
9154: The block-stash is used for values set with `MatSetValuesBlocked()` while
9155: the stash is used for values set with `MatSetValues()`
9157: Run with the option `-info` and look for output of the form
9158: MatAssemblyBegin_MPIXXX:Stash has MM entries, uses nn mallocs.
9159: to determine the appropriate value, MM, to use for size and
9160: MatAssemblyBegin_MPIXXX:Block-Stash has BMM entries, uses nn mallocs.
9161: to determine the value, BMM to use for bsize
9163: .seealso: [](ch_matrices), `MatAssemblyBegin()`, `MatAssemblyEnd()`, `Mat`, `MatStashGetInfo()`
9164: @*/
9165: PetscErrorCode MatStashSetInitialSize(Mat mat, PetscInt size, PetscInt bsize)
9166: {
9167: PetscFunctionBegin;
9170: PetscCall(MatStashSetInitialSize_Private(&mat->stash, size));
9171: PetscCall(MatStashSetInitialSize_Private(&mat->bstash, bsize));
9172: PetscFunctionReturn(PETSC_SUCCESS);
9173: }
9175: /*@
9176: MatInterpolateAdd - $w = y + A x$ or $A^T x$ depending on the shape of
9177: the matrix
9179: Neighbor-wise Collective
9181: Input Parameters:
9182: + A - the matrix
9183: . x - the vector to be multiplied by the interpolation operator
9184: - y - the vector to be added to the result
9186: Output Parameter:
9187: . w - the resulting vector
9189: Level: intermediate
9191: Notes:
9192: `w` may be the same vector as `y`.
9194: This allows one to use either the restriction or interpolation (its transpose)
9195: matrix to do the interpolation
9197: .seealso: [](ch_matrices), `Mat`, `MatMultAdd()`, `MatMultTransposeAdd()`, `MatRestrict()`, `PCMG`
9198: @*/
9199: PetscErrorCode MatInterpolateAdd(Mat A, Vec x, Vec y, Vec w)
9200: {
9201: PetscInt M, N, Ny;
9203: PetscFunctionBegin;
9208: PetscCall(MatGetSize(A, &M, &N));
9209: PetscCall(VecGetSize(y, &Ny));
9210: if (M == Ny) PetscCall(MatMultAdd(A, x, y, w));
9211: else PetscCall(MatMultTransposeAdd(A, x, y, w));
9212: PetscFunctionReturn(PETSC_SUCCESS);
9213: }
9215: /*@
9216: MatInterpolate - $y = A x$ or $A^T x$ depending on the shape of
9217: the matrix
9219: Neighbor-wise Collective
9221: Input Parameters:
9222: + A - the matrix
9223: - x - the vector to be interpolated
9225: Output Parameter:
9226: . y - the resulting vector
9228: Level: intermediate
9230: Note:
9231: This allows one to use either the restriction or interpolation (its transpose)
9232: matrix to do the interpolation
9234: .seealso: [](ch_matrices), `Mat`, `MatMultAdd()`, `MatMultTransposeAdd()`, `MatRestrict()`, `PCMG`
9235: @*/
9236: PetscErrorCode MatInterpolate(Mat A, Vec x, Vec y)
9237: {
9238: PetscInt M, N, Ny;
9240: PetscFunctionBegin;
9244: PetscCall(MatGetSize(A, &M, &N));
9245: PetscCall(VecGetSize(y, &Ny));
9246: if (M == Ny) PetscCall(MatMult(A, x, y));
9247: else PetscCall(MatMultTranspose(A, x, y));
9248: PetscFunctionReturn(PETSC_SUCCESS);
9249: }
9251: /*@
9252: MatRestrict - $y = A x$ or $A^T x$
9254: Neighbor-wise Collective
9256: Input Parameters:
9257: + A - the matrix
9258: - x - the vector to be restricted
9260: Output Parameter:
9261: . y - the resulting vector
9263: Level: intermediate
9265: Note:
9266: This allows one to use either the restriction or interpolation (its transpose)
9267: matrix to do the restriction
9269: .seealso: [](ch_matrices), `Mat`, `MatMultAdd()`, `MatMultTransposeAdd()`, `MatInterpolate()`, `PCMG`
9270: @*/
9271: PetscErrorCode MatRestrict(Mat A, Vec x, Vec y)
9272: {
9273: PetscInt M, N, Nx;
9275: PetscFunctionBegin;
9279: PetscCall(MatGetSize(A, &M, &N));
9280: PetscCall(VecGetSize(x, &Nx));
9281: if (M == Nx) PetscCall(MatMultTranspose(A, x, y));
9282: else PetscCall(MatMult(A, x, y));
9283: PetscFunctionReturn(PETSC_SUCCESS);
9284: }
9286: /*@
9287: MatMatInterpolateAdd - $Y = W + A X$ or $W + A^T X$ depending on the shape of `A`
9289: Neighbor-wise Collective
9291: Input Parameters:
9292: + A - the matrix
9293: . x - the input dense matrix to be multiplied
9294: - w - the input dense matrix to be added to the result
9296: Output Parameter:
9297: . y - the output dense matrix
9299: Level: intermediate
9301: Note:
9302: This allows one to use either the restriction or interpolation (its transpose)
9303: matrix to do the interpolation. `y` matrix can be reused if already created with the proper sizes,
9304: otherwise it will be recreated. `y` must be initialized to `NULL` if not supplied.
9306: .seealso: [](ch_matrices), `Mat`, `MatInterpolateAdd()`, `MatMatInterpolate()`, `MatMatRestrict()`, `PCMG`
9307: @*/
9308: PetscErrorCode MatMatInterpolateAdd(Mat A, Mat x, Mat w, Mat *y)
9309: {
9310: PetscInt M, N, Mx, Nx, Mo, My = 0, Ny = 0;
9311: PetscBool trans = PETSC_TRUE;
9312: MatReuse reuse = MAT_INITIAL_MATRIX;
9314: PetscFunctionBegin;
9320: PetscCall(MatGetSize(A, &M, &N));
9321: PetscCall(MatGetSize(x, &Mx, &Nx));
9322: if (N == Mx) trans = PETSC_FALSE;
9323: 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);
9324: Mo = trans ? N : M;
9325: if (*y) {
9326: PetscCall(MatGetSize(*y, &My, &Ny));
9327: if (Mo == My && Nx == Ny) reuse = MAT_REUSE_MATRIX;
9328: else {
9329: 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);
9330: PetscCall(MatDestroy(y));
9331: }
9332: }
9334: if (w && *y == w) { /* this is to minimize changes in PCMG */
9335: PetscBool flg;
9337: PetscCall(PetscObjectQuery((PetscObject)*y, "__MatMatIntAdd_w", (PetscObject *)&w));
9338: if (w) {
9339: PetscInt My, Ny, Mw, Nw;
9341: PetscCall(PetscObjectTypeCompare((PetscObject)*y, ((PetscObject)w)->type_name, &flg));
9342: PetscCall(MatGetSize(*y, &My, &Ny));
9343: PetscCall(MatGetSize(w, &Mw, &Nw));
9344: if (!flg || My != Mw || Ny != Nw) w = NULL;
9345: }
9346: if (!w) {
9347: PetscCall(MatDuplicate(*y, MAT_COPY_VALUES, &w));
9348: PetscCall(PetscObjectCompose((PetscObject)*y, "__MatMatIntAdd_w", (PetscObject)w));
9349: PetscCall(PetscObjectDereference((PetscObject)w));
9350: } else PetscCall(MatCopy(*y, w, UNKNOWN_NONZERO_PATTERN));
9351: }
9352: if (!trans) PetscCall(MatMatMult(A, x, reuse, PETSC_DETERMINE, y));
9353: else PetscCall(MatTransposeMatMult(A, x, reuse, PETSC_DETERMINE, y));
9354: if (w) PetscCall(MatAXPY(*y, 1.0, w, UNKNOWN_NONZERO_PATTERN));
9355: PetscFunctionReturn(PETSC_SUCCESS);
9356: }
9358: /*@
9359: MatMatInterpolate - $Y = A X$ or $A^T X$ depending on the shape of `A`
9361: Neighbor-wise Collective
9363: Input Parameters:
9364: + A - the matrix
9365: - x - the input dense matrix
9367: Output Parameter:
9368: . y - the output dense matrix
9370: Level: intermediate
9372: Note:
9373: This allows one to use either the restriction or interpolation (its transpose)
9374: matrix to do the interpolation. `y` matrix can be reused if already created with the proper sizes,
9375: otherwise it will be recreated. `y` must be initialized to `NULL` if not supplied.
9377: .seealso: [](ch_matrices), `Mat`, `MatInterpolate()`, `MatRestrict()`, `MatMatRestrict()`, `PCMG`
9378: @*/
9379: PetscErrorCode MatMatInterpolate(Mat A, Mat x, Mat *y)
9380: {
9381: PetscFunctionBegin;
9382: PetscCall(MatMatInterpolateAdd(A, x, NULL, y));
9383: PetscFunctionReturn(PETSC_SUCCESS);
9384: }
9386: /*@
9387: MatMatRestrict - $Y = A X$ or $A^T X$ depending on the shape of `A`
9389: Neighbor-wise Collective
9391: Input Parameters:
9392: + A - the matrix
9393: - x - the input dense matrix
9395: Output Parameter:
9396: . y - the output dense matrix
9398: Level: intermediate
9400: Note:
9401: This allows one to use either the restriction or interpolation (its transpose)
9402: matrix to do the restriction. `y` matrix can be reused if already created with the proper sizes,
9403: otherwise it will be recreated. `y` must be initialized to `NULL` if not supplied.
9405: .seealso: [](ch_matrices), `Mat`, `MatRestrict()`, `MatInterpolate()`, `MatMatInterpolate()`, `PCMG`
9406: @*/
9407: PetscErrorCode MatMatRestrict(Mat A, Mat x, Mat *y)
9408: {
9409: PetscFunctionBegin;
9410: PetscCall(MatMatInterpolateAdd(A, x, NULL, y));
9411: PetscFunctionReturn(PETSC_SUCCESS);
9412: }
9414: /*@
9415: MatGetNullSpace - retrieves the null space of a matrix that was provided with `MatSetNullSpace()`
9417: Logically Collective
9419: Input Parameters:
9420: + mat - the matrix
9421: - nullsp - the null space object
9423: Level: developer
9425: .seealso: [](ch_matrices), `Mat`, `MatCreate()`, `MatNullSpaceCreate()`, `MatSetNearNullSpace()`, `MatSetNullSpace()`, `MatNullSpace`
9426: @*/
9427: PetscErrorCode MatGetNullSpace(Mat mat, MatNullSpace *nullsp)
9428: {
9429: PetscFunctionBegin;
9431: PetscAssertPointer(nullsp, 2);
9432: *nullsp = (mat->symmetric == PETSC_BOOL3_TRUE && !mat->nullsp) ? mat->transnullsp : mat->nullsp;
9433: PetscFunctionReturn(PETSC_SUCCESS);
9434: }
9436: /*@
9437: MatGetNullSpaces - gets the null spaces, transpose null spaces, and near null spaces from an array of matrices that were supplied with `MatSetNullSpace()`,
9438: `MatSetTransposeNullSpace()`, and `MatSetNearNullSpace()`
9440: Logically Collective
9442: Input Parameters:
9443: + n - the number of matrices
9444: - mat - the array of matrices
9446: Output Parameters:
9447: . nullsp - an array of null spaces, `NULL` will be inserted for each matrix that does not have a null space, length 3 * `n`
9449: Level: developer
9451: Note:
9452: Call `MatRestoreNullspaces()` to provide these to another array of matrices
9454: .seealso: [](ch_matrices), `Mat`, `MatCreate()`, `MatNullSpaceCreate()`, `MatSetNearNullSpace()`, `MatGetNullSpace()`, `MatSetTransposeNullSpace()`, `MatGetTransposeNullSpace()`,
9455: `MatNullSpaceRemove()`, `MatRestoreNullSpaces()`, `MatNullSpace`
9456: @*/
9457: PetscErrorCode MatGetNullSpaces(PetscInt n, Mat mat[], MatNullSpace *nullsp[])
9458: {
9459: PetscFunctionBegin;
9460: PetscCheck(n >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Number of matrices %" PetscInt_FMT " must be non-negative", n);
9461: PetscAssertPointer(mat, 2);
9462: PetscAssertPointer(nullsp, 3);
9464: PetscCall(PetscCalloc1(3 * n, nullsp));
9465: for (PetscInt i = 0; i < n; i++) {
9467: (*nullsp)[i] = mat[i]->nullsp;
9468: PetscCall(PetscObjectReference((PetscObject)(*nullsp)[i]));
9469: (*nullsp)[n + i] = mat[i]->nearnullsp;
9470: PetscCall(PetscObjectReference((PetscObject)(*nullsp)[n + i]));
9471: (*nullsp)[2 * n + i] = mat[i]->transnullsp;
9472: PetscCall(PetscObjectReference((PetscObject)(*nullsp)[2 * n + i]));
9473: }
9474: PetscFunctionReturn(PETSC_SUCCESS);
9475: }
9477: /*@
9478: MatRestoreNullSpaces - sets the null spaces, transpose null spaces, and near null spaces obtained with `MatGetNullSpaces()` for an array of matrices
9480: Logically Collective
9482: Input Parameters:
9483: + n - the number of matrices
9484: . mat - the array of matrices
9485: - nullsp - an array of null spaces, of length 3 * `n`
9487: Level: developer
9489: Notes:
9490: Call `MatGetNullSpaces()` to create `nullsp`.
9492: Frees `nullsp`.
9494: Developer Note:
9495: The name of this function is confusing. Traditionally in PETSc, a restore operation undoes something that was previously done on an object (or objects) with a get operation.
9496: This restore routine does something to a new set of objects using the results of a get operation on a previous set of objects. Perhaps this routine
9497: should have simply been called `MatSetNullSpaces()`
9499: .seealso: [](ch_matrices), `Mat`, `MatCreate()`, `MatNullSpaceCreate()`, `MatSetNearNullSpace()`, `MatGetNullSpace()`, `MatSetTransposeNullSpace()`, `MatGetTransposeNullSpace()`,
9500: `MatNullSpaceRemove()`, `MatGetNullSpaces()`, `MatNullSpace`
9501: @*/
9502: PetscErrorCode MatRestoreNullSpaces(PetscInt n, Mat mat[], MatNullSpace *nullsp[])
9503: {
9504: PetscFunctionBegin;
9505: PetscCheck(n >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Number of matrices %" PetscInt_FMT " must be non-negative", n);
9506: PetscAssertPointer(mat, 2);
9507: PetscAssertPointer(nullsp, 3);
9508: PetscAssertPointer(*nullsp, 3);
9510: for (PetscInt i = 0; i < n; i++) {
9512: PetscCall(MatSetNullSpace(mat[i], (*nullsp)[i]));
9513: PetscCall(PetscObjectDereference((PetscObject)(*nullsp)[i]));
9514: PetscCall(MatSetNearNullSpace(mat[i], (*nullsp)[n + i]));
9515: PetscCall(PetscObjectDereference((PetscObject)(*nullsp)[n + i]));
9516: PetscCall(MatSetTransposeNullSpace(mat[i], (*nullsp)[2 * n + i]));
9517: PetscCall(PetscObjectDereference((PetscObject)(*nullsp)[2 * n + i]));
9518: }
9519: PetscCall(PetscFree(*nullsp));
9520: PetscFunctionReturn(PETSC_SUCCESS);
9521: }
9523: /*@
9524: MatSetNullSpace - attaches a null space to a matrix.
9526: Logically Collective
9528: Input Parameters:
9529: + mat - the matrix
9530: - nullsp - the null space object
9532: Level: advanced
9534: Notes:
9535: This null space is used by the `KSP` linear solvers to solve singular systems.
9537: 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`
9539: 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
9540: to zero but the linear system will still be solved in a least squares sense.
9542: The fundamental theorem of linear algebra (Gilbert Strang, Introduction to Applied Mathematics, page 72) states that
9543: 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)$.
9544: 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
9545: $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
9546: 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)$.
9547: This $\hat{b}$ can be obtained by calling `MatNullSpaceRemove()` with the null space of the transpose of the matrix.
9549: If the matrix is known to be symmetric because it is an `MATSBAIJ` matrix or one has called
9550: `MatSetOption`(mat,`MAT_SYMMETRIC` or possibly `MAT_SYMMETRY_ETERNAL`,`PETSC_TRUE`); this
9551: routine also automatically calls `MatSetTransposeNullSpace()`.
9553: The user should call `MatNullSpaceDestroy()`.
9555: .seealso: [](ch_matrices), `Mat`, `MatCreate()`, `MatNullSpaceCreate()`, `MatSetNearNullSpace()`, `MatGetNullSpace()`, `MatSetTransposeNullSpace()`, `MatGetTransposeNullSpace()`, `MatNullSpaceRemove()`,
9556: `KSPSetPCSide()`, `MatNullSpace`
9557: @*/
9558: PetscErrorCode MatSetNullSpace(Mat mat, MatNullSpace nullsp)
9559: {
9560: PetscFunctionBegin;
9563: PetscCall(PetscObjectReference((PetscObject)nullsp));
9564: PetscCall(MatNullSpaceDestroy(&mat->nullsp));
9565: mat->nullsp = nullsp;
9566: if (mat->symmetric == PETSC_BOOL3_TRUE) PetscCall(MatSetTransposeNullSpace(mat, nullsp));
9567: PetscFunctionReturn(PETSC_SUCCESS);
9568: }
9570: /*@
9571: MatGetTransposeNullSpace - retrieves the null space of the transpose of a matrix that was set with `MatSetTransposeNullSpace()`
9573: Logically Collective
9575: Input Parameters:
9576: + mat - the matrix
9577: - nullsp - the null space object
9579: Level: developer
9581: .seealso: [](ch_matrices), `Mat`, `MatNullSpace`, `MatCreate()`, `MatNullSpaceCreate()`, `MatSetNearNullSpace()`, `MatSetTransposeNullSpace()`, `MatSetNullSpace()`, `MatGetNullSpace()`
9582: @*/
9583: PetscErrorCode MatGetTransposeNullSpace(Mat mat, MatNullSpace *nullsp)
9584: {
9585: PetscFunctionBegin;
9588: PetscAssertPointer(nullsp, 2);
9589: *nullsp = (mat->symmetric == PETSC_BOOL3_TRUE && !mat->transnullsp) ? mat->nullsp : mat->transnullsp;
9590: PetscFunctionReturn(PETSC_SUCCESS);
9591: }
9593: /*@
9594: MatSetTransposeNullSpace - attaches the null space of a transpose of a matrix to the matrix
9596: Logically Collective
9598: Input Parameters:
9599: + mat - the matrix
9600: - nullsp - the null space object
9602: Level: advanced
9604: Notes:
9605: This allows solving singular linear systems defined by the transpose of the matrix using `KSP` solvers with left preconditioning.
9607: See `MatSetNullSpace()`
9609: .seealso: [](ch_matrices), `Mat`, `MatNullSpace`, `MatCreate()`, `MatNullSpaceCreate()`, `MatSetNearNullSpace()`, `MatGetNullSpace()`, `MatSetNullSpace()`, `MatGetTransposeNullSpace()`, `MatNullSpaceRemove()`, `KSPSetPCSide()`
9610: @*/
9611: PetscErrorCode MatSetTransposeNullSpace(Mat mat, MatNullSpace nullsp)
9612: {
9613: PetscFunctionBegin;
9616: PetscCall(PetscObjectReference((PetscObject)nullsp));
9617: PetscCall(MatNullSpaceDestroy(&mat->transnullsp));
9618: mat->transnullsp = nullsp;
9619: PetscFunctionReturn(PETSC_SUCCESS);
9620: }
9622: /*@
9623: MatSetNearNullSpace - attaches a null space to a matrix, which is often the null space (rigid body modes) of the operator without boundary conditions
9624: This null space will be used to provide near null space vectors to a multigrid preconditioner built from this matrix.
9626: Logically Collective
9628: Input Parameters:
9629: + mat - the matrix
9630: - nullsp - the null space object
9632: Level: advanced
9634: Notes:
9635: Overwrites any previous near null space that may have been attached
9637: You can remove the null space by calling this routine with an `nullsp` of `NULL`
9639: .seealso: [](ch_matrices), `Mat`, `MatNullSpace`, `MatCreate()`, `MatNullSpaceCreate()`, `MatSetNullSpace()`, `MatNullSpaceCreateRigidBody()`, `MatGetNearNullSpace()`
9640: @*/
9641: PetscErrorCode MatSetNearNullSpace(Mat mat, MatNullSpace nullsp)
9642: {
9643: PetscFunctionBegin;
9647: MatCheckPreallocated(mat, 1);
9648: PetscCall(PetscObjectReference((PetscObject)nullsp));
9649: PetscCall(MatNullSpaceDestroy(&mat->nearnullsp));
9650: mat->nearnullsp = nullsp;
9651: PetscFunctionReturn(PETSC_SUCCESS);
9652: }
9654: /*@
9655: MatGetNearNullSpace - Get null space from a matrix that was attached with `MatSetNearNullSpace()`
9657: Not Collective
9659: Input Parameter:
9660: . mat - the matrix
9662: Output Parameter:
9663: . nullsp - the null space object, `NULL` if not set
9665: Level: advanced
9667: .seealso: [](ch_matrices), `Mat`, `MatNullSpace`, `MatSetNearNullSpace()`, `MatGetNullSpace()`, `MatNullSpaceCreate()`
9668: @*/
9669: PetscErrorCode MatGetNearNullSpace(Mat mat, MatNullSpace *nullsp)
9670: {
9671: PetscFunctionBegin;
9674: PetscAssertPointer(nullsp, 2);
9675: MatCheckPreallocated(mat, 1);
9676: *nullsp = mat->nearnullsp;
9677: PetscFunctionReturn(PETSC_SUCCESS);
9678: }
9680: /*@
9681: MatICCFactor - Performs in-place incomplete Cholesky factorization of matrix.
9683: Collective
9685: Input Parameters:
9686: + mat - the matrix
9687: . row - row/column permutation
9688: - info - information on desired factorization process
9690: Level: developer
9692: Notes:
9693: Probably really in-place only when level of fill is zero, otherwise allocates
9694: new space to store factored matrix and deletes previous memory.
9696: Most users should employ the `KSP` interface for linear solvers
9697: instead of working directly with matrix algebra routines such as this.
9698: See, e.g., `KSPCreate()`.
9700: Fortran Note:
9701: A valid (non-null) `info` argument must be provided
9703: .seealso: [](ch_matrices), `Mat`, `MatFactorInfo`, `MatGetFactor()`, `MatICCFactorSymbolic()`, `MatLUFactorNumeric()`, `MatCholeskyFactor()`
9704: @*/
9705: PetscErrorCode MatICCFactor(Mat mat, IS row, const MatFactorInfo *info)
9706: {
9707: PetscFunctionBegin;
9711: PetscAssertPointer(info, 3);
9712: PetscCheck(mat->rmap->N == mat->cmap->N, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONG, "matrix must be square");
9713: PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
9714: PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
9715: MatCheckPreallocated(mat, 1);
9716: PetscUseTypeMethod(mat, iccfactor, row, info);
9717: PetscCall(PetscObjectStateIncrease((PetscObject)mat));
9718: PetscFunctionReturn(PETSC_SUCCESS);
9719: }
9721: /*@
9722: MatDiagonalScaleLocal - Scales columns of a matrix given the scaling values including the
9723: ghosted ones.
9725: Not Collective
9727: Input Parameters:
9728: + mat - the matrix
9729: - diag - the diagonal values, including ghost ones
9731: Level: developer
9733: Notes:
9734: Works only for `MATMPIAIJ` and `MATMPIBAIJ` matrices
9736: `diag` is a sequential vector that has a length which is the same as the local (ghosted) length of the vector associated with
9737: the matrix's `ISLocalToGlobalMapping` set with `MatSetLocalToGlobalMapping()`.
9739: This allows one to avoid during communication to perform the scaling that must be done with `MatDiagonalScale()`.
9741: .seealso: [](ch_matrices), `Mat`, `MatDiagonalScale()`, `MatSetLocalToGlobalMapping()`, `ISLocalToGlobalMapping`
9742: @*/
9743: PetscErrorCode MatDiagonalScaleLocal(Mat mat, Vec diag)
9744: {
9745: PetscMPIInt size;
9747: PetscFunctionBegin;
9752: PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Matrix must be already assembled");
9753: PetscCall(PetscLogEventBegin(MAT_Scale, mat, 0, 0, 0));
9754: PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)mat), &size));
9755: if (size == 1) {
9756: PetscInt n, m;
9757: PetscCall(VecGetSize(diag, &n));
9758: PetscCall(MatGetSize(mat, NULL, &m));
9759: PetscCheck(m == n, PETSC_COMM_SELF, PETSC_ERR_SUP, "Only supported for sequential matrices when no ghost points/periodic conditions");
9760: PetscCall(MatDiagonalScale(mat, NULL, diag));
9761: } else PetscUseMethod(mat, "MatDiagonalScaleLocal_C", (Mat, Vec), (mat, diag));
9762: PetscCall(PetscLogEventEnd(MAT_Scale, mat, 0, 0, 0));
9763: PetscCall(PetscObjectStateIncrease((PetscObject)mat));
9764: PetscFunctionReturn(PETSC_SUCCESS);
9765: }
9767: /*@
9768: MatGetInertia - Gets the inertia from a factored matrix
9770: Collective
9772: Input Parameter:
9773: . mat - the matrix
9775: Output Parameters:
9776: + nneg - number of negative eigenvalues
9777: . nzero - number of zero eigenvalues
9778: - npos - number of positive eigenvalues
9780: Level: advanced
9782: Note:
9783: Matrix must have been factored by `MatCholeskyFactor()`
9785: .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatCholeskyFactor()`
9786: @*/
9787: PetscErrorCode MatGetInertia(Mat mat, PetscInt *nneg, PetscInt *nzero, PetscInt *npos)
9788: {
9789: PetscFunctionBegin;
9792: PetscCheck(mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Unfactored matrix");
9793: PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Numeric factor mat is not assembled");
9794: PetscUseTypeMethod(mat, getinertia, nneg, nzero, npos);
9795: PetscFunctionReturn(PETSC_SUCCESS);
9796: }
9798: /*@
9799: MatSolves - Solves $A x = b$, given a factored matrix, for a collection of vectors
9801: Neighbor-wise Collective
9803: Input Parameters:
9804: + mat - the factored matrix obtained with `MatGetFactor()`
9805: - b - the right-hand-side vectors
9807: Output Parameter:
9808: . x - the result vectors
9810: Level: developer
9812: Note:
9813: The vectors `b` and `x` cannot be the same. I.e., one cannot
9814: call `MatSolves`(A,x,x).
9816: .seealso: [](ch_matrices), `Mat`, `Vecs`, `MatGetFactor()`, `MatSolveAdd()`, `MatSolveTranspose()`, `MatSolveTransposeAdd()`, `MatSolve()`
9817: @*/
9818: PetscErrorCode MatSolves(Mat mat, Vecs b, Vecs x)
9819: {
9820: PetscFunctionBegin;
9823: PetscCheck(x != b, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_IDN, "x and b must be different vectors");
9824: PetscCheck(mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Unfactored matrix");
9825: if (!mat->rmap->N && !mat->cmap->N) PetscFunctionReturn(PETSC_SUCCESS);
9827: MatCheckPreallocated(mat, 1);
9828: PetscCall(PetscLogEventBegin(MAT_Solves, mat, 0, 0, 0));
9829: PetscUseTypeMethod(mat, solves, b, x);
9830: PetscCall(PetscLogEventEnd(MAT_Solves, mat, 0, 0, 0));
9831: PetscFunctionReturn(PETSC_SUCCESS);
9832: }
9834: /*@
9835: MatIsSymmetric - Test whether a matrix is symmetric
9837: Collective
9839: Input Parameters:
9840: + A - the matrix to test
9841: - tol - difference between value and its transpose less than this amount counts as equal (use 0.0 for exact transpose)
9843: Output Parameter:
9844: . flg - the result
9846: Level: intermediate
9848: Notes:
9849: For real numbers `MatIsSymmetric()` and `MatIsHermitian()` return identical results
9851: If the matrix does not yet know if it is symmetric or not this can be an expensive operation, also available `MatIsSymmetricKnown()`
9853: One can declare that a matrix is symmetric with `MatSetOption`(mat,`MAT_SYMMETRIC`,`PETSC_TRUE`) and if it is known to remain symmetric
9854: after changes to the matrices values one can call `MatSetOption`(mat,`MAT_SYMMETRY_ETERNAL`,`PETSC_TRUE`). If these properties
9855: have been set then `MatIsSymmetric()` does not need to perform any computations and returns immediately with the result.
9857: .seealso: [](ch_matrices), `Mat`, `MatTranspose()`, `MatIsTranspose()`, `MatIsHermitian()`, `MatIsStructurallySymmetric()`, `MatSetOption()`, `MatIsSymmetricKnown()`,
9858: `MAT_SYMMETRIC`, `MAT_SYMMETRY_ETERNAL`
9859: @*/
9860: PetscErrorCode MatIsSymmetric(Mat A, PetscReal tol, PetscBool *flg)
9861: {
9862: PetscFunctionBegin;
9864: PetscAssertPointer(flg, 3);
9865: if (A->symmetric != PETSC_BOOL3_UNKNOWN && !tol) *flg = PetscBool3ToBool(A->symmetric);
9866: else {
9867: if (A->ops->issymmetric) PetscUseTypeMethod(A, issymmetric, tol, flg);
9868: else PetscCall(MatIsTranspose(A, A, tol, flg));
9869: if (!tol) PetscCall(MatSetOption(A, MAT_SYMMETRIC, *flg));
9870: }
9871: PetscFunctionReturn(PETSC_SUCCESS);
9872: }
9874: /*@
9875: MatIsHermitian - Test whether a matrix is Hermitian
9877: Collective
9879: Input Parameters:
9880: + A - the matrix to test
9881: - tol - difference between value and its transpose less than this amount counts as equal (use 0.0 for exact Hermitian)
9883: Output Parameter:
9884: . flg - the result
9886: Level: intermediate
9888: Notes:
9889: For real numbers `MatIsSymmetric()` and `MatIsHermitian()` return identical results
9891: If the matrix does not yet know if it is Hermitian or not this can be an expensive operation, also available `MatIsHermitianKnown()`
9893: One can declare that a matrix is Hermitian with `MatSetOption`(mat,`MAT_HERMITIAN`,`PETSC_TRUE`) and if it is known to remain Hermitian
9894: after changes to the matrices values one can call `MatSetOption`(mat,`MAT_SYMMETRY_ETERNAL`,`PETSC_TRUE`). If these properties
9895: have been set then `MatIsHermitian()` does not need to perform any computations and returns immediately with the result.
9897: .seealso: [](ch_matrices), `Mat`, `MatTranspose()`, `MatIsTranspose()`, `MatIsHermitianKnown()`, `MatIsStructurallySymmetric()`, `MatSetOption()`,
9898: `MatIsSymmetricKnown()`, `MatIsSymmetric()`, `MAT_HERMITIAN`, `MAT_SYMMETRY_ETERNAL`
9899: @*/
9900: PetscErrorCode MatIsHermitian(Mat A, PetscReal tol, PetscBool *flg)
9901: {
9902: PetscFunctionBegin;
9904: PetscAssertPointer(flg, 3);
9905: if (A->hermitian != PETSC_BOOL3_UNKNOWN && !tol) *flg = PetscBool3ToBool(A->hermitian);
9906: else {
9907: if (A->ops->ishermitian) PetscUseTypeMethod(A, ishermitian, tol, flg);
9908: else PetscCall(MatIsHermitianTranspose(A, A, tol, flg));
9909: if (!tol) PetscCall(MatSetOption(A, MAT_HERMITIAN, *flg));
9910: }
9911: PetscFunctionReturn(PETSC_SUCCESS);
9912: }
9914: /*@
9915: MatIsSymmetricKnown - Checks if a matrix knows if it is symmetric or not and its symmetric state
9917: Not Collective
9919: Input Parameter:
9920: . A - the matrix to check
9922: Output Parameters:
9923: + set - `PETSC_TRUE` if the matrix knows its symmetry state (this tells you if the next flag is valid)
9924: - flg - the result (only valid if set is `PETSC_TRUE`)
9926: Level: advanced
9928: Notes:
9929: Does not check the matrix values directly, so this may return unknown (set = `PETSC_FALSE`). Use `MatIsSymmetric()`
9930: if you want it explicitly checked
9932: One can declare that a matrix is symmetric with `MatSetOption`(mat,`MAT_SYMMETRIC`,`PETSC_TRUE`) and if it is known to remain symmetric
9933: after changes to the matrices values one can call `MatSetOption`(mat,`MAT_SYMMETRY_ETERNAL`,`PETSC_TRUE`)
9935: .seealso: [](ch_matrices), `Mat`, `MAT_SYMMETRY_ETERNAL`, `MatTranspose()`, `MatIsTranspose()`, `MatIsHermitian()`, `MatIsStructurallySymmetric()`, `MatSetOption()`, `MatIsSymmetric()`, `MatIsHermitianKnown()`
9936: @*/
9937: PetscErrorCode MatIsSymmetricKnown(Mat A, PetscBool *set, PetscBool *flg)
9938: {
9939: PetscFunctionBegin;
9941: PetscAssertPointer(set, 2);
9942: PetscAssertPointer(flg, 3);
9943: if (A->symmetric != PETSC_BOOL3_UNKNOWN) {
9944: *set = PETSC_TRUE;
9945: *flg = PetscBool3ToBool(A->symmetric);
9946: } else *set = PETSC_FALSE;
9947: PetscFunctionReturn(PETSC_SUCCESS);
9948: }
9950: /*@
9951: MatIsSPDKnown - Checks if a matrix knows if it is symmetric positive definite or not and its symmetric positive definite state
9953: Not Collective
9955: Input Parameter:
9956: . A - the matrix to check
9958: Output Parameters:
9959: + set - `PETSC_TRUE` if the matrix knows its symmetric positive definite state (this tells you if the next flag is valid)
9960: - flg - the result (only valid if set is `PETSC_TRUE`)
9962: Level: advanced
9964: Notes:
9965: Does not check the matrix values directly, so this may return unknown (set = `PETSC_FALSE`).
9967: One can declare that a matrix is SPD with `MatSetOption`(mat,`MAT_SPD`,`PETSC_TRUE`) and if it is known to remain SPD
9968: after changes to the matrices values one can call `MatSetOption`(mat,`MAT_SPD_ETERNAL`,`PETSC_TRUE`)
9970: .seealso: [](ch_matrices), `Mat`, `MAT_SPD_ETERNAL`, `MAT_SPD`, `MatTranspose()`, `MatIsTranspose()`, `MatIsHermitian()`, `MatIsStructurallySymmetric()`, `MatSetOption()`, `MatIsSymmetric()`, `MatIsHermitianKnown()`
9971: @*/
9972: PetscErrorCode MatIsSPDKnown(Mat A, PetscBool *set, PetscBool *flg)
9973: {
9974: PetscFunctionBegin;
9976: PetscAssertPointer(set, 2);
9977: PetscAssertPointer(flg, 3);
9978: if (A->spd != PETSC_BOOL3_UNKNOWN) {
9979: *set = PETSC_TRUE;
9980: *flg = PetscBool3ToBool(A->spd);
9981: } else *set = PETSC_FALSE;
9982: PetscFunctionReturn(PETSC_SUCCESS);
9983: }
9985: /*@
9986: MatIsHermitianKnown - Checks if a matrix knows if it is Hermitian or not and its Hermitian state
9988: Not Collective
9990: Input Parameter:
9991: . A - the matrix to check
9993: Output Parameters:
9994: + set - `PETSC_TRUE` if the matrix knows its Hermitian state (this tells you if the next flag is valid)
9995: - flg - the result (only valid if set is `PETSC_TRUE`)
9997: Level: advanced
9999: Notes:
10000: Does not check the matrix values directly, so this may return unknown (set = `PETSC_FALSE`). Use `MatIsHermitian()`
10001: if you want it explicitly checked
10003: One can declare that a matrix is Hermitian with `MatSetOption`(mat,`MAT_HERMITIAN`,`PETSC_TRUE`) and if it is known to remain Hermitian
10004: after changes to the matrices values one can call `MatSetOption`(mat,`MAT_SYMMETRY_ETERNAL`,`PETSC_TRUE`)
10006: .seealso: [](ch_matrices), `Mat`, `MAT_SYMMETRY_ETERNAL`, `MAT_HERMITIAN`, `MatTranspose()`, `MatIsTranspose()`, `MatIsHermitian()`, `MatIsStructurallySymmetric()`, `MatSetOption()`, `MatIsSymmetric()`
10007: @*/
10008: PetscErrorCode MatIsHermitianKnown(Mat A, PetscBool *set, PetscBool *flg)
10009: {
10010: PetscFunctionBegin;
10012: PetscAssertPointer(set, 2);
10013: PetscAssertPointer(flg, 3);
10014: if (A->hermitian != PETSC_BOOL3_UNKNOWN) {
10015: *set = PETSC_TRUE;
10016: *flg = PetscBool3ToBool(A->hermitian);
10017: } else *set = PETSC_FALSE;
10018: PetscFunctionReturn(PETSC_SUCCESS);
10019: }
10021: /*@
10022: MatIsStructurallySymmetric - Test whether a matrix is structurally symmetric
10024: Collective
10026: Input Parameter:
10027: . A - the matrix to test
10029: Output Parameter:
10030: . flg - the result
10032: Level: intermediate
10034: Notes:
10035: If the matrix does yet know it is structurally symmetric this can be an expensive operation, also available `MatIsStructurallySymmetricKnown()`
10037: 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
10038: symmetric after changes to the matrices values one can call `MatSetOption`(mat,`MAT_STRUCTURAL_SYMMETRY_ETERNAL`,`PETSC_TRUE`). If these properties
10039: have been set then `MatIsStructurallySymmetric()` does not need to perform any computations and returns immediately with the result.
10041: .seealso: [](ch_matrices), `Mat`, `MAT_STRUCTURALLY_SYMMETRIC`, `MAT_STRUCTURAL_SYMMETRY_ETERNAL`, `MatTranspose()`, `MatIsTranspose()`, `MatIsHermitian()`, `MatIsSymmetric()`, `MatSetOption()`, `MatIsStructurallySymmetricKnown()`
10042: @*/
10043: PetscErrorCode MatIsStructurallySymmetric(Mat A, PetscBool *flg)
10044: {
10045: PetscFunctionBegin;
10047: PetscAssertPointer(flg, 2);
10048: if (A->structurally_symmetric != PETSC_BOOL3_UNKNOWN) *flg = PetscBool3ToBool(A->structurally_symmetric);
10049: else {
10050: PetscUseTypeMethod(A, isstructurallysymmetric, flg);
10051: PetscCall(MatSetOption(A, MAT_STRUCTURALLY_SYMMETRIC, *flg));
10052: }
10053: PetscFunctionReturn(PETSC_SUCCESS);
10054: }
10056: /*@
10057: MatIsStructurallySymmetricKnown - Checks if a matrix knows if it is structurally symmetric or not and its structurally symmetric state
10059: Not Collective
10061: Input Parameter:
10062: . A - the matrix to check
10064: Output Parameters:
10065: + set - `PETSC_TRUE` if the matrix knows its structurally symmetric state (this tells you if the next flag is valid)
10066: - flg - the result (only valid if set is `PETSC_TRUE`)
10068: Level: advanced
10070: Notes:
10071: 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
10072: symmetric after changes to the matrices values one can call `MatSetOption`(mat,`MAT_STRUCTURAL_SYMMETRY_ETERNAL`,`PETSC_TRUE`)
10074: Use `MatIsStructurallySymmetric()` to explicitly check if a matrix is structurally symmetric (this is an expensive operation)
10076: .seealso: [](ch_matrices), `Mat`, `MAT_STRUCTURALLY_SYMMETRIC`, `MatTranspose()`, `MatIsTranspose()`, `MatIsHermitian()`, `MatIsStructurallySymmetric()`, `MatSetOption()`, `MatIsSymmetric()`, `MatIsHermitianKnown()`
10077: @*/
10078: PetscErrorCode MatIsStructurallySymmetricKnown(Mat A, PetscBool *set, PetscBool *flg)
10079: {
10080: PetscFunctionBegin;
10082: PetscAssertPointer(set, 2);
10083: PetscAssertPointer(flg, 3);
10084: if (A->structurally_symmetric != PETSC_BOOL3_UNKNOWN) {
10085: *set = PETSC_TRUE;
10086: *flg = PetscBool3ToBool(A->structurally_symmetric);
10087: } else *set = PETSC_FALSE;
10088: PetscFunctionReturn(PETSC_SUCCESS);
10089: }
10091: /*@
10092: MatStashGetInfo - Gets how many values are currently in the matrix stash, i.e. need
10093: to be communicated to other processes during the `MatAssemblyBegin()`/`MatAssemblyEnd()` process
10095: Not Collective
10097: Input Parameter:
10098: . mat - the matrix
10100: Output Parameters:
10101: + nstash - the size of the stash
10102: . reallocs - the number of additional mallocs incurred.
10103: . bnstash - the size of the block stash
10104: - breallocs - the number of additional mallocs incurred.in the block stash
10106: Level: advanced
10108: .seealso: [](ch_matrices), `MatAssemblyBegin()`, `MatAssemblyEnd()`, `Mat`, `MatStashSetInitialSize()`
10109: @*/
10110: PetscErrorCode MatStashGetInfo(Mat mat, PetscInt *nstash, PetscInt *reallocs, PetscInt *bnstash, PetscInt *breallocs)
10111: {
10112: PetscFunctionBegin;
10113: PetscCall(MatStashGetInfo_Private(&mat->stash, nstash, reallocs));
10114: PetscCall(MatStashGetInfo_Private(&mat->bstash, bnstash, breallocs));
10115: PetscFunctionReturn(PETSC_SUCCESS);
10116: }
10118: /*@
10119: MatCreateVecs - Get vector(s) compatible with the matrix, i.e. with the same
10120: parallel layout, `PetscLayout` for rows and columns
10122: Collective
10124: Input Parameter:
10125: . mat - the matrix
10127: Output Parameters:
10128: + right - (optional) vector that the matrix can be multiplied against
10129: - left - (optional) vector that the matrix vector product can be stored in
10131: Options Database Key:
10132: . -mat_vec_type type - set the `VecType` of the created vectors during `MatSetFromOptions()`
10134: Level: advanced
10136: Notes:
10137: 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()`.
10139: 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`.
10141: These are new vectors which are not owned by the `mat`, they should be destroyed with `VecDestroy()` when no longer needed.
10143: PETSc `Vec` always have all zero entries when created with `MatCreateVecs()` until routines such as `VecSet()` or `VecSetValues()`
10144: are used to change the values. There is no reason to call `VecZeroEntries()` after creation.
10146: .seealso: [](ch_matrices), `Mat`, `Vec`, `VecCreate()`, `VecDestroy()`, `DMCreateGlobalVector()`, `MatSetVecType()`
10147: @*/
10148: PetscErrorCode MatCreateVecs(Mat mat, Vec *right, Vec *left)
10149: {
10150: PetscFunctionBegin;
10153: if (mat->ops->getvecs) {
10154: PetscUseTypeMethod(mat, getvecs, right, left);
10155: } else {
10156: if (right) {
10157: PetscCheck(mat->cmap->n >= 0, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "PetscLayout for columns not yet setup");
10158: PetscCall(VecCreateWithLayout_Private(mat->cmap, right));
10159: PetscCall(VecSetType(*right, mat->defaultvectype));
10160: #if PetscDefined(HAVE_VIENNACL) || PetscDefined(HAVE_CUDA) || PetscDefined(HAVE_HIP)
10161: if (mat->boundtocpu && mat->bindingpropagates) {
10162: PetscCall(VecSetBindingPropagates(*right, PETSC_TRUE));
10163: PetscCall(VecBindToCPU(*right, PETSC_TRUE));
10164: }
10165: #endif
10166: }
10167: if (left) {
10168: PetscCheck(mat->rmap->n >= 0, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "PetscLayout for rows not yet setup");
10169: PetscCall(VecCreateWithLayout_Private(mat->rmap, left));
10170: PetscCall(VecSetType(*left, mat->defaultvectype));
10171: #if PetscDefined(HAVE_VIENNACL) || PetscDefined(HAVE_CUDA) || PetscDefined(HAVE_HIP)
10172: if (mat->boundtocpu && mat->bindingpropagates) {
10173: PetscCall(VecSetBindingPropagates(*left, PETSC_TRUE));
10174: PetscCall(VecBindToCPU(*left, PETSC_TRUE));
10175: }
10176: #endif
10177: }
10178: }
10179: PetscFunctionReturn(PETSC_SUCCESS);
10180: }
10182: /*@
10183: MatFactorInfoInitialize - Initializes a `MatFactorInfo` data structure
10184: with default values.
10186: Not Collective
10188: Input Parameter:
10189: . info - the `MatFactorInfo` data structure
10191: Level: developer
10193: Notes:
10194: The solvers are generally used through the `KSP` and `PC` objects, for example
10195: `PCLU`, `PCILU`, `PCCHOLESKY`, `PCICC`
10197: Once the data structure is initialized one may change certain entries as desired for the particular factorization to be performed
10199: .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatFactorInfo`
10200: @*/
10201: PetscErrorCode MatFactorInfoInitialize(MatFactorInfo *info)
10202: {
10203: PetscFunctionBegin;
10204: PetscCall(PetscMemzero(info, sizeof(MatFactorInfo)));
10205: PetscFunctionReturn(PETSC_SUCCESS);
10206: }
10208: /*@
10209: MatFactorSetSchurIS - Set indices corresponding to the Schur complement you wish to have computed
10211: Collective
10213: Input Parameters:
10214: + mat - the factored matrix
10215: - is - the index set defining the Schur indices (0-based)
10217: Level: advanced
10219: Notes:
10220: Call `MatFactorSolveSchurComplement()` or `MatFactorSolveSchurComplementTranspose()` after this call to solve a Schur complement system.
10222: You can call `MatFactorGetSchurComplement()` or `MatFactorCreateSchurComplement()` after this call.
10224: This functionality is only supported for `MATSOLVERMUMPS` and `MATSOLVERMKL_PARDISO`
10226: .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatFactorGetSchurComplement()`, `MatFactorRestoreSchurComplement()`, `MatFactorCreateSchurComplement()`, `MatFactorSolveSchurComplement()`,
10227: `MatFactorSolveSchurComplementTranspose()`, `MATSOLVERMUMPS`, `MATSOLVERMKL_PARDISO`
10228: @*/
10229: PetscErrorCode MatFactorSetSchurIS(Mat mat, IS is)
10230: {
10231: PetscErrorCode (*f)(Mat, IS);
10233: PetscFunctionBegin;
10238: PetscCheckSameComm(mat, 1, is, 2);
10239: PetscCheck(mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Only for factored matrix");
10240: PetscCall(PetscObjectQueryFunction((PetscObject)mat, "MatFactorSetSchurIS_C", &f));
10241: PetscCheck(f, PetscObjectComm((PetscObject)mat), PETSC_ERR_SUP, "The selected MatSolverType does not support Schur complement computation. You should use MATSOLVERMUMPS or MATSOLVERMKL_PARDISO");
10242: PetscCall((*f)(mat, is));
10243: PetscCheck(mat->schur, PetscObjectComm((PetscObject)mat), PETSC_ERR_PLIB, "Schur complement has not been created");
10244: PetscFunctionReturn(PETSC_SUCCESS);
10245: }
10247: /*@
10248: MatFactorCreateSchurComplement - Create a Schur complement matrix object using Schur data computed during the factorization step
10250: Logically Collective
10252: Input Parameters:
10253: + F - the factored matrix obtained by calling `MatGetFactor()`
10254: . S - location where to return the Schur complement, can be `NULL`
10255: - status - the status of the Schur complement matrix, can be `NULL`
10257: Level: advanced
10259: Notes:
10260: You must call `MatFactorSetSchurIS()` before calling this routine.
10262: This functionality is only supported for `MATSOLVERMUMPS` and `MATSOLVERMKL_PARDISO`
10264: The routine provides a copy of the Schur matrix stored within the solver data structures.
10265: The caller must destroy the object when it is no longer needed.
10266: If `MatFactorInvertSchurComplement()` has been called, the routine gets back the inverse.
10268: 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)
10270: See `MatCreateSchurComplement()` or `MatGetSchurComplement()` for ways to create virtual or approximate Schur complements.
10272: Developer Note:
10273: The reason this routine exists is because the representation of the Schur complement within the factor matrix may be different than a standard PETSc
10274: matrix representation and we normally do not want to use the time or memory to make a copy as a regular PETSc matrix.
10276: .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatFactorSetSchurIS()`, `MatFactorGetSchurComplement()`, `MatFactorSchurStatus`, `MATSOLVERMUMPS`, `MATSOLVERMKL_PARDISO`
10277: @*/
10278: PetscErrorCode MatFactorCreateSchurComplement(Mat F, Mat *S, MatFactorSchurStatus *status)
10279: {
10280: PetscFunctionBegin;
10282: if (S) PetscAssertPointer(S, 2);
10283: if (status) PetscAssertPointer(status, 3);
10284: if (S) {
10285: PetscErrorCode (*f)(Mat, Mat *);
10287: PetscCall(PetscObjectQueryFunction((PetscObject)F, "MatFactorCreateSchurComplement_C", &f));
10288: if (f) PetscCall((*f)(F, S));
10289: else PetscCall(MatDuplicate(F->schur, MAT_COPY_VALUES, S));
10290: }
10291: if (status) *status = F->schur_status;
10292: PetscFunctionReturn(PETSC_SUCCESS);
10293: }
10295: /*@
10296: MatFactorGetSchurComplement - Gets access to a Schur complement matrix using the current Schur data within a factored matrix
10298: Logically Collective
10300: Input Parameters:
10301: + F - the factored matrix obtained by calling `MatGetFactor()`
10302: . S - location where to return the Schur complement, can be `NULL`
10303: - status - the status of the Schur complement matrix, can be `NULL`
10305: Level: advanced
10307: Notes:
10308: You must call `MatFactorSetSchurIS()` before calling this routine.
10310: Schur complement mode is currently implemented for sequential matrices with factor type of `MATSOLVERMUMPS`
10312: The routine returns a the Schur Complement stored within the data structures of the solver.
10314: If `MatFactorInvertSchurComplement()` has previously been called, the returned matrix is actually the inverse of the Schur complement.
10316: The returned matrix should not be destroyed; the caller should call `MatFactorRestoreSchurComplement()` when the object is no longer needed.
10318: Use `MatFactorCreateSchurComplement()` to create a copy of the Schur complement matrix that is within a factored matrix
10320: See `MatCreateSchurComplement()` or `MatGetSchurComplement()` for ways to create virtual or approximate Schur complements.
10322: .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatFactorSetSchurIS()`, `MatFactorRestoreSchurComplement()`, `MatFactorCreateSchurComplement()`, `MatFactorSchurStatus`
10323: @*/
10324: PetscErrorCode MatFactorGetSchurComplement(Mat F, Mat *S, MatFactorSchurStatus *status)
10325: {
10326: PetscFunctionBegin;
10328: if (S) {
10329: PetscAssertPointer(S, 2);
10330: *S = F->schur;
10331: }
10332: if (status) {
10333: PetscAssertPointer(status, 3);
10334: *status = F->schur_status;
10335: }
10336: PetscFunctionReturn(PETSC_SUCCESS);
10337: }
10339: static PetscErrorCode MatFactorUpdateSchurStatus_Private(Mat F)
10340: {
10341: Mat S = F->schur;
10343: PetscFunctionBegin;
10344: switch (F->schur_status) {
10345: case MAT_FACTOR_SCHUR_UNFACTORED: // fall-through
10346: case MAT_FACTOR_SCHUR_INVERTED:
10347: if (S) {
10348: S->ops->solve = NULL;
10349: S->ops->matsolve = NULL;
10350: S->ops->solvetranspose = NULL;
10351: S->ops->matsolvetranspose = NULL;
10352: S->ops->solveadd = NULL;
10353: S->ops->solvetransposeadd = NULL;
10354: S->factortype = MAT_FACTOR_NONE;
10355: PetscCall(PetscFree(S->solvertype));
10356: }
10357: case MAT_FACTOR_SCHUR_FACTORED: // fall-through
10358: break;
10359: default:
10360: SETERRQ(PetscObjectComm((PetscObject)F), PETSC_ERR_SUP, "Unhandled MatFactorSchurStatus %d", F->schur_status);
10361: }
10362: PetscFunctionReturn(PETSC_SUCCESS);
10363: }
10365: /*@
10366: MatFactorRestoreSchurComplement - Restore the Schur complement matrix object obtained from a call to `MatFactorGetSchurComplement()`
10368: Logically Collective
10370: Input Parameters:
10371: + F - the factored matrix obtained by calling `MatGetFactor()`
10372: . S - location where the Schur complement is stored
10373: - status - the status of the Schur complement matrix (see `MatFactorSchurStatus`)
10375: Level: advanced
10377: .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatFactorSetSchurIS()`, `MatFactorCreateSchurComplement()`, `MatFactorSchurStatus`
10378: @*/
10379: PetscErrorCode MatFactorRestoreSchurComplement(Mat F, Mat *S, MatFactorSchurStatus status)
10380: {
10381: PetscFunctionBegin;
10383: if (S) {
10385: *S = NULL;
10386: }
10387: F->schur_status = status;
10388: PetscCall(MatFactorUpdateSchurStatus_Private(F));
10389: PetscFunctionReturn(PETSC_SUCCESS);
10390: }
10392: /*@
10393: MatFactorSolveSchurComplementTranspose - Solve the transpose of the Schur complement system computed during the factorization step
10395: Logically Collective
10397: Input Parameters:
10398: + F - the factored matrix obtained by calling `MatGetFactor()`
10399: . rhs - location where the right-hand side of the Schur complement system is stored
10400: - sol - location where the solution of the Schur complement system has to be returned
10402: Level: advanced
10404: Notes:
10405: The sizes of the vectors should match the size of the Schur complement
10407: Must be called after `MatFactorSetSchurIS()`
10409: .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatFactorSetSchurIS()`, `MatFactorSolveSchurComplement()`
10410: @*/
10411: PetscErrorCode MatFactorSolveSchurComplementTranspose(Mat F, Vec rhs, Vec sol)
10412: {
10413: PetscFunctionBegin;
10420: PetscCheckSameComm(F, 1, rhs, 2);
10421: PetscCheckSameComm(F, 1, sol, 3);
10422: PetscCall(MatFactorFactorizeSchurComplement(F));
10423: switch (F->schur_status) {
10424: case MAT_FACTOR_SCHUR_FACTORED:
10425: PetscCall(MatSolveTranspose(F->schur, rhs, sol));
10426: break;
10427: case MAT_FACTOR_SCHUR_INVERTED:
10428: PetscCall(MatMultTranspose(F->schur, rhs, sol));
10429: break;
10430: default:
10431: SETERRQ(PetscObjectComm((PetscObject)F), PETSC_ERR_SUP, "Unhandled MatFactorSchurStatus %d", F->schur_status);
10432: }
10433: PetscFunctionReturn(PETSC_SUCCESS);
10434: }
10436: /*@
10437: MatFactorSolveSchurComplement - Solve the Schur complement system computed during the factorization step
10439: Logically Collective
10441: Input Parameters:
10442: + F - the factored matrix obtained by calling `MatGetFactor()`
10443: . rhs - location where the right-hand side of the Schur complement system is stored
10444: - sol - location where the solution of the Schur complement system has to be returned
10446: Level: advanced
10448: Notes:
10449: The sizes of the vectors should match the size of the Schur complement
10451: Must be called after `MatFactorSetSchurIS()`
10453: .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatFactorSetSchurIS()`, `MatFactorSolveSchurComplementTranspose()`
10454: @*/
10455: PetscErrorCode MatFactorSolveSchurComplement(Mat F, Vec rhs, Vec sol)
10456: {
10457: PetscFunctionBegin;
10464: PetscCheckSameComm(F, 1, rhs, 2);
10465: PetscCheckSameComm(F, 1, sol, 3);
10466: PetscCall(MatFactorFactorizeSchurComplement(F));
10467: switch (F->schur_status) {
10468: case MAT_FACTOR_SCHUR_FACTORED:
10469: PetscCall(MatSolve(F->schur, rhs, sol));
10470: break;
10471: case MAT_FACTOR_SCHUR_INVERTED:
10472: PetscCall(MatMult(F->schur, rhs, sol));
10473: break;
10474: default:
10475: SETERRQ(PetscObjectComm((PetscObject)F), PETSC_ERR_SUP, "Unhandled MatFactorSchurStatus %d", F->schur_status);
10476: }
10477: PetscFunctionReturn(PETSC_SUCCESS);
10478: }
10480: PETSC_SINGLE_LIBRARY_INTERN PetscErrorCode MatSeqDenseInvertFactors_Private(Mat);
10481: #if PetscDefined(HAVE_CUDA)
10482: PETSC_SINGLE_LIBRARY_INTERN PetscErrorCode MatSeqDenseCUDAInvertFactors_Internal(Mat);
10483: #endif
10485: /* Schur status updated in the interface */
10486: static PetscErrorCode MatFactorInvertSchurComplement_Private(Mat F)
10487: {
10488: Mat S = F->schur;
10490: PetscFunctionBegin;
10491: if (S) {
10492: PetscMPIInt size;
10493: PetscBool isdense, isdensecuda;
10495: PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)S), &size));
10496: PetscCheck(size <= 1, PetscObjectComm((PetscObject)S), PETSC_ERR_SUP, "Not yet implemented");
10497: PetscCall(PetscObjectTypeCompare((PetscObject)S, MATSEQDENSE, &isdense));
10498: PetscCall(PetscObjectTypeCompare((PetscObject)S, MATSEQDENSECUDA, &isdensecuda));
10499: PetscCheck(isdense || isdensecuda, PetscObjectComm((PetscObject)S), PETSC_ERR_SUP, "Not implemented for type %s", ((PetscObject)S)->type_name);
10500: PetscCall(PetscLogEventBegin(MAT_FactorInvS, F, 0, 0, 0));
10501: if (isdense) {
10502: PetscCall(MatSeqDenseInvertFactors_Private(S));
10503: } else if (isdensecuda) {
10504: #if PetscDefined(HAVE_CUDA)
10505: PetscCall(MatSeqDenseCUDAInvertFactors_Internal(S));
10506: #endif
10507: }
10508: // HIP??????????????
10509: PetscCall(PetscLogEventEnd(MAT_FactorInvS, F, 0, 0, 0));
10510: }
10511: PetscFunctionReturn(PETSC_SUCCESS);
10512: }
10514: /*@
10515: MatFactorInvertSchurComplement - Invert the Schur complement matrix computed during the factorization step
10517: Logically Collective
10519: Input Parameter:
10520: . F - the factored matrix obtained by calling `MatGetFactor()`
10522: Level: advanced
10524: Notes:
10525: Must be called after `MatFactorSetSchurIS()`.
10527: Call `MatFactorGetSchurComplement()` or `MatFactorCreateSchurComplement()` AFTER this call to actually compute the inverse and get access to it.
10529: .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatFactorSetSchurIS()`, `MatFactorGetSchurComplement()`, `MatFactorCreateSchurComplement()`
10530: @*/
10531: PetscErrorCode MatFactorInvertSchurComplement(Mat F)
10532: {
10533: PetscFunctionBegin;
10536: if (F->schur_status == MAT_FACTOR_SCHUR_INVERTED) PetscFunctionReturn(PETSC_SUCCESS);
10537: PetscCall(MatFactorFactorizeSchurComplement(F));
10538: PetscCall(MatFactorInvertSchurComplement_Private(F));
10539: F->schur_status = MAT_FACTOR_SCHUR_INVERTED;
10540: PetscFunctionReturn(PETSC_SUCCESS);
10541: }
10543: /*@
10544: MatFactorFactorizeSchurComplement - Factorize the Schur complement matrix computed during the factorization step
10546: Logically Collective
10548: Input Parameter:
10549: . F - the factored matrix obtained by calling `MatGetFactor()`
10551: Level: advanced
10553: Note:
10554: Must be called after `MatFactorSetSchurIS()`
10556: .seealso: [](ch_matrices), `Mat`, `MatGetFactor()`, `MatFactorSetSchurIS()`, `MatFactorInvertSchurComplement()`
10557: @*/
10558: PetscErrorCode MatFactorFactorizeSchurComplement(Mat F)
10559: {
10560: MatFactorInfo info;
10562: PetscFunctionBegin;
10565: if (F->schur_status == MAT_FACTOR_SCHUR_INVERTED || F->schur_status == MAT_FACTOR_SCHUR_FACTORED) PetscFunctionReturn(PETSC_SUCCESS);
10566: PetscCall(PetscLogEventBegin(MAT_FactorFactS, F, 0, 0, 0));
10567: PetscCall(PetscMemzero(&info, sizeof(MatFactorInfo)));
10568: if (F->factortype == MAT_FACTOR_CHOLESKY) { /* LDL^t regarded as Cholesky */
10569: PetscCall(MatCholeskyFactor(F->schur, NULL, &info));
10570: } else {
10571: PetscCall(MatLUFactor(F->schur, NULL, NULL, &info));
10572: }
10573: PetscCall(PetscLogEventEnd(MAT_FactorFactS, F, 0, 0, 0));
10574: F->schur_status = MAT_FACTOR_SCHUR_FACTORED;
10575: PetscFunctionReturn(PETSC_SUCCESS);
10576: }
10578: /*@
10579: MatPtAP - Creates the matrix product $C = P^T A P$
10581: Neighbor-wise Collective
10583: Input Parameters:
10584: + A - the matrix
10585: . P - the projection matrix
10586: . scall - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`
10587: - 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
10588: if the result is a dense matrix this is irrelevant
10590: Output Parameter:
10591: . C - the product matrix
10593: Level: intermediate
10595: Notes:
10596: `C` will be created and must be destroyed by the user with `MatDestroy()`.
10598: This is a convenience routine that wraps the use of the `MatProductCreate()` with a `MatProductType` of `MATPRODUCT_PtAP`
10599: functionality into a single function call. For more involved matrix-matrix operations see `MatProductCreate()`.
10601: The deprecated `PETSC_DEFAULT` in `fill` also means use the current value
10603: Developer Note:
10604: For matrix types without special implementation the function fallbacks to `MatMatMult()` followed by `MatTransposeMatMult()`.
10606: .seealso: [](ch_matrices), `Mat`, `MatProductCreate()`, `MatMatMult()`, `MatRARt()`
10607: @*/
10608: PetscErrorCode MatPtAP(Mat A, Mat P, MatReuse scall, PetscReal fill, Mat *C)
10609: {
10610: PetscFunctionBegin;
10611: if (scall == MAT_REUSE_MATRIX) MatCheckProduct(*C, 5);
10612: PetscCheck(scall != MAT_INPLACE_MATRIX, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "Inplace product not supported");
10614: if (scall == MAT_INITIAL_MATRIX) {
10615: PetscCall(MatProductCreate(A, P, NULL, C));
10616: PetscCall(MatProductSetType(*C, MATPRODUCT_PtAP));
10617: PetscCall(MatProductSetAlgorithm(*C, "default"));
10618: PetscCall(MatProductSetFill(*C, fill));
10620: (*C)->product->api_user = PETSC_TRUE;
10621: PetscCall(MatProductSetFromOptions(*C));
10622: 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);
10623: PetscCall(MatProductSymbolic(*C));
10624: } else { /* scall == MAT_REUSE_MATRIX */
10625: PetscCall(MatProductReplaceMats(A, P, NULL, *C));
10626: }
10628: PetscCall(MatProductNumeric(*C));
10629: if (A->symmetric == PETSC_BOOL3_TRUE) {
10630: PetscCall(MatSetOption(*C, MAT_SYMMETRIC, PETSC_TRUE));
10631: (*C)->spd = A->spd;
10632: }
10633: PetscFunctionReturn(PETSC_SUCCESS);
10634: }
10636: /*@
10637: MatRARt - Creates the matrix product $C = R A R^T$
10639: Neighbor-wise Collective
10641: Input Parameters:
10642: + A - the matrix
10643: . R - the projection matrix
10644: . scall - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`
10645: - fill - expected fill as ratio of nnz(C)/nnz(A), use `PETSC_DETERMINE` or `PETSC_CURRENT` if you do not have a good estimate
10646: if the result is a dense matrix this is irrelevant
10648: Output Parameter:
10649: . C - the product matrix
10651: Level: intermediate
10653: Notes:
10654: `C` will be created and must be destroyed by the user with `MatDestroy()`.
10656: This is a convenience routine that wraps the use of the `MatProductCreate()` with a `MatProductType` of `MATPRODUCT_RARt`
10657: functionality into a single function call. For more involved matrix-matrix operations see `MatProductCreate()`.
10659: This routine is currently only implemented for pairs of `MATAIJ` matrices and classes
10660: which inherit from `MATAIJ`. Due to PETSc sparse matrix block row distribution among processes,
10661: the parallel `MatRARt()` is implemented computing the explicit transpose of `R`, which can be very expensive.
10662: We recommend using `MatPtAP()` when possible.
10664: The deprecated `PETSC_DEFAULT` in `fill` also means use the current value
10666: .seealso: [](ch_matrices), `Mat`, `MatProductCreate()`, `MatMatMult()`, `MatPtAP()`
10667: @*/
10668: PetscErrorCode MatRARt(Mat A, Mat R, MatReuse scall, PetscReal fill, Mat *C)
10669: {
10670: PetscFunctionBegin;
10671: if (scall == MAT_REUSE_MATRIX) MatCheckProduct(*C, 5);
10672: PetscCheck(scall != MAT_INPLACE_MATRIX, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "Inplace product not supported");
10674: if (scall == MAT_INITIAL_MATRIX) {
10675: PetscCall(MatProductCreate(A, R, NULL, C));
10676: PetscCall(MatProductSetType(*C, MATPRODUCT_RARt));
10677: PetscCall(MatProductSetAlgorithm(*C, "default"));
10678: PetscCall(MatProductSetFill(*C, fill));
10680: (*C)->product->api_user = PETSC_TRUE;
10681: PetscCall(MatProductSetFromOptions(*C));
10682: 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);
10683: PetscCall(MatProductSymbolic(*C));
10684: } else { /* scall == MAT_REUSE_MATRIX */
10685: PetscCall(MatProductReplaceMats(A, R, NULL, *C));
10686: }
10688: PetscCall(MatProductNumeric(*C));
10689: if (A->symmetric == PETSC_BOOL3_TRUE) PetscCall(MatSetOption(*C, MAT_SYMMETRIC, PETSC_TRUE));
10690: PetscFunctionReturn(PETSC_SUCCESS);
10691: }
10693: /* MatProductComputeWithMat_Private - Computes D = A * B or D = A^T * B into an existing matrix D, keeping the product on a dense D
10695: Collective
10697: Input Parameters:
10698: + A - the left matrix
10699: . B - the right matrix
10700: . ptype - MATPRODUCT_AB or MATPRODUCT_AtB
10701: - D - the result, of the size of the product
10703: Level: developer
10705: Notes:
10706: For a dense D, this routine keeps the product on D between calls, so only the first call runs the symbolic phase. The product is created
10707: again only when ptype, A, or the nonzero pattern of A changes; a different B of the same size and type reuses it. The kept product holds
10708: references to A and B until MatProductClear() is called on D or D is destroyed. In contrast, MatMatMult() with MAT_REUSE_MATRIX creates the
10709: product and destroys it again on every call into a dense D that does not already have a product.
10711: For any other D, which must already have a product, this calls MatMatMult() or MatTransposeMatMult() with MAT_REUSE_MATRIX.
10713: Developer Note:
10714: The nonzero state of A is compared without a reduction, since the parallel AIJ and BAIJ types make it the same on all processes during
10715: assembly.
10717: .seealso: `MatMatMult()`, `MatTransposeMatMult()`, `MatProductReplaceMats()`, `PCMGMatResidualDefault()`
10718: */
10719: PetscErrorCode MatProductComputeWithMat_Private(Mat A, Mat B, MatProductType ptype, Mat D)
10720: {
10721: Mat_Product *product = D->product;
10722: PetscObjectState state;
10723: PetscBool flg;
10725: PetscFunctionBegin;
10726: PetscCall(PetscObjectBaseTypeCompareAny((PetscObject)D, &flg, MATSEQDENSE, MATMPIDENSE, ""));
10727: if (!flg) { /* only a dense result can be given without a product, MatMatMult() and MatTransposeMatMult() reuse the product of any other */
10728: if (ptype == MATPRODUCT_AB) PetscCall(MatMatMult(A, B, MAT_REUSE_MATRIX, PETSC_CURRENT, &D));
10729: else PetscCall(MatTransposeMatMult(A, B, MAT_REUSE_MATRIX, PETSC_CURRENT, &D));
10730: PetscFunctionReturn(PETSC_SUCCESS);
10731: }
10732: PetscCall(MatGetNonzeroState(A, &state));
10733: if (product == NULL || product->type != ptype || product->A != A || product->Anonzerostate != state) {
10734: PetscCall(PetscInfo(D, "Setting up the %s product into the supplied dense matrix\n", MatProductTypes[ptype]));
10735: PetscCall(MatProductCreateWithMat(A, B, NULL, D));
10736: D->product->api_user = PETSC_TRUE;
10737: PetscCall(MatProductSetType(D, ptype));
10738: PetscCall(MatProductSetFromOptions(D));
10739: PetscCall(MatProductSymbolic(D));
10740: } else {
10741: PetscCall(PetscInfo(D, "Reusing the %s product attached to the supplied dense matrix\n", MatProductTypes[ptype]));
10742: if (product->B != B) PetscCall(MatProductReplaceMats(NULL, B, NULL, D));
10743: }
10744: PetscCall(MatProductNumeric(D));
10745: PetscFunctionReturn(PETSC_SUCCESS);
10746: }
10748: static PetscErrorCode MatProduct_Private(Mat A, Mat B, MatReuse scall, PetscReal fill, MatProductType ptype, Mat *C)
10749: {
10750: PetscBool flg = PETSC_TRUE;
10752: PetscFunctionBegin;
10753: PetscCheck(scall != MAT_INPLACE_MATRIX, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "MAT_INPLACE_MATRIX product not supported");
10754: if (scall == MAT_INITIAL_MATRIX) {
10755: PetscCall(PetscInfo(A, "Calling MatProduct API with MAT_INITIAL_MATRIX and product type %s\n", MatProductTypes[ptype]));
10756: PetscCall(MatProductCreate(A, B, NULL, C));
10757: PetscCall(MatProductSetAlgorithm(*C, MATPRODUCTALGORITHMDEFAULT));
10758: PetscCall(MatProductSetFill(*C, fill));
10759: } else { /* scall == MAT_REUSE_MATRIX */
10760: Mat_Product *product = (*C)->product;
10762: PetscCall(PetscObjectBaseTypeCompareAny((PetscObject)*C, &flg, MATSEQDENSE, MATMPIDENSE, ""));
10763: if (flg && product && product->type != ptype) {
10764: PetscCall(MatProductClear(*C));
10765: product = NULL;
10766: }
10767: PetscCall(PetscInfo(A, "Calling MatProduct API with MAT_REUSE_MATRIX %s product present and product type %s\n", product ? "with" : "without", MatProductTypes[ptype]));
10768: if (!product) { /* user provide the dense matrix *C without calling MatProductCreate() or reusing it from previous calls */
10769: PetscCheck(flg, PetscObjectComm((PetscObject)*C), PETSC_ERR_SUP, "Call MatProductCreate() first");
10770: PetscCall(MatProductCreate_Private(A, B, NULL, *C));
10771: product = (*C)->product;
10772: product->fill = fill;
10773: product->clear = PETSC_TRUE;
10774: } else { /* user may change input matrices A or B when MAT_REUSE_MATRIX */
10775: flg = PETSC_FALSE;
10776: PetscCall(MatProductReplaceMats(A, B, NULL, *C));
10777: }
10778: }
10779: if (flg) {
10780: (*C)->product->api_user = PETSC_TRUE;
10781: PetscCall(MatProductSetType(*C, ptype));
10782: PetscCall(MatProductSetFromOptions(*C));
10783: PetscCall(MatProductSymbolic(*C));
10784: }
10785: PetscCall(MatProductNumeric(*C));
10786: PetscFunctionReturn(PETSC_SUCCESS);
10787: }
10789: /*@
10790: MatMatMult - Performs matrix-matrix multiplication $C=A B$.
10792: Neighbor-wise Collective
10794: Input Parameters:
10795: + A - the left matrix
10796: . B - the right matrix
10797: . scall - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`
10798: - 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
10799: if the result is a dense matrix this is irrelevant
10801: Output Parameter:
10802: . C - the product matrix
10804: Notes:
10805: Unless scall is `MAT_REUSE_MATRIX` C will be created.
10807: `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
10808: call to this function with `MAT_INITIAL_MATRIX`.
10810: To determine the correct fill value, run with `-info` and search for the string "Fill ratio" to see the value actually needed.
10812: 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`,
10813: rather than first having `MatMatMult()` create it for you. You can NEVER do this if the matrix `C` is sparse.
10815: The deprecated `PETSC_DEFAULT` in `fill` also means use the current value
10817: This is a convenience routine that wraps the use of the `MatProductCreate()` with a `MatProductType` of `MATPRODUCT_AB`
10818: functionality into a single function call. For more involved matrix-matrix operations see `MatProductCreate()`.
10820: Example of Usage:
10821: .vb
10822: MatProductCreate(A,B,NULL,&C);
10823: MatProductSetType(C,MATPRODUCT_AB);
10824: MatProductSymbolic(C);
10825: MatProductNumeric(C); // compute C=A * B
10826: MatProductReplaceMats(A1,B1,NULL,C); // compute C=A1 * B1
10827: MatProductNumeric(C);
10828: MatProductReplaceMats(A2,NULL,NULL,C); // compute C=A2 * B1
10829: MatProductNumeric(C);
10830: .ve
10832: Level: intermediate
10834: .seealso: [](ch_matrices), `Mat`, `MatProductType`, `MATPRODUCT_AB`, `MatTransposeMatMult()`, `MatMatTransposeMult()`, `MatPtAP()`, `MatProductCreate()`, `MatProductSymbolic()`, `MatProductReplaceMats()`, `MatProductNumeric()`
10835: @*/
10836: PetscErrorCode MatMatMult(Mat A, Mat B, MatReuse scall, PetscReal fill, Mat *C)
10837: {
10838: PetscFunctionBegin;
10839: PetscCall(MatProduct_Private(A, B, scall, fill, MATPRODUCT_AB, C));
10840: PetscFunctionReturn(PETSC_SUCCESS);
10841: }
10843: /*@
10844: MatMatTransposeMult - Performs matrix-matrix multiplication $C = A B^T$.
10846: Neighbor-wise Collective
10848: Input Parameters:
10849: + A - the left matrix
10850: . B - the right matrix
10851: . scall - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`
10852: - fill - expected fill as ratio of nnz(C)/(nnz(A) + nnz(B)), use `PETSC_DETERMINE` or `PETSC_CURRENT` if not known
10854: Output Parameter:
10855: . C - the product matrix
10857: Options Database Key:
10858: . -matmattransmult_mpidense_mpidense_via {allgatherv,cyclic} - Choose between algorithms for `MATMPIDENSE` matrices: the
10859: first redundantly copies the transposed `B` matrix on each process and requires O(log P) communication complexity;
10860: the second never stores more than one portion of the `B` matrix at a time but requires O(P) communication complexity.
10862: Level: intermediate
10864: Notes:
10865: C will be created if `MAT_INITIAL_MATRIX` and must be destroyed by the user with `MatDestroy()`.
10867: `MAT_REUSE_MATRIX` can only be used if the matrices A and B have the same nonzero pattern as in the previous call
10869: To determine the correct fill value, run with -info and search for the string "Fill ratio" to see the value
10870: actually needed.
10872: This routine is currently only implemented for pairs of `MATSEQAIJ` matrices, for the `MATSEQDENSE` class,
10873: and for pairs of `MATMPIDENSE` matrices.
10875: This is a convenience routine that wraps the use of the `MatProductCreate()` with a `MatProductType` of `MATPRODUCT_ABt`
10876: functionality into a single function call. For more involved matrix-matrix operations see `MatProductCreate()`.
10878: The deprecated `PETSC_DEFAULT` in `fill` also means use the current value
10880: .seealso: [](ch_matrices), `Mat`, `MatProductCreate()`, `MATPRODUCT_ABt`, `MatMatMult()`, `MatTransposeMatMult()`, `MatPtAP()`, `MatProductAlgorithm`, `MatProductType`
10881: @*/
10882: PetscErrorCode MatMatTransposeMult(Mat A, Mat B, MatReuse scall, PetscReal fill, Mat *C)
10883: {
10884: PetscFunctionBegin;
10885: PetscCall(MatProduct_Private(A, B, scall, fill, MATPRODUCT_ABt, C));
10886: if (A == B) PetscCall(MatSetOption(*C, MAT_SYMMETRIC, PETSC_TRUE));
10887: PetscFunctionReturn(PETSC_SUCCESS);
10888: }
10890: /*@
10891: MatTransposeMatMult - Performs matrix-matrix multiplication $C = A^T B$.
10893: Neighbor-wise Collective
10895: Input Parameters:
10896: + A - the left matrix
10897: . B - the right matrix
10898: . scall - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`
10899: - fill - expected fill as ratio of nnz(C)/(nnz(A) + nnz(B)), use `PETSC_DETERMINE` or `PETSC_CURRENT` if not known
10901: Output Parameter:
10902: . C - the product matrix
10904: Level: intermediate
10906: Notes:
10907: `C` will be created if `MAT_INITIAL_MATRIX` and must be destroyed by the user with `MatDestroy()`.
10909: `MAT_REUSE_MATRIX` can only be used if `A` and `B` have the same nonzero pattern as in the previous call.
10911: This is a convenience routine that wraps the use of `MatProductCreate()` with a `MatProductType` of `MATPRODUCT_AtB`
10912: functionality into a single function call. For more involved matrix-matrix operations see `MatProductCreate()`.
10914: To determine the correct fill value, run with -info and search for the string "Fill ratio" to see the value
10915: actually needed.
10917: This routine is currently implemented for pairs of `MATAIJ` matrices and pairs of `MATSEQDENSE` matrices and classes
10918: which inherit from `MATSEQAIJ`. `C` will be of the same type as the input matrices.
10920: The deprecated `PETSC_DEFAULT` in `fill` also means use the current value
10922: .seealso: [](ch_matrices), `Mat`, `MatProductCreate()`, `MATPRODUCT_AtB`, `MatMatMult()`, `MatMatTransposeMult()`, `MatPtAP()`
10923: @*/
10924: PetscErrorCode MatTransposeMatMult(Mat A, Mat B, MatReuse scall, PetscReal fill, Mat *C)
10925: {
10926: PetscFunctionBegin;
10927: PetscCall(MatProduct_Private(A, B, scall, fill, MATPRODUCT_AtB, C));
10928: PetscFunctionReturn(PETSC_SUCCESS);
10929: }
10931: /*@
10932: MatMatMatMult - Performs matrix-matrix-matrix multiplication D=A*B*C.
10934: Neighbor-wise Collective
10936: Input Parameters:
10937: + A - the left matrix
10938: . B - the middle matrix
10939: . C - the right matrix
10940: . scall - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`
10941: - 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
10942: if the result is a dense matrix this is irrelevant
10944: Output Parameter:
10945: . D - the product matrix
10947: Level: intermediate
10949: Notes:
10950: Unless `scall` is `MAT_REUSE_MATRIX` `D` will be created.
10952: `MAT_REUSE_MATRIX` can only be used if the matrices `A`, `B`, and `C` have the same nonzero pattern as in the previous call
10954: This is a convenience routine that wraps the use of the `MatProductCreate()` with a `MatProductType` of `MATPRODUCT_ABC`
10955: functionality into a single function call. For more involved matrix-matrix operations see `MatProductCreate()`.
10957: To determine the correct fill value, run with `-info` and search for the string "Fill ratio" to see the value
10958: actually needed.
10960: If you have many matrices with the same non-zero structure to multiply, you
10961: should use `MAT_REUSE_MATRIX` in all calls but the first
10963: The deprecated `PETSC_DEFAULT` in `fill` also means use the current value
10965: .seealso: [](ch_matrices), `Mat`, `MatProductCreate()`, `MATPRODUCT_ABC`, `MatMatMult`, `MatPtAP()`, `MatMatTransposeMult()`, `MatTransposeMatMult()`
10966: @*/
10967: PetscErrorCode MatMatMatMult(Mat A, Mat B, Mat C, MatReuse scall, PetscReal fill, Mat *D)
10968: {
10969: PetscFunctionBegin;
10970: if (scall == MAT_REUSE_MATRIX) MatCheckProduct(*D, 6);
10971: PetscCheck(scall != MAT_INPLACE_MATRIX, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "Inplace product not supported");
10973: if (scall == MAT_INITIAL_MATRIX) {
10974: PetscCall(MatProductCreate(A, B, C, D));
10975: PetscCall(MatProductSetType(*D, MATPRODUCT_ABC));
10976: PetscCall(MatProductSetAlgorithm(*D, "default"));
10977: PetscCall(MatProductSetFill(*D, fill));
10979: (*D)->product->api_user = PETSC_TRUE;
10980: PetscCall(MatProductSetFromOptions(*D));
10981: 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,
10982: ((PetscObject)C)->type_name);
10983: PetscCall(MatProductSymbolic(*D));
10984: } else { /* user may change input matrices when REUSE */
10985: PetscCall(MatProductReplaceMats(A, B, C, *D));
10986: }
10987: PetscCall(MatProductNumeric(*D));
10988: PetscFunctionReturn(PETSC_SUCCESS);
10989: }
10991: /*@
10992: MatCreateRedundantMatrix - Create redundant matrices and put them into processes of subcommunicators.
10994: Collective
10996: Input Parameters:
10997: + mat - the matrix
10998: . nsubcomm - the number of subcommunicators (= number of redundant parallel or sequential matrices)
10999: . subcomm - MPI communicator split from the communicator where mat resides in (or `MPI_COMM_NULL` if nsubcomm is used)
11000: - reuse - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`
11002: Output Parameter:
11003: . matredundant - redundant matrix
11005: Level: advanced
11007: Notes:
11008: `MAT_REUSE_MATRIX` can only be used when the nonzero structure of the
11009: original matrix has not changed from that last call to `MatCreateRedundantMatrix()`.
11011: This routine creates the duplicated matrices in the subcommunicators; you should NOT create them before
11012: calling it.
11014: `PetscSubcommCreate()` can be used to manage the creation of the subcomm but need not be.
11016: .seealso: [](ch_matrices), `Mat`, `MatDestroy()`, `PetscSubcommCreate()`, `PetscSubcomm`
11017: @*/
11018: PetscErrorCode MatCreateRedundantMatrix(Mat mat, PetscInt nsubcomm, MPI_Comm subcomm, MatReuse reuse, Mat *matredundant)
11019: {
11020: MPI_Comm comm;
11021: PetscMPIInt size;
11022: PetscInt mloc_sub, nloc_sub, rstart, rend, M = mat->rmap->N, N = mat->cmap->N, bs = mat->rmap->bs;
11023: Mat_Redundant *redund = NULL;
11024: PetscSubcomm psubcomm = NULL;
11025: MPI_Comm subcomm_in = subcomm;
11026: Mat *matseq;
11027: IS isrow, iscol;
11028: PetscBool newsubcomm = PETSC_FALSE;
11030: PetscFunctionBegin;
11032: if (nsubcomm && reuse == MAT_REUSE_MATRIX) {
11033: PetscAssertPointer(*matredundant, 5);
11035: }
11037: PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)mat), &size));
11038: if (size == 1 || nsubcomm == 1) {
11039: if (reuse == MAT_INITIAL_MATRIX) {
11040: PetscCall(MatDuplicate(mat, MAT_COPY_VALUES, matredundant));
11041: } else {
11042: 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");
11043: PetscCall(MatCopy(mat, *matredundant, SAME_NONZERO_PATTERN));
11044: }
11045: PetscFunctionReturn(PETSC_SUCCESS);
11046: }
11048: PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
11049: PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
11050: MatCheckPreallocated(mat, 1);
11052: PetscCall(PetscLogEventBegin(MAT_RedundantMat, mat, 0, 0, 0));
11053: if (subcomm_in == MPI_COMM_NULL && reuse == MAT_INITIAL_MATRIX) { /* get subcomm if user does not provide subcomm */
11054: /* create psubcomm, then get subcomm */
11055: PetscCall(PetscObjectGetComm((PetscObject)mat, &comm));
11056: PetscCallMPI(MPI_Comm_size(comm, &size));
11057: PetscCheck(nsubcomm >= 1 && nsubcomm <= size, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "nsubcomm must between 1 and %d", size);
11059: PetscCall(PetscSubcommCreate(comm, &psubcomm));
11060: PetscCall(PetscSubcommSetNumber(psubcomm, nsubcomm));
11061: PetscCall(PetscSubcommSetType(psubcomm, PETSC_SUBCOMM_CONTIGUOUS));
11062: PetscCall(PetscSubcommSetFromOptions(psubcomm));
11063: PetscCall(PetscCommDuplicate(PetscSubcommChild(psubcomm), &subcomm, NULL));
11064: newsubcomm = PETSC_TRUE;
11065: PetscCall(PetscSubcommDestroy(&psubcomm));
11066: }
11068: /* get isrow, iscol and a local sequential matrix matseq[0] */
11069: if (reuse == MAT_INITIAL_MATRIX) {
11070: mloc_sub = PETSC_DECIDE;
11071: nloc_sub = PETSC_DECIDE;
11072: if (bs < 1) {
11073: PetscCall(PetscSplitOwnership(subcomm, &mloc_sub, &M));
11074: PetscCall(PetscSplitOwnership(subcomm, &nloc_sub, &N));
11075: } else {
11076: PetscCall(PetscSplitOwnershipBlock(subcomm, bs, &mloc_sub, &M));
11077: PetscCall(PetscSplitOwnershipBlock(subcomm, bs, &nloc_sub, &N));
11078: }
11079: PetscCallMPI(MPI_Scan(&mloc_sub, &rend, 1, MPIU_INT, MPI_SUM, subcomm));
11080: rstart = rend - mloc_sub;
11081: PetscCall(ISCreateStride(PETSC_COMM_SELF, mloc_sub, rstart, 1, &isrow));
11082: PetscCall(ISCreateStride(PETSC_COMM_SELF, N, 0, 1, &iscol));
11083: PetscCall(ISSetIdentity(iscol));
11084: } else { /* reuse == MAT_REUSE_MATRIX */
11085: 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");
11086: /* retrieve subcomm */
11087: PetscCall(PetscObjectGetComm((PetscObject)*matredundant, &subcomm));
11088: redund = (*matredundant)->redundant;
11089: isrow = redund->isrow;
11090: iscol = redund->iscol;
11091: matseq = redund->matseq;
11092: }
11093: PetscCall(MatCreateSubMatrices(mat, 1, &isrow, &iscol, reuse, &matseq));
11095: /* get matredundant over subcomm */
11096: if (reuse == MAT_INITIAL_MATRIX) {
11097: PetscCall(MatCreateMPIMatConcatenateSeqMat(subcomm, matseq[0], nloc_sub, reuse, matredundant));
11099: /* create a supporting struct and attach it to C for reuse */
11100: PetscCall(PetscNew(&redund));
11101: (*matredundant)->redundant = redund;
11102: redund->isrow = isrow;
11103: redund->iscol = iscol;
11104: redund->matseq = matseq;
11105: if (newsubcomm) {
11106: redund->subcomm = subcomm;
11107: } else {
11108: redund->subcomm = MPI_COMM_NULL;
11109: }
11110: } else {
11111: PetscCall(MatCreateMPIMatConcatenateSeqMat(subcomm, matseq[0], PETSC_DECIDE, reuse, matredundant));
11112: }
11113: #if PetscDefined(HAVE_VIENNACL) || PetscDefined(HAVE_CUDA) || PetscDefined(HAVE_HIP)
11114: if (matseq[0]->boundtocpu && matseq[0]->bindingpropagates) {
11115: PetscCall(MatBindToCPU(*matredundant, PETSC_TRUE));
11116: PetscCall(MatSetBindingPropagates(*matredundant, PETSC_TRUE));
11117: }
11118: #endif
11119: PetscCall(PetscLogEventEnd(MAT_RedundantMat, mat, 0, 0, 0));
11120: PetscFunctionReturn(PETSC_SUCCESS);
11121: }
11123: /*@
11124: MatGetMultiProcBlock - Create multiple 'parallel submatrices' from
11125: a given `Mat`. Each submatrix can span multiple procs.
11127: Collective
11129: Input Parameters:
11130: + mat - the matrix
11131: . subComm - the sub communicator obtained as if by `MPI_Comm_split(PetscObjectComm((PetscObject)mat))`
11132: - scall - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`
11134: Output Parameter:
11135: . subMat - parallel sub-matrices each spanning a given `subcomm`
11137: Level: advanced
11139: Notes:
11140: The submatrix partition across processes is dictated by `subComm` a
11141: communicator obtained by `MPI_comm_split()` or via `PetscSubcommCreate()`. The `subComm`
11142: is not restricted to be grouped with consecutive original MPI processes.
11144: Due the `MPI_Comm_split()` usage, the parallel layout of the submatrices
11145: map directly to the layout of the original matrix [wrt the local
11146: row,col partitioning]. So the original 'DiagonalMat' naturally maps
11147: into the 'DiagonalMat' of the `subMat`, hence it is used directly from
11148: the `subMat`. However the offDiagMat looses some columns - and this is
11149: reconstructed with `MatSetValues()`
11151: This is used by `PCBJACOBI` when a single block spans multiple MPI processes.
11153: .seealso: [](ch_matrices), `Mat`, `MatCreateRedundantMatrix()`, `MatCreateSubMatrices()`, `PCBJACOBI`
11154: @*/
11155: PetscErrorCode MatGetMultiProcBlock(Mat mat, MPI_Comm subComm, MatReuse scall, Mat *subMat)
11156: {
11157: PetscMPIInt commsize, subCommSize;
11159: PetscFunctionBegin;
11160: PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)mat), &commsize));
11161: PetscCallMPI(MPI_Comm_size(subComm, &subCommSize));
11162: PetscCheck(subCommSize <= commsize, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_OUTOFRANGE, "CommSize %d < SubCommZize %d", commsize, subCommSize);
11164: 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");
11165: PetscCall(PetscLogEventBegin(MAT_GetMultiProcBlock, mat, 0, 0, 0));
11166: PetscUseTypeMethod(mat, getmultiprocblock, subComm, scall, subMat);
11167: PetscCall(PetscLogEventEnd(MAT_GetMultiProcBlock, mat, 0, 0, 0));
11168: PetscFunctionReturn(PETSC_SUCCESS);
11169: }
11171: /*@
11172: MatGetLocalSubMatrix - Gets a reference to a submatrix specified in local numbering
11174: Not Collective
11176: Input Parameters:
11177: + mat - matrix to extract local submatrix from
11178: . isrow - local row indices for submatrix
11179: - iscol - local column indices for submatrix
11181: Output Parameter:
11182: . submat - the submatrix
11184: Level: intermediate
11186: Notes:
11187: `submat` should be disposed of with `MatRestoreLocalSubMatrix()`.
11189: Depending on the format of `mat`, the returned `submat` may not implement `MatMult()`. Its communicator may be
11190: the same as `mat`, it may be `PETSC_COMM_SELF`, or some other sub-communictor of `mat`'s.
11192: `submat` always implements `MatSetValuesLocal()`. If `isrow` and `iscol` have the same block size, then
11193: `MatSetValuesBlockedLocal()` will also be implemented.
11195: `mat` must have had a `ISLocalToGlobalMapping` provided to it with `MatSetLocalToGlobalMapping()`.
11196: Matrices obtained with `DMCreateMatrix()` generally already have the local to global mapping provided.
11198: .seealso: [](ch_matrices), `Mat`, `MatRestoreLocalSubMatrix()`, `MatCreateLocalRef()`, `MatSetLocalToGlobalMapping()`
11199: @*/
11200: PetscErrorCode MatGetLocalSubMatrix(Mat mat, IS isrow, IS iscol, Mat *submat)
11201: {
11202: PetscFunctionBegin;
11206: PetscCheckSameComm(isrow, 2, iscol, 3);
11207: PetscAssertPointer(submat, 4);
11208: PetscCheck(mat->rmap->mapping, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Matrix must have local to global mapping provided before this call");
11210: if (mat->ops->getlocalsubmatrix) {
11211: PetscUseTypeMethod(mat, getlocalsubmatrix, isrow, iscol, submat);
11212: } else {
11213: PetscCall(MatCreateLocalRef(mat, isrow, iscol, submat));
11214: }
11215: (*submat)->assembled = mat->assembled;
11216: PetscFunctionReturn(PETSC_SUCCESS);
11217: }
11219: /*@
11220: MatRestoreLocalSubMatrix - Restores a reference to a submatrix specified in local numbering obtained with `MatGetLocalSubMatrix()`
11222: Not Collective
11224: Input Parameters:
11225: + mat - matrix to extract local submatrix from
11226: . isrow - local row indices for submatrix
11227: . iscol - local column indices for submatrix
11228: - submat - the submatrix
11230: Level: intermediate
11232: .seealso: [](ch_matrices), `Mat`, `MatGetLocalSubMatrix()`
11233: @*/
11234: PetscErrorCode MatRestoreLocalSubMatrix(Mat mat, IS isrow, IS iscol, Mat *submat)
11235: {
11236: PetscFunctionBegin;
11240: PetscCheckSameComm(isrow, 2, iscol, 3);
11241: PetscAssertPointer(submat, 4);
11244: if (mat->ops->restorelocalsubmatrix) {
11245: PetscUseTypeMethod(mat, restorelocalsubmatrix, isrow, iscol, submat);
11246: } else {
11247: PetscCall(MatDestroy(submat));
11248: }
11249: *submat = NULL;
11250: PetscFunctionReturn(PETSC_SUCCESS);
11251: }
11253: /*@
11254: MatFindZeroDiagonals - Finds all the rows of a matrix that have zero or no diagonal entry in the matrix
11256: Collective
11258: Input Parameter:
11259: . mat - the matrix
11261: Output Parameter:
11262: . is - if any rows have zero diagonals this contains the list of them
11264: Level: developer
11266: .seealso: [](ch_matrices), `Mat`, `MatMultTranspose()`, `MatMultAdd()`, `MatMultTransposeAdd()`
11267: @*/
11268: PetscErrorCode MatFindZeroDiagonals(Mat mat, IS *is)
11269: {
11270: PetscFunctionBegin;
11273: PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
11274: PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
11276: if (!mat->ops->findzerodiagonals) {
11277: Vec diag;
11278: const PetscScalar *a;
11279: PetscInt *rows;
11280: PetscInt rStart, rEnd, r, nrow = 0;
11282: PetscCall(MatCreateVecs(mat, &diag, NULL));
11283: PetscCall(MatGetDiagonal(mat, diag));
11284: PetscCall(MatGetOwnershipRange(mat, &rStart, &rEnd));
11285: PetscCall(VecGetArrayRead(diag, &a));
11286: for (r = 0; r < rEnd - rStart; ++r)
11287: if (a[r] == 0.0) ++nrow;
11288: PetscCall(PetscMalloc1(nrow, &rows));
11289: nrow = 0;
11290: for (r = 0; r < rEnd - rStart; ++r)
11291: if (a[r] == 0.0) rows[nrow++] = r + rStart;
11292: PetscCall(VecRestoreArrayRead(diag, &a));
11293: PetscCall(VecDestroy(&diag));
11294: PetscCall(ISCreateGeneral(PetscObjectComm((PetscObject)mat), nrow, rows, PETSC_OWN_POINTER, is));
11295: } else {
11296: PetscUseTypeMethod(mat, findzerodiagonals, is);
11297: }
11298: PetscFunctionReturn(PETSC_SUCCESS);
11299: }
11301: /*@
11302: MatFindOffBlockDiagonalEntries - Finds all the rows of a matrix that have entries outside of the main diagonal block (defined by the matrix block size)
11304: Collective
11306: Input Parameter:
11307: . mat - the matrix
11309: Output Parameter:
11310: . is - contains the list of rows with off block diagonal entries
11312: Level: developer
11314: .seealso: [](ch_matrices), `Mat`, `MatMultTranspose()`, `MatMultAdd()`, `MatMultTransposeAdd()`
11315: @*/
11316: PetscErrorCode MatFindOffBlockDiagonalEntries(Mat mat, IS *is)
11317: {
11318: PetscFunctionBegin;
11321: PetscCheck(mat->assembled, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
11322: PetscCheck(!mat->factortype, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
11324: PetscUseTypeMethod(mat, findoffblockdiagonalentries, is);
11325: PetscFunctionReturn(PETSC_SUCCESS);
11326: }
11328: /*@
11329: MatInvertBlockDiagonal - Inverts the block diagonal entries.
11331: Collective; No Fortran Support
11333: Input Parameter:
11334: . mat - the matrix
11336: Output Parameter:
11337: . values - the block inverses in column major order (FORTRAN-like)
11339: Level: advanced
11341: Notes:
11342: The size of the blocks is determined by the block size of the matrix.
11344: The blocks never overlap between two MPI processes, use `MatInvertVariableBlockEnvelope()` for that case
11346: The blocks all have the same size, use `MatInvertVariableBlockDiagonal()` for variable block size
11348: .seealso: [](ch_matrices), `Mat`, `MatInvertVariableBlockEnvelope()`, `MatInvertBlockDiagonalMat()`
11349: @*/
11350: PetscErrorCode MatInvertBlockDiagonal(Mat mat, const PetscScalar *values[])
11351: {
11352: PetscFunctionBegin;
11354: PetscCheck(mat->assembled, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
11355: PetscCheck(!mat->factortype, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
11356: PetscUseTypeMethod(mat, invertblockdiagonal, values);
11357: PetscFunctionReturn(PETSC_SUCCESS);
11358: }
11360: /*@
11361: MatInvertVariableBlockDiagonal - Inverts the point block diagonal entries.
11363: Collective; No Fortran Support
11365: Input Parameters:
11366: + mat - the matrix
11367: . nblocks - the number of blocks on the process, set with `MatSetVariableBlockSizes()`
11368: - bsizes - the size of each block on the process, set with `MatSetVariableBlockSizes()`
11370: Output Parameter:
11371: . values - the block inverses in column major order (FORTRAN-like)
11373: Level: advanced
11375: Notes:
11376: Use `MatInvertBlockDiagonal()` if all blocks have the same size
11378: The blocks never overlap between two MPI processes, use `MatInvertVariableBlockEnvelope()` for that case
11380: .seealso: [](ch_matrices), `Mat`, `MatInvertBlockDiagonal()`, `MatSetVariableBlockSizes()`, `MatInvertVariableBlockEnvelope()`
11381: @*/
11382: PetscErrorCode MatInvertVariableBlockDiagonal(Mat mat, PetscInt nblocks, const PetscInt bsizes[], PetscScalar values[])
11383: {
11384: PetscFunctionBegin;
11386: PetscCheck(mat->assembled, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
11387: PetscCheck(!mat->factortype, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
11388: PetscUseTypeMethod(mat, invertvariableblockdiagonal, nblocks, bsizes, values);
11389: PetscFunctionReturn(PETSC_SUCCESS);
11390: }
11392: /*@
11393: MatInvertBlockDiagonalMat - set the values of matrix C to be the inverted block diagonal of matrix A
11395: Collective
11397: Input Parameters:
11398: + A - the matrix
11399: - C - matrix with inverted block diagonal of `A`. This matrix should be created and may have its type set.
11401: Level: advanced
11403: Note:
11404: The blocksize of the matrix is used to determine the blocks on the diagonal of `C`
11406: .seealso: [](ch_matrices), `Mat`, `MatInvertBlockDiagonal()`
11407: @*/
11408: PetscErrorCode MatInvertBlockDiagonalMat(Mat A, Mat C)
11409: {
11410: const PetscScalar *vals;
11411: PetscInt *dnnz;
11412: PetscInt m, rstart, rend, bs, i, j;
11414: PetscFunctionBegin;
11415: PetscCall(MatInvertBlockDiagonal(A, &vals));
11416: PetscCall(MatGetBlockSize(A, &bs));
11417: PetscCall(MatGetLocalSize(A, &m, NULL));
11418: PetscCall(MatSetLayouts(C, A->rmap, A->cmap));
11419: PetscCall(MatSetBlockSizes(C, A->rmap->bs, A->cmap->bs));
11420: PetscCall(PetscMalloc1(m / bs, &dnnz));
11421: for (j = 0; j < m / bs; j++) dnnz[j] = 1;
11422: PetscCall(MatXAIJSetPreallocation(C, bs, dnnz, NULL, NULL, NULL));
11423: PetscCall(PetscFree(dnnz));
11424: PetscCall(MatGetOwnershipRange(C, &rstart, &rend));
11425: PetscCall(MatSetOption(C, MAT_ROW_ORIENTED, PETSC_FALSE));
11426: for (i = rstart / bs; i < rend / bs; i++) PetscCall(MatSetValuesBlocked(C, 1, &i, 1, &i, &vals[(i - rstart / bs) * bs * bs], INSERT_VALUES));
11427: PetscCall(MatSetOption(C, MAT_NO_OFF_PROC_ENTRIES, PETSC_TRUE));
11428: PetscCall(MatAssemblyBegin(C, MAT_FINAL_ASSEMBLY));
11429: PetscCall(MatAssemblyEnd(C, MAT_FINAL_ASSEMBLY));
11430: PetscCall(MatSetOption(C, MAT_NO_OFF_PROC_ENTRIES, PETSC_FALSE));
11431: PetscCall(MatSetOption(C, MAT_ROW_ORIENTED, PETSC_TRUE));
11432: PetscFunctionReturn(PETSC_SUCCESS);
11433: }
11435: /*@
11436: MatTransposeColoringDestroy - Destroys a coloring context for matrix product $C = A B^T$ that was created
11437: via `MatTransposeColoringCreate()`.
11439: Collective
11441: Input Parameter:
11442: . c - coloring context
11444: Level: intermediate
11446: .seealso: [](ch_matrices), `Mat`, `MatTransposeColoringCreate()`
11447: @*/
11448: PetscErrorCode MatTransposeColoringDestroy(MatTransposeColoring *c)
11449: {
11450: MatTransposeColoring matcolor = *c;
11452: PetscFunctionBegin;
11453: if (!matcolor) PetscFunctionReturn(PETSC_SUCCESS);
11454: if (--((PetscObject)matcolor)->refct > 0) {
11455: matcolor = NULL;
11456: PetscFunctionReturn(PETSC_SUCCESS);
11457: }
11459: PetscCall(PetscFree3(matcolor->ncolumns, matcolor->nrows, matcolor->colorforrow));
11460: PetscCall(PetscFree(matcolor->rows));
11461: PetscCall(PetscFree(matcolor->den2sp));
11462: PetscCall(PetscFree(matcolor->colorforcol));
11463: PetscCall(PetscFree(matcolor->columns));
11464: if (matcolor->brows > 0) PetscCall(PetscFree(matcolor->lstart));
11465: PetscCall(PetscHeaderDestroy(c));
11466: PetscFunctionReturn(PETSC_SUCCESS);
11467: }
11469: /*@
11470: MatTransColoringApplySpToDen - Given a symbolic matrix product $C = A B^T$ for which
11471: a `MatTransposeColoring` context has been created, computes a dense $B^T$ by applying
11472: `MatTransposeColoring` to sparse `B`.
11474: Collective
11476: Input Parameters:
11477: + coloring - coloring context created with `MatTransposeColoringCreate()`
11478: - B - sparse matrix
11480: Output Parameter:
11481: . Btdense - dense matrix $B^T$
11483: Level: developer
11485: Note:
11486: These are used internally for some implementations of `MatRARt()`
11488: .seealso: [](ch_matrices), `Mat`, `MatTransposeColoringCreate()`, `MatTransposeColoringDestroy()`, `MatTransColoringApplyDenToSp()`
11489: @*/
11490: PetscErrorCode MatTransColoringApplySpToDen(MatTransposeColoring coloring, Mat B, Mat Btdense)
11491: {
11492: PetscFunctionBegin;
11497: PetscCall((*B->ops->transcoloringapplysptoden)(coloring, B, Btdense));
11498: PetscFunctionReturn(PETSC_SUCCESS);
11499: }
11501: /*@
11502: MatTransColoringApplyDenToSp - Given a symbolic matrix product $C_{sp} = A B^T$ for which
11503: a `MatTransposeColoring` context has been created and a dense matrix $C_{den} = A B^T_{dense}$
11504: in which `B^T_{dens}` is obtained from `MatTransColoringApplySpToDen()`, recover sparse matrix
11505: $C_{sp}$ from $C_{den}$.
11507: Collective
11509: Input Parameters:
11510: + matcoloring - coloring context created with `MatTransposeColoringCreate()`
11511: - Cden - matrix product of a sparse matrix and a dense matrix Btdense
11513: Output Parameter:
11514: . Csp - sparse matrix
11516: Level: developer
11518: Note:
11519: These are used internally for some implementations of `MatRARt()`
11521: .seealso: [](ch_matrices), `Mat`, `MatTransposeColoringCreate()`, `MatTransposeColoringDestroy()`, `MatTransColoringApplySpToDen()`
11522: @*/
11523: PetscErrorCode MatTransColoringApplyDenToSp(MatTransposeColoring matcoloring, Mat Cden, Mat Csp)
11524: {
11525: PetscFunctionBegin;
11530: PetscCall((*Csp->ops->transcoloringapplydentosp)(matcoloring, Cden, Csp));
11531: PetscCall(MatAssemblyBegin(Csp, MAT_FINAL_ASSEMBLY));
11532: PetscCall(MatAssemblyEnd(Csp, MAT_FINAL_ASSEMBLY));
11533: PetscFunctionReturn(PETSC_SUCCESS);
11534: }
11536: /*@
11537: MatTransposeColoringCreate - Creates a matrix coloring context for the matrix product $C = A B^T$.
11539: Collective
11541: Input Parameters:
11542: + mat - the matrix product C
11543: - iscoloring - the coloring of the matrix; usually obtained with `MatColoringCreate()` or `DMCreateColoring()`
11545: Output Parameter:
11546: . color - the new coloring context
11548: Level: intermediate
11550: .seealso: [](ch_matrices), `Mat`, `MatTransposeColoringDestroy()`, `MatTransColoringApplySpToDen()`,
11551: `MatTransColoringApplyDenToSp()`
11552: @*/
11553: PetscErrorCode MatTransposeColoringCreate(Mat mat, ISColoring iscoloring, MatTransposeColoring *color)
11554: {
11555: MatTransposeColoring c;
11556: MPI_Comm comm;
11558: PetscFunctionBegin;
11559: PetscAssertPointer(color, 3);
11561: PetscCall(PetscLogEventBegin(MAT_TransposeColoringCreate, mat, 0, 0, 0));
11562: PetscCall(PetscObjectGetComm((PetscObject)mat, &comm));
11563: PetscCall(PetscHeaderCreate(c, MAT_TRANSPOSECOLORING_CLASSID, "MatTransposeColoring", "Matrix product C=A*B^T via coloring", "Mat", comm, MatTransposeColoringDestroy, NULL));
11564: c->ctype = iscoloring->ctype;
11565: PetscUseTypeMethod(mat, transposecoloringcreate, iscoloring, c);
11566: *color = c;
11567: PetscCall(PetscLogEventEnd(MAT_TransposeColoringCreate, mat, 0, 0, 0));
11568: PetscFunctionReturn(PETSC_SUCCESS);
11569: }
11571: /*@
11572: MatGetNonzeroState - Returns a 64-bit integer representing the current state of nonzeros in the matrix. If the
11573: matrix has had new nonzero locations added to (or removed from) the matrix since the previous call, the value will be larger.
11575: Not Collective
11577: Input Parameter:
11578: . mat - the matrix
11580: Output Parameter:
11581: . state - the current state
11583: Level: intermediate
11585: Notes:
11586: You can only compare states from two different calls to the SAME matrix, you cannot compare calls between
11587: different matrices
11589: Use `PetscObjectStateGet()` to check for changes to the numerical values in a matrix
11591: Use the result of `PetscObjectGetId()` to compare if a previously checked matrix is the same as the current matrix, do not compare object pointers.
11593: .seealso: [](ch_matrices), `Mat`, `PetscObjectStateGet()`, `PetscObjectGetId()`
11594: @*/
11595: PetscErrorCode MatGetNonzeroState(Mat mat, PetscObjectState *state)
11596: {
11597: PetscFunctionBegin;
11599: *state = mat->nonzerostate;
11600: PetscFunctionReturn(PETSC_SUCCESS);
11601: }
11603: /*@
11604: MatCreateMPIMatConcatenateSeqMat - Creates a single large PETSc matrix by concatenating sequential
11605: matrices from each process
11607: Collective
11609: Input Parameters:
11610: + comm - the communicators the parallel matrix will live on
11611: . seqmat - the input sequential matrices
11612: . n - number of local columns (or `PETSC_DECIDE`)
11613: - reuse - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`
11615: Output Parameter:
11616: . mpimat - the parallel matrix generated
11618: Level: developer
11620: Note:
11621: The number of columns of the matrix in EACH process MUST be the same.
11623: .seealso: [](ch_matrices), `Mat`
11624: @*/
11625: PetscErrorCode MatCreateMPIMatConcatenateSeqMat(MPI_Comm comm, Mat seqmat, PetscInt n, MatReuse reuse, Mat *mpimat)
11626: {
11627: PetscMPIInt size;
11629: PetscFunctionBegin;
11630: PetscCallMPI(MPI_Comm_size(comm, &size));
11631: if (size == 1) {
11632: if (reuse == MAT_INITIAL_MATRIX) {
11633: PetscCall(MatDuplicate(seqmat, MAT_COPY_VALUES, mpimat));
11634: } else {
11635: PetscCall(MatCopy(seqmat, *mpimat, SAME_NONZERO_PATTERN));
11636: }
11637: PetscFunctionReturn(PETSC_SUCCESS);
11638: }
11640: 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");
11642: PetscCall(PetscLogEventBegin(MAT_Merge, seqmat, 0, 0, 0));
11643: PetscCall((*seqmat->ops->creatempimatconcatenateseqmat)(comm, seqmat, n, reuse, mpimat));
11644: PetscCall(PetscLogEventEnd(MAT_Merge, seqmat, 0, 0, 0));
11645: PetscFunctionReturn(PETSC_SUCCESS);
11646: }
11648: /*@
11649: MatSubdomainsCreateCoalesce - Creates index subdomains by coalescing adjacent MPI processes' ownership ranges.
11651: Collective
11653: Input Parameters:
11654: + A - the matrix to create subdomains from
11655: - N - requested number of subdomains
11657: Output Parameters:
11658: + n - number of subdomains resulting on this MPI process
11659: - iss - `IS` list with indices of subdomains on this MPI process
11661: Level: advanced
11663: Note:
11664: The number of subdomains must be smaller than the communicator size
11666: .seealso: [](ch_matrices), `Mat`, `IS`
11667: @*/
11668: PetscErrorCode MatSubdomainsCreateCoalesce(Mat A, PetscInt N, PetscInt *n, IS *iss[])
11669: {
11670: MPI_Comm comm, subcomm;
11671: PetscMPIInt size, rank, color;
11672: PetscInt rstart, rend, k;
11674: PetscFunctionBegin;
11675: PetscCall(PetscObjectGetComm((PetscObject)A, &comm));
11676: PetscCallMPI(MPI_Comm_size(comm, &size));
11677: PetscCallMPI(MPI_Comm_rank(comm, &rank));
11678: 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);
11679: *n = 1;
11680: k = size / N + (size % N > 0); /* There are up to k ranks to a color */
11681: color = rank / k;
11682: PetscCallMPI(MPI_Comm_split(comm, color, rank, &subcomm));
11683: PetscCall(PetscMalloc1(1, iss));
11684: PetscCall(MatGetOwnershipRange(A, &rstart, &rend));
11685: PetscCall(ISCreateStride(subcomm, rend - rstart, rstart, 1, iss[0]));
11686: PetscCallMPI(MPI_Comm_free(&subcomm));
11687: PetscFunctionReturn(PETSC_SUCCESS);
11688: }
11690: /*@
11691: MatGalerkin - Constructs the coarse grid problem matrix via Galerkin projection.
11693: If the interpolation and restriction operators are the same, uses `MatPtAP()`.
11694: If they are not the same, uses `MatMatMatMult()`.
11696: Once the coarse grid problem is constructed, correct for interpolation operators
11697: that are not of full rank, which can legitimately happen in the case of non-nested
11698: geometric multigrid.
11700: Input Parameters:
11701: + restrct - restriction operator
11702: . dA - fine grid matrix
11703: . interpolate - interpolation operator
11704: . reuse - either `MAT_INITIAL_MATRIX` or `MAT_REUSE_MATRIX`
11705: - fill - expected fill, use `PETSC_DETERMINE` or `PETSC_DETERMINE` if you do not have a good estimate
11707: Output Parameter:
11708: . A - the Galerkin coarse matrix
11710: Options Database Key:
11711: . -pc_mg_galerkin (both|pmat|mat|none) - for what matrices the Galerkin process should be used
11713: Level: developer
11715: Note:
11716: The deprecated `PETSC_DEFAULT` in `fill` also means use the current value
11718: .seealso: [](ch_matrices), `Mat`, `MatPtAP()`, `MatMatMatMult()`
11719: @*/
11720: PetscErrorCode MatGalerkin(Mat restrct, Mat dA, Mat interpolate, MatReuse reuse, PetscReal fill, Mat *A)
11721: {
11722: IS zerorows;
11723: Vec diag;
11725: PetscFunctionBegin;
11726: PetscCheck(reuse != MAT_INPLACE_MATRIX, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "Inplace product not supported");
11727: /* Construct the coarse grid matrix */
11728: if (interpolate == restrct) {
11729: PetscCall(MatPtAP(dA, interpolate, reuse, fill, A));
11730: } else {
11731: PetscCall(MatMatMatMult(restrct, dA, interpolate, reuse, fill, A));
11732: }
11734: /* If the interpolation matrix is not of full rank, A will have zero rows.
11735: This can legitimately happen in the case of non-nested geometric multigrid.
11736: In that event, we set the rows of the matrix to the rows of the identity,
11737: ignoring the equations (as the RHS will also be zero). */
11739: PetscCall(MatFindZeroRows(*A, &zerorows));
11741: if (zerorows != NULL) { /* if there are any zero rows */
11742: PetscCall(MatCreateVecs(*A, &diag, NULL));
11743: PetscCall(MatGetDiagonal(*A, diag));
11744: PetscCall(VecISSet(diag, zerorows, 1.0));
11745: PetscCall(MatDiagonalSet(*A, diag, INSERT_VALUES));
11746: PetscCall(VecDestroy(&diag));
11747: PetscCall(ISDestroy(&zerorows));
11748: }
11749: PetscFunctionReturn(PETSC_SUCCESS);
11750: }
11752: /*@
11753: MatSetOperation - Allows user to set a matrix operation for any matrix type
11755: Logically Collective
11757: Input Parameters:
11758: + mat - the matrix
11759: . op - the name of the operation
11760: - f - the function that provides the operation
11762: Level: developer
11764: Example Usage:
11765: .vb
11766: extern PetscErrorCode usermult(Mat, Vec, Vec);
11768: PetscCall(MatCreateXXX(comm, ..., &A));
11769: PetscCall(MatSetOperation(A, MATOP_MULT, (PetscErrorCodeFn *)usermult));
11770: .ve
11772: Notes:
11773: See the file `include/petscmat.h` for a complete list of matrix
11774: operations, which all have the form MATOP_<OPERATION>, where
11775: <OPERATION> is the name (in all capital letters) of the
11776: user interface routine (e.g., `MatMult()` -> `MATOP_MULT`).
11778: All user-provided functions (except for `MATOP_DESTROY`) should have the same calling
11779: sequence as the usual matrix interface routines, since they
11780: are intended to be accessed via the usual matrix interface
11781: routines, e.g.,
11782: .vb
11783: MatMult(Mat, Vec, Vec) -> usermult(Mat, Vec, Vec)
11784: .ve
11786: In particular each function MUST return `PETSC_SUCCESS` on success and
11787: nonzero on failure.
11789: This routine is distinct from `MatShellSetOperation()` in that it can be called on any matrix type.
11791: .seealso: [](ch_matrices), `Mat`, `MatGetOperation()`, `MatCreateShell()`, `MatShellSetContext()`, `MatShellSetOperation()`
11792: @*/
11793: PetscErrorCode MatSetOperation(Mat mat, MatOperation op, PetscErrorCodeFn *f)
11794: {
11795: PetscFunctionBegin;
11798: if (op == MATOP_VIEW && !mat->ops->viewnative && f != (PetscErrorCodeFn *)mat->ops->view) mat->ops->viewnative = mat->ops->view;
11799: #if !PetscDefined(USE_COMPLEX)
11800: if (op == MATOP_MULT_HERMITIAN_TRANSPOSE) op = MATOP_MULT_TRANSPOSE;
11801: else if (op == MATOP_MULT_HERMITIAN_TRANS_ADD) op = MATOP_MULT_TRANSPOSE_ADD;
11802: else if (op == MATOP_HERMITIAN_TRANSPOSE) op = MATOP_TRANSPOSE;
11803: #endif
11804: ((PetscErrorCodeFn **)mat->ops)[op] = f;
11805: PetscFunctionReturn(PETSC_SUCCESS);
11806: }
11808: /*@
11809: MatGetOperation - Gets a matrix operation for any matrix type.
11811: Not Collective
11813: Input Parameters:
11814: + mat - the matrix
11815: - op - the name of the operation
11817: Output Parameter:
11818: . f - the function that provides the operation
11820: Level: developer
11822: Example Usage:
11823: .vb
11824: PetscErrorCode (*usermult)(Mat, Vec, Vec);
11826: MatGetOperation(A, MATOP_MULT, (PetscErrorCodeFn **)&usermult);
11827: .ve
11829: Notes:
11830: See the file `include/petscmat.h` for a complete list of matrix
11831: operations, which all have the form MATOP_<OPERATION>, where
11832: <OPERATION> is the name (in all capital letters) of the
11833: user interface routine (e.g., `MatMult()` -> `MATOP_MULT`).
11835: This routine is distinct from `MatShellGetOperation()` in that it can be called on any matrix type.
11837: .seealso: [](ch_matrices), `Mat`, `MatSetOperation()`, `MatCreateShell()`, `MatShellGetContext()`, `MatShellGetOperation()`
11838: @*/
11839: PetscErrorCode MatGetOperation(Mat mat, MatOperation op, PetscErrorCodeFn **f)
11840: {
11841: PetscFunctionBegin;
11843: PetscAssertPointer(f, 3);
11844: #if !PetscDefined(USE_COMPLEX)
11845: if (op == MATOP_MULT_HERMITIAN_TRANSPOSE) op = MATOP_MULT_TRANSPOSE;
11846: else if (op == MATOP_MULT_HERMITIAN_TRANS_ADD) op = MATOP_MULT_TRANSPOSE_ADD;
11847: else if (op == MATOP_HERMITIAN_TRANSPOSE) op = MATOP_TRANSPOSE;
11848: #endif
11849: *f = ((PetscErrorCodeFn **)mat->ops)[op];
11850: PetscFunctionReturn(PETSC_SUCCESS);
11851: }
11853: /*@
11854: MatHasOperation - Determines whether the given matrix supports the particular operation.
11856: Not Collective
11858: Input Parameters:
11859: + mat - the matrix
11860: - op - the operation, for example, `MATOP_GET_DIAGONAL`
11862: Output Parameter:
11863: . has - either `PETSC_TRUE` or `PETSC_FALSE`
11865: Level: advanced
11867: Note:
11868: See `MatSetOperation()` for additional discussion on naming convention and usage of `op`.
11870: .seealso: [](ch_matrices), `Mat`, `MatCreateShell()`, `MatGetOperation()`, `MatSetOperation()`
11871: @*/
11872: PetscErrorCode MatHasOperation(Mat mat, MatOperation op, PetscBool *has)
11873: {
11874: PetscFunctionBegin;
11876: PetscAssertPointer(has, 3);
11877: #if !PetscDefined(USE_COMPLEX)
11878: if (op == MATOP_MULT_HERMITIAN_TRANSPOSE) op = MATOP_MULT_TRANSPOSE;
11879: else if (op == MATOP_MULT_HERMITIAN_TRANS_ADD) op = MATOP_MULT_TRANSPOSE_ADD;
11880: else if (op == MATOP_HERMITIAN_TRANSPOSE) op = MATOP_TRANSPOSE;
11881: #endif
11882: if (op == MATOP_ADOT || op == MATOP_ANORM) {
11883: /* MatADot() and MatANorm() fall back to MatMult() when the type has no method */
11884: if (((void **)mat->ops)[op]) *has = PETSC_TRUE;
11885: else PetscCall(MatHasOperation(mat, MATOP_MULT, has));
11886: PetscFunctionReturn(PETSC_SUCCESS);
11887: }
11888: if (mat->ops->hasoperation) {
11889: PetscUseTypeMethod(mat, hasoperation, op, has);
11890: } else {
11891: if (((void **)mat->ops)[op]) *has = PETSC_TRUE;
11892: else {
11893: *has = PETSC_FALSE;
11894: if (op == MATOP_CREATE_SUBMATRIX) {
11895: PetscMPIInt size;
11897: PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)mat), &size));
11898: if (size == 1) PetscCall(MatHasOperation(mat, MATOP_CREATE_SUBMATRICES, has));
11899: }
11900: }
11901: }
11902: PetscFunctionReturn(PETSC_SUCCESS);
11903: }
11905: /*@
11906: MatHasCongruentLayouts - Determines whether the rows and columns layouts of the matrix are congruent
11908: Collective
11910: Input Parameter:
11911: . mat - the matrix
11913: Output Parameter:
11914: . cong - either `PETSC_TRUE` or `PETSC_FALSE`
11916: Level: beginner
11918: .seealso: [](ch_matrices), `Mat`, `MatCreate()`, `MatSetSizes()`, `PetscLayout`
11919: @*/
11920: PetscErrorCode MatHasCongruentLayouts(Mat mat, PetscBool *cong)
11921: {
11922: PetscFunctionBegin;
11925: PetscAssertPointer(cong, 2);
11926: if (!mat->rmap || !mat->cmap) {
11927: *cong = mat->rmap == mat->cmap ? PETSC_TRUE : PETSC_FALSE;
11928: PetscFunctionReturn(PETSC_SUCCESS);
11929: }
11930: if (mat->congruentlayouts == PETSC_DECIDE) { /* first time we compare rows and cols layouts */
11931: PetscCall(PetscLayoutSetUp(mat->rmap));
11932: PetscCall(PetscLayoutSetUp(mat->cmap));
11933: PetscCall(PetscLayoutCompare(mat->rmap, mat->cmap, cong));
11934: if (*cong) mat->congruentlayouts = 1;
11935: else mat->congruentlayouts = 0;
11936: } else *cong = mat->congruentlayouts ? PETSC_TRUE : PETSC_FALSE;
11937: PetscFunctionReturn(PETSC_SUCCESS);
11938: }
11940: /*@
11941: MatFlag - set infinity into the local part of the matrix on any subset of MPI processes
11943: Logically Collective
11945: Input Parameters:
11946: + A - the matrix, can be `NULL` but only if on all processes
11947: - flg - indicates if this processes portion of the matrix should be set to infinity
11949: Level: developer
11951: Notes:
11952: This is used to flag a block of solutions that a linear solver failed to compute, as `VecFlag()` does for a single solution.
11954: The state of `A` is increased on all processes, whether or not their portion is flagged, so an outer solver that tracks it detects the failure even when the entries were already infinite.
11956: Only the dense types (`MATSEQDENSE`, `MATMPIDENSE`, and their device variants) currently implement this operation.
11958: .seealso: [](ch_matrices), `Mat`, `VecFlag()`, `MatZeroEntries()`, `MatSetValues()`
11959: @*/
11960: PetscErrorCode MatFlag(Mat A, PetscInt flg)
11961: {
11962: PetscFunctionBegin;
11963: if (!A) PetscFunctionReturn(PETSC_SUCCESS);
11966: MatCheckPreallocated(A, 1);
11967: PetscCall(PetscObjectStateIncrease((PetscObject)A));
11968: if (flg) PetscUseTypeMethod(A, setinf);
11969: PetscFunctionReturn(PETSC_SUCCESS);
11970: }
11972: /*@
11973: 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
11974: and possibly removes small values from the graph structure.
11976: Collective
11978: Input Parameters:
11979: + A - the matrix
11980: . sym - `PETSC_TRUE` indicates that the graph should be symmetrized
11981: . scale - `PETSC_TRUE` indicates that the graph edge weights should be symmetrically scaled with the diagonal entry
11982: . filter - filter value - < 0: does nothing; == 0: removes only 0.0 entries; otherwise: removes entries with $|entries| \le filter$
11983: . num_idx - size of `index` array
11984: - index - array of block indices to use for graph strength of connection weight
11986: Output Parameter:
11987: . graph - the resulting graph
11989: Level: advanced
11991: .seealso: [](ch_matrices), `Mat`, `MatCreate()`, `PCGAMG`
11992: @*/
11993: PetscErrorCode MatCreateGraph(Mat A, PetscBool sym, PetscBool scale, PetscReal filter, PetscInt num_idx, PetscInt index[], Mat *graph)
11994: {
11995: PetscFunctionBegin;
11999: PetscAssertPointer(graph, 7);
12000: PetscCall(PetscLogEventBegin(MAT_CreateGraph, A, 0, 0, 0));
12001: PetscUseTypeMethod(A, creategraph, sym, scale, filter, num_idx, index, graph);
12002: PetscCall(PetscLogEventEnd(MAT_CreateGraph, A, 0, 0, 0));
12003: PetscFunctionReturn(PETSC_SUCCESS);
12004: }
12006: /*@
12007: MatEliminateZeros - eliminate the nondiagonal zero entries in place from the nonzero structure of a sparse `Mat` in place,
12008: meaning the same memory is used for the matrix, and no new memory is allocated.
12010: Collective
12012: Input Parameters:
12013: + A - the matrix
12014: - 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
12016: Level: intermediate
12018: Developer Note:
12019: The entries in the sparse matrix data structure are shifted to fill in the unneeded locations in the data. Thus the end
12020: of the arrays in the data structure may be no longer needed to represent the matrix.
12022: .seealso: [](ch_matrices), `Mat`, `MatCreate()`, `MatCreateGraph()`, `MatFilter()`
12023: @*/
12024: PetscErrorCode MatEliminateZeros(Mat A, PetscBool keep)
12025: {
12026: PetscFunctionBegin;
12028: PetscUseTypeMethod(A, eliminatezeros, keep);
12029: PetscFunctionReturn(PETSC_SUCCESS);
12030: }
12032: /*@
12033: MatGetCurrentMemType - Get the memory location of the matrix
12035: Not Collective, but the result will be the same on all MPI processes
12037: Input Parameter:
12038: . A - the matrix whose memory type we are checking
12040: Output Parameter:
12041: . m - the memory type, see `PetscMemType`
12043: Level: intermediate
12045: .seealso: [](ch_matrices), `Mat`, `MatBoundToCPU()`, `PetscMemType`
12046: @*/
12047: PetscErrorCode MatGetCurrentMemType(Mat A, PetscMemType *m)
12048: {
12049: PetscFunctionBegin;
12051: PetscAssertPointer(m, 2);
12052: if (A->ops->getcurrentmemtype) PetscUseTypeMethod(A, getcurrentmemtype, m);
12053: else *m = PETSC_MEMTYPE_HOST;
12054: PetscFunctionReturn(PETSC_SUCCESS);
12055: }