Actual source code: matrix.c
petsc-3.13.1 2020-05-02
1: /*
2: This is where the abstract matrix operations are defined
3: */
5: #include <petsc/private/matimpl.h>
6: #include <petsc/private/isimpl.h>
7: #include <petsc/private/vecimpl.h>
9: /* Logging support */
10: PetscClassId MAT_CLASSID;
11: PetscClassId MAT_COLORING_CLASSID;
12: PetscClassId MAT_FDCOLORING_CLASSID;
13: PetscClassId MAT_TRANSPOSECOLORING_CLASSID;
15: PetscLogEvent MAT_Mult, MAT_Mults, MAT_MultConstrained, MAT_MultAdd, MAT_MultTranspose;
16: PetscLogEvent MAT_MultTransposeConstrained, MAT_MultTransposeAdd, MAT_Solve, MAT_Solves, MAT_SolveAdd, MAT_SolveTranspose, MAT_MatSolve,MAT_MatTrSolve;
17: PetscLogEvent MAT_SolveTransposeAdd, MAT_SOR, MAT_ForwardSolve, MAT_BackwardSolve, MAT_LUFactor, MAT_LUFactorSymbolic;
18: PetscLogEvent MAT_LUFactorNumeric, MAT_CholeskyFactor, MAT_CholeskyFactorSymbolic, MAT_CholeskyFactorNumeric, MAT_ILUFactor;
19: PetscLogEvent MAT_ILUFactorSymbolic, MAT_ICCFactorSymbolic, MAT_Copy, MAT_Convert, MAT_Scale, MAT_AssemblyBegin;
20: PetscLogEvent MAT_AssemblyEnd, MAT_SetValues, MAT_GetValues, MAT_GetRow, MAT_GetRowIJ, MAT_CreateSubMats, MAT_GetOrdering, MAT_RedundantMat, MAT_GetSeqNonzeroStructure;
21: PetscLogEvent MAT_IncreaseOverlap, MAT_Partitioning, MAT_PartitioningND, MAT_Coarsen, MAT_ZeroEntries, MAT_Load, MAT_View, MAT_AXPY, MAT_FDColoringCreate;
22: PetscLogEvent MAT_FDColoringSetUp, MAT_FDColoringApply,MAT_Transpose,MAT_FDColoringFunction, MAT_CreateSubMat;
23: PetscLogEvent MAT_TransposeColoringCreate;
24: PetscLogEvent MAT_MatMult, MAT_MatMultSymbolic, MAT_MatMultNumeric;
25: PetscLogEvent MAT_PtAP, MAT_PtAPSymbolic, MAT_PtAPNumeric,MAT_RARt, MAT_RARtSymbolic, MAT_RARtNumeric;
26: PetscLogEvent MAT_MatTransposeMult, MAT_MatTransposeMultSymbolic, MAT_MatTransposeMultNumeric;
27: PetscLogEvent MAT_TransposeMatMult, MAT_TransposeMatMultSymbolic, MAT_TransposeMatMultNumeric;
28: PetscLogEvent MAT_MatMatMult, MAT_MatMatMultSymbolic, MAT_MatMatMultNumeric;
29: PetscLogEvent MAT_MultHermitianTranspose,MAT_MultHermitianTransposeAdd;
30: PetscLogEvent MAT_Getsymtranspose, MAT_Getsymtransreduced, MAT_GetBrowsOfAcols;
31: PetscLogEvent MAT_GetBrowsOfAocols, MAT_Getlocalmat, MAT_Getlocalmatcondensed, MAT_Seqstompi, MAT_Seqstompinum, MAT_Seqstompisym;
32: PetscLogEvent MAT_Applypapt, MAT_Applypapt_numeric, MAT_Applypapt_symbolic, MAT_GetSequentialNonzeroStructure;
33: PetscLogEvent MAT_GetMultiProcBlock;
34: PetscLogEvent MAT_CUSPARSECopyToGPU, MAT_SetValuesBatch;
35: PetscLogEvent MAT_ViennaCLCopyToGPU;
36: PetscLogEvent MAT_DenseCopyToGPU, MAT_DenseCopyFromGPU;
37: PetscLogEvent MAT_Merge,MAT_Residual,MAT_SetRandom;
38: PetscLogEvent MAT_FactorFactS,MAT_FactorInvS;
39: PetscLogEvent MATCOLORING_Apply,MATCOLORING_Comm,MATCOLORING_Local,MATCOLORING_ISCreate,MATCOLORING_SetUp,MATCOLORING_Weights;
41: const char *const MatFactorTypes[] = {"NONE","LU","CHOLESKY","ILU","ICC","ILUDT","MatFactorType","MAT_FACTOR_",0};
43: /*@
44: MatSetRandom - Sets all components of a matrix to random numbers. For sparse matrices that have been preallocated but not been assembled it randomly selects appropriate locations,
45: for sparse matrices that already have locations it fills the locations with random numbers
47: Logically Collective on Mat
49: Input Parameters:
50: + x - the matrix
51: - rctx - the random number context, formed by PetscRandomCreate(), or NULL and
52: it will create one internally.
54: Output Parameter:
55: . x - the matrix
57: Example of Usage:
58: .vb
59: PetscRandomCreate(PETSC_COMM_WORLD,&rctx);
60: MatSetRandom(x,rctx);
61: PetscRandomDestroy(rctx);
62: .ve
64: Level: intermediate
67: .seealso: MatZeroEntries(), MatSetValues(), PetscRandomCreate(), PetscRandomDestroy()
68: @*/
69: PetscErrorCode MatSetRandom(Mat x,PetscRandom rctx)
70: {
72: PetscRandom randObj = NULL;
79: if (!x->ops->setrandom) SETERRQ1(PetscObjectComm((PetscObject)x),PETSC_ERR_SUP,"Mat type %s",((PetscObject)x)->type_name);
81: if (!rctx) {
82: MPI_Comm comm;
83: PetscObjectGetComm((PetscObject)x,&comm);
84: PetscRandomCreate(comm,&randObj);
85: PetscRandomSetFromOptions(randObj);
86: rctx = randObj;
87: }
89: PetscLogEventBegin(MAT_SetRandom,x,rctx,0,0);
90: (*x->ops->setrandom)(x,rctx);
91: PetscLogEventEnd(MAT_SetRandom,x,rctx,0,0);
93: MatAssemblyBegin(x, MAT_FINAL_ASSEMBLY);
94: MatAssemblyEnd(x, MAT_FINAL_ASSEMBLY);
95: PetscRandomDestroy(&randObj);
96: return(0);
97: }
99: /*@
100: MatFactorGetErrorZeroPivot - returns the pivot value that was determined to be zero and the row it occurred in
102: Logically Collective on Mat
104: Input Parameters:
105: . mat - the factored matrix
107: Output Parameter:
108: + pivot - the pivot value computed
109: - row - the row that the zero pivot occurred. Note that this row must be interpreted carefully due to row reorderings and which processes
110: the share the matrix
112: Level: advanced
114: Notes:
115: This routine does not work for factorizations done with external packages.
116: This routine should only be called if MatGetFactorError() returns a value of MAT_FACTOR_NUMERIC_ZEROPIVOT
118: This can be called on non-factored matrices that come from, for example, matrices used in SOR.
120: .seealso: MatZeroEntries(), MatFactor(), MatGetFactor(), MatFactorSymbolic(), MatFactorClearError(), MatFactorGetErrorZeroPivot()
121: @*/
122: PetscErrorCode MatFactorGetErrorZeroPivot(Mat mat,PetscReal *pivot,PetscInt *row)
123: {
126: *pivot = mat->factorerror_zeropivot_value;
127: *row = mat->factorerror_zeropivot_row;
128: return(0);
129: }
131: /*@
132: MatFactorGetError - gets the error code from a factorization
134: Logically Collective on Mat
136: Input Parameters:
137: . mat - the factored matrix
139: Output Parameter:
140: . err - the error code
142: Level: advanced
144: Notes:
145: This can be called on non-factored matrices that come from, for example, matrices used in SOR.
147: .seealso: MatZeroEntries(), MatFactor(), MatGetFactor(), MatFactorSymbolic(), MatFactorClearError(), MatFactorGetErrorZeroPivot()
148: @*/
149: PetscErrorCode MatFactorGetError(Mat mat,MatFactorError *err)
150: {
153: *err = mat->factorerrortype;
154: return(0);
155: }
157: /*@
158: MatFactorClearError - clears the error code in a factorization
160: Logically Collective on Mat
162: Input Parameter:
163: . mat - the factored matrix
165: Level: developer
167: Notes:
168: This can be called on non-factored matrices that come from, for example, matrices used in SOR.
170: .seealso: MatZeroEntries(), MatFactor(), MatGetFactor(), MatFactorSymbolic(), MatFactorGetError(), MatFactorGetErrorZeroPivot()
171: @*/
172: PetscErrorCode MatFactorClearError(Mat mat)
173: {
176: mat->factorerrortype = MAT_FACTOR_NOERROR;
177: mat->factorerror_zeropivot_value = 0.0;
178: mat->factorerror_zeropivot_row = 0;
179: return(0);
180: }
182: PETSC_INTERN PetscErrorCode MatFindNonzeroRowsOrCols_Basic(Mat mat,PetscBool cols,PetscReal tol,IS *nonzero)
183: {
184: PetscErrorCode ierr;
185: Vec r,l;
186: const PetscScalar *al;
187: PetscInt i,nz,gnz,N,n;
190: MatCreateVecs(mat,&r,&l);
191: if (!cols) { /* nonzero rows */
192: MatGetSize(mat,&N,NULL);
193: MatGetLocalSize(mat,&n,NULL);
194: VecSet(l,0.0);
195: VecSetRandom(r,NULL);
196: MatMult(mat,r,l);
197: VecGetArrayRead(l,&al);
198: } else { /* nonzero columns */
199: MatGetSize(mat,NULL,&N);
200: MatGetLocalSize(mat,NULL,&n);
201: VecSet(r,0.0);
202: VecSetRandom(l,NULL);
203: MatMultTranspose(mat,l,r);
204: VecGetArrayRead(r,&al);
205: }
206: if (tol <= 0.0) { for (i=0,nz=0;i<n;i++) if (al[i] != 0.0) nz++; }
207: else { for (i=0,nz=0;i<n;i++) if (PetscAbsScalar(al[i]) > tol) nz++; }
208: MPIU_Allreduce(&nz,&gnz,1,MPIU_INT,MPI_SUM,PetscObjectComm((PetscObject)mat));
209: if (gnz != N) {
210: PetscInt *nzr;
211: PetscMalloc1(nz,&nzr);
212: if (nz) {
213: if (tol < 0) { for (i=0,nz=0;i<n;i++) if (al[i] != 0.0) nzr[nz++] = i; }
214: else { for (i=0,nz=0;i<n;i++) if (PetscAbsScalar(al[i]) > tol) nzr[nz++] = i; }
215: }
216: ISCreateGeneral(PetscObjectComm((PetscObject)mat),nz,nzr,PETSC_OWN_POINTER,nonzero);
217: } else *nonzero = NULL;
218: if (!cols) { /* nonzero rows */
219: VecRestoreArrayRead(l,&al);
220: } else {
221: VecRestoreArrayRead(r,&al);
222: }
223: VecDestroy(&l);
224: VecDestroy(&r);
225: return(0);
226: }
228: /*@
229: MatFindNonzeroRows - Locate all rows that are not completely zero in the matrix
231: Input Parameter:
232: . A - the matrix
234: Output Parameter:
235: . keptrows - the rows that are not completely zero
237: Notes:
238: keptrows is set to NULL if all rows are nonzero.
240: Level: intermediate
242: @*/
243: PetscErrorCode MatFindNonzeroRows(Mat mat,IS *keptrows)
244: {
251: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
252: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
253: if (!mat->ops->findnonzerorows) {
254: MatFindNonzeroRowsOrCols_Basic(mat,PETSC_FALSE,0.0,keptrows);
255: } else {
256: (*mat->ops->findnonzerorows)(mat,keptrows);
257: }
258: return(0);
259: }
261: /*@
262: MatFindZeroRows - Locate all rows that are completely zero in the matrix
264: Input Parameter:
265: . A - the matrix
267: Output Parameter:
268: . zerorows - the rows that are completely zero
270: Notes:
271: zerorows is set to NULL if no rows are zero.
273: Level: intermediate
275: @*/
276: PetscErrorCode MatFindZeroRows(Mat mat,IS *zerorows)
277: {
279: IS keptrows;
280: PetscInt m, n;
285: MatFindNonzeroRows(mat, &keptrows);
286: /* MatFindNonzeroRows sets keptrows to NULL if there are no zero rows.
287: In keeping with this convention, we set zerorows to NULL if there are no zero
288: rows. */
289: if (keptrows == NULL) {
290: *zerorows = NULL;
291: } else {
292: MatGetOwnershipRange(mat,&m,&n);
293: ISComplement(keptrows,m,n,zerorows);
294: ISDestroy(&keptrows);
295: }
296: return(0);
297: }
299: /*@
300: MatGetDiagonalBlock - Returns the part of the matrix associated with the on-process coupling
302: Not Collective
304: Input Parameters:
305: . A - the matrix
307: Output Parameters:
308: . a - the diagonal part (which is a SEQUENTIAL matrix)
310: Notes:
311: see the manual page for MatCreateAIJ() for more information on the "diagonal part" of the matrix.
312: Use caution, as the reference count on the returned matrix is not incremented and it is used as
313: part of the containing MPI Mat's normal operation.
315: Level: advanced
317: @*/
318: PetscErrorCode MatGetDiagonalBlock(Mat A,Mat *a)
319: {
326: if (A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
327: if (!A->ops->getdiagonalblock) {
328: PetscMPIInt size;
329: MPI_Comm_size(PetscObjectComm((PetscObject)A),&size);
330: if (size == 1) {
331: *a = A;
332: return(0);
333: } else SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Not coded for matrix type %s",((PetscObject)A)->type_name);
334: }
335: (*A->ops->getdiagonalblock)(A,a);
336: return(0);
337: }
339: /*@
340: MatGetTrace - Gets the trace of a matrix. The sum of the diagonal entries.
342: Collective on Mat
344: Input Parameters:
345: . mat - the matrix
347: Output Parameter:
348: . trace - the sum of the diagonal entries
350: Level: advanced
352: @*/
353: PetscErrorCode MatGetTrace(Mat mat,PetscScalar *trace)
354: {
356: Vec diag;
359: MatCreateVecs(mat,&diag,NULL);
360: MatGetDiagonal(mat,diag);
361: VecSum(diag,trace);
362: VecDestroy(&diag);
363: return(0);
364: }
366: /*@
367: MatRealPart - Zeros out the imaginary part of the matrix
369: Logically Collective on Mat
371: Input Parameters:
372: . mat - the matrix
374: Level: advanced
377: .seealso: MatImaginaryPart()
378: @*/
379: PetscErrorCode MatRealPart(Mat mat)
380: {
386: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
387: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
388: if (!mat->ops->realpart) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
389: MatCheckPreallocated(mat,1);
390: (*mat->ops->realpart)(mat);
391: return(0);
392: }
394: /*@C
395: MatGetGhosts - Get the global index of all ghost nodes defined by the sparse matrix
397: Collective on Mat
399: Input Parameter:
400: . mat - the matrix
402: Output Parameters:
403: + nghosts - number of ghosts (note for BAIJ matrices there is one ghost for each block)
404: - ghosts - the global indices of the ghost points
406: Notes:
407: the nghosts and ghosts are suitable to pass into VecCreateGhost()
409: Level: advanced
411: @*/
412: PetscErrorCode MatGetGhosts(Mat mat,PetscInt *nghosts,const PetscInt *ghosts[])
413: {
419: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
420: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
421: if (!mat->ops->getghosts) {
422: if (nghosts) *nghosts = 0;
423: if (ghosts) *ghosts = 0;
424: } else {
425: (*mat->ops->getghosts)(mat,nghosts,ghosts);
426: }
427: return(0);
428: }
431: /*@
432: MatImaginaryPart - Moves the imaginary part of the matrix to the real part and zeros the imaginary part
434: Logically Collective on Mat
436: Input Parameters:
437: . mat - the matrix
439: Level: advanced
442: .seealso: MatRealPart()
443: @*/
444: PetscErrorCode MatImaginaryPart(Mat mat)
445: {
451: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
452: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
453: if (!mat->ops->imaginarypart) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
454: MatCheckPreallocated(mat,1);
455: (*mat->ops->imaginarypart)(mat);
456: return(0);
457: }
459: /*@
460: MatMissingDiagonal - Determine if sparse matrix is missing a diagonal entry (or block entry for BAIJ matrices)
462: Not Collective
464: Input Parameter:
465: . mat - the matrix
467: Output Parameters:
468: + missing - is any diagonal missing
469: - dd - first diagonal entry that is missing (optional) on this process
471: Level: advanced
474: .seealso: MatRealPart()
475: @*/
476: PetscErrorCode MatMissingDiagonal(Mat mat,PetscBool *missing,PetscInt *dd)
477: {
484: if (!mat->assembled) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix %s",((PetscObject)mat)->type_name);
485: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
486: if (!mat->ops->missingdiagonal) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
487: (*mat->ops->missingdiagonal)(mat,missing,dd);
488: return(0);
489: }
491: /*@C
492: MatGetRow - Gets a row of a matrix. You MUST call MatRestoreRow()
493: for each row that you get to ensure that your application does
494: not bleed memory.
496: Not Collective
498: Input Parameters:
499: + mat - the matrix
500: - row - the row to get
502: Output Parameters:
503: + ncols - if not NULL, the number of nonzeros in the row
504: . cols - if not NULL, the column numbers
505: - vals - if not NULL, the values
507: Notes:
508: This routine is provided for people who need to have direct access
509: to the structure of a matrix. We hope that we provide enough
510: high-level matrix routines that few users will need it.
512: MatGetRow() always returns 0-based column indices, regardless of
513: whether the internal representation is 0-based (default) or 1-based.
515: For better efficiency, set cols and/or vals to NULL if you do
516: not wish to extract these quantities.
518: The user can only examine the values extracted with MatGetRow();
519: the values cannot be altered. To change the matrix entries, one
520: must use MatSetValues().
522: You can only have one call to MatGetRow() outstanding for a particular
523: matrix at a time, per processor. MatGetRow() can only obtain rows
524: associated with the given processor, it cannot get rows from the
525: other processors; for that we suggest using MatCreateSubMatrices(), then
526: MatGetRow() on the submatrix. The row index passed to MatGetRow()
527: is in the global number of rows.
529: Fortran Notes:
530: The calling sequence from Fortran is
531: .vb
532: MatGetRow(matrix,row,ncols,cols,values,ierr)
533: Mat matrix (input)
534: integer row (input)
535: integer ncols (output)
536: integer cols(maxcols) (output)
537: double precision (or double complex) values(maxcols) output
538: .ve
539: where maxcols >= maximum nonzeros in any row of the matrix.
542: Caution:
543: Do not try to change the contents of the output arrays (cols and vals).
544: In some cases, this may corrupt the matrix.
546: Level: advanced
548: .seealso: MatRestoreRow(), MatSetValues(), MatGetValues(), MatCreateSubMatrices(), MatGetDiagonal()
549: @*/
550: PetscErrorCode MatGetRow(Mat mat,PetscInt row,PetscInt *ncols,const PetscInt *cols[],const PetscScalar *vals[])
551: {
553: PetscInt incols;
558: if (!mat->assembled) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
559: if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
560: if (!mat->ops->getrow) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
561: MatCheckPreallocated(mat,1);
562: PetscLogEventBegin(MAT_GetRow,mat,0,0,0);
563: (*mat->ops->getrow)(mat,row,&incols,(PetscInt**)cols,(PetscScalar**)vals);
564: if (ncols) *ncols = incols;
565: PetscLogEventEnd(MAT_GetRow,mat,0,0,0);
566: return(0);
567: }
569: /*@
570: MatConjugate - replaces the matrix values with their complex conjugates
572: Logically Collective on Mat
574: Input Parameters:
575: . mat - the matrix
577: Level: advanced
579: .seealso: VecConjugate()
580: @*/
581: PetscErrorCode MatConjugate(Mat mat)
582: {
583: #if defined(PETSC_USE_COMPLEX)
588: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
589: if (!mat->ops->conjugate) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Not provided for matrix type %s, send email to petsc-maint@mcs.anl.gov",((PetscObject)mat)->type_name);
590: (*mat->ops->conjugate)(mat);
591: #else
593: #endif
594: return(0);
595: }
597: /*@C
598: MatRestoreRow - Frees any temporary space allocated by MatGetRow().
600: Not Collective
602: Input Parameters:
603: + mat - the matrix
604: . row - the row to get
605: . ncols, cols - the number of nonzeros and their columns
606: - vals - if nonzero the column values
608: Notes:
609: This routine should be called after you have finished examining the entries.
611: This routine zeros out ncols, cols, and vals. This is to prevent accidental
612: us of the array after it has been restored. If you pass NULL, it will
613: not zero the pointers. Use of cols or vals after MatRestoreRow is invalid.
615: Fortran Notes:
616: The calling sequence from Fortran is
617: .vb
618: MatRestoreRow(matrix,row,ncols,cols,values,ierr)
619: Mat matrix (input)
620: integer row (input)
621: integer ncols (output)
622: integer cols(maxcols) (output)
623: double precision (or double complex) values(maxcols) output
624: .ve
625: Where maxcols >= maximum nonzeros in any row of the matrix.
627: In Fortran MatRestoreRow() MUST be called after MatGetRow()
628: before another call to MatGetRow() can be made.
630: Level: advanced
632: .seealso: MatGetRow()
633: @*/
634: PetscErrorCode MatRestoreRow(Mat mat,PetscInt row,PetscInt *ncols,const PetscInt *cols[],const PetscScalar *vals[])
635: {
641: if (!mat->assembled) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
642: if (!mat->ops->restorerow) return(0);
643: (*mat->ops->restorerow)(mat,row,ncols,(PetscInt **)cols,(PetscScalar **)vals);
644: if (ncols) *ncols = 0;
645: if (cols) *cols = NULL;
646: if (vals) *vals = NULL;
647: return(0);
648: }
650: /*@
651: MatGetRowUpperTriangular - Sets a flag to enable calls to MatGetRow() for matrix in MATSBAIJ format.
652: You should call MatRestoreRowUpperTriangular() after calling MatGetRow/MatRestoreRow() to disable the flag.
654: Not Collective
656: Input Parameters:
657: . mat - the matrix
659: Notes:
660: The flag is to ensure that users are aware of MatGetRow() only provides the upper triangular part of the row for the matrices in MATSBAIJ format.
662: Level: advanced
664: .seealso: MatRestoreRowUpperTriangular()
665: @*/
666: PetscErrorCode MatGetRowUpperTriangular(Mat mat)
667: {
673: if (!mat->assembled) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
674: if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
675: MatCheckPreallocated(mat,1);
676: if (!mat->ops->getrowuppertriangular) return(0);
677: (*mat->ops->getrowuppertriangular)(mat);
678: return(0);
679: }
681: /*@
682: MatRestoreRowUpperTriangular - Disable calls to MatGetRow() for matrix in MATSBAIJ format.
684: Not Collective
686: Input Parameters:
687: . mat - the matrix
689: Notes:
690: This routine should be called after you have finished MatGetRow/MatRestoreRow().
693: Level: advanced
695: .seealso: MatGetRowUpperTriangular()
696: @*/
697: PetscErrorCode MatRestoreRowUpperTriangular(Mat mat)
698: {
704: if (!mat->assembled) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
705: if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
706: MatCheckPreallocated(mat,1);
707: if (!mat->ops->restorerowuppertriangular) return(0);
708: (*mat->ops->restorerowuppertriangular)(mat);
709: return(0);
710: }
712: /*@C
713: MatSetOptionsPrefix - Sets the prefix used for searching for all
714: Mat options in the database.
716: Logically Collective on Mat
718: Input Parameter:
719: + A - the Mat context
720: - prefix - the prefix to prepend to all option names
722: Notes:
723: A hyphen (-) must NOT be given at the beginning of the prefix name.
724: The first character of all runtime options is AUTOMATICALLY the hyphen.
726: Level: advanced
728: .seealso: MatSetFromOptions()
729: @*/
730: PetscErrorCode MatSetOptionsPrefix(Mat A,const char prefix[])
731: {
736: PetscObjectSetOptionsPrefix((PetscObject)A,prefix);
737: return(0);
738: }
740: /*@C
741: MatAppendOptionsPrefix - Appends to the prefix used for searching for all
742: Mat options in the database.
744: Logically Collective on Mat
746: Input Parameters:
747: + A - the Mat context
748: - prefix - the prefix to prepend to all option names
750: Notes:
751: A hyphen (-) must NOT be given at the beginning of the prefix name.
752: The first character of all runtime options is AUTOMATICALLY the hyphen.
754: Level: advanced
756: .seealso: MatGetOptionsPrefix()
757: @*/
758: PetscErrorCode MatAppendOptionsPrefix(Mat A,const char prefix[])
759: {
764: PetscObjectAppendOptionsPrefix((PetscObject)A,prefix);
765: return(0);
766: }
768: /*@C
769: MatGetOptionsPrefix - Gets the prefix used for searching for all
770: Mat options in the database.
772: Not Collective
774: Input Parameter:
775: . A - the Mat context
777: Output Parameter:
778: . prefix - pointer to the prefix string used
780: Notes:
781: On the fortran side, the user should pass in a string 'prefix' of
782: sufficient length to hold the prefix.
784: Level: advanced
786: .seealso: MatAppendOptionsPrefix()
787: @*/
788: PetscErrorCode MatGetOptionsPrefix(Mat A,const char *prefix[])
789: {
794: PetscObjectGetOptionsPrefix((PetscObject)A,prefix);
795: return(0);
796: }
798: /*@
799: MatResetPreallocation - Reset mat to use the original nonzero pattern provided by users.
801: Collective on Mat
803: Input Parameters:
804: . A - the Mat context
806: Notes:
807: The allocated memory will be shrunk after calling MatAssembly with MAT_FINAL_ASSEMBLY. Users can reset the preallocation to access the original memory.
808: Currently support MPIAIJ and SEQAIJ.
810: Level: beginner
812: .seealso: MatSeqAIJSetPreallocation(), MatMPIAIJSetPreallocation(), MatXAIJSetPreallocation()
813: @*/
814: PetscErrorCode MatResetPreallocation(Mat A)
815: {
821: PetscUseMethod(A,"MatResetPreallocation_C",(Mat),(A));
822: return(0);
823: }
826: /*@
827: MatSetUp - Sets up the internal matrix data structures for later use.
829: Collective on Mat
831: Input Parameters:
832: . A - the Mat context
834: Notes:
835: If the user has not set preallocation for this matrix then a default preallocation that is likely to be inefficient is used.
837: If a suitable preallocation routine is used, this function does not need to be called.
839: See the Performance chapter of the PETSc users manual for how to preallocate matrices
841: Level: beginner
843: .seealso: MatCreate(), MatDestroy()
844: @*/
845: PetscErrorCode MatSetUp(Mat A)
846: {
847: PetscMPIInt size;
852: if (!((PetscObject)A)->type_name) {
853: MPI_Comm_size(PetscObjectComm((PetscObject)A), &size);
854: if (size == 1) {
855: MatSetType(A, MATSEQAIJ);
856: } else {
857: MatSetType(A, MATMPIAIJ);
858: }
859: }
860: if (!A->preallocated && A->ops->setup) {
861: PetscInfo(A,"Warning not preallocating matrix storage\n");
862: (*A->ops->setup)(A);
863: }
864: PetscLayoutSetUp(A->rmap);
865: PetscLayoutSetUp(A->cmap);
866: A->preallocated = PETSC_TRUE;
867: return(0);
868: }
870: #if defined(PETSC_HAVE_SAWS)
871: #include <petscviewersaws.h>
872: #endif
874: /*@C
875: MatViewFromOptions - View from Options
877: Collective on Mat
879: Input Parameters:
880: + A - the Mat context
881: . obj - Optional object
882: - name - command line option
884: Level: intermediate
885: .seealso: Mat, MatView, PetscObjectViewFromOptions(), MatCreate()
886: @*/
887: PetscErrorCode MatViewFromOptions(Mat A,PetscObject obj,const char name[])
888: {
893: PetscObjectViewFromOptions((PetscObject)A,obj,name);
894: return(0);
895: }
897: /*@C
898: MatView - Visualizes a matrix object.
900: Collective on Mat
902: Input Parameters:
903: + mat - the matrix
904: - viewer - visualization context
906: Notes:
907: The available visualization contexts include
908: + PETSC_VIEWER_STDOUT_SELF - for sequential matrices
909: . PETSC_VIEWER_STDOUT_WORLD - for parallel matrices created on PETSC_COMM_WORLD
910: . PETSC_VIEWER_STDOUT_(comm) - for matrices created on MPI communicator comm
911: - PETSC_VIEWER_DRAW_WORLD - graphical display of nonzero structure
913: The user can open alternative visualization contexts with
914: + PetscViewerASCIIOpen() - Outputs matrix to a specified file
915: . PetscViewerBinaryOpen() - Outputs matrix in binary to a
916: specified file; corresponding input uses MatLoad()
917: . PetscViewerDrawOpen() - Outputs nonzero matrix structure to
918: an X window display
919: - PetscViewerSocketOpen() - Outputs matrix to Socket viewer.
920: Currently only the sequential dense and AIJ
921: matrix types support the Socket viewer.
923: The user can call PetscViewerPushFormat() to specify the output
924: format of ASCII printed objects (when using PETSC_VIEWER_STDOUT_SELF,
925: PETSC_VIEWER_STDOUT_WORLD and PetscViewerASCIIOpen). Available formats include
926: + PETSC_VIEWER_DEFAULT - default, prints matrix contents
927: . PETSC_VIEWER_ASCII_MATLAB - prints matrix contents in Matlab format
928: . PETSC_VIEWER_ASCII_DENSE - prints entire matrix including zeros
929: . PETSC_VIEWER_ASCII_COMMON - prints matrix contents, using a sparse
930: format common among all matrix types
931: . PETSC_VIEWER_ASCII_IMPL - prints matrix contents, using an implementation-specific
932: format (which is in many cases the same as the default)
933: . PETSC_VIEWER_ASCII_INFO - prints basic information about the matrix
934: size and structure (not the matrix entries)
935: - PETSC_VIEWER_ASCII_INFO_DETAIL - prints more detailed information about
936: the matrix structure
938: Options Database Keys:
939: + -mat_view ::ascii_info - Prints info on matrix at conclusion of MatAssemblyEnd()
940: . -mat_view ::ascii_info_detail - Prints more detailed info
941: . -mat_view - Prints matrix in ASCII format
942: . -mat_view ::ascii_matlab - Prints matrix in Matlab format
943: . -mat_view draw - PetscDraws nonzero structure of matrix, using MatView() and PetscDrawOpenX().
944: . -display <name> - Sets display name (default is host)
945: . -draw_pause <sec> - Sets number of seconds to pause after display
946: . -mat_view socket - Sends matrix to socket, can be accessed from Matlab (see Users-Manual: Chapter 12 Using MATLAB with PETSc for details)
947: . -viewer_socket_machine <machine> -
948: . -viewer_socket_port <port> -
949: . -mat_view binary - save matrix to file in binary format
950: - -viewer_binary_filename <name> -
951: Level: beginner
953: Notes:
954: The ASCII viewers are only recommended for small matrices on at most a moderate number of processes,
955: the program will seemingly hang and take hours for larger matrices, for larger matrices one should use the binary format.
957: See the manual page for MatLoad() for the exact format of the binary file when the binary
958: viewer is used.
960: See share/petsc/matlab/PetscBinaryRead.m for a Matlab code that can read in the binary file when the binary
961: viewer is used.
963: One can use '-mat_view draw -draw_pause -1' to pause the graphical display of matrix nonzero structure,
964: and then use the following mouse functions.
965: + left mouse: zoom in
966: . middle mouse: zoom out
967: - right mouse: continue with the simulation
969: .seealso: PetscViewerPushFormat(), PetscViewerASCIIOpen(), PetscViewerDrawOpen(),
970: PetscViewerSocketOpen(), PetscViewerBinaryOpen(), MatLoad()
971: @*/
972: PetscErrorCode MatView(Mat mat,PetscViewer viewer)
973: {
974: PetscErrorCode ierr;
975: PetscInt rows,cols,rbs,cbs;
976: PetscBool isascii,isstring,issaws;
977: PetscViewerFormat format;
978: PetscMPIInt size;
983: if (!viewer) {PetscViewerASCIIGetStdout(PetscObjectComm((PetscObject)mat),&viewer);}
986: MatCheckPreallocated(mat,1);
988: PetscViewerGetFormat(viewer,&format);
989: MPI_Comm_size(PetscObjectComm((PetscObject)mat),&size);
990: if (size == 1 && format == PETSC_VIEWER_LOAD_BALANCE) return(0);
992: PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERSTRING,&isstring);
993: PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERASCII,&isascii);
994: PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERSAWS,&issaws);
995: if ((!isascii || (format != PETSC_VIEWER_ASCII_INFO || format == PETSC_VIEWER_ASCII_INFO_DETAIL)) && mat->factortype) {
996: SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"No viewers for factored matrix except ASCII info or info_detail");
997: }
999: PetscLogEventBegin(MAT_View,mat,viewer,0,0);
1000: if (isascii) {
1001: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ORDER,"Must call MatAssemblyBegin/End() before viewing matrix");
1002: PetscObjectPrintClassNamePrefixType((PetscObject)mat,viewer);
1003: if (format == PETSC_VIEWER_ASCII_INFO || format == PETSC_VIEWER_ASCII_INFO_DETAIL) {
1004: MatNullSpace nullsp,transnullsp;
1006: PetscViewerASCIIPushTab(viewer);
1007: MatGetSize(mat,&rows,&cols);
1008: MatGetBlockSizes(mat,&rbs,&cbs);
1009: if (rbs != 1 || cbs != 1) {
1010: if (rbs != cbs) {PetscViewerASCIIPrintf(viewer,"rows=%D, cols=%D, rbs=%D, cbs=%D\n",rows,cols,rbs,cbs);}
1011: else {PetscViewerASCIIPrintf(viewer,"rows=%D, cols=%D, bs=%D\n",rows,cols,rbs);}
1012: } else {
1013: PetscViewerASCIIPrintf(viewer,"rows=%D, cols=%D\n",rows,cols);
1014: }
1015: if (mat->factortype) {
1016: MatSolverType solver;
1017: MatFactorGetSolverType(mat,&solver);
1018: PetscViewerASCIIPrintf(viewer,"package used to perform factorization: %s\n",solver);
1019: }
1020: if (mat->ops->getinfo) {
1021: MatInfo info;
1022: MatGetInfo(mat,MAT_GLOBAL_SUM,&info);
1023: PetscViewerASCIIPrintf(viewer,"total: nonzeros=%.f, allocated nonzeros=%.f\n",info.nz_used,info.nz_allocated);
1024: PetscViewerASCIIPrintf(viewer,"total number of mallocs used during MatSetValues calls=%D\n",(PetscInt)info.mallocs);
1025: }
1026: MatGetNullSpace(mat,&nullsp);
1027: MatGetTransposeNullSpace(mat,&transnullsp);
1028: if (nullsp) {PetscViewerASCIIPrintf(viewer," has attached null space\n");}
1029: if (transnullsp && transnullsp != nullsp) {PetscViewerASCIIPrintf(viewer," has attached transposed null space\n");}
1030: MatGetNearNullSpace(mat,&nullsp);
1031: if (nullsp) {PetscViewerASCIIPrintf(viewer," has attached near null space\n");}
1032: }
1033: } else if (issaws) {
1034: #if defined(PETSC_HAVE_SAWS)
1035: PetscMPIInt rank;
1037: PetscObjectName((PetscObject)mat);
1038: MPI_Comm_rank(PETSC_COMM_WORLD,&rank);
1039: if (!((PetscObject)mat)->amsmem && !rank) {
1040: PetscObjectViewSAWs((PetscObject)mat,viewer);
1041: }
1042: #endif
1043: } else if (isstring) {
1044: const char *type;
1045: MatGetType(mat,&type);
1046: PetscViewerStringSPrintf(viewer," MatType: %-7.7s",type);
1047: if (mat->ops->view) {(*mat->ops->view)(mat,viewer);}
1048: }
1049: if ((format == PETSC_VIEWER_NATIVE || format == PETSC_VIEWER_LOAD_BALANCE) && mat->ops->viewnative) {
1050: PetscViewerASCIIPushTab(viewer);
1051: (*mat->ops->viewnative)(mat,viewer);
1052: PetscViewerASCIIPopTab(viewer);
1053: } else if (mat->ops->view) {
1054: PetscViewerASCIIPushTab(viewer);
1055: (*mat->ops->view)(mat,viewer);
1056: PetscViewerASCIIPopTab(viewer);
1057: }
1058: if (isascii) {
1059: PetscViewerGetFormat(viewer,&format);
1060: if (format == PETSC_VIEWER_ASCII_INFO || format == PETSC_VIEWER_ASCII_INFO_DETAIL) {
1061: PetscViewerASCIIPopTab(viewer);
1062: }
1063: }
1064: PetscLogEventEnd(MAT_View,mat,viewer,0,0);
1065: return(0);
1066: }
1068: #if defined(PETSC_USE_DEBUG)
1069: #include <../src/sys/totalview/tv_data_display.h>
1070: PETSC_UNUSED static int TV_display_type(const struct _p_Mat *mat)
1071: {
1072: TV_add_row("Local rows", "int", &mat->rmap->n);
1073: TV_add_row("Local columns", "int", &mat->cmap->n);
1074: TV_add_row("Global rows", "int", &mat->rmap->N);
1075: TV_add_row("Global columns", "int", &mat->cmap->N);
1076: TV_add_row("Typename", TV_ascii_string_type, ((PetscObject)mat)->type_name);
1077: return TV_format_OK;
1078: }
1079: #endif
1081: /*@C
1082: MatLoad - Loads a matrix that has been stored in binary/HDF5 format
1083: with MatView(). The matrix format is determined from the options database.
1084: Generates a parallel MPI matrix if the communicator has more than one
1085: processor. The default matrix type is AIJ.
1087: Collective on PetscViewer
1089: Input Parameters:
1090: + mat - the newly loaded matrix, this needs to have been created with MatCreate()
1091: or some related function before a call to MatLoad()
1092: - viewer - binary/HDF5 file viewer
1094: Options Database Keys:
1095: Used with block matrix formats (MATSEQBAIJ, ...) to specify
1096: block size
1097: . -matload_block_size <bs>
1099: Level: beginner
1101: Notes:
1102: If the Mat type has not yet been given then MATAIJ is used, call MatSetFromOptions() on the
1103: Mat before calling this routine if you wish to set it from the options database.
1105: MatLoad() automatically loads into the options database any options
1106: given in the file filename.info where filename is the name of the file
1107: that was passed to the PetscViewerBinaryOpen(). The options in the info
1108: file will be ignored if you use the -viewer_binary_skip_info option.
1110: If the type or size of mat is not set before a call to MatLoad, PETSc
1111: sets the default matrix type AIJ and sets the local and global sizes.
1112: If type and/or size is already set, then the same are used.
1114: In parallel, each processor can load a subset of rows (or the
1115: entire matrix). This routine is especially useful when a large
1116: matrix is stored on disk and only part of it is desired on each
1117: processor. For example, a parallel solver may access only some of
1118: the rows from each processor. The algorithm used here reads
1119: relatively small blocks of data rather than reading the entire
1120: matrix and then subsetting it.
1122: Viewer's PetscViewerType must be either PETSCVIEWERBINARY or PETSCVIEWERHDF5.
1123: Such viewer can be created using PetscViewerBinaryOpen()/PetscViewerHDF5Open(),
1124: or the sequence like
1125: $ PetscViewer v;
1126: $ PetscViewerCreate(PETSC_COMM_WORLD,&v);
1127: $ PetscViewerSetType(v,PETSCVIEWERBINARY);
1128: $ PetscViewerSetFromOptions(v);
1129: $ PetscViewerFileSetMode(v,FILE_MODE_READ);
1130: $ PetscViewerFileSetName(v,"datafile");
1131: The optional PetscViewerSetFromOptions() call allows to override PetscViewerSetType() using option
1132: $ -viewer_type {binary,hdf5}
1134: See the example src/ksp/ksp/tutorials/ex27.c with the first approach,
1135: and src/mat/tutorials/ex10.c with the second approach.
1137: Notes about the PETSc binary format:
1138: In case of PETSCVIEWERBINARY, a native PETSc binary format is used. Each of the blocks
1139: is read onto rank 0 and then shipped to its destination rank, one after another.
1140: Multiple objects, both matrices and vectors, can be stored within the same file.
1141: Their PetscObject name is ignored; they are loaded in the order of their storage.
1143: Most users should not need to know the details of the binary storage
1144: format, since MatLoad() and MatView() completely hide these details.
1145: But for anyone who's interested, the standard binary matrix storage
1146: format is
1148: $ PetscInt MAT_FILE_CLASSID
1149: $ PetscInt number of rows
1150: $ PetscInt number of columns
1151: $ PetscInt total number of nonzeros
1152: $ PetscInt *number nonzeros in each row
1153: $ PetscInt *column indices of all nonzeros (starting index is zero)
1154: $ PetscScalar *values of all nonzeros
1156: PETSc automatically does the byte swapping for
1157: machines that store the bytes reversed, e.g. DEC alpha, freebsd,
1158: linux, Windows and the paragon; thus if you write your own binary
1159: read/write routines you have to swap the bytes; see PetscBinaryRead()
1160: and PetscBinaryWrite() to see how this may be done.
1162: Notes about the HDF5 (MATLAB MAT-File Version 7.3) format:
1163: In case of PETSCVIEWERHDF5, a parallel HDF5 reader is used.
1164: Each processor's chunk is loaded independently by its owning rank.
1165: Multiple objects, both matrices and vectors, can be stored within the same file.
1166: They are looked up by their PetscObject name.
1168: As the MATLAB MAT-File Version 7.3 format is also a HDF5 flavor, we decided to use
1169: by default the same structure and naming of the AIJ arrays and column count
1170: within the HDF5 file. This means that a MAT file saved with -v7.3 flag, e.g.
1171: $ save example.mat A b -v7.3
1172: can be directly read by this routine (see Reference 1 for details).
1173: Note that depending on your MATLAB version, this format might be a default,
1174: otherwise you can set it as default in Preferences.
1176: Unless -nocompression flag is used to save the file in MATLAB,
1177: PETSc must be configured with ZLIB package.
1179: See also examples src/mat/tutorials/ex10.c and src/ksp/ksp/tutorials/ex27.c
1181: Current HDF5 (MAT-File) limitations:
1182: This reader currently supports only real MATSEQAIJ, MATMPIAIJ, MATSEQDENSE and MATMPIDENSE matrices.
1184: Corresponding MatView() is not yet implemented.
1186: The loaded matrix is actually a transpose of the original one in MATLAB,
1187: unless you push PETSC_VIEWER_HDF5_MAT format (see examples above).
1188: With this format, matrix is automatically transposed by PETSc,
1189: unless the matrix is marked as SPD or symmetric
1190: (see MatSetOption(), MAT_SPD, MAT_SYMMETRIC).
1192: References:
1193: 1. MATLAB(R) Documentation, manual page of save(), https://www.mathworks.com/help/matlab/ref/save.html#btox10b-1-version
1195: .seealso: PetscViewerBinaryOpen(), PetscViewerSetType(), MatView(), VecLoad()
1197: @*/
1198: PetscErrorCode MatLoad(Mat mat,PetscViewer viewer)
1199: {
1201: PetscBool flg;
1207: if (!((PetscObject)mat)->type_name) {
1208: MatSetType(mat,MATAIJ);
1209: }
1211: flg = PETSC_FALSE;
1212: PetscOptionsGetBool(((PetscObject)mat)->options,((PetscObject)mat)->prefix,"-matload_symmetric",&flg,NULL);
1213: if (flg) {
1214: MatSetOption(mat,MAT_SYMMETRIC,PETSC_TRUE);
1215: MatSetOption(mat,MAT_SYMMETRY_ETERNAL,PETSC_TRUE);
1216: }
1217: flg = PETSC_FALSE;
1218: PetscOptionsGetBool(((PetscObject)mat)->options,((PetscObject)mat)->prefix,"-matload_spd",&flg,NULL);
1219: if (flg) {
1220: MatSetOption(mat,MAT_SPD,PETSC_TRUE);
1221: }
1223: if (!mat->ops->load) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"MatLoad is not supported for type %s",((PetscObject)mat)->type_name);
1224: PetscLogEventBegin(MAT_Load,mat,viewer,0,0);
1225: (*mat->ops->load)(mat,viewer);
1226: PetscLogEventEnd(MAT_Load,mat,viewer,0,0);
1227: return(0);
1228: }
1230: static PetscErrorCode MatDestroy_Redundant(Mat_Redundant **redundant)
1231: {
1233: Mat_Redundant *redund = *redundant;
1234: PetscInt i;
1237: if (redund){
1238: if (redund->matseq) { /* via MatCreateSubMatrices() */
1239: ISDestroy(&redund->isrow);
1240: ISDestroy(&redund->iscol);
1241: MatDestroySubMatrices(1,&redund->matseq);
1242: } else {
1243: PetscFree2(redund->send_rank,redund->recv_rank);
1244: PetscFree(redund->sbuf_j);
1245: PetscFree(redund->sbuf_a);
1246: for (i=0; i<redund->nrecvs; i++) {
1247: PetscFree(redund->rbuf_j[i]);
1248: PetscFree(redund->rbuf_a[i]);
1249: }
1250: PetscFree4(redund->sbuf_nz,redund->rbuf_nz,redund->rbuf_j,redund->rbuf_a);
1251: }
1253: if (redund->subcomm) {
1254: PetscCommDestroy(&redund->subcomm);
1255: }
1256: PetscFree(redund);
1257: }
1258: return(0);
1259: }
1261: /*@
1262: MatDestroy - Frees space taken by a matrix.
1264: Collective on Mat
1266: Input Parameter:
1267: . A - the matrix
1269: Level: beginner
1271: @*/
1272: PetscErrorCode MatDestroy(Mat *A)
1273: {
1277: if (!*A) return(0);
1279: if (--((PetscObject)(*A))->refct > 0) {*A = NULL; return(0);}
1281: /* if memory was published with SAWs then destroy it */
1282: PetscObjectSAWsViewOff((PetscObject)*A);
1283: if ((*A)->ops->destroy) {
1284: (*(*A)->ops->destroy)(*A);
1285: }
1287: PetscFree((*A)->defaultvectype);
1288: PetscFree((*A)->bsizes);
1289: PetscFree((*A)->solvertype);
1290: MatDestroy_Redundant(&(*A)->redundant);
1291: MatProductClear(*A);
1293: MatNullSpaceDestroy(&(*A)->nullsp);
1294: MatNullSpaceDestroy(&(*A)->transnullsp);
1295: MatNullSpaceDestroy(&(*A)->nearnullsp);
1296: MatDestroy(&(*A)->schur);
1297: PetscLayoutDestroy(&(*A)->rmap);
1298: PetscLayoutDestroy(&(*A)->cmap);
1299: PetscHeaderDestroy(A);
1300: return(0);
1301: }
1303: /*@C
1304: MatSetValues - Inserts or adds a block of values into a matrix.
1305: These values may be cached, so MatAssemblyBegin() and MatAssemblyEnd()
1306: MUST be called after all calls to MatSetValues() have been completed.
1308: Not Collective
1310: Input Parameters:
1311: + mat - the matrix
1312: . v - a logically two-dimensional array of values
1313: . m, idxm - the number of rows and their global indices
1314: . n, idxn - the number of columns and their global indices
1315: - addv - either ADD_VALUES or INSERT_VALUES, where
1316: ADD_VALUES adds values to any existing entries, and
1317: INSERT_VALUES replaces existing entries with new values
1319: Notes:
1320: If you create the matrix yourself (that is not with a call to DMCreateMatrix()) then you MUST call MatXXXXSetPreallocation() or
1321: MatSetUp() before using this routine
1323: By default the values, v, are row-oriented. See MatSetOption() for other options.
1325: Calls to MatSetValues() with the INSERT_VALUES and ADD_VALUES
1326: options cannot be mixed without intervening calls to the assembly
1327: routines.
1329: MatSetValues() uses 0-based row and column numbers in Fortran
1330: as well as in C.
1332: Negative indices may be passed in idxm and idxn, these rows and columns are
1333: simply ignored. This allows easily inserting element stiffness matrices
1334: with homogeneous Dirchlet boundary conditions that you don't want represented
1335: in the matrix.
1337: Efficiency Alert:
1338: The routine MatSetValuesBlocked() may offer much better efficiency
1339: for users of block sparse formats (MATSEQBAIJ and MATMPIBAIJ).
1341: Level: beginner
1343: Developer Notes:
1344: This is labeled with C so does not automatically generate Fortran stubs and interfaces
1345: because it requires multiple Fortran interfaces depending on which arguments are scalar or arrays.
1347: .seealso: MatSetOption(), MatAssemblyBegin(), MatAssemblyEnd(), MatSetValuesBlocked(), MatSetValuesLocal(),
1348: InsertMode, INSERT_VALUES, ADD_VALUES
1349: @*/
1350: PetscErrorCode MatSetValues(Mat mat,PetscInt m,const PetscInt idxm[],PetscInt n,const PetscInt idxn[],const PetscScalar v[],InsertMode addv)
1351: {
1353: #if defined(PETSC_USE_DEBUG)
1354: PetscInt i,j;
1355: #endif
1360: if (!m || !n) return(0); /* no values to insert */
1363: MatCheckPreallocated(mat,1);
1365: if (mat->insertmode == NOT_SET_VALUES) {
1366: mat->insertmode = addv;
1367: }
1368: #if defined(PETSC_USE_DEBUG)
1369: else if (mat->insertmode != addv) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Cannot mix add values and insert values");
1370: if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
1371: if (!mat->ops->setvalues) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
1373: for (i=0; i<m; i++) {
1374: for (j=0; j<n; j++) {
1375: if (mat->erroriffailure && PetscIsInfOrNanScalar(v[i*n+j]))
1376: #if defined(PETSC_USE_COMPLEX)
1377: SETERRQ4(PETSC_COMM_SELF,PETSC_ERR_FP,"Inserting %g+ig at matrix entry (%D,%D)",(double)PetscRealPart(v[i*n+j]),(double)PetscImaginaryPart(v[i*n+j]),idxm[i],idxn[j]);
1378: #else
1379: SETERRQ3(PETSC_COMM_SELF,PETSC_ERR_FP,"Inserting %g at matrix entry (%D,%D)",(double)v[i*n+j],idxm[i],idxn[j]);
1380: #endif
1381: }
1382: }
1383: #endif
1385: if (mat->assembled) {
1386: mat->was_assembled = PETSC_TRUE;
1387: mat->assembled = PETSC_FALSE;
1388: }
1389: PetscLogEventBegin(MAT_SetValues,mat,0,0,0);
1390: (*mat->ops->setvalues)(mat,m,idxm,n,idxn,v,addv);
1391: PetscLogEventEnd(MAT_SetValues,mat,0,0,0);
1392: return(0);
1393: }
1396: /*@
1397: MatSetValuesRowLocal - Inserts a row (block row for BAIJ matrices) of nonzero
1398: values into a matrix
1400: Not Collective
1402: Input Parameters:
1403: + mat - the matrix
1404: . row - the (block) row to set
1405: - v - a logically two-dimensional array of values
1407: Notes:
1408: By the values, v, are column-oriented (for the block version) and sorted
1410: All the nonzeros in the row must be provided
1412: The matrix must have previously had its column indices set
1414: The row must belong to this process
1416: Level: intermediate
1418: .seealso: MatSetOption(), MatAssemblyBegin(), MatAssemblyEnd(), MatSetValuesBlocked(), MatSetValuesLocal(),
1419: InsertMode, INSERT_VALUES, ADD_VALUES, MatSetValues(), MatSetValuesRow(), MatSetLocalToGlobalMapping()
1420: @*/
1421: PetscErrorCode MatSetValuesRowLocal(Mat mat,PetscInt row,const PetscScalar v[])
1422: {
1424: PetscInt globalrow;
1430: ISLocalToGlobalMappingApply(mat->rmap->mapping,1,&row,&globalrow);
1431: MatSetValuesRow(mat,globalrow,v);
1432: return(0);
1433: }
1435: /*@
1436: MatSetValuesRow - Inserts a row (block row for BAIJ matrices) of nonzero
1437: values into a matrix
1439: Not Collective
1441: Input Parameters:
1442: + mat - the matrix
1443: . row - the (block) row to set
1444: - v - a logically two-dimensional (column major) array of values for block matrices with blocksize larger than one, otherwise a one dimensional array of values
1446: Notes:
1447: The values, v, are column-oriented for the block version.
1449: All the nonzeros in the row must be provided
1451: THE MATRIX MUST HAVE PREVIOUSLY HAD ITS COLUMN INDICES SET. IT IS RARE THAT THIS ROUTINE IS USED, usually MatSetValues() is used.
1453: The row must belong to this process
1455: Level: advanced
1457: .seealso: MatSetOption(), MatAssemblyBegin(), MatAssemblyEnd(), MatSetValuesBlocked(), MatSetValuesLocal(),
1458: InsertMode, INSERT_VALUES, ADD_VALUES, MatSetValues()
1459: @*/
1460: PetscErrorCode MatSetValuesRow(Mat mat,PetscInt row,const PetscScalar v[])
1461: {
1467: MatCheckPreallocated(mat,1);
1469: #if defined(PETSC_USE_DEBUG)
1470: if (mat->insertmode == ADD_VALUES) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Cannot mix add and insert values");
1471: if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
1472: #endif
1473: mat->insertmode = INSERT_VALUES;
1475: if (mat->assembled) {
1476: mat->was_assembled = PETSC_TRUE;
1477: mat->assembled = PETSC_FALSE;
1478: }
1479: PetscLogEventBegin(MAT_SetValues,mat,0,0,0);
1480: if (!mat->ops->setvaluesrow) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
1481: (*mat->ops->setvaluesrow)(mat,row,v);
1482: PetscLogEventEnd(MAT_SetValues,mat,0,0,0);
1483: return(0);
1484: }
1486: /*@
1487: MatSetValuesStencil - Inserts or adds a block of values into a matrix.
1488: Using structured grid indexing
1490: Not Collective
1492: Input Parameters:
1493: + mat - the matrix
1494: . m - number of rows being entered
1495: . idxm - grid coordinates (and component number when dof > 1) for matrix rows being entered
1496: . n - number of columns being entered
1497: . idxn - grid coordinates (and component number when dof > 1) for matrix columns being entered
1498: . v - a logically two-dimensional array of values
1499: - addv - either ADD_VALUES or INSERT_VALUES, where
1500: ADD_VALUES adds values to any existing entries, and
1501: INSERT_VALUES replaces existing entries with new values
1503: Notes:
1504: By default the values, v, are row-oriented. See MatSetOption() for other options.
1506: Calls to MatSetValuesStencil() with the INSERT_VALUES and ADD_VALUES
1507: options cannot be mixed without intervening calls to the assembly
1508: routines.
1510: The grid coordinates are across the entire grid, not just the local portion
1512: MatSetValuesStencil() uses 0-based row and column numbers in Fortran
1513: as well as in C.
1515: For setting/accessing vector values via array coordinates you can use the DMDAVecGetArray() routine
1517: In order to use this routine you must either obtain the matrix with DMCreateMatrix()
1518: or call MatSetLocalToGlobalMapping() and MatSetStencil() first.
1520: The columns and rows in the stencil passed in MUST be contained within the
1521: ghost region of the given process as set with DMDACreateXXX() or MatSetStencil(). For example,
1522: if you create a DMDA with an overlap of one grid level and on a particular process its first
1523: local nonghost x logical coordinate is 6 (so its first ghost x logical coordinate is 5) the
1524: first i index you can use in your column and row indices in MatSetStencil() is 5.
1526: In Fortran idxm and idxn should be declared as
1527: $ MatStencil idxm(4,m),idxn(4,n)
1528: and the values inserted using
1529: $ idxm(MatStencil_i,1) = i
1530: $ idxm(MatStencil_j,1) = j
1531: $ idxm(MatStencil_k,1) = k
1532: $ idxm(MatStencil_c,1) = c
1533: etc
1535: For periodic boundary conditions use negative indices for values to the left (below 0; that are to be
1536: obtained by wrapping values from right edge). For values to the right of the last entry using that index plus one
1537: etc to obtain values that obtained by wrapping the values from the left edge. This does not work for anything but the
1538: DM_BOUNDARY_PERIODIC boundary type.
1540: 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
1541: a single value per point) you can skip filling those indices.
1543: Inspired by the structured grid interface to the HYPRE package
1544: (https://computation.llnl.gov/projects/hypre-scalable-linear-solvers-multigrid-methods)
1546: Efficiency Alert:
1547: The routine MatSetValuesBlockedStencil() may offer much better efficiency
1548: for users of block sparse formats (MATSEQBAIJ and MATMPIBAIJ).
1550: Level: beginner
1552: .seealso: MatSetOption(), MatAssemblyBegin(), MatAssemblyEnd(), MatSetValuesBlocked(), MatSetValuesLocal()
1553: MatSetValues(), MatSetValuesBlockedStencil(), MatSetStencil(), DMCreateMatrix(), DMDAVecGetArray(), MatStencil
1554: @*/
1555: PetscErrorCode MatSetValuesStencil(Mat mat,PetscInt m,const MatStencil idxm[],PetscInt n,const MatStencil idxn[],const PetscScalar v[],InsertMode addv)
1556: {
1558: PetscInt buf[8192],*bufm=0,*bufn=0,*jdxm,*jdxn;
1559: PetscInt j,i,dim = mat->stencil.dim,*dims = mat->stencil.dims+1,tmp;
1560: PetscInt *starts = mat->stencil.starts,*dxm = (PetscInt*)idxm,*dxn = (PetscInt*)idxn,sdim = dim - (1 - (PetscInt)mat->stencil.noc);
1563: if (!m || !n) return(0); /* no values to insert */
1569: if ((m+n) <= (PetscInt)(sizeof(buf)/sizeof(PetscInt))) {
1570: jdxm = buf; jdxn = buf+m;
1571: } else {
1572: PetscMalloc2(m,&bufm,n,&bufn);
1573: jdxm = bufm; jdxn = bufn;
1574: }
1575: for (i=0; i<m; i++) {
1576: for (j=0; j<3-sdim; j++) dxm++;
1577: tmp = *dxm++ - starts[0];
1578: for (j=0; j<dim-1; j++) {
1579: if ((*dxm++ - starts[j+1]) < 0 || tmp < 0) tmp = -1;
1580: else tmp = tmp*dims[j] + *(dxm-1) - starts[j+1];
1581: }
1582: if (mat->stencil.noc) dxm++;
1583: jdxm[i] = tmp;
1584: }
1585: for (i=0; i<n; i++) {
1586: for (j=0; j<3-sdim; j++) dxn++;
1587: tmp = *dxn++ - starts[0];
1588: for (j=0; j<dim-1; j++) {
1589: if ((*dxn++ - starts[j+1]) < 0 || tmp < 0) tmp = -1;
1590: else tmp = tmp*dims[j] + *(dxn-1) - starts[j+1];
1591: }
1592: if (mat->stencil.noc) dxn++;
1593: jdxn[i] = tmp;
1594: }
1595: MatSetValuesLocal(mat,m,jdxm,n,jdxn,v,addv);
1596: PetscFree2(bufm,bufn);
1597: return(0);
1598: }
1600: /*@
1601: MatSetValuesBlockedStencil - Inserts or adds a block of values into a matrix.
1602: Using structured grid indexing
1604: Not Collective
1606: Input Parameters:
1607: + mat - the matrix
1608: . m - number of rows being entered
1609: . idxm - grid coordinates for matrix rows being entered
1610: . n - number of columns being entered
1611: . idxn - grid coordinates for matrix columns being entered
1612: . v - a logically two-dimensional array of values
1613: - addv - either ADD_VALUES or INSERT_VALUES, where
1614: ADD_VALUES adds values to any existing entries, and
1615: INSERT_VALUES replaces existing entries with new values
1617: Notes:
1618: By default the values, v, are row-oriented and unsorted.
1619: See MatSetOption() for other options.
1621: Calls to MatSetValuesBlockedStencil() with the INSERT_VALUES and ADD_VALUES
1622: options cannot be mixed without intervening calls to the assembly
1623: routines.
1625: The grid coordinates are across the entire grid, not just the local portion
1627: MatSetValuesBlockedStencil() uses 0-based row and column numbers in Fortran
1628: as well as in C.
1630: For setting/accessing vector values via array coordinates you can use the DMDAVecGetArray() routine
1632: In order to use this routine you must either obtain the matrix with DMCreateMatrix()
1633: or call MatSetBlockSize(), MatSetLocalToGlobalMapping() and MatSetStencil() first.
1635: The columns and rows in the stencil passed in MUST be contained within the
1636: ghost region of the given process as set with DMDACreateXXX() or MatSetStencil(). For example,
1637: if you create a DMDA with an overlap of one grid level and on a particular process its first
1638: local nonghost x logical coordinate is 6 (so its first ghost x logical coordinate is 5) the
1639: first i index you can use in your column and row indices in MatSetStencil() is 5.
1641: In Fortran idxm and idxn should be declared as
1642: $ MatStencil idxm(4,m),idxn(4,n)
1643: and the values inserted using
1644: $ idxm(MatStencil_i,1) = i
1645: $ idxm(MatStencil_j,1) = j
1646: $ idxm(MatStencil_k,1) = k
1647: etc
1649: Negative indices may be passed in idxm and idxn, these rows and columns are
1650: simply ignored. This allows easily inserting element stiffness matrices
1651: with homogeneous Dirchlet boundary conditions that you don't want represented
1652: in the matrix.
1654: Inspired by the structured grid interface to the HYPRE package
1655: (https://computation.llnl.gov/projects/hypre-scalable-linear-solvers-multigrid-methods)
1657: Level: beginner
1659: .seealso: MatSetOption(), MatAssemblyBegin(), MatAssemblyEnd(), MatSetValuesBlocked(), MatSetValuesLocal()
1660: MatSetValues(), MatSetValuesStencil(), MatSetStencil(), DMCreateMatrix(), DMDAVecGetArray(), MatStencil,
1661: MatSetBlockSize(), MatSetLocalToGlobalMapping()
1662: @*/
1663: PetscErrorCode MatSetValuesBlockedStencil(Mat mat,PetscInt m,const MatStencil idxm[],PetscInt n,const MatStencil idxn[],const PetscScalar v[],InsertMode addv)
1664: {
1666: PetscInt buf[8192],*bufm=0,*bufn=0,*jdxm,*jdxn;
1667: PetscInt j,i,dim = mat->stencil.dim,*dims = mat->stencil.dims+1,tmp;
1668: PetscInt *starts = mat->stencil.starts,*dxm = (PetscInt*)idxm,*dxn = (PetscInt*)idxn,sdim = dim - (1 - (PetscInt)mat->stencil.noc);
1671: if (!m || !n) return(0); /* no values to insert */
1678: if ((m+n) <= (PetscInt)(sizeof(buf)/sizeof(PetscInt))) {
1679: jdxm = buf; jdxn = buf+m;
1680: } else {
1681: PetscMalloc2(m,&bufm,n,&bufn);
1682: jdxm = bufm; jdxn = bufn;
1683: }
1684: for (i=0; i<m; i++) {
1685: for (j=0; j<3-sdim; j++) dxm++;
1686: tmp = *dxm++ - starts[0];
1687: for (j=0; j<sdim-1; j++) {
1688: if ((*dxm++ - starts[j+1]) < 0 || tmp < 0) tmp = -1;
1689: else tmp = tmp*dims[j] + *(dxm-1) - starts[j+1];
1690: }
1691: dxm++;
1692: jdxm[i] = tmp;
1693: }
1694: for (i=0; i<n; i++) {
1695: for (j=0; j<3-sdim; j++) dxn++;
1696: tmp = *dxn++ - starts[0];
1697: for (j=0; j<sdim-1; j++) {
1698: if ((*dxn++ - starts[j+1]) < 0 || tmp < 0) tmp = -1;
1699: else tmp = tmp*dims[j] + *(dxn-1) - starts[j+1];
1700: }
1701: dxn++;
1702: jdxn[i] = tmp;
1703: }
1704: MatSetValuesBlockedLocal(mat,m,jdxm,n,jdxn,v,addv);
1705: PetscFree2(bufm,bufn);
1706: return(0);
1707: }
1709: /*@
1710: MatSetStencil - Sets the grid information for setting values into a matrix via
1711: MatSetValuesStencil()
1713: Not Collective
1715: Input Parameters:
1716: + mat - the matrix
1717: . dim - dimension of the grid 1, 2, or 3
1718: . dims - number of grid points in x, y, and z direction, including ghost points on your processor
1719: . starts - starting point of ghost nodes on your processor in x, y, and z direction
1720: - dof - number of degrees of freedom per node
1723: Inspired by the structured grid interface to the HYPRE package
1724: (www.llnl.gov/CASC/hyper)
1726: For matrices generated with DMCreateMatrix() this routine is automatically called and so not needed by the
1727: user.
1729: Level: beginner
1731: .seealso: MatSetOption(), MatAssemblyBegin(), MatAssemblyEnd(), MatSetValuesBlocked(), MatSetValuesLocal()
1732: MatSetValues(), MatSetValuesBlockedStencil(), MatSetValuesStencil()
1733: @*/
1734: PetscErrorCode MatSetStencil(Mat mat,PetscInt dim,const PetscInt dims[],const PetscInt starts[],PetscInt dof)
1735: {
1736: PetscInt i;
1743: mat->stencil.dim = dim + (dof > 1);
1744: for (i=0; i<dim; i++) {
1745: mat->stencil.dims[i] = dims[dim-i-1]; /* copy the values in backwards */
1746: mat->stencil.starts[i] = starts[dim-i-1];
1747: }
1748: mat->stencil.dims[dim] = dof;
1749: mat->stencil.starts[dim] = 0;
1750: mat->stencil.noc = (PetscBool)(dof == 1);
1751: return(0);
1752: }
1754: /*@C
1755: MatSetValuesBlocked - Inserts or adds a block of values into a matrix.
1757: Not Collective
1759: Input Parameters:
1760: + mat - the matrix
1761: . v - a logically two-dimensional array of values
1762: . m, idxm - the number of block rows and their global block indices
1763: . n, idxn - the number of block columns and their global block indices
1764: - addv - either ADD_VALUES or INSERT_VALUES, where
1765: ADD_VALUES adds values to any existing entries, and
1766: INSERT_VALUES replaces existing entries with new values
1768: Notes:
1769: If you create the matrix yourself (that is not with a call to DMCreateMatrix()) then you MUST call
1770: MatXXXXSetPreallocation() or MatSetUp() before using this routine.
1772: The m and n count the NUMBER of blocks in the row direction and column direction,
1773: NOT the total number of rows/columns; for example, if the block size is 2 and
1774: you are passing in values for rows 2,3,4,5 then m would be 2 (not 4).
1775: The values in idxm would be 1 2; that is the first index for each block divided by
1776: the block size.
1778: Note that you must call MatSetBlockSize() when constructing this matrix (before
1779: preallocating it).
1781: By default the values, v, are row-oriented, so the layout of
1782: v is the same as for MatSetValues(). See MatSetOption() for other options.
1784: Calls to MatSetValuesBlocked() with the INSERT_VALUES and ADD_VALUES
1785: options cannot be mixed without intervening calls to the assembly
1786: routines.
1788: MatSetValuesBlocked() uses 0-based row and column numbers in Fortran
1789: as well as in C.
1791: Negative indices may be passed in idxm and idxn, these rows and columns are
1792: simply ignored. This allows easily inserting element stiffness matrices
1793: with homogeneous Dirchlet boundary conditions that you don't want represented
1794: in the matrix.
1796: Each time an entry is set within a sparse matrix via MatSetValues(),
1797: internal searching must be done to determine where to place the
1798: data in the matrix storage space. By instead inserting blocks of
1799: entries via MatSetValuesBlocked(), the overhead of matrix assembly is
1800: reduced.
1802: Example:
1803: $ Suppose m=n=2 and block size(bs) = 2 The array is
1804: $
1805: $ 1 2 | 3 4
1806: $ 5 6 | 7 8
1807: $ - - - | - - -
1808: $ 9 10 | 11 12
1809: $ 13 14 | 15 16
1810: $
1811: $ v[] should be passed in like
1812: $ v[] = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]
1813: $
1814: $ If you are not using row oriented storage of v (that is you called MatSetOption(mat,MAT_ROW_ORIENTED,PETSC_FALSE)) then
1815: $ v[] = [1,5,9,13,2,6,10,14,3,7,11,15,4,8,12,16]
1817: Level: intermediate
1819: .seealso: MatSetBlockSize(), MatSetOption(), MatAssemblyBegin(), MatAssemblyEnd(), MatSetValues(), MatSetValuesBlockedLocal()
1820: @*/
1821: PetscErrorCode MatSetValuesBlocked(Mat mat,PetscInt m,const PetscInt idxm[],PetscInt n,const PetscInt idxn[],const PetscScalar v[],InsertMode addv)
1822: {
1828: if (!m || !n) return(0); /* no values to insert */
1832: MatCheckPreallocated(mat,1);
1833: if (mat->insertmode == NOT_SET_VALUES) {
1834: mat->insertmode = addv;
1835: }
1836: #if defined(PETSC_USE_DEBUG)
1837: else if (mat->insertmode != addv) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Cannot mix add values and insert values");
1838: if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
1839: if (!mat->ops->setvaluesblocked && !mat->ops->setvalues) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
1840: #endif
1842: if (mat->assembled) {
1843: mat->was_assembled = PETSC_TRUE;
1844: mat->assembled = PETSC_FALSE;
1845: }
1846: PetscLogEventBegin(MAT_SetValues,mat,0,0,0);
1847: if (mat->ops->setvaluesblocked) {
1848: (*mat->ops->setvaluesblocked)(mat,m,idxm,n,idxn,v,addv);
1849: } else {
1850: PetscInt buf[8192],*bufr=0,*bufc=0,*iidxm,*iidxn;
1851: PetscInt i,j,bs,cbs;
1852: MatGetBlockSizes(mat,&bs,&cbs);
1853: if (m*bs+n*cbs <= (PetscInt)(sizeof(buf)/sizeof(PetscInt))) {
1854: iidxm = buf; iidxn = buf + m*bs;
1855: } else {
1856: PetscMalloc2(m*bs,&bufr,n*cbs,&bufc);
1857: iidxm = bufr; iidxn = bufc;
1858: }
1859: for (i=0; i<m; i++) {
1860: for (j=0; j<bs; j++) {
1861: iidxm[i*bs+j] = bs*idxm[i] + j;
1862: }
1863: }
1864: for (i=0; i<n; i++) {
1865: for (j=0; j<cbs; j++) {
1866: iidxn[i*cbs+j] = cbs*idxn[i] + j;
1867: }
1868: }
1869: MatSetValues(mat,m*bs,iidxm,n*cbs,iidxn,v,addv);
1870: PetscFree2(bufr,bufc);
1871: }
1872: PetscLogEventEnd(MAT_SetValues,mat,0,0,0);
1873: return(0);
1874: }
1876: /*@C
1877: MatGetValues - Gets a block of values from a matrix.
1879: Not Collective; currently only returns a local block
1881: Input Parameters:
1882: + mat - the matrix
1883: . v - a logically two-dimensional array for storing the values
1884: . m, idxm - the number of rows and their global indices
1885: - n, idxn - the number of columns and their global indices
1887: Notes:
1888: The user must allocate space (m*n PetscScalars) for the values, v.
1889: The values, v, are then returned in a row-oriented format,
1890: analogous to that used by default in MatSetValues().
1892: MatGetValues() uses 0-based row and column numbers in
1893: Fortran as well as in C.
1895: MatGetValues() requires that the matrix has been assembled
1896: with MatAssemblyBegin()/MatAssemblyEnd(). Thus, calls to
1897: MatSetValues() and MatGetValues() CANNOT be made in succession
1898: without intermediate matrix assembly.
1900: Negative row or column indices will be ignored and those locations in v[] will be
1901: left unchanged.
1903: Level: advanced
1905: .seealso: MatGetRow(), MatCreateSubMatrices(), MatSetValues()
1906: @*/
1907: PetscErrorCode MatGetValues(Mat mat,PetscInt m,const PetscInt idxm[],PetscInt n,const PetscInt idxn[],PetscScalar v[])
1908: {
1914: if (!m || !n) return(0);
1918: if (!mat->assembled) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
1919: if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
1920: if (!mat->ops->getvalues) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
1921: MatCheckPreallocated(mat,1);
1923: PetscLogEventBegin(MAT_GetValues,mat,0,0,0);
1924: (*mat->ops->getvalues)(mat,m,idxm,n,idxn,v);
1925: PetscLogEventEnd(MAT_GetValues,mat,0,0,0);
1926: return(0);
1927: }
1929: /*@C
1930: MatGetValuesLocal - retrieves values into certain locations of a matrix,
1931: using a local numbering of the nodes.
1933: Not Collective
1935: Input Parameters:
1936: + mat - the matrix
1937: . nrow, irow - number of rows and their local indices
1938: - ncol, icol - number of columns and their local indices
1940: Output Parameter:
1941: . y - a logically two-dimensional array of values
1943: Notes:
1944: If you create the matrix yourself (that is not with a call to DMCreateMatrix()) then you MUST call MatSetLocalToGlobalMapping() before using this routine
1946: Level: advanced
1948: Developer Notes:
1949: This is labelled with C so does not automatically generate Fortran stubs and interfaces
1950: because it requires multiple Fortran interfaces depending on which arguments are scalar or arrays.
1952: .seealso: MatAssemblyBegin(), MatAssemblyEnd(), MatSetValues(), MatSetLocalToGlobalMapping(),
1953: MatSetValuesLocal()
1954: @*/
1955: PetscErrorCode MatGetValuesLocal(Mat mat,PetscInt nrow,const PetscInt irow[],PetscInt ncol,const PetscInt icol[],PetscScalar y[])
1956: {
1962: MatCheckPreallocated(mat,1);
1963: if (!nrow || !ncol) return(0); /* no values to retrieve */
1966: #if defined(PETSC_USE_DEBUG)
1967: if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
1968: if (!mat->ops->getvalueslocal && !mat->ops->getvalues) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
1969: #endif
1970: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
1971: PetscLogEventBegin(MAT_GetValues,mat,0,0,0);
1972: if (mat->ops->getvalueslocal) {
1973: (*mat->ops->getvalueslocal)(mat,nrow,irow,ncol,icol,y);
1974: } else {
1975: PetscInt buf[8192],*bufr=0,*bufc=0,*irowm,*icolm;
1976: if ((nrow+ncol) <= (PetscInt)(sizeof(buf)/sizeof(PetscInt))) {
1977: irowm = buf; icolm = buf+nrow;
1978: } else {
1979: PetscMalloc2(nrow,&bufr,ncol,&bufc);
1980: irowm = bufr; icolm = bufc;
1981: }
1982: if (!mat->rmap->mapping) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"MatGetValuesLocal() cannot proceed without local-to-global row mapping (See MatSetLocalToGlobalMapping()).");
1983: if (!mat->cmap->mapping) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"MatGetValuesLocal() cannot proceed without local-to-global column mapping (See MatSetLocalToGlobalMapping()).");
1984: ISLocalToGlobalMappingApply(mat->rmap->mapping,nrow,irow,irowm);
1985: ISLocalToGlobalMappingApply(mat->cmap->mapping,ncol,icol,icolm);
1986: MatGetValues(mat,nrow,irowm,ncol,icolm,y);
1987: PetscFree2(bufr,bufc);
1988: }
1989: PetscLogEventEnd(MAT_GetValues,mat,0,0,0);
1990: return(0);
1991: }
1993: /*@
1994: MatSetValuesBatch - Adds (ADD_VALUES) many blocks of values into a matrix at once. The blocks must all be square and
1995: the same size. Currently, this can only be called once and creates the given matrix.
1997: Not Collective
1999: Input Parameters:
2000: + mat - the matrix
2001: . nb - the number of blocks
2002: . bs - the number of rows (and columns) in each block
2003: . rows - a concatenation of the rows for each block
2004: - v - a concatenation of logically two-dimensional arrays of values
2006: Notes:
2007: In the future, we will extend this routine to handle rectangular blocks, and to allow multiple calls for a given matrix.
2009: Level: advanced
2011: .seealso: MatSetOption(), MatAssemblyBegin(), MatAssemblyEnd(), MatSetValuesBlocked(), MatSetValuesLocal(),
2012: InsertMode, INSERT_VALUES, ADD_VALUES, MatSetValues()
2013: @*/
2014: PetscErrorCode MatSetValuesBatch(Mat mat, PetscInt nb, PetscInt bs, PetscInt rows[], const PetscScalar v[])
2015: {
2023: #if defined(PETSC_USE_DEBUG)
2024: if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2025: #endif
2027: PetscLogEventBegin(MAT_SetValuesBatch,mat,0,0,0);
2028: if (mat->ops->setvaluesbatch) {
2029: (*mat->ops->setvaluesbatch)(mat,nb,bs,rows,v);
2030: } else {
2031: PetscInt b;
2032: for (b = 0; b < nb; ++b) {
2033: MatSetValues(mat, bs, &rows[b*bs], bs, &rows[b*bs], &v[b*bs*bs], ADD_VALUES);
2034: }
2035: }
2036: PetscLogEventEnd(MAT_SetValuesBatch,mat,0,0,0);
2037: return(0);
2038: }
2040: /*@
2041: MatSetLocalToGlobalMapping - Sets a local-to-global numbering for use by
2042: the routine MatSetValuesLocal() to allow users to insert matrix entries
2043: using a local (per-processor) numbering.
2045: Not Collective
2047: Input Parameters:
2048: + x - the matrix
2049: . rmapping - row mapping created with ISLocalToGlobalMappingCreate() or ISLocalToGlobalMappingCreateIS()
2050: - cmapping - column mapping
2052: Level: intermediate
2055: .seealso: MatAssemblyBegin(), MatAssemblyEnd(), MatSetValues(), MatSetValuesLocal()
2056: @*/
2057: PetscErrorCode MatSetLocalToGlobalMapping(Mat x,ISLocalToGlobalMapping rmapping,ISLocalToGlobalMapping cmapping)
2058: {
2067: if (x->ops->setlocaltoglobalmapping) {
2068: (*x->ops->setlocaltoglobalmapping)(x,rmapping,cmapping);
2069: } else {
2070: PetscLayoutSetISLocalToGlobalMapping(x->rmap,rmapping);
2071: PetscLayoutSetISLocalToGlobalMapping(x->cmap,cmapping);
2072: }
2073: return(0);
2074: }
2077: /*@
2078: MatGetLocalToGlobalMapping - Gets the local-to-global numbering set by MatSetLocalToGlobalMapping()
2080: Not Collective
2082: Input Parameters:
2083: . A - the matrix
2085: Output Parameters:
2086: + rmapping - row mapping
2087: - cmapping - column mapping
2089: Level: advanced
2092: .seealso: MatSetValuesLocal()
2093: @*/
2094: PetscErrorCode MatGetLocalToGlobalMapping(Mat A,ISLocalToGlobalMapping *rmapping,ISLocalToGlobalMapping *cmapping)
2095: {
2101: if (rmapping) *rmapping = A->rmap->mapping;
2102: if (cmapping) *cmapping = A->cmap->mapping;
2103: return(0);
2104: }
2106: /*@
2107: MatGetLayouts - Gets the PetscLayout objects for rows and columns
2109: Not Collective
2111: Input Parameters:
2112: . A - the matrix
2114: Output Parameters:
2115: + rmap - row layout
2116: - cmap - column layout
2118: Level: advanced
2120: .seealso: MatCreateVecs(), MatGetLocalToGlobalMapping()
2121: @*/
2122: PetscErrorCode MatGetLayouts(Mat A,PetscLayout *rmap,PetscLayout *cmap)
2123: {
2129: if (rmap) *rmap = A->rmap;
2130: if (cmap) *cmap = A->cmap;
2131: return(0);
2132: }
2134: /*@C
2135: MatSetValuesLocal - Inserts or adds values into certain locations of a matrix,
2136: using a local numbering of the nodes.
2138: Not Collective
2140: Input Parameters:
2141: + mat - the matrix
2142: . nrow, irow - number of rows and their local indices
2143: . ncol, icol - number of columns and their local indices
2144: . y - a logically two-dimensional array of values
2145: - addv - either INSERT_VALUES or ADD_VALUES, where
2146: ADD_VALUES adds values to any existing entries, and
2147: INSERT_VALUES replaces existing entries with new values
2149: Notes:
2150: If you create the matrix yourself (that is not with a call to DMCreateMatrix()) then you MUST call MatXXXXSetPreallocation() or
2151: MatSetUp() before using this routine
2153: If you create the matrix yourself (that is not with a call to DMCreateMatrix()) then you MUST call MatSetLocalToGlobalMapping() before using this routine
2155: Calls to MatSetValuesLocal() with the INSERT_VALUES and ADD_VALUES
2156: options cannot be mixed without intervening calls to the assembly
2157: routines.
2159: These values may be cached, so MatAssemblyBegin() and MatAssemblyEnd()
2160: MUST be called after all calls to MatSetValuesLocal() have been completed.
2162: Level: intermediate
2164: Developer Notes:
2165: This is labeled with C so does not automatically generate Fortran stubs and interfaces
2166: because it requires multiple Fortran interfaces depending on which arguments are scalar or arrays.
2168: .seealso: MatAssemblyBegin(), MatAssemblyEnd(), MatSetValues(), MatSetLocalToGlobalMapping(),
2169: MatSetValueLocal(), MatGetValuesLocal()
2170: @*/
2171: PetscErrorCode MatSetValuesLocal(Mat mat,PetscInt nrow,const PetscInt irow[],PetscInt ncol,const PetscInt icol[],const PetscScalar y[],InsertMode addv)
2172: {
2178: MatCheckPreallocated(mat,1);
2179: if (!nrow || !ncol) return(0); /* no values to insert */
2182: if (mat->insertmode == NOT_SET_VALUES) {
2183: mat->insertmode = addv;
2184: }
2185: #if defined(PETSC_USE_DEBUG)
2186: else if (mat->insertmode != addv) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Cannot mix add values and insert values");
2187: if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2188: if (!mat->ops->setvalueslocal && !mat->ops->setvalues) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
2189: #endif
2191: if (mat->assembled) {
2192: mat->was_assembled = PETSC_TRUE;
2193: mat->assembled = PETSC_FALSE;
2194: }
2195: PetscLogEventBegin(MAT_SetValues,mat,0,0,0);
2196: if (mat->ops->setvalueslocal) {
2197: (*mat->ops->setvalueslocal)(mat,nrow,irow,ncol,icol,y,addv);
2198: } else {
2199: PetscInt buf[8192],*bufr=0,*bufc=0,*irowm,*icolm;
2200: if ((nrow+ncol) <= (PetscInt)(sizeof(buf)/sizeof(PetscInt))) {
2201: irowm = buf; icolm = buf+nrow;
2202: } else {
2203: PetscMalloc2(nrow,&bufr,ncol,&bufc);
2204: irowm = bufr; icolm = bufc;
2205: }
2206: if (!mat->rmap->mapping) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"MatSetValuesLocal() cannot proceed without local-to-global row mapping (See MatSetLocalToGlobalMapping()).");
2207: if (!mat->cmap->mapping) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"MatSetValuesLocal() cannot proceed without local-to-global column mapping (See MatSetLocalToGlobalMapping()).");
2208: ISLocalToGlobalMappingApply(mat->rmap->mapping,nrow,irow,irowm);
2209: ISLocalToGlobalMappingApply(mat->cmap->mapping,ncol,icol,icolm);
2210: MatSetValues(mat,nrow,irowm,ncol,icolm,y,addv);
2211: PetscFree2(bufr,bufc);
2212: }
2213: PetscLogEventEnd(MAT_SetValues,mat,0,0,0);
2214: return(0);
2215: }
2217: /*@C
2218: MatSetValuesBlockedLocal - Inserts or adds values into certain locations of a matrix,
2219: using a local ordering of the nodes a block at a time.
2221: Not Collective
2223: Input Parameters:
2224: + x - the matrix
2225: . nrow, irow - number of rows and their local indices
2226: . ncol, icol - number of columns and their local indices
2227: . y - a logically two-dimensional array of values
2228: - addv - either INSERT_VALUES or ADD_VALUES, where
2229: ADD_VALUES adds values to any existing entries, and
2230: INSERT_VALUES replaces existing entries with new values
2232: Notes:
2233: If you create the matrix yourself (that is not with a call to DMCreateMatrix()) then you MUST call MatXXXXSetPreallocation() or
2234: MatSetUp() before using this routine
2236: If you create the matrix yourself (that is not with a call to DMCreateMatrix()) then you MUST call MatSetBlockSize() and MatSetLocalToGlobalMapping()
2237: before using this routineBefore calling MatSetValuesLocal(), the user must first set the
2239: Calls to MatSetValuesBlockedLocal() with the INSERT_VALUES and ADD_VALUES
2240: options cannot be mixed without intervening calls to the assembly
2241: routines.
2243: These values may be cached, so MatAssemblyBegin() and MatAssemblyEnd()
2244: MUST be called after all calls to MatSetValuesBlockedLocal() have been completed.
2246: Level: intermediate
2248: Developer Notes:
2249: This is labeled with C so does not automatically generate Fortran stubs and interfaces
2250: because it requires multiple Fortran interfaces depending on which arguments are scalar or arrays.
2252: .seealso: MatSetBlockSize(), MatSetLocalToGlobalMapping(), MatAssemblyBegin(), MatAssemblyEnd(),
2253: MatSetValuesLocal(), MatSetValuesBlocked()
2254: @*/
2255: PetscErrorCode MatSetValuesBlockedLocal(Mat mat,PetscInt nrow,const PetscInt irow[],PetscInt ncol,const PetscInt icol[],const PetscScalar y[],InsertMode addv)
2256: {
2262: MatCheckPreallocated(mat,1);
2263: if (!nrow || !ncol) return(0); /* no values to insert */
2267: if (mat->insertmode == NOT_SET_VALUES) {
2268: mat->insertmode = addv;
2269: }
2270: #if defined(PETSC_USE_DEBUG)
2271: else if (mat->insertmode != addv) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Cannot mix add values and insert values");
2272: if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2273: if (!mat->ops->setvaluesblockedlocal && !mat->ops->setvaluesblocked && !mat->ops->setvalueslocal && !mat->ops->setvalues) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
2274: #endif
2276: if (mat->assembled) {
2277: mat->was_assembled = PETSC_TRUE;
2278: mat->assembled = PETSC_FALSE;
2279: }
2280: #if defined(PETSC_USE_DEBUG)
2281: /* Condition on the mapping existing, because MatSetValuesBlockedLocal_IS does not require it to be set. */
2282: if (mat->rmap->mapping) {
2283: PetscInt irbs, rbs;
2284: MatGetBlockSizes(mat, &rbs, NULL);
2285: ISLocalToGlobalMappingGetBlockSize(mat->rmap->mapping,&irbs);
2286: if (rbs != irbs) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Different row block sizes! mat %D, row l2g map %D",rbs,irbs);
2287: }
2288: if (mat->cmap->mapping) {
2289: PetscInt icbs, cbs;
2290: MatGetBlockSizes(mat,NULL,&cbs);
2291: ISLocalToGlobalMappingGetBlockSize(mat->cmap->mapping,&icbs);
2292: if (cbs != icbs) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Different col block sizes! mat %D, col l2g map %D",cbs,icbs);
2293: }
2294: #endif
2295: PetscLogEventBegin(MAT_SetValues,mat,0,0,0);
2296: if (mat->ops->setvaluesblockedlocal) {
2297: (*mat->ops->setvaluesblockedlocal)(mat,nrow,irow,ncol,icol,y,addv);
2298: } else {
2299: PetscInt buf[8192],*bufr=0,*bufc=0,*irowm,*icolm;
2300: if ((nrow+ncol) <= (PetscInt)(sizeof(buf)/sizeof(PetscInt))) {
2301: irowm = buf; icolm = buf + nrow;
2302: } else {
2303: PetscMalloc2(nrow,&bufr,ncol,&bufc);
2304: irowm = bufr; icolm = bufc;
2305: }
2306: ISLocalToGlobalMappingApplyBlock(mat->rmap->mapping,nrow,irow,irowm);
2307: ISLocalToGlobalMappingApplyBlock(mat->cmap->mapping,ncol,icol,icolm);
2308: MatSetValuesBlocked(mat,nrow,irowm,ncol,icolm,y,addv);
2309: PetscFree2(bufr,bufc);
2310: }
2311: PetscLogEventEnd(MAT_SetValues,mat,0,0,0);
2312: return(0);
2313: }
2315: /*@
2316: MatMultDiagonalBlock - Computes the matrix-vector product, y = Dx. Where D is defined by the inode or block structure of the diagonal
2318: Collective on Mat
2320: Input Parameters:
2321: + mat - the matrix
2322: - x - the vector to be multiplied
2324: Output Parameters:
2325: . y - the result
2327: Notes:
2328: The vectors x and y cannot be the same. I.e., one cannot
2329: call MatMult(A,y,y).
2331: Level: developer
2333: .seealso: MatMultTranspose(), MatMultAdd(), MatMultTransposeAdd()
2334: @*/
2335: PetscErrorCode MatMultDiagonalBlock(Mat mat,Vec x,Vec y)
2336: {
2345: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2346: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2347: if (x == y) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"x and y must be different vectors");
2348: MatCheckPreallocated(mat,1);
2350: if (!mat->ops->multdiagonalblock) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Matrix type %s does not have a multiply defined",((PetscObject)mat)->type_name);
2351: (*mat->ops->multdiagonalblock)(mat,x,y);
2352: PetscObjectStateIncrease((PetscObject)y);
2353: return(0);
2354: }
2356: /* --------------------------------------------------------*/
2357: /*@
2358: MatMult - Computes the matrix-vector product, y = Ax.
2360: Neighbor-wise Collective on Mat
2362: Input Parameters:
2363: + mat - the matrix
2364: - x - the vector to be multiplied
2366: Output Parameters:
2367: . y - the result
2369: Notes:
2370: The vectors x and y cannot be the same. I.e., one cannot
2371: call MatMult(A,y,y).
2373: Level: beginner
2375: .seealso: MatMultTranspose(), MatMultAdd(), MatMultTransposeAdd()
2376: @*/
2377: PetscErrorCode MatMult(Mat mat,Vec x,Vec y)
2378: {
2386: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2387: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2388: if (x == y) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"x and y must be different vectors");
2389: #if !defined(PETSC_HAVE_CONSTRAINTS)
2390: if (mat->cmap->N != x->map->N) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Mat mat,Vec x: global dim %D %D",mat->cmap->N,x->map->N);
2391: if (mat->rmap->N != y->map->N) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Mat mat,Vec y: global dim %D %D",mat->rmap->N,y->map->N);
2392: if (mat->rmap->n != y->map->n) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Mat mat,Vec y: local dim %D %D",mat->rmap->n,y->map->n);
2393: #endif
2394: VecSetErrorIfLocked(y,3);
2395: if (mat->erroriffailure) {VecValidValues(x,2,PETSC_TRUE);}
2396: MatCheckPreallocated(mat,1);
2398: VecLockReadPush(x);
2399: if (!mat->ops->mult) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Matrix type %s does not have a multiply defined",((PetscObject)mat)->type_name);
2400: PetscLogEventBegin(MAT_Mult,mat,x,y,0);
2401: (*mat->ops->mult)(mat,x,y);
2402: PetscLogEventEnd(MAT_Mult,mat,x,y,0);
2403: if (mat->erroriffailure) {VecValidValues(y,3,PETSC_FALSE);}
2404: VecLockReadPop(x);
2405: return(0);
2406: }
2408: /*@
2409: MatMultTranspose - Computes matrix transpose times a vector y = A^T * x.
2411: Neighbor-wise Collective on Mat
2413: Input Parameters:
2414: + mat - the matrix
2415: - x - the vector to be multiplied
2417: Output Parameters:
2418: . y - the result
2420: Notes:
2421: The vectors x and y cannot be the same. I.e., one cannot
2422: call MatMultTranspose(A,y,y).
2424: For complex numbers this does NOT compute the Hermitian (complex conjugate) transpose multiple,
2425: use MatMultHermitianTranspose()
2427: Level: beginner
2429: .seealso: MatMult(), MatMultAdd(), MatMultTransposeAdd(), MatMultHermitianTranspose(), MatTranspose()
2430: @*/
2431: PetscErrorCode MatMultTranspose(Mat mat,Vec x,Vec y)
2432: {
2441: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2442: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2443: if (x == y) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"x and y must be different vectors");
2444: #if !defined(PETSC_HAVE_CONSTRAINTS)
2445: if (mat->rmap->N != x->map->N) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Mat mat,Vec x: global dim %D %D",mat->rmap->N,x->map->N);
2446: if (mat->cmap->N != y->map->N) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Mat mat,Vec y: global dim %D %D",mat->cmap->N,y->map->N);
2447: #endif
2448: if (mat->erroriffailure) {VecValidValues(x,2,PETSC_TRUE);}
2449: MatCheckPreallocated(mat,1);
2451: if (!mat->ops->multtranspose) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Matrix type %s does not have a multiply transpose defined",((PetscObject)mat)->type_name);
2452: PetscLogEventBegin(MAT_MultTranspose,mat,x,y,0);
2453: VecLockReadPush(x);
2454: (*mat->ops->multtranspose)(mat,x,y);
2455: VecLockReadPop(x);
2456: PetscLogEventEnd(MAT_MultTranspose,mat,x,y,0);
2457: PetscObjectStateIncrease((PetscObject)y);
2458: if (mat->erroriffailure) {VecValidValues(y,3,PETSC_FALSE);}
2459: return(0);
2460: }
2462: /*@
2463: MatMultHermitianTranspose - Computes matrix Hermitian transpose times a vector.
2465: Neighbor-wise Collective on Mat
2467: Input Parameters:
2468: + mat - the matrix
2469: - x - the vector to be multilplied
2471: Output Parameters:
2472: . y - the result
2474: Notes:
2475: The vectors x and y cannot be the same. I.e., one cannot
2476: call MatMultHermitianTranspose(A,y,y).
2478: Also called the conjugate transpose, complex conjugate transpose, or adjoint.
2480: For real numbers MatMultTranspose() and MatMultHermitianTranspose() are identical.
2482: Level: beginner
2484: .seealso: MatMult(), MatMultAdd(), MatMultHermitianTransposeAdd(), MatMultTranspose()
2485: @*/
2486: PetscErrorCode MatMultHermitianTranspose(Mat mat,Vec x,Vec y)
2487: {
2489: Vec w;
2497: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2498: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2499: if (x == y) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"x and y must be different vectors");
2500: #if !defined(PETSC_HAVE_CONSTRAINTS)
2501: if (mat->rmap->N != x->map->N) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Mat mat,Vec x: global dim %D %D",mat->rmap->N,x->map->N);
2502: if (mat->cmap->N != y->map->N) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Mat mat,Vec y: global dim %D %D",mat->cmap->N,y->map->N);
2503: #endif
2504: MatCheckPreallocated(mat,1);
2506: PetscLogEventBegin(MAT_MultHermitianTranspose,mat,x,y,0);
2507: if (mat->ops->multhermitiantranspose) {
2508: VecLockReadPush(x);
2509: (*mat->ops->multhermitiantranspose)(mat,x,y);
2510: VecLockReadPop(x);
2511: } else {
2512: VecDuplicate(x,&w);
2513: VecCopy(x,w);
2514: VecConjugate(w);
2515: MatMultTranspose(mat,w,y);
2516: VecDestroy(&w);
2517: VecConjugate(y);
2518: }
2519: PetscLogEventEnd(MAT_MultHermitianTranspose,mat,x,y,0);
2520: PetscObjectStateIncrease((PetscObject)y);
2521: return(0);
2522: }
2524: /*@
2525: MatMultAdd - Computes v3 = v2 + A * v1.
2527: Neighbor-wise Collective on Mat
2529: Input Parameters:
2530: + mat - the matrix
2531: - v1, v2 - the vectors
2533: Output Parameters:
2534: . v3 - the result
2536: Notes:
2537: The vectors v1 and v3 cannot be the same. I.e., one cannot
2538: call MatMultAdd(A,v1,v2,v1).
2540: Level: beginner
2542: .seealso: MatMultTranspose(), MatMult(), MatMultTransposeAdd()
2543: @*/
2544: PetscErrorCode MatMultAdd(Mat mat,Vec v1,Vec v2,Vec v3)
2545: {
2555: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2556: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2557: if (mat->cmap->N != v1->map->N) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_SIZ,"Mat mat,Vec v1: global dim %D %D",mat->cmap->N,v1->map->N);
2558: /* if (mat->rmap->N != v2->map->N) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Mat mat,Vec v2: global dim %D %D",mat->rmap->N,v2->map->N);
2559: if (mat->rmap->N != v3->map->N) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Mat mat,Vec v3: global dim %D %D",mat->rmap->N,v3->map->N); */
2560: if (mat->rmap->n != v3->map->n) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Mat mat,Vec v3: local dim %D %D",mat->rmap->n,v3->map->n);
2561: if (mat->rmap->n != v2->map->n) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Mat mat,Vec v2: local dim %D %D",mat->rmap->n,v2->map->n);
2562: if (v1 == v3) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"v1 and v3 must be different vectors");
2563: MatCheckPreallocated(mat,1);
2565: if (!mat->ops->multadd) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"No MatMultAdd() for matrix type %s",((PetscObject)mat)->type_name);
2566: PetscLogEventBegin(MAT_MultAdd,mat,v1,v2,v3);
2567: VecLockReadPush(v1);
2568: (*mat->ops->multadd)(mat,v1,v2,v3);
2569: VecLockReadPop(v1);
2570: PetscLogEventEnd(MAT_MultAdd,mat,v1,v2,v3);
2571: PetscObjectStateIncrease((PetscObject)v3);
2572: return(0);
2573: }
2575: /*@
2576: MatMultTransposeAdd - Computes v3 = v2 + A' * v1.
2578: Neighbor-wise Collective on Mat
2580: Input Parameters:
2581: + mat - the matrix
2582: - v1, v2 - the vectors
2584: Output Parameters:
2585: . v3 - the result
2587: Notes:
2588: The vectors v1 and v3 cannot be the same. I.e., one cannot
2589: call MatMultTransposeAdd(A,v1,v2,v1).
2591: Level: beginner
2593: .seealso: MatMultTranspose(), MatMultAdd(), MatMult()
2594: @*/
2595: PetscErrorCode MatMultTransposeAdd(Mat mat,Vec v1,Vec v2,Vec v3)
2596: {
2606: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2607: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2608: if (!mat->ops->multtransposeadd) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
2609: if (v1 == v3) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"v1 and v3 must be different vectors");
2610: if (mat->rmap->N != v1->map->N) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_SIZ,"Mat mat,Vec v1: global dim %D %D",mat->rmap->N,v1->map->N);
2611: if (mat->cmap->N != v2->map->N) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_SIZ,"Mat mat,Vec v2: global dim %D %D",mat->cmap->N,v2->map->N);
2612: if (mat->cmap->N != v3->map->N) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_SIZ,"Mat mat,Vec v3: global dim %D %D",mat->cmap->N,v3->map->N);
2613: MatCheckPreallocated(mat,1);
2615: PetscLogEventBegin(MAT_MultTransposeAdd,mat,v1,v2,v3);
2616: VecLockReadPush(v1);
2617: (*mat->ops->multtransposeadd)(mat,v1,v2,v3);
2618: VecLockReadPop(v1);
2619: PetscLogEventEnd(MAT_MultTransposeAdd,mat,v1,v2,v3);
2620: PetscObjectStateIncrease((PetscObject)v3);
2621: return(0);
2622: }
2624: /*@
2625: MatMultHermitianTransposeAdd - Computes v3 = v2 + A^H * v1.
2627: Neighbor-wise Collective on Mat
2629: Input Parameters:
2630: + mat - the matrix
2631: - v1, v2 - the vectors
2633: Output Parameters:
2634: . v3 - the result
2636: Notes:
2637: The vectors v1 and v3 cannot be the same. I.e., one cannot
2638: call MatMultHermitianTransposeAdd(A,v1,v2,v1).
2640: Level: beginner
2642: .seealso: MatMultHermitianTranspose(), MatMultTranspose(), MatMultAdd(), MatMult()
2643: @*/
2644: PetscErrorCode MatMultHermitianTransposeAdd(Mat mat,Vec v1,Vec v2,Vec v3)
2645: {
2655: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2656: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2657: if (v1 == v3) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"v1 and v3 must be different vectors");
2658: if (mat->rmap->N != v1->map->N) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_SIZ,"Mat mat,Vec v1: global dim %D %D",mat->rmap->N,v1->map->N);
2659: if (mat->cmap->N != v2->map->N) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_SIZ,"Mat mat,Vec v2: global dim %D %D",mat->cmap->N,v2->map->N);
2660: if (mat->cmap->N != v3->map->N) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_SIZ,"Mat mat,Vec v3: global dim %D %D",mat->cmap->N,v3->map->N);
2661: MatCheckPreallocated(mat,1);
2663: PetscLogEventBegin(MAT_MultHermitianTransposeAdd,mat,v1,v2,v3);
2664: VecLockReadPush(v1);
2665: if (mat->ops->multhermitiantransposeadd) {
2666: (*mat->ops->multhermitiantransposeadd)(mat,v1,v2,v3);
2667: } else {
2668: Vec w,z;
2669: VecDuplicate(v1,&w);
2670: VecCopy(v1,w);
2671: VecConjugate(w);
2672: VecDuplicate(v3,&z);
2673: MatMultTranspose(mat,w,z);
2674: VecDestroy(&w);
2675: VecConjugate(z);
2676: if (v2 != v3) {
2677: VecWAXPY(v3,1.0,v2,z);
2678: } else {
2679: VecAXPY(v3,1.0,z);
2680: }
2681: VecDestroy(&z);
2682: }
2683: VecLockReadPop(v1);
2684: PetscLogEventEnd(MAT_MultHermitianTransposeAdd,mat,v1,v2,v3);
2685: PetscObjectStateIncrease((PetscObject)v3);
2686: return(0);
2687: }
2689: /*@
2690: MatMultConstrained - The inner multiplication routine for a
2691: constrained matrix P^T A P.
2693: Neighbor-wise Collective on Mat
2695: Input Parameters:
2696: + mat - the matrix
2697: - x - the vector to be multilplied
2699: Output Parameters:
2700: . y - the result
2702: Notes:
2703: The vectors x and y cannot be the same. I.e., one cannot
2704: call MatMult(A,y,y).
2706: Level: beginner
2708: .seealso: MatMult(), MatMultTranspose(), MatMultAdd(), MatMultTransposeAdd()
2709: @*/
2710: PetscErrorCode MatMultConstrained(Mat mat,Vec x,Vec y)
2711: {
2718: if (!mat->assembled) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2719: if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2720: if (x == y) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"x and y must be different vectors");
2721: if (mat->cmap->N != x->map->N) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Mat mat,Vec x: global dim %D %D",mat->cmap->N,x->map->N);
2722: if (mat->rmap->N != y->map->N) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Mat mat,Vec y: global dim %D %D",mat->rmap->N,y->map->N);
2723: if (mat->rmap->n != y->map->n) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Mat mat,Vec y: local dim %D %D",mat->rmap->n,y->map->n);
2725: PetscLogEventBegin(MAT_MultConstrained,mat,x,y,0);
2726: VecLockReadPush(x);
2727: (*mat->ops->multconstrained)(mat,x,y);
2728: VecLockReadPop(x);
2729: PetscLogEventEnd(MAT_MultConstrained,mat,x,y,0);
2730: PetscObjectStateIncrease((PetscObject)y);
2731: return(0);
2732: }
2734: /*@
2735: MatMultTransposeConstrained - The inner multiplication routine for a
2736: constrained matrix P^T A^T P.
2738: Neighbor-wise Collective on Mat
2740: Input Parameters:
2741: + mat - the matrix
2742: - x - the vector to be multilplied
2744: Output Parameters:
2745: . y - the result
2747: Notes:
2748: The vectors x and y cannot be the same. I.e., one cannot
2749: call MatMult(A,y,y).
2751: Level: beginner
2753: .seealso: MatMult(), MatMultTranspose(), MatMultAdd(), MatMultTransposeAdd()
2754: @*/
2755: PetscErrorCode MatMultTransposeConstrained(Mat mat,Vec x,Vec y)
2756: {
2763: if (!mat->assembled) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2764: if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2765: if (x == y) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"x and y must be different vectors");
2766: if (mat->rmap->N != x->map->N) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Mat mat,Vec x: global dim %D %D",mat->cmap->N,x->map->N);
2767: if (mat->cmap->N != y->map->N) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Mat mat,Vec y: global dim %D %D",mat->rmap->N,y->map->N);
2769: PetscLogEventBegin(MAT_MultConstrained,mat,x,y,0);
2770: (*mat->ops->multtransposeconstrained)(mat,x,y);
2771: PetscLogEventEnd(MAT_MultConstrained,mat,x,y,0);
2772: PetscObjectStateIncrease((PetscObject)y);
2773: return(0);
2774: }
2776: /*@C
2777: MatGetFactorType - gets the type of factorization it is
2779: Not Collective
2781: Input Parameters:
2782: . mat - the matrix
2784: Output Parameters:
2785: . t - the type, one of MAT_FACTOR_NONE, MAT_FACTOR_LU, MAT_FACTOR_CHOLESKY, MAT_FACTOR_ILU, MAT_FACTOR_ICC,MAT_FACTOR_ILUDT
2787: Level: intermediate
2789: .seealso: MatFactorType, MatGetFactor(), MatSetFactorType()
2790: @*/
2791: PetscErrorCode MatGetFactorType(Mat mat,MatFactorType *t)
2792: {
2797: *t = mat->factortype;
2798: return(0);
2799: }
2801: /*@C
2802: MatSetFactorType - sets the type of factorization it is
2804: Logically Collective on Mat
2806: Input Parameters:
2807: + mat - the matrix
2808: - t - the type, one of MAT_FACTOR_NONE, MAT_FACTOR_LU, MAT_FACTOR_CHOLESKY, MAT_FACTOR_ILU, MAT_FACTOR_ICC,MAT_FACTOR_ILUDT
2810: Level: intermediate
2812: .seealso: MatFactorType, MatGetFactor(), MatGetFactorType()
2813: @*/
2814: PetscErrorCode MatSetFactorType(Mat mat, MatFactorType t)
2815: {
2819: mat->factortype = t;
2820: return(0);
2821: }
2823: /* ------------------------------------------------------------*/
2824: /*@C
2825: MatGetInfo - Returns information about matrix storage (number of
2826: nonzeros, memory, etc.).
2828: Collective on Mat if MAT_GLOBAL_MAX or MAT_GLOBAL_SUM is used as the flag
2830: Input Parameters:
2831: . mat - the matrix
2833: Output Parameters:
2834: + flag - flag indicating the type of parameters to be returned
2835: (MAT_LOCAL - local matrix, MAT_GLOBAL_MAX - maximum over all processors,
2836: MAT_GLOBAL_SUM - sum over all processors)
2837: - info - matrix information context
2839: Notes:
2840: The MatInfo context contains a variety of matrix data, including
2841: number of nonzeros allocated and used, number of mallocs during
2842: matrix assembly, etc. Additional information for factored matrices
2843: is provided (such as the fill ratio, number of mallocs during
2844: factorization, etc.). Much of this info is printed to PETSC_STDOUT
2845: when using the runtime options
2846: $ -info -mat_view ::ascii_info
2848: Example for C/C++ Users:
2849: See the file ${PETSC_DIR}/include/petscmat.h for a complete list of
2850: data within the MatInfo context. For example,
2851: .vb
2852: MatInfo info;
2853: Mat A;
2854: double mal, nz_a, nz_u;
2856: MatGetInfo(A,MAT_LOCAL,&info);
2857: mal = info.mallocs;
2858: nz_a = info.nz_allocated;
2859: .ve
2861: Example for Fortran Users:
2862: Fortran users should declare info as a double precision
2863: array of dimension MAT_INFO_SIZE, and then extract the parameters
2864: of interest. See the file ${PETSC_DIR}/include/petsc/finclude/petscmat.h
2865: a complete list of parameter names.
2866: .vb
2867: double precision info(MAT_INFO_SIZE)
2868: double precision mal, nz_a
2869: Mat A
2870: integer ierr
2872: call MatGetInfo(A,MAT_LOCAL,info,ierr)
2873: mal = info(MAT_INFO_MALLOCS)
2874: nz_a = info(MAT_INFO_NZ_ALLOCATED)
2875: .ve
2877: Level: intermediate
2879: Developer Note: fortran interface is not autogenerated as the f90
2880: interface defintion cannot be generated correctly [due to MatInfo]
2882: .seealso: MatStashGetInfo()
2884: @*/
2885: PetscErrorCode MatGetInfo(Mat mat,MatInfoType flag,MatInfo *info)
2886: {
2893: if (!mat->ops->getinfo) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
2894: MatCheckPreallocated(mat,1);
2895: (*mat->ops->getinfo)(mat,flag,info);
2896: return(0);
2897: }
2899: /*
2900: This is used by external packages where it is not easy to get the info from the actual
2901: matrix factorization.
2902: */
2903: PetscErrorCode MatGetInfo_External(Mat A,MatInfoType flag,MatInfo *info)
2904: {
2908: PetscMemzero(info,sizeof(MatInfo));
2909: return(0);
2910: }
2912: /* ----------------------------------------------------------*/
2914: /*@C
2915: MatLUFactor - Performs in-place LU factorization of matrix.
2917: Collective on Mat
2919: Input Parameters:
2920: + mat - the matrix
2921: . row - row permutation
2922: . col - column permutation
2923: - info - options for factorization, includes
2924: $ fill - expected fill as ratio of original fill.
2925: $ dtcol - pivot tolerance (0 no pivot, 1 full column pivoting)
2926: $ Run with the option -info to determine an optimal value to use
2928: Notes:
2929: Most users should employ the simplified KSP interface for linear solvers
2930: instead of working directly with matrix algebra routines such as this.
2931: See, e.g., KSPCreate().
2933: This changes the state of the matrix to a factored matrix; it cannot be used
2934: for example with MatSetValues() unless one first calls MatSetUnfactored().
2936: Level: developer
2938: .seealso: MatLUFactorSymbolic(), MatLUFactorNumeric(), MatCholeskyFactor(),
2939: MatGetOrdering(), MatSetUnfactored(), MatFactorInfo, MatGetFactor()
2941: Developer Note: fortran interface is not autogenerated as the f90
2942: interface defintion cannot be generated correctly [due to MatFactorInfo]
2944: @*/
2945: PetscErrorCode MatLUFactor(Mat mat,IS row,IS col,const MatFactorInfo *info)
2946: {
2948: MatFactorInfo tinfo;
2956: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2957: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2958: if (!mat->ops->lufactor) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
2959: MatCheckPreallocated(mat,1);
2960: if (!info) {
2961: MatFactorInfoInitialize(&tinfo);
2962: info = &tinfo;
2963: }
2965: PetscLogEventBegin(MAT_LUFactor,mat,row,col,0);
2966: (*mat->ops->lufactor)(mat,row,col,info);
2967: PetscLogEventEnd(MAT_LUFactor,mat,row,col,0);
2968: PetscObjectStateIncrease((PetscObject)mat);
2969: return(0);
2970: }
2972: /*@C
2973: MatILUFactor - Performs in-place ILU factorization of matrix.
2975: Collective on Mat
2977: Input Parameters:
2978: + mat - the matrix
2979: . row - row permutation
2980: . col - column permutation
2981: - info - structure containing
2982: $ levels - number of levels of fill.
2983: $ expected fill - as ratio of original fill.
2984: $ 1 or 0 - indicating force fill on diagonal (improves robustness for matrices
2985: missing diagonal entries)
2987: Notes:
2988: Probably really in-place only when level of fill is zero, otherwise allocates
2989: new space to store factored matrix and deletes previous memory.
2991: Most users should employ the simplified KSP interface for linear solvers
2992: instead of working directly with matrix algebra routines such as this.
2993: See, e.g., KSPCreate().
2995: Level: developer
2997: .seealso: MatILUFactorSymbolic(), MatLUFactorNumeric(), MatCholeskyFactor(), MatFactorInfo
2999: Developer Note: fortran interface is not autogenerated as the f90
3000: interface defintion cannot be generated correctly [due to MatFactorInfo]
3002: @*/
3003: PetscErrorCode MatILUFactor(Mat mat,IS row,IS col,const MatFactorInfo *info)
3004: {
3013: if (mat->rmap->N != mat->cmap->N) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONG,"matrix must be square");
3014: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
3015: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
3016: if (!mat->ops->ilufactor) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
3017: MatCheckPreallocated(mat,1);
3019: PetscLogEventBegin(MAT_ILUFactor,mat,row,col,0);
3020: (*mat->ops->ilufactor)(mat,row,col,info);
3021: PetscLogEventEnd(MAT_ILUFactor,mat,row,col,0);
3022: PetscObjectStateIncrease((PetscObject)mat);
3023: return(0);
3024: }
3026: /*@C
3027: MatLUFactorSymbolic - Performs symbolic LU factorization of matrix.
3028: Call this routine before calling MatLUFactorNumeric().
3030: Collective on Mat
3032: Input Parameters:
3033: + fact - the factor matrix obtained with MatGetFactor()
3034: . mat - the matrix
3035: . row, col - row and column permutations
3036: - info - options for factorization, includes
3037: $ fill - expected fill as ratio of original fill.
3038: $ dtcol - pivot tolerance (0 no pivot, 1 full column pivoting)
3039: $ Run with the option -info to determine an optimal value to use
3042: Notes:
3043: See Users-Manual: ch_mat for additional information about choosing the fill factor for better efficiency.
3045: Most users should employ the simplified KSP interface for linear solvers
3046: instead of working directly with matrix algebra routines such as this.
3047: See, e.g., KSPCreate().
3049: Level: developer
3051: .seealso: MatLUFactor(), MatLUFactorNumeric(), MatCholeskyFactor(), MatFactorInfo, MatFactorInfoInitialize()
3053: Developer Note: fortran interface is not autogenerated as the f90
3054: interface defintion cannot be generated correctly [due to MatFactorInfo]
3056: @*/
3057: PetscErrorCode MatLUFactorSymbolic(Mat fact,Mat mat,IS row,IS col,const MatFactorInfo *info)
3058: {
3060: MatFactorInfo tinfo;
3069: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
3070: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
3071: if (!(fact)->ops->lufactorsymbolic) {
3072: MatSolverType spackage;
3073: MatFactorGetSolverType(fact,&spackage);
3074: SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Matrix type %s symbolic LU using solver package %s",((PetscObject)mat)->type_name,spackage);
3075: }
3076: MatCheckPreallocated(mat,2);
3077: if (!info) {
3078: MatFactorInfoInitialize(&tinfo);
3079: info = &tinfo;
3080: }
3082: PetscLogEventBegin(MAT_LUFactorSymbolic,mat,row,col,0);
3083: (fact->ops->lufactorsymbolic)(fact,mat,row,col,info);
3084: PetscLogEventEnd(MAT_LUFactorSymbolic,mat,row,col,0);
3085: PetscObjectStateIncrease((PetscObject)fact);
3086: return(0);
3087: }
3089: /*@C
3090: MatLUFactorNumeric - Performs numeric LU factorization of a matrix.
3091: Call this routine after first calling MatLUFactorSymbolic().
3093: Collective on Mat
3095: Input Parameters:
3096: + fact - the factor matrix obtained with MatGetFactor()
3097: . mat - the matrix
3098: - info - options for factorization
3100: Notes:
3101: See MatLUFactor() for in-place factorization. See
3102: MatCholeskyFactorNumeric() for the symmetric, positive definite case.
3104: Most users should employ the simplified KSP interface for linear solvers
3105: instead of working directly with matrix algebra routines such as this.
3106: See, e.g., KSPCreate().
3108: Level: developer
3110: .seealso: MatLUFactorSymbolic(), MatLUFactor(), MatCholeskyFactor()
3112: Developer Note: fortran interface is not autogenerated as the f90
3113: interface defintion cannot be generated correctly [due to MatFactorInfo]
3115: @*/
3116: PetscErrorCode MatLUFactorNumeric(Mat fact,Mat mat,const MatFactorInfo *info)
3117: {
3118: MatFactorInfo tinfo;
3126: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
3127: if (mat->rmap->N != (fact)->rmap->N || mat->cmap->N != (fact)->cmap->N) SETERRQ4(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_SIZ,"Mat mat,Mat fact: global dimensions are different %D should = %D %D should = %D",mat->rmap->N,(fact)->rmap->N,mat->cmap->N,(fact)->cmap->N);
3129: if (!(fact)->ops->lufactornumeric) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s numeric LU",((PetscObject)mat)->type_name);
3130: MatCheckPreallocated(mat,2);
3131: if (!info) {
3132: MatFactorInfoInitialize(&tinfo);
3133: info = &tinfo;
3134: }
3136: PetscLogEventBegin(MAT_LUFactorNumeric,mat,fact,0,0);
3137: (fact->ops->lufactornumeric)(fact,mat,info);
3138: PetscLogEventEnd(MAT_LUFactorNumeric,mat,fact,0,0);
3139: MatViewFromOptions(fact,NULL,"-mat_factor_view");
3140: PetscObjectStateIncrease((PetscObject)fact);
3141: return(0);
3142: }
3144: /*@C
3145: MatCholeskyFactor - Performs in-place Cholesky factorization of a
3146: symmetric matrix.
3148: Collective on Mat
3150: Input Parameters:
3151: + mat - the matrix
3152: . perm - row and column permutations
3153: - f - expected fill as ratio of original fill
3155: Notes:
3156: See MatLUFactor() for the nonsymmetric case. See also
3157: MatCholeskyFactorSymbolic(), and MatCholeskyFactorNumeric().
3159: Most users should employ the simplified KSP interface for linear solvers
3160: instead of working directly with matrix algebra routines such as this.
3161: See, e.g., KSPCreate().
3163: Level: developer
3165: .seealso: MatLUFactor(), MatCholeskyFactorSymbolic(), MatCholeskyFactorNumeric()
3166: MatGetOrdering()
3168: Developer Note: fortran interface is not autogenerated as the f90
3169: interface defintion cannot be generated correctly [due to MatFactorInfo]
3171: @*/
3172: PetscErrorCode MatCholeskyFactor(Mat mat,IS perm,const MatFactorInfo *info)
3173: {
3175: MatFactorInfo tinfo;
3182: if (mat->rmap->N != mat->cmap->N) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONG,"Matrix must be square");
3183: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
3184: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
3185: if (!mat->ops->choleskyfactor) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"In-place factorization for Mat type %s is not supported, try out-of-place factorization. See MatCholeskyFactorSymbolic/Numeric",((PetscObject)mat)->type_name);
3186: MatCheckPreallocated(mat,1);
3187: if (!info) {
3188: MatFactorInfoInitialize(&tinfo);
3189: info = &tinfo;
3190: }
3192: PetscLogEventBegin(MAT_CholeskyFactor,mat,perm,0,0);
3193: (*mat->ops->choleskyfactor)(mat,perm,info);
3194: PetscLogEventEnd(MAT_CholeskyFactor,mat,perm,0,0);
3195: PetscObjectStateIncrease((PetscObject)mat);
3196: return(0);
3197: }
3199: /*@C
3200: MatCholeskyFactorSymbolic - Performs symbolic Cholesky factorization
3201: of a symmetric matrix.
3203: Collective on Mat
3205: Input Parameters:
3206: + fact - the factor matrix obtained with MatGetFactor()
3207: . mat - the matrix
3208: . perm - row and column permutations
3209: - info - options for factorization, includes
3210: $ fill - expected fill as ratio of original fill.
3211: $ dtcol - pivot tolerance (0 no pivot, 1 full column pivoting)
3212: $ Run with the option -info to determine an optimal value to use
3214: Notes:
3215: See MatLUFactorSymbolic() for the nonsymmetric case. See also
3216: MatCholeskyFactor() and MatCholeskyFactorNumeric().
3218: Most users should employ the simplified KSP interface for linear solvers
3219: instead of working directly with matrix algebra routines such as this.
3220: See, e.g., KSPCreate().
3222: Level: developer
3224: .seealso: MatLUFactorSymbolic(), MatCholeskyFactor(), MatCholeskyFactorNumeric()
3225: MatGetOrdering()
3227: Developer Note: fortran interface is not autogenerated as the f90
3228: interface defintion cannot be generated correctly [due to MatFactorInfo]
3230: @*/
3231: PetscErrorCode MatCholeskyFactorSymbolic(Mat fact,Mat mat,IS perm,const MatFactorInfo *info)
3232: {
3234: MatFactorInfo tinfo;
3242: if (mat->rmap->N != mat->cmap->N) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONG,"Matrix must be square");
3243: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
3244: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
3245: if (!(fact)->ops->choleskyfactorsymbolic) {
3246: MatSolverType spackage;
3247: MatFactorGetSolverType(fact,&spackage);
3248: SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s symbolic factor Cholesky using solver package %s",((PetscObject)mat)->type_name,spackage);
3249: }
3250: MatCheckPreallocated(mat,2);
3251: if (!info) {
3252: MatFactorInfoInitialize(&tinfo);
3253: info = &tinfo;
3254: }
3256: PetscLogEventBegin(MAT_CholeskyFactorSymbolic,mat,perm,0,0);
3257: (fact->ops->choleskyfactorsymbolic)(fact,mat,perm,info);
3258: PetscLogEventEnd(MAT_CholeskyFactorSymbolic,mat,perm,0,0);
3259: PetscObjectStateIncrease((PetscObject)fact);
3260: return(0);
3261: }
3263: /*@C
3264: MatCholeskyFactorNumeric - Performs numeric Cholesky factorization
3265: of a symmetric matrix. Call this routine after first calling
3266: MatCholeskyFactorSymbolic().
3268: Collective on Mat
3270: Input Parameters:
3271: + fact - the factor matrix obtained with MatGetFactor()
3272: . mat - the initial matrix
3273: . info - options for factorization
3274: - fact - the symbolic factor of mat
3277: Notes:
3278: Most users should employ the simplified KSP interface for linear solvers
3279: instead of working directly with matrix algebra routines such as this.
3280: See, e.g., KSPCreate().
3282: Level: developer
3284: .seealso: MatCholeskyFactorSymbolic(), MatCholeskyFactor(), MatLUFactorNumeric()
3286: Developer Note: fortran interface is not autogenerated as the f90
3287: interface defintion cannot be generated correctly [due to MatFactorInfo]
3289: @*/
3290: PetscErrorCode MatCholeskyFactorNumeric(Mat fact,Mat mat,const MatFactorInfo *info)
3291: {
3292: MatFactorInfo tinfo;
3300: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
3301: if (!(fact)->ops->choleskyfactornumeric) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s numeric factor Cholesky",((PetscObject)mat)->type_name);
3302: if (mat->rmap->N != (fact)->rmap->N || mat->cmap->N != (fact)->cmap->N) SETERRQ4(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_SIZ,"Mat mat,Mat fact: global dim %D should = %D %D should = %D",mat->rmap->N,(fact)->rmap->N,mat->cmap->N,(fact)->cmap->N);
3303: MatCheckPreallocated(mat,2);
3304: if (!info) {
3305: MatFactorInfoInitialize(&tinfo);
3306: info = &tinfo;
3307: }
3309: PetscLogEventBegin(MAT_CholeskyFactorNumeric,mat,fact,0,0);
3310: (fact->ops->choleskyfactornumeric)(fact,mat,info);
3311: PetscLogEventEnd(MAT_CholeskyFactorNumeric,mat,fact,0,0);
3312: MatViewFromOptions(fact,NULL,"-mat_factor_view");
3313: PetscObjectStateIncrease((PetscObject)fact);
3314: return(0);
3315: }
3317: /* ----------------------------------------------------------------*/
3318: /*@
3319: MatSolve - Solves A x = b, given a factored matrix.
3321: Neighbor-wise Collective on Mat
3323: Input Parameters:
3324: + mat - the factored matrix
3325: - b - the right-hand-side vector
3327: Output Parameter:
3328: . x - the result vector
3330: Notes:
3331: The vectors b and x cannot be the same. I.e., one cannot
3332: call MatSolve(A,x,x).
3334: Notes:
3335: Most users should employ the simplified KSP interface for linear solvers
3336: instead of working directly with matrix algebra routines such as this.
3337: See, e.g., KSPCreate().
3339: Level: developer
3341: .seealso: MatSolveAdd(), MatSolveTranspose(), MatSolveTransposeAdd()
3342: @*/
3343: PetscErrorCode MatSolve(Mat mat,Vec b,Vec x)
3344: {
3354: if (x == b) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"x and b must be different vectors");
3355: if (mat->cmap->N != x->map->N) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_SIZ,"Mat mat,Vec x: global dim %D %D",mat->cmap->N,x->map->N);
3356: if (mat->rmap->N != b->map->N) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_SIZ,"Mat mat,Vec b: global dim %D %D",mat->rmap->N,b->map->N);
3357: if (mat->rmap->n != b->map->n) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Mat mat,Vec b: local dim %D %D",mat->rmap->n,b->map->n);
3358: if (!mat->rmap->N && !mat->cmap->N) return(0);
3359: MatCheckPreallocated(mat,1);
3361: PetscLogEventBegin(MAT_Solve,mat,b,x,0);
3362: if (mat->factorerrortype) {
3363: PetscInfo1(mat,"MatFactorError %D\n",mat->factorerrortype);
3364: VecSetInf(x);
3365: } else {
3366: if (!mat->ops->solve) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
3367: (*mat->ops->solve)(mat,b,x);
3368: }
3369: PetscLogEventEnd(MAT_Solve,mat,b,x,0);
3370: PetscObjectStateIncrease((PetscObject)x);
3371: return(0);
3372: }
3374: static PetscErrorCode MatMatSolve_Basic(Mat A,Mat B,Mat X,PetscBool trans)
3375: {
3377: Vec b,x;
3378: PetscInt m,N,i;
3379: PetscScalar *bb,*xx;
3382: MatDenseGetArrayRead(B,(const PetscScalar**)&bb);
3383: MatDenseGetArray(X,&xx);
3384: MatGetLocalSize(B,&m,NULL); /* number local rows */
3385: MatGetSize(B,NULL,&N); /* total columns in dense matrix */
3386: MatCreateVecs(A,&x,&b);
3387: for (i=0; i<N; i++) {
3388: VecPlaceArray(b,bb + i*m);
3389: VecPlaceArray(x,xx + i*m);
3390: if (trans) {
3391: MatSolveTranspose(A,b,x);
3392: } else {
3393: MatSolve(A,b,x);
3394: }
3395: VecResetArray(x);
3396: VecResetArray(b);
3397: }
3398: VecDestroy(&b);
3399: VecDestroy(&x);
3400: MatDenseRestoreArrayRead(B,(const PetscScalar**)&bb);
3401: MatDenseRestoreArray(X,&xx);
3402: return(0);
3403: }
3405: /*@
3406: MatMatSolve - Solves A X = B, given a factored matrix.
3408: Neighbor-wise Collective on Mat
3410: Input Parameters:
3411: + A - the factored matrix
3412: - B - the right-hand-side matrix MATDENSE (or sparse -- when using MUMPS)
3414: Output Parameter:
3415: . X - the result matrix (dense matrix)
3417: Notes:
3418: If B is a MATDENSE matrix then one can call MatMatSolve(A,B,B);
3419: otherwise, B and X cannot be the same.
3421: Notes:
3422: Most users should usually employ the simplified KSP interface for linear solvers
3423: instead of working directly with matrix algebra routines such as this.
3424: See, e.g., KSPCreate(). However KSP can only solve for one vector (column of X)
3425: at a time.
3427: Level: developer
3429: .seealso: MatMatSolveTranspose(), MatLUFactor(), MatCholeskyFactor()
3430: @*/
3431: PetscErrorCode MatMatSolve(Mat A,Mat B,Mat X)
3432: {
3442: if (A->cmap->N != X->rmap->N) SETERRQ2(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Mat A,Mat X: global dim %D %D",A->cmap->N,X->rmap->N);
3443: if (A->rmap->N != B->rmap->N) SETERRQ2(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Mat A,Mat B: global dim %D %D",A->rmap->N,B->rmap->N);
3444: if (X->cmap->N != B->cmap->N) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Solution matrix must have same number of columns as rhs matrix");
3445: if (!A->rmap->N && !A->cmap->N) return(0);
3446: if (!A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
3447: MatCheckPreallocated(A,1);
3449: PetscLogEventBegin(MAT_MatSolve,A,B,X,0);
3450: if (!A->ops->matsolve) {
3451: PetscInfo1(A,"Mat type %s using basic MatMatSolve\n",((PetscObject)A)->type_name);
3452: MatMatSolve_Basic(A,B,X,PETSC_FALSE);
3453: } else {
3454: (*A->ops->matsolve)(A,B,X);
3455: }
3456: PetscLogEventEnd(MAT_MatSolve,A,B,X,0);
3457: PetscObjectStateIncrease((PetscObject)X);
3458: return(0);
3459: }
3461: /*@
3462: MatMatSolveTranspose - Solves A^T X = B, given a factored matrix.
3464: Neighbor-wise Collective on Mat
3466: Input Parameters:
3467: + A - the factored matrix
3468: - B - the right-hand-side matrix (dense matrix)
3470: Output Parameter:
3471: . X - the result matrix (dense matrix)
3473: Notes:
3474: The matrices B and X cannot be the same. I.e., one cannot
3475: call MatMatSolveTranspose(A,X,X).
3477: Notes:
3478: Most users should usually employ the simplified KSP interface for linear solvers
3479: instead of working directly with matrix algebra routines such as this.
3480: See, e.g., KSPCreate(). However KSP can only solve for one vector (column of X)
3481: at a time.
3483: When using SuperLU_Dist or MUMPS as a parallel solver, PETSc will use their functionality to solve multiple right hand sides simultaneously.
3485: Level: developer
3487: .seealso: MatMatSolve(), MatLUFactor(), MatCholeskyFactor()
3488: @*/
3489: PetscErrorCode MatMatSolveTranspose(Mat A,Mat B,Mat X)
3490: {
3500: if (X == B) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_IDN,"X and B must be different matrices");
3501: if (A->cmap->N != X->rmap->N) SETERRQ2(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Mat A,Mat X: global dim %D %D",A->cmap->N,X->rmap->N);
3502: if (A->rmap->N != B->rmap->N) SETERRQ2(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Mat A,Mat B: global dim %D %D",A->rmap->N,B->rmap->N);
3503: if (A->rmap->n != B->rmap->n) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Mat A,Mat B: local dim %D %D",A->rmap->n,B->rmap->n);
3504: if (X->cmap->N < B->cmap->N) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Solution matrix must have same number of columns as rhs matrix");
3505: if (!A->rmap->N && !A->cmap->N) return(0);
3506: if (!A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
3507: MatCheckPreallocated(A,1);
3509: PetscLogEventBegin(MAT_MatSolve,A,B,X,0);
3510: if (!A->ops->matsolvetranspose) {
3511: PetscInfo1(A,"Mat type %s using basic MatMatSolveTranspose\n",((PetscObject)A)->type_name);
3512: MatMatSolve_Basic(A,B,X,PETSC_TRUE);
3513: } else {
3514: (*A->ops->matsolvetranspose)(A,B,X);
3515: }
3516: PetscLogEventEnd(MAT_MatSolve,A,B,X,0);
3517: PetscObjectStateIncrease((PetscObject)X);
3518: return(0);
3519: }
3521: /*@
3522: MatMatTransposeSolve - Solves A X = B^T, given a factored matrix.
3524: Neighbor-wise Collective on Mat
3526: Input Parameters:
3527: + A - the factored matrix
3528: - Bt - the transpose of right-hand-side matrix
3530: Output Parameter:
3531: . X - the result matrix (dense matrix)
3533: Notes:
3534: Most users should usually employ the simplified KSP interface for linear solvers
3535: instead of working directly with matrix algebra routines such as this.
3536: See, e.g., KSPCreate(). However KSP can only solve for one vector (column of X)
3537: at a time.
3539: For MUMPS, it only supports centralized sparse compressed column format on the host processor for right hand side matrix. User must create B^T in sparse compressed row format on the host processor and call MatMatTransposeSolve() to implement MUMPS' MatMatSolve().
3541: Level: developer
3543: .seealso: MatMatSolve(), MatMatSolveTranspose(), MatLUFactor(), MatCholeskyFactor()
3544: @*/
3545: PetscErrorCode MatMatTransposeSolve(Mat A,Mat Bt,Mat X)
3546: {
3557: if (X == Bt) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_IDN,"X and B must be different matrices");
3558: if (A->cmap->N != X->rmap->N) SETERRQ2(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Mat A,Mat X: global dim %D %D",A->cmap->N,X->rmap->N);
3559: if (A->rmap->N != Bt->cmap->N) SETERRQ2(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Mat A,Mat Bt: global dim %D %D",A->rmap->N,Bt->cmap->N);
3560: if (X->cmap->N < Bt->rmap->N) SETERRQ(PetscObjectComm((PetscObject)X),PETSC_ERR_ARG_SIZ,"Solution matrix must have same number of columns as row number of the rhs matrix");
3561: if (!A->rmap->N && !A->cmap->N) return(0);
3562: if (!A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
3563: MatCheckPreallocated(A,1);
3565: if (!A->ops->mattransposesolve) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Mat type %s",((PetscObject)A)->type_name);
3566: PetscLogEventBegin(MAT_MatTrSolve,A,Bt,X,0);
3567: (*A->ops->mattransposesolve)(A,Bt,X);
3568: PetscLogEventEnd(MAT_MatTrSolve,A,Bt,X,0);
3569: PetscObjectStateIncrease((PetscObject)X);
3570: return(0);
3571: }
3573: /*@
3574: MatForwardSolve - Solves L x = b, given a factored matrix, A = LU, or
3575: U^T*D^(1/2) x = b, given a factored symmetric matrix, A = U^T*D*U,
3577: Neighbor-wise Collective on Mat
3579: Input Parameters:
3580: + mat - the factored matrix
3581: - b - the right-hand-side vector
3583: Output Parameter:
3584: . x - the result vector
3586: Notes:
3587: MatSolve() should be used for most applications, as it performs
3588: a forward solve followed by a backward solve.
3590: The vectors b and x cannot be the same, i.e., one cannot
3591: call MatForwardSolve(A,x,x).
3593: For matrix in seqsbaij format with block size larger than 1,
3594: the diagonal blocks are not implemented as D = D^(1/2) * D^(1/2) yet.
3595: MatForwardSolve() solves U^T*D y = b, and
3596: MatBackwardSolve() solves U x = y.
3597: Thus they do not provide a symmetric preconditioner.
3599: Most users should employ the simplified KSP interface for linear solvers
3600: instead of working directly with matrix algebra routines such as this.
3601: See, e.g., KSPCreate().
3603: Level: developer
3605: .seealso: MatSolve(), MatBackwardSolve()
3606: @*/
3607: PetscErrorCode MatForwardSolve(Mat mat,Vec b,Vec x)
3608: {
3618: if (x == b) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"x and b must be different vectors");
3619: if (mat->cmap->N != x->map->N) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_SIZ,"Mat mat,Vec x: global dim %D %D",mat->cmap->N,x->map->N);
3620: if (mat->rmap->N != b->map->N) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_SIZ,"Mat mat,Vec b: global dim %D %D",mat->rmap->N,b->map->N);
3621: if (mat->rmap->n != b->map->n) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Mat mat,Vec b: local dim %D %D",mat->rmap->n,b->map->n);
3622: if (!mat->rmap->N && !mat->cmap->N) return(0);
3623: MatCheckPreallocated(mat,1);
3625: if (!mat->ops->forwardsolve) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
3626: PetscLogEventBegin(MAT_ForwardSolve,mat,b,x,0);
3627: (*mat->ops->forwardsolve)(mat,b,x);
3628: PetscLogEventEnd(MAT_ForwardSolve,mat,b,x,0);
3629: PetscObjectStateIncrease((PetscObject)x);
3630: return(0);
3631: }
3633: /*@
3634: MatBackwardSolve - Solves U x = b, given a factored matrix, A = LU.
3635: D^(1/2) U x = b, given a factored symmetric matrix, A = U^T*D*U,
3637: Neighbor-wise Collective on Mat
3639: Input Parameters:
3640: + mat - the factored matrix
3641: - b - the right-hand-side vector
3643: Output Parameter:
3644: . x - the result vector
3646: Notes:
3647: MatSolve() should be used for most applications, as it performs
3648: a forward solve followed by a backward solve.
3650: The vectors b and x cannot be the same. I.e., one cannot
3651: call MatBackwardSolve(A,x,x).
3653: For matrix in seqsbaij format with block size larger than 1,
3654: the diagonal blocks are not implemented as D = D^(1/2) * D^(1/2) yet.
3655: MatForwardSolve() solves U^T*D y = b, and
3656: MatBackwardSolve() solves U x = y.
3657: Thus they do not provide a symmetric preconditioner.
3659: Most users should employ the simplified KSP interface for linear solvers
3660: instead of working directly with matrix algebra routines such as this.
3661: See, e.g., KSPCreate().
3663: Level: developer
3665: .seealso: MatSolve(), MatForwardSolve()
3666: @*/
3667: PetscErrorCode MatBackwardSolve(Mat mat,Vec b,Vec x)
3668: {
3678: if (x == b) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"x and b must be different vectors");
3679: if (mat->cmap->N != x->map->N) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_SIZ,"Mat mat,Vec x: global dim %D %D",mat->cmap->N,x->map->N);
3680: if (mat->rmap->N != b->map->N) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_SIZ,"Mat mat,Vec b: global dim %D %D",mat->rmap->N,b->map->N);
3681: if (mat->rmap->n != b->map->n) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Mat mat,Vec b: local dim %D %D",mat->rmap->n,b->map->n);
3682: if (!mat->rmap->N && !mat->cmap->N) return(0);
3683: MatCheckPreallocated(mat,1);
3685: if (!mat->ops->backwardsolve) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
3686: PetscLogEventBegin(MAT_BackwardSolve,mat,b,x,0);
3687: (*mat->ops->backwardsolve)(mat,b,x);
3688: PetscLogEventEnd(MAT_BackwardSolve,mat,b,x,0);
3689: PetscObjectStateIncrease((PetscObject)x);
3690: return(0);
3691: }
3693: /*@
3694: MatSolveAdd - Computes x = y + inv(A)*b, given a factored matrix.
3696: Neighbor-wise Collective on Mat
3698: Input Parameters:
3699: + mat - the factored matrix
3700: . b - the right-hand-side vector
3701: - y - the vector to be added to
3703: Output Parameter:
3704: . x - the result vector
3706: Notes:
3707: The vectors b and x cannot be the same. I.e., one cannot
3708: call MatSolveAdd(A,x,y,x).
3710: Most users should employ the simplified KSP interface for linear solvers
3711: instead of working directly with matrix algebra routines such as this.
3712: See, e.g., KSPCreate().
3714: Level: developer
3716: .seealso: MatSolve(), MatSolveTranspose(), MatSolveTransposeAdd()
3717: @*/
3718: PetscErrorCode MatSolveAdd(Mat mat,Vec b,Vec y,Vec x)
3719: {
3720: PetscScalar one = 1.0;
3721: Vec tmp;
3733: if (x == b) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"x and b must be different vectors");
3734: if (mat->cmap->N != x->map->N) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_SIZ,"Mat mat,Vec x: global dim %D %D",mat->cmap->N,x->map->N);
3735: if (mat->rmap->N != b->map->N) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_SIZ,"Mat mat,Vec b: global dim %D %D",mat->rmap->N,b->map->N);
3736: if (mat->rmap->N != y->map->N) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_SIZ,"Mat mat,Vec y: global dim %D %D",mat->rmap->N,y->map->N);
3737: if (mat->rmap->n != b->map->n) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Mat mat,Vec b: local dim %D %D",mat->rmap->n,b->map->n);
3738: if (x->map->n != y->map->n) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Vec x,Vec y: local dim %D %D",x->map->n,y->map->n);
3739: if (!mat->rmap->N && !mat->cmap->N) return(0);
3740: MatCheckPreallocated(mat,1);
3742: PetscLogEventBegin(MAT_SolveAdd,mat,b,x,y);
3743: if (mat->factorerrortype) {
3744: PetscInfo1(mat,"MatFactorError %D\n",mat->factorerrortype);
3745: VecSetInf(x);
3746: } else if (mat->ops->solveadd) {
3747: (*mat->ops->solveadd)(mat,b,y,x);
3748: } else {
3749: /* do the solve then the add manually */
3750: if (x != y) {
3751: MatSolve(mat,b,x);
3752: VecAXPY(x,one,y);
3753: } else {
3754: VecDuplicate(x,&tmp);
3755: PetscLogObjectParent((PetscObject)mat,(PetscObject)tmp);
3756: VecCopy(x,tmp);
3757: MatSolve(mat,b,x);
3758: VecAXPY(x,one,tmp);
3759: VecDestroy(&tmp);
3760: }
3761: }
3762: PetscLogEventEnd(MAT_SolveAdd,mat,b,x,y);
3763: PetscObjectStateIncrease((PetscObject)x);
3764: return(0);
3765: }
3767: /*@
3768: MatSolveTranspose - Solves A' x = b, given a factored matrix.
3770: Neighbor-wise Collective on Mat
3772: Input Parameters:
3773: + mat - the factored matrix
3774: - b - the right-hand-side vector
3776: Output Parameter:
3777: . x - the result vector
3779: Notes:
3780: The vectors b and x cannot be the same. I.e., one cannot
3781: call MatSolveTranspose(A,x,x).
3783: Most users should employ the simplified KSP interface for linear solvers
3784: instead of working directly with matrix algebra routines such as this.
3785: See, e.g., KSPCreate().
3787: Level: developer
3789: .seealso: MatSolve(), MatSolveAdd(), MatSolveTransposeAdd()
3790: @*/
3791: PetscErrorCode MatSolveTranspose(Mat mat,Vec b,Vec x)
3792: {
3802: if (x == b) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"x and b must be different vectors");
3803: if (mat->rmap->N != x->map->N) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_SIZ,"Mat mat,Vec x: global dim %D %D",mat->rmap->N,x->map->N);
3804: if (mat->cmap->N != b->map->N) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_SIZ,"Mat mat,Vec b: global dim %D %D",mat->cmap->N,b->map->N);
3805: if (!mat->rmap->N && !mat->cmap->N) return(0);
3806: MatCheckPreallocated(mat,1);
3807: PetscLogEventBegin(MAT_SolveTranspose,mat,b,x,0);
3808: if (mat->factorerrortype) {
3809: PetscInfo1(mat,"MatFactorError %D\n",mat->factorerrortype);
3810: VecSetInf(x);
3811: } else {
3812: if (!mat->ops->solvetranspose) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Matrix type %s",((PetscObject)mat)->type_name);
3813: (*mat->ops->solvetranspose)(mat,b,x);
3814: }
3815: PetscLogEventEnd(MAT_SolveTranspose,mat,b,x,0);
3816: PetscObjectStateIncrease((PetscObject)x);
3817: return(0);
3818: }
3820: /*@
3821: MatSolveTransposeAdd - Computes x = y + inv(Transpose(A)) b, given a
3822: factored matrix.
3824: Neighbor-wise Collective on Mat
3826: Input Parameters:
3827: + mat - the factored matrix
3828: . b - the right-hand-side vector
3829: - y - the vector to be added to
3831: Output Parameter:
3832: . x - the result vector
3834: Notes:
3835: The vectors b and x cannot be the same. I.e., one cannot
3836: call MatSolveTransposeAdd(A,x,y,x).
3838: Most users should employ the simplified KSP interface for linear solvers
3839: instead of working directly with matrix algebra routines such as this.
3840: See, e.g., KSPCreate().
3842: Level: developer
3844: .seealso: MatSolve(), MatSolveAdd(), MatSolveTranspose()
3845: @*/
3846: PetscErrorCode MatSolveTransposeAdd(Mat mat,Vec b,Vec y,Vec x)
3847: {
3848: PetscScalar one = 1.0;
3850: Vec tmp;
3861: if (x == b) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"x and b must be different vectors");
3862: if (mat->rmap->N != x->map->N) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_SIZ,"Mat mat,Vec x: global dim %D %D",mat->rmap->N,x->map->N);
3863: if (mat->cmap->N != b->map->N) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_SIZ,"Mat mat,Vec b: global dim %D %D",mat->cmap->N,b->map->N);
3864: if (mat->cmap->N != y->map->N) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_SIZ,"Mat mat,Vec y: global dim %D %D",mat->cmap->N,y->map->N);
3865: if (x->map->n != y->map->n) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Vec x,Vec y: local dim %D %D",x->map->n,y->map->n);
3866: if (!mat->rmap->N && !mat->cmap->N) return(0);
3867: MatCheckPreallocated(mat,1);
3869: PetscLogEventBegin(MAT_SolveTransposeAdd,mat,b,x,y);
3870: if (mat->factorerrortype) {
3871: PetscInfo1(mat,"MatFactorError %D\n",mat->factorerrortype);
3872: VecSetInf(x);
3873: } else if (mat->ops->solvetransposeadd){
3874: (*mat->ops->solvetransposeadd)(mat,b,y,x);
3875: } else {
3876: /* do the solve then the add manually */
3877: if (x != y) {
3878: MatSolveTranspose(mat,b,x);
3879: VecAXPY(x,one,y);
3880: } else {
3881: VecDuplicate(x,&tmp);
3882: PetscLogObjectParent((PetscObject)mat,(PetscObject)tmp);
3883: VecCopy(x,tmp);
3884: MatSolveTranspose(mat,b,x);
3885: VecAXPY(x,one,tmp);
3886: VecDestroy(&tmp);
3887: }
3888: }
3889: PetscLogEventEnd(MAT_SolveTransposeAdd,mat,b,x,y);
3890: PetscObjectStateIncrease((PetscObject)x);
3891: return(0);
3892: }
3893: /* ----------------------------------------------------------------*/
3895: /*@
3896: MatSOR - Computes relaxation (SOR, Gauss-Seidel) sweeps.
3898: Neighbor-wise Collective on Mat
3900: Input Parameters:
3901: + mat - the matrix
3902: . b - the right hand side
3903: . omega - the relaxation factor
3904: . flag - flag indicating the type of SOR (see below)
3905: . shift - diagonal shift
3906: . its - the number of iterations
3907: - lits - the number of local iterations
3909: Output Parameters:
3910: . x - the solution (can contain an initial guess, use option SOR_ZERO_INITIAL_GUESS to indicate no guess)
3912: SOR Flags:
3913: + SOR_FORWARD_SWEEP - forward SOR
3914: . SOR_BACKWARD_SWEEP - backward SOR
3915: . SOR_SYMMETRIC_SWEEP - SSOR (symmetric SOR)
3916: . SOR_LOCAL_FORWARD_SWEEP - local forward SOR
3917: . SOR_LOCAL_BACKWARD_SWEEP - local forward SOR
3918: . SOR_LOCAL_SYMMETRIC_SWEEP - local SSOR
3919: . SOR_APPLY_UPPER, SOR_APPLY_LOWER - applies
3920: upper/lower triangular part of matrix to
3921: vector (with omega)
3922: - SOR_ZERO_INITIAL_GUESS - zero initial guess
3924: Notes:
3925: SOR_LOCAL_FORWARD_SWEEP, SOR_LOCAL_BACKWARD_SWEEP, and
3926: SOR_LOCAL_SYMMETRIC_SWEEP perform separate independent smoothings
3927: on each processor.
3929: Application programmers will not generally use MatSOR() directly,
3930: but instead will employ the KSP/PC interface.
3932: Notes:
3933: for BAIJ, SBAIJ, and AIJ matrices with Inodes this does a block SOR smoothing, otherwise it does a pointwise smoothing
3935: Notes for Advanced Users:
3936: The flags are implemented as bitwise inclusive or operations.
3937: For example, use (SOR_ZERO_INITIAL_GUESS | SOR_SYMMETRIC_SWEEP)
3938: to specify a zero initial guess for SSOR.
3940: Most users should employ the simplified KSP interface for linear solvers
3941: instead of working directly with matrix algebra routines such as this.
3942: See, e.g., KSPCreate().
3944: Vectors x and b CANNOT be the same
3946: Developer Note: We should add block SOR support for AIJ matrices with block size set to great than one and no inodes
3948: Level: developer
3950: @*/
3951: PetscErrorCode MatSOR(Mat mat,Vec b,PetscReal omega,MatSORType flag,PetscReal shift,PetscInt its,PetscInt lits,Vec x)
3952: {
3962: if (!mat->ops->sor) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
3963: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
3964: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
3965: if (mat->cmap->N != x->map->N) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_SIZ,"Mat mat,Vec x: global dim %D %D",mat->cmap->N,x->map->N);
3966: if (mat->rmap->N != b->map->N) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_SIZ,"Mat mat,Vec b: global dim %D %D",mat->rmap->N,b->map->N);
3967: if (mat->rmap->n != b->map->n) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Mat mat,Vec b: local dim %D %D",mat->rmap->n,b->map->n);
3968: if (its <= 0) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONG,"Relaxation requires global its %D positive",its);
3969: if (lits <= 0) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONG,"Relaxation requires local its %D positive",lits);
3970: if (b == x) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_IDN,"b and x vector cannot be the same");
3972: MatCheckPreallocated(mat,1);
3973: PetscLogEventBegin(MAT_SOR,mat,b,x,0);
3974: ierr =(*mat->ops->sor)(mat,b,omega,flag,shift,its,lits,x);
3975: PetscLogEventEnd(MAT_SOR,mat,b,x,0);
3976: PetscObjectStateIncrease((PetscObject)x);
3977: return(0);
3978: }
3980: /*
3981: Default matrix copy routine.
3982: */
3983: PetscErrorCode MatCopy_Basic(Mat A,Mat B,MatStructure str)
3984: {
3985: PetscErrorCode ierr;
3986: PetscInt i,rstart = 0,rend = 0,nz;
3987: const PetscInt *cwork;
3988: const PetscScalar *vwork;
3991: if (B->assembled) {
3992: MatZeroEntries(B);
3993: }
3994: if (str == SAME_NONZERO_PATTERN) {
3995: MatGetOwnershipRange(A,&rstart,&rend);
3996: for (i=rstart; i<rend; i++) {
3997: MatGetRow(A,i,&nz,&cwork,&vwork);
3998: MatSetValues(B,1,&i,nz,cwork,vwork,INSERT_VALUES);
3999: MatRestoreRow(A,i,&nz,&cwork,&vwork);
4000: }
4001: } else {
4002: MatAYPX(B,0.0,A,str);
4003: }
4004: MatAssemblyBegin(B,MAT_FINAL_ASSEMBLY);
4005: MatAssemblyEnd(B,MAT_FINAL_ASSEMBLY);
4006: return(0);
4007: }
4009: /*@
4010: MatCopy - Copies a matrix to another matrix.
4012: Collective on Mat
4014: Input Parameters:
4015: + A - the matrix
4016: - str - SAME_NONZERO_PATTERN or DIFFERENT_NONZERO_PATTERN
4018: Output Parameter:
4019: . B - where the copy is put
4021: Notes:
4022: If you use SAME_NONZERO_PATTERN then the two matrices had better have the
4023: same nonzero pattern or the routine will crash.
4025: MatCopy() copies the matrix entries of a matrix to another existing
4026: matrix (after first zeroing the second matrix). A related routine is
4027: MatConvert(), which first creates a new matrix and then copies the data.
4029: Level: intermediate
4031: .seealso: MatConvert(), MatDuplicate()
4033: @*/
4034: PetscErrorCode MatCopy(Mat A,Mat B,MatStructure str)
4035: {
4037: PetscInt i;
4045: MatCheckPreallocated(B,2);
4046: if (!A->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
4047: if (A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
4048: if (A->rmap->N != B->rmap->N || A->cmap->N != B->cmap->N) SETERRQ4(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Mat A,Mat B: global dim (%D,%D) (%D,%D)",A->rmap->N,B->rmap->N,A->cmap->N,B->cmap->N);
4049: MatCheckPreallocated(A,1);
4050: if (A == B) return(0);
4052: PetscLogEventBegin(MAT_Copy,A,B,0,0);
4053: if (A->ops->copy) {
4054: (*A->ops->copy)(A,B,str);
4055: } else { /* generic conversion */
4056: MatCopy_Basic(A,B,str);
4057: }
4059: B->stencil.dim = A->stencil.dim;
4060: B->stencil.noc = A->stencil.noc;
4061: for (i=0; i<=A->stencil.dim; i++) {
4062: B->stencil.dims[i] = A->stencil.dims[i];
4063: B->stencil.starts[i] = A->stencil.starts[i];
4064: }
4066: PetscLogEventEnd(MAT_Copy,A,B,0,0);
4067: PetscObjectStateIncrease((PetscObject)B);
4068: return(0);
4069: }
4071: /*@C
4072: MatConvert - Converts a matrix to another matrix, either of the same
4073: or different type.
4075: Collective on Mat
4077: Input Parameters:
4078: + mat - the matrix
4079: . newtype - new matrix type. Use MATSAME to create a new matrix of the
4080: same type as the original matrix.
4081: - reuse - denotes if the destination matrix is to be created or reused.
4082: 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
4083: 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).
4085: Output Parameter:
4086: . M - pointer to place new matrix
4088: Notes:
4089: MatConvert() first creates a new matrix and then copies the data from
4090: the first matrix. A related routine is MatCopy(), which copies the matrix
4091: entries of one matrix to another already existing matrix context.
4093: Cannot be used to convert a sequential matrix to parallel or parallel to sequential,
4094: the MPI communicator of the generated matrix is always the same as the communicator
4095: of the input matrix.
4097: Level: intermediate
4099: .seealso: MatCopy(), MatDuplicate()
4100: @*/
4101: PetscErrorCode MatConvert(Mat mat, MatType newtype,MatReuse reuse,Mat *M)
4102: {
4104: PetscBool sametype,issame,flg,issymmetric,ishermitian;
4105: char convname[256],mtype[256];
4106: Mat B;
4112: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
4113: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
4114: MatCheckPreallocated(mat,1);
4116: PetscOptionsGetString(((PetscObject)mat)->options,((PetscObject)mat)->prefix,"-matconvert_type",mtype,256,&flg);
4117: if (flg) newtype = mtype;
4119: PetscObjectTypeCompare((PetscObject)mat,newtype,&sametype);
4120: PetscStrcmp(newtype,"same",&issame);
4121: if ((reuse == MAT_INPLACE_MATRIX) && (mat != *M)) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"MAT_INPLACE_MATRIX requires same input and output matrix");
4122: if ((reuse == MAT_REUSE_MATRIX) && (mat == *M)) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"MAT_REUSE_MATRIX means reuse matrix in final argument, perhaps you mean MAT_INPLACE_MATRIX");
4124: if ((reuse == MAT_INPLACE_MATRIX) && (issame || sametype)) {
4125: PetscInfo3(mat,"Early return for inplace %s %d %d\n",((PetscObject)mat)->type_name,sametype,issame);
4126: return(0);
4127: }
4129: /* Cache Mat options because some converter use MatHeaderReplace */
4130: issymmetric = mat->symmetric;
4131: ishermitian = mat->hermitian;
4133: if ((sametype || issame) && (reuse==MAT_INITIAL_MATRIX) && mat->ops->duplicate) {
4134: PetscInfo3(mat,"Calling duplicate for initial matrix %s %d %d\n",((PetscObject)mat)->type_name,sametype,issame);
4135: (*mat->ops->duplicate)(mat,MAT_COPY_VALUES,M);
4136: } else {
4137: PetscErrorCode (*conv)(Mat, MatType,MatReuse,Mat*)=NULL;
4138: const char *prefix[3] = {"seq","mpi",""};
4139: PetscInt i;
4140: /*
4141: Order of precedence:
4142: 0) See if newtype is a superclass of the current matrix.
4143: 1) See if a specialized converter is known to the current matrix.
4144: 2) See if a specialized converter is known to the desired matrix class.
4145: 3) See if a good general converter is registered for the desired class
4146: (as of 6/27/03 only MATMPIADJ falls into this category).
4147: 4) See if a good general converter is known for the current matrix.
4148: 5) Use a really basic converter.
4149: */
4151: /* 0) See if newtype is a superclass of the current matrix.
4152: i.e mat is mpiaij and newtype is aij */
4153: for (i=0; i<2; i++) {
4154: PetscStrncpy(convname,prefix[i],sizeof(convname));
4155: PetscStrlcat(convname,newtype,sizeof(convname));
4156: PetscStrcmp(convname,((PetscObject)mat)->type_name,&flg);
4157: PetscInfo3(mat,"Check superclass %s %s -> %d\n",convname,((PetscObject)mat)->type_name,flg);
4158: if (flg) {
4159: if (reuse == MAT_INPLACE_MATRIX) {
4160: return(0);
4161: } else if (reuse == MAT_INITIAL_MATRIX && mat->ops->duplicate) {
4162: (*mat->ops->duplicate)(mat,MAT_COPY_VALUES,M);
4163: return(0);
4164: } else if (reuse == MAT_REUSE_MATRIX && mat->ops->copy) {
4165: MatCopy(mat,*M,SAME_NONZERO_PATTERN);
4166: return(0);
4167: }
4168: }
4169: }
4170: /* 1) See if a specialized converter is known to the current matrix and the desired class */
4171: for (i=0; i<3; i++) {
4172: PetscStrncpy(convname,"MatConvert_",sizeof(convname));
4173: PetscStrlcat(convname,((PetscObject)mat)->type_name,sizeof(convname));
4174: PetscStrlcat(convname,"_",sizeof(convname));
4175: PetscStrlcat(convname,prefix[i],sizeof(convname));
4176: PetscStrlcat(convname,issame ? ((PetscObject)mat)->type_name : newtype,sizeof(convname));
4177: PetscStrlcat(convname,"_C",sizeof(convname));
4178: PetscObjectQueryFunction((PetscObject)mat,convname,&conv);
4179: PetscInfo3(mat,"Check specialized (1) %s (%s) -> %d\n",convname,((PetscObject)mat)->type_name,!!conv);
4180: if (conv) goto foundconv;
4181: }
4183: /* 2) See if a specialized converter is known to the desired matrix class. */
4184: MatCreate(PetscObjectComm((PetscObject)mat),&B);
4185: MatSetSizes(B,mat->rmap->n,mat->cmap->n,mat->rmap->N,mat->cmap->N);
4186: MatSetType(B,newtype);
4187: for (i=0; i<3; i++) {
4188: PetscStrncpy(convname,"MatConvert_",sizeof(convname));
4189: PetscStrlcat(convname,((PetscObject)mat)->type_name,sizeof(convname));
4190: PetscStrlcat(convname,"_",sizeof(convname));
4191: PetscStrlcat(convname,prefix[i],sizeof(convname));
4192: PetscStrlcat(convname,newtype,sizeof(convname));
4193: PetscStrlcat(convname,"_C",sizeof(convname));
4194: PetscObjectQueryFunction((PetscObject)B,convname,&conv);
4195: PetscInfo3(mat,"Check specialized (2) %s (%s) -> %d\n",convname,((PetscObject)B)->type_name,!!conv);
4196: if (conv) {
4197: MatDestroy(&B);
4198: goto foundconv;
4199: }
4200: }
4202: /* 3) See if a good general converter is registered for the desired class */
4203: conv = B->ops->convertfrom;
4204: PetscInfo2(mat,"Check convertfrom (%s) -> %d\n",((PetscObject)B)->type_name,!!conv);
4205: MatDestroy(&B);
4206: if (conv) goto foundconv;
4208: /* 4) See if a good general converter is known for the current matrix */
4209: if (mat->ops->convert) conv = mat->ops->convert;
4211: PetscInfo2(mat,"Check general convert (%s) -> %d\n",((PetscObject)mat)->type_name,!!conv);
4212: if (conv) goto foundconv;
4214: /* 5) Use a really basic converter. */
4215: PetscInfo(mat,"Using MatConvert_Basic\n");
4216: conv = MatConvert_Basic;
4218: foundconv:
4219: PetscLogEventBegin(MAT_Convert,mat,0,0,0);
4220: (*conv)(mat,newtype,reuse,M);
4221: if (mat->rmap->mapping && mat->cmap->mapping && !(*M)->rmap->mapping && !(*M)->cmap->mapping) {
4222: /* the block sizes must be same if the mappings are copied over */
4223: (*M)->rmap->bs = mat->rmap->bs;
4224: (*M)->cmap->bs = mat->cmap->bs;
4225: PetscObjectReference((PetscObject)mat->rmap->mapping);
4226: PetscObjectReference((PetscObject)mat->cmap->mapping);
4227: (*M)->rmap->mapping = mat->rmap->mapping;
4228: (*M)->cmap->mapping = mat->cmap->mapping;
4229: }
4230: (*M)->stencil.dim = mat->stencil.dim;
4231: (*M)->stencil.noc = mat->stencil.noc;
4232: for (i=0; i<=mat->stencil.dim; i++) {
4233: (*M)->stencil.dims[i] = mat->stencil.dims[i];
4234: (*M)->stencil.starts[i] = mat->stencil.starts[i];
4235: }
4236: PetscLogEventEnd(MAT_Convert,mat,0,0,0);
4237: }
4238: PetscObjectStateIncrease((PetscObject)*M);
4240: /* Copy Mat options */
4241: if (issymmetric) {
4242: MatSetOption(*M,MAT_SYMMETRIC,PETSC_TRUE);
4243: }
4244: if (ishermitian) {
4245: MatSetOption(*M,MAT_HERMITIAN,PETSC_TRUE);
4246: }
4247: return(0);
4248: }
4250: /*@C
4251: MatFactorGetSolverType - Returns name of the package providing the factorization routines
4253: Not Collective
4255: Input Parameter:
4256: . mat - the matrix, must be a factored matrix
4258: Output Parameter:
4259: . type - the string name of the package (do not free this string)
4261: Notes:
4262: In Fortran you pass in a empty string and the package name will be copied into it.
4263: (Make sure the string is long enough)
4265: Level: intermediate
4267: .seealso: MatCopy(), MatDuplicate(), MatGetFactorAvailable(), MatGetFactor()
4268: @*/
4269: PetscErrorCode MatFactorGetSolverType(Mat mat, MatSolverType *type)
4270: {
4271: PetscErrorCode ierr, (*conv)(Mat,MatSolverType*);
4276: if (!mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Only for factored matrix");
4277: PetscObjectQueryFunction((PetscObject)mat,"MatFactorGetSolverType_C",&conv);
4278: if (!conv) {
4279: *type = MATSOLVERPETSC;
4280: } else {
4281: (*conv)(mat,type);
4282: }
4283: return(0);
4284: }
4286: typedef struct _MatSolverTypeForSpecifcType* MatSolverTypeForSpecifcType;
4287: struct _MatSolverTypeForSpecifcType {
4288: MatType mtype;
4289: PetscErrorCode (*getfactor[4])(Mat,MatFactorType,Mat*);
4290: MatSolverTypeForSpecifcType next;
4291: };
4293: typedef struct _MatSolverTypeHolder* MatSolverTypeHolder;
4294: struct _MatSolverTypeHolder {
4295: char *name;
4296: MatSolverTypeForSpecifcType handlers;
4297: MatSolverTypeHolder next;
4298: };
4300: static MatSolverTypeHolder MatSolverTypeHolders = NULL;
4302: /*@C
4303: MatSolvePackageRegister - Registers a MatSolverType that works for a particular matrix type
4305: Input Parameters:
4306: + package - name of the package, for example petsc or superlu
4307: . mtype - the matrix type that works with this package
4308: . ftype - the type of factorization supported by the package
4309: - getfactor - routine that will create the factored matrix ready to be used
4311: Level: intermediate
4313: .seealso: MatCopy(), MatDuplicate(), MatGetFactorAvailable()
4314: @*/
4315: PetscErrorCode MatSolverTypeRegister(MatSolverType package,MatType mtype,MatFactorType ftype,PetscErrorCode (*getfactor)(Mat,MatFactorType,Mat*))
4316: {
4317: PetscErrorCode ierr;
4318: MatSolverTypeHolder next = MatSolverTypeHolders,prev = NULL;
4319: PetscBool flg;
4320: MatSolverTypeForSpecifcType inext,iprev = NULL;
4323: MatInitializePackage();
4324: if (!next) {
4325: PetscNew(&MatSolverTypeHolders);
4326: PetscStrallocpy(package,&MatSolverTypeHolders->name);
4327: PetscNew(&MatSolverTypeHolders->handlers);
4328: PetscStrallocpy(mtype,(char **)&MatSolverTypeHolders->handlers->mtype);
4329: MatSolverTypeHolders->handlers->getfactor[(int)ftype-1] = getfactor;
4330: return(0);
4331: }
4332: while (next) {
4333: PetscStrcasecmp(package,next->name,&flg);
4334: if (flg) {
4335: if (!next->handlers) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_PLIB,"MatSolverTypeHolder is missing handlers");
4336: inext = next->handlers;
4337: while (inext) {
4338: PetscStrcasecmp(mtype,inext->mtype,&flg);
4339: if (flg) {
4340: inext->getfactor[(int)ftype-1] = getfactor;
4341: return(0);
4342: }
4343: iprev = inext;
4344: inext = inext->next;
4345: }
4346: PetscNew(&iprev->next);
4347: PetscStrallocpy(mtype,(char **)&iprev->next->mtype);
4348: iprev->next->getfactor[(int)ftype-1] = getfactor;
4349: return(0);
4350: }
4351: prev = next;
4352: next = next->next;
4353: }
4354: PetscNew(&prev->next);
4355: PetscStrallocpy(package,&prev->next->name);
4356: PetscNew(&prev->next->handlers);
4357: PetscStrallocpy(mtype,(char **)&prev->next->handlers->mtype);
4358: prev->next->handlers->getfactor[(int)ftype-1] = getfactor;
4359: return(0);
4360: }
4362: /*@C
4363: MatSolvePackageGet - Get's the function that creates the factor matrix if it exist
4365: Input Parameters:
4366: + package - name of the package, for example petsc or superlu
4367: . ftype - the type of factorization supported by the package
4368: - mtype - the matrix type that works with this package
4370: Output Parameters:
4371: + foundpackage - PETSC_TRUE if the package was registered
4372: . foundmtype - PETSC_TRUE if the package supports the requested mtype
4373: - getfactor - routine that will create the factored matrix ready to be used or NULL if not found
4375: Level: intermediate
4377: .seealso: MatCopy(), MatDuplicate(), MatGetFactorAvailable()
4378: @*/
4379: PetscErrorCode MatSolverTypeGet(MatSolverType package,MatType mtype,MatFactorType ftype,PetscBool *foundpackage,PetscBool *foundmtype,PetscErrorCode (**getfactor)(Mat,MatFactorType,Mat*))
4380: {
4381: PetscErrorCode ierr;
4382: MatSolverTypeHolder next = MatSolverTypeHolders;
4383: PetscBool flg;
4384: MatSolverTypeForSpecifcType inext;
4387: if (foundpackage) *foundpackage = PETSC_FALSE;
4388: if (foundmtype) *foundmtype = PETSC_FALSE;
4389: if (getfactor) *getfactor = NULL;
4391: if (package) {
4392: while (next) {
4393: PetscStrcasecmp(package,next->name,&flg);
4394: if (flg) {
4395: if (foundpackage) *foundpackage = PETSC_TRUE;
4396: inext = next->handlers;
4397: while (inext) {
4398: PetscStrbeginswith(mtype,inext->mtype,&flg);
4399: if (flg) {
4400: if (foundmtype) *foundmtype = PETSC_TRUE;
4401: if (getfactor) *getfactor = inext->getfactor[(int)ftype-1];
4402: return(0);
4403: }
4404: inext = inext->next;
4405: }
4406: }
4407: next = next->next;
4408: }
4409: } else {
4410: while (next) {
4411: inext = next->handlers;
4412: while (inext) {
4413: PetscStrbeginswith(mtype,inext->mtype,&flg);
4414: if (flg && inext->getfactor[(int)ftype-1]) {
4415: if (foundpackage) *foundpackage = PETSC_TRUE;
4416: if (foundmtype) *foundmtype = PETSC_TRUE;
4417: if (getfactor) *getfactor = inext->getfactor[(int)ftype-1];
4418: return(0);
4419: }
4420: inext = inext->next;
4421: }
4422: next = next->next;
4423: }
4424: }
4425: return(0);
4426: }
4428: PetscErrorCode MatSolverTypeDestroy(void)
4429: {
4430: PetscErrorCode ierr;
4431: MatSolverTypeHolder next = MatSolverTypeHolders,prev;
4432: MatSolverTypeForSpecifcType inext,iprev;
4435: while (next) {
4436: PetscFree(next->name);
4437: inext = next->handlers;
4438: while (inext) {
4439: PetscFree(inext->mtype);
4440: iprev = inext;
4441: inext = inext->next;
4442: PetscFree(iprev);
4443: }
4444: prev = next;
4445: next = next->next;
4446: PetscFree(prev);
4447: }
4448: MatSolverTypeHolders = NULL;
4449: return(0);
4450: }
4452: /*@C
4453: MatGetFactor - Returns a matrix suitable to calls to MatXXFactorSymbolic()
4455: Collective on Mat
4457: Input Parameters:
4458: + mat - the matrix
4459: . type - name of solver type, for example, superlu, petsc (to use PETSc's default)
4460: - ftype - factor type, MAT_FACTOR_LU, MAT_FACTOR_CHOLESKY, MAT_FACTOR_ICC, MAT_FACTOR_ILU,
4462: Output Parameters:
4463: . f - the factor matrix used with MatXXFactorSymbolic() calls
4465: Notes:
4466: Some PETSc matrix formats have alternative solvers available that are contained in alternative packages
4467: such as pastix, superlu, mumps etc.
4469: PETSc must have been ./configure to use the external solver, using the option --download-package
4471: Level: intermediate
4473: .seealso: MatCopy(), MatDuplicate(), MatGetFactorAvailable()
4474: @*/
4475: PetscErrorCode MatGetFactor(Mat mat, MatSolverType type,MatFactorType ftype,Mat *f)
4476: {
4477: PetscErrorCode ierr,(*conv)(Mat,MatFactorType,Mat*);
4478: PetscBool foundpackage,foundmtype;
4484: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
4485: MatCheckPreallocated(mat,1);
4487: MatSolverTypeGet(type,((PetscObject)mat)->type_name,ftype,&foundpackage,&foundmtype,&conv);
4488: if (!foundpackage) {
4489: if (type) {
4490: SETERRQ4(PetscObjectComm((PetscObject)mat),PETSC_ERR_MISSING_FACTOR,"Could not locate solver package %s for factorization type %s and matrix type %s. Perhaps you must ./configure with --download-%s",type,MatFactorTypes[ftype],((PetscObject)mat)->type_name,type);
4491: } else {
4492: SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_MISSING_FACTOR,"Could not locate a solver package for factorization type %s and matrix type %s.",MatFactorTypes[ftype],((PetscObject)mat)->type_name);
4493: }
4494: }
4495: if (!foundmtype) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_MISSING_FACTOR,"MatSolverType %s does not support matrix type %s",type,((PetscObject)mat)->type_name);
4496: if (!conv) SETERRQ3(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);
4498: (*conv)(mat,ftype,f);
4499: return(0);
4500: }
4502: /*@C
4503: MatGetFactorAvailable - Returns a a flag if matrix supports particular package and factor type
4505: Not Collective
4507: Input Parameters:
4508: + mat - the matrix
4509: . type - name of solver type, for example, superlu, petsc (to use PETSc's default)
4510: - ftype - factor type, MAT_FACTOR_LU, MAT_FACTOR_CHOLESKY, MAT_FACTOR_ICC, MAT_FACTOR_ILU,
4512: Output Parameter:
4513: . flg - PETSC_TRUE if the factorization is available
4515: Notes:
4516: Some PETSc matrix formats have alternative solvers available that are contained in alternative packages
4517: such as pastix, superlu, mumps etc.
4519: PETSc must have been ./configure to use the external solver, using the option --download-package
4521: Level: intermediate
4523: .seealso: MatCopy(), MatDuplicate(), MatGetFactor()
4524: @*/
4525: PetscErrorCode MatGetFactorAvailable(Mat mat, MatSolverType type,MatFactorType ftype,PetscBool *flg)
4526: {
4527: PetscErrorCode ierr, (*gconv)(Mat,MatFactorType,Mat*);
4533: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
4534: MatCheckPreallocated(mat,1);
4536: *flg = PETSC_FALSE;
4537: MatSolverTypeGet(type,((PetscObject)mat)->type_name,ftype,NULL,NULL,&gconv);
4538: if (gconv) {
4539: *flg = PETSC_TRUE;
4540: }
4541: return(0);
4542: }
4544: #include <petscdmtypes.h>
4546: /*@
4547: MatDuplicate - Duplicates a matrix including the non-zero structure.
4549: Collective on Mat
4551: Input Parameters:
4552: + mat - the matrix
4553: - op - One of MAT_DO_NOT_COPY_VALUES, MAT_COPY_VALUES, or MAT_SHARE_NONZERO_PATTERN.
4554: See the manual page for MatDuplicateOption for an explanation of these options.
4556: Output Parameter:
4557: . M - pointer to place new matrix
4559: Level: intermediate
4561: Notes:
4562: You cannot change the nonzero pattern for the parent or child matrix if you use MAT_SHARE_NONZERO_PATTERN.
4563: When original mat is a product of matrix operation, e.g., an output of MatMatMult() or MatCreateSubMatrix(), only the simple matrix data structure of mat is duplicated and the internal data structures created for the reuse of previous matrix operations are not duplicated. User should not use MatDuplicate() to create new matrix M if M is intended to be reused as the product of matrix operation.
4565: .seealso: MatCopy(), MatConvert(), MatDuplicateOption
4566: @*/
4567: PetscErrorCode MatDuplicate(Mat mat,MatDuplicateOption op,Mat *M)
4568: {
4570: Mat B;
4571: PetscInt i;
4572: DM dm;
4573: void (*viewf)(void);
4579: if (op == MAT_COPY_VALUES && !mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"MAT_COPY_VALUES not allowed for unassembled matrix");
4580: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
4581: MatCheckPreallocated(mat,1);
4583: *M = 0;
4584: if (!mat->ops->duplicate) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Not written for matrix type %s\n",((PetscObject)mat)->type_name);
4585: PetscLogEventBegin(MAT_Convert,mat,0,0,0);
4586: (*mat->ops->duplicate)(mat,op,M);
4587: B = *M;
4589: MatGetOperation(mat,MATOP_VIEW,&viewf);
4590: if (viewf) {
4591: MatSetOperation(B,MATOP_VIEW,viewf);
4592: }
4594: B->stencil.dim = mat->stencil.dim;
4595: B->stencil.noc = mat->stencil.noc;
4596: for (i=0; i<=mat->stencil.dim; i++) {
4597: B->stencil.dims[i] = mat->stencil.dims[i];
4598: B->stencil.starts[i] = mat->stencil.starts[i];
4599: }
4601: B->nooffproczerorows = mat->nooffproczerorows;
4602: B->nooffprocentries = mat->nooffprocentries;
4604: PetscObjectQuery((PetscObject) mat, "__PETSc_dm", (PetscObject*) &dm);
4605: if (dm) {
4606: PetscObjectCompose((PetscObject) B, "__PETSc_dm", (PetscObject) dm);
4607: }
4608: PetscLogEventEnd(MAT_Convert,mat,0,0,0);
4609: PetscObjectStateIncrease((PetscObject)B);
4610: return(0);
4611: }
4613: /*@
4614: MatGetDiagonal - Gets the diagonal of a matrix.
4616: Logically Collective on Mat
4618: Input Parameters:
4619: + mat - the matrix
4620: - v - the vector for storing the diagonal
4622: Output Parameter:
4623: . v - the diagonal of the matrix
4625: Level: intermediate
4627: Note:
4628: Currently only correct in parallel for square matrices.
4630: .seealso: MatGetRow(), MatCreateSubMatrices(), MatCreateSubMatrix(), MatGetRowMaxAbs()
4631: @*/
4632: PetscErrorCode MatGetDiagonal(Mat mat,Vec v)
4633: {
4640: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
4641: if (!mat->ops->getdiagonal) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
4642: MatCheckPreallocated(mat,1);
4644: (*mat->ops->getdiagonal)(mat,v);
4645: PetscObjectStateIncrease((PetscObject)v);
4646: return(0);
4647: }
4649: /*@C
4650: MatGetRowMin - Gets the minimum value (of the real part) of each
4651: row of the matrix
4653: Logically Collective on Mat
4655: Input Parameters:
4656: . mat - the matrix
4658: Output Parameter:
4659: + v - the vector for storing the maximums
4660: - idx - the indices of the column found for each row (optional)
4662: Level: intermediate
4664: Notes:
4665: The result of this call are the same as if one converted the matrix to dense format
4666: and found the minimum value in each row (i.e. the implicit zeros are counted as zeros).
4668: This code is only implemented for a couple of matrix formats.
4670: .seealso: MatGetDiagonal(), MatCreateSubMatrices(), MatCreateSubMatrix(), MatGetRowMaxAbs(),
4671: MatGetRowMax()
4672: @*/
4673: PetscErrorCode MatGetRowMin(Mat mat,Vec v,PetscInt idx[])
4674: {
4681: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
4682: if (!mat->ops->getrowmax) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
4683: MatCheckPreallocated(mat,1);
4685: (*mat->ops->getrowmin)(mat,v,idx);
4686: PetscObjectStateIncrease((PetscObject)v);
4687: return(0);
4688: }
4690: /*@C
4691: MatGetRowMinAbs - Gets the minimum value (in absolute value) of each
4692: row of the matrix
4694: Logically Collective on Mat
4696: Input Parameters:
4697: . mat - the matrix
4699: Output Parameter:
4700: + v - the vector for storing the minimums
4701: - idx - the indices of the column found for each row (or NULL if not needed)
4703: Level: intermediate
4705: Notes:
4706: if a row is completely empty or has only 0.0 values then the idx[] value for that
4707: row is 0 (the first column).
4709: This code is only implemented for a couple of matrix formats.
4711: .seealso: MatGetDiagonal(), MatCreateSubMatrices(), MatCreateSubMatrix(), MatGetRowMax(), MatGetRowMaxAbs(), MatGetRowMin()
4712: @*/
4713: PetscErrorCode MatGetRowMinAbs(Mat mat,Vec v,PetscInt idx[])
4714: {
4721: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
4722: if (!mat->ops->getrowminabs) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
4723: MatCheckPreallocated(mat,1);
4724: if (idx) {PetscArrayzero(idx,mat->rmap->n);}
4726: (*mat->ops->getrowminabs)(mat,v,idx);
4727: PetscObjectStateIncrease((PetscObject)v);
4728: return(0);
4729: }
4731: /*@C
4732: MatGetRowMax - Gets the maximum value (of the real part) of each
4733: row of the matrix
4735: Logically Collective on Mat
4737: Input Parameters:
4738: . mat - the matrix
4740: Output Parameter:
4741: + v - the vector for storing the maximums
4742: - idx - the indices of the column found for each row (optional)
4744: Level: intermediate
4746: Notes:
4747: The result of this call are the same as if one converted the matrix to dense format
4748: and found the minimum value in each row (i.e. the implicit zeros are counted as zeros).
4750: This code is only implemented for a couple of matrix formats.
4752: .seealso: MatGetDiagonal(), MatCreateSubMatrices(), MatCreateSubMatrix(), MatGetRowMaxAbs(), MatGetRowMin()
4753: @*/
4754: PetscErrorCode MatGetRowMax(Mat mat,Vec v,PetscInt idx[])
4755: {
4762: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
4763: if (!mat->ops->getrowmax) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
4764: MatCheckPreallocated(mat,1);
4766: (*mat->ops->getrowmax)(mat,v,idx);
4767: PetscObjectStateIncrease((PetscObject)v);
4768: return(0);
4769: }
4771: /*@C
4772: MatGetRowMaxAbs - Gets the maximum value (in absolute value) of each
4773: row of the matrix
4775: Logically Collective on Mat
4777: Input Parameters:
4778: . mat - the matrix
4780: Output Parameter:
4781: + v - the vector for storing the maximums
4782: - idx - the indices of the column found for each row (or NULL if not needed)
4784: Level: intermediate
4786: Notes:
4787: if a row is completely empty or has only 0.0 values then the idx[] value for that
4788: row is 0 (the first column).
4790: This code is only implemented for a couple of matrix formats.
4792: .seealso: MatGetDiagonal(), MatCreateSubMatrices(), MatCreateSubMatrix(), MatGetRowMax(), MatGetRowMin()
4793: @*/
4794: PetscErrorCode MatGetRowMaxAbs(Mat mat,Vec v,PetscInt idx[])
4795: {
4802: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
4803: if (!mat->ops->getrowmaxabs) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
4804: MatCheckPreallocated(mat,1);
4805: if (idx) {PetscArrayzero(idx,mat->rmap->n);}
4807: (*mat->ops->getrowmaxabs)(mat,v,idx);
4808: PetscObjectStateIncrease((PetscObject)v);
4809: return(0);
4810: }
4812: /*@
4813: MatGetRowSum - Gets the sum of each row of the matrix
4815: Logically or Neighborhood Collective on Mat
4817: Input Parameters:
4818: . mat - the matrix
4820: Output Parameter:
4821: . v - the vector for storing the sum of rows
4823: Level: intermediate
4825: Notes:
4826: This code is slow since it is not currently specialized for different formats
4828: .seealso: MatGetDiagonal(), MatCreateSubMatrices(), MatCreateSubMatrix(), MatGetRowMax(), MatGetRowMin()
4829: @*/
4830: PetscErrorCode MatGetRowSum(Mat mat, Vec v)
4831: {
4832: Vec ones;
4839: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
4840: MatCheckPreallocated(mat,1);
4841: MatCreateVecs(mat,&ones,NULL);
4842: VecSet(ones,1.);
4843: MatMult(mat,ones,v);
4844: VecDestroy(&ones);
4845: return(0);
4846: }
4848: /*@
4849: MatTranspose - Computes an in-place or out-of-place transpose of a matrix.
4851: Collective on Mat
4853: Input Parameter:
4854: + mat - the matrix to transpose
4855: - reuse - either MAT_INITIAL_MATRIX, MAT_REUSE_MATRIX, or MAT_INPLACE_MATRIX
4857: Output Parameters:
4858: . B - the transpose
4860: Notes:
4861: If you use MAT_INPLACE_MATRIX then you must pass in &mat for B
4863: MAT_REUSE_MATRIX causes the B matrix from a previous call to this function with MAT_INITIAL_MATRIX to be used
4865: Consider using MatCreateTranspose() instead if you only need a matrix that behaves like the transpose, but don't need the storage to be changed.
4867: Level: intermediate
4869: .seealso: MatMultTranspose(), MatMultTransposeAdd(), MatIsTranspose(), MatReuse
4870: @*/
4871: PetscErrorCode MatTranspose(Mat mat,MatReuse reuse,Mat *B)
4872: {
4878: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
4879: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
4880: if (!mat->ops->transpose) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
4881: if (reuse == MAT_INPLACE_MATRIX && mat != *B) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"MAT_INPLACE_MATRIX requires last matrix to match first");
4882: if (reuse == MAT_REUSE_MATRIX && mat == *B) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Perhaps you mean MAT_INPLACE_MATRIX");
4883: MatCheckPreallocated(mat,1);
4885: PetscLogEventBegin(MAT_Transpose,mat,0,0,0);
4886: (*mat->ops->transpose)(mat,reuse,B);
4887: PetscLogEventEnd(MAT_Transpose,mat,0,0,0);
4888: if (B) {PetscObjectStateIncrease((PetscObject)*B);}
4889: return(0);
4890: }
4892: /*@
4893: MatIsTranspose - Test whether a matrix is another one's transpose,
4894: or its own, in which case it tests symmetry.
4896: Collective on Mat
4898: Input Parameter:
4899: + A - the matrix to test
4900: - B - the matrix to test against, this can equal the first parameter
4902: Output Parameters:
4903: . flg - the result
4905: Notes:
4906: Only available for SeqAIJ/MPIAIJ matrices. The sequential algorithm
4907: has a running time of the order of the number of nonzeros; the parallel
4908: test involves parallel copies of the block-offdiagonal parts of the matrix.
4910: Level: intermediate
4912: .seealso: MatTranspose(), MatIsSymmetric(), MatIsHermitian()
4913: @*/
4914: PetscErrorCode MatIsTranspose(Mat A,Mat B,PetscReal tol,PetscBool *flg)
4915: {
4916: PetscErrorCode ierr,(*f)(Mat,Mat,PetscReal,PetscBool*),(*g)(Mat,Mat,PetscReal,PetscBool*);
4922: PetscObjectQueryFunction((PetscObject)A,"MatIsTranspose_C",&f);
4923: PetscObjectQueryFunction((PetscObject)B,"MatIsTranspose_C",&g);
4924: *flg = PETSC_FALSE;
4925: if (f && g) {
4926: if (f == g) {
4927: (*f)(A,B,tol,flg);
4928: } else SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_NOTSAMETYPE,"Matrices do not have the same comparator for symmetry test");
4929: } else {
4930: MatType mattype;
4931: if (!f) {
4932: MatGetType(A,&mattype);
4933: } else {
4934: MatGetType(B,&mattype);
4935: }
4936: SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Matrix of type %s does not support checking for transpose",mattype);
4937: }
4938: return(0);
4939: }
4941: /*@
4942: MatHermitianTranspose - Computes an in-place or out-of-place transpose of a matrix in complex conjugate.
4944: Collective on Mat
4946: Input Parameter:
4947: + mat - the matrix to transpose and complex conjugate
4948: - reuse - MAT_INITIAL_MATRIX to create a new matrix, MAT_INPLACE_MATRIX to reuse the first argument to store the transpose
4950: Output Parameters:
4951: . B - the Hermitian
4953: Level: intermediate
4955: .seealso: MatTranspose(), MatMultTranspose(), MatMultTransposeAdd(), MatIsTranspose(), MatReuse
4956: @*/
4957: PetscErrorCode MatHermitianTranspose(Mat mat,MatReuse reuse,Mat *B)
4958: {
4962: MatTranspose(mat,reuse,B);
4963: #if defined(PETSC_USE_COMPLEX)
4964: MatConjugate(*B);
4965: #endif
4966: return(0);
4967: }
4969: /*@
4970: MatIsHermitianTranspose - Test whether a matrix is another one's Hermitian transpose,
4972: Collective on Mat
4974: Input Parameter:
4975: + A - the matrix to test
4976: - B - the matrix to test against, this can equal the first parameter
4978: Output Parameters:
4979: . flg - the result
4981: Notes:
4982: Only available for SeqAIJ/MPIAIJ matrices. The sequential algorithm
4983: has a running time of the order of the number of nonzeros; the parallel
4984: test involves parallel copies of the block-offdiagonal parts of the matrix.
4986: Level: intermediate
4988: .seealso: MatTranspose(), MatIsSymmetric(), MatIsHermitian(), MatIsTranspose()
4989: @*/
4990: PetscErrorCode MatIsHermitianTranspose(Mat A,Mat B,PetscReal tol,PetscBool *flg)
4991: {
4992: PetscErrorCode ierr,(*f)(Mat,Mat,PetscReal,PetscBool*),(*g)(Mat,Mat,PetscReal,PetscBool*);
4998: PetscObjectQueryFunction((PetscObject)A,"MatIsHermitianTranspose_C",&f);
4999: PetscObjectQueryFunction((PetscObject)B,"MatIsHermitianTranspose_C",&g);
5000: if (f && g) {
5001: if (f==g) {
5002: (*f)(A,B,tol,flg);
5003: } else SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_NOTSAMETYPE,"Matrices do not have the same comparator for Hermitian test");
5004: }
5005: return(0);
5006: }
5008: /*@
5009: MatPermute - Creates a new matrix with rows and columns permuted from the
5010: original.
5012: Collective on Mat
5014: Input Parameters:
5015: + mat - the matrix to permute
5016: . row - row permutation, each processor supplies only the permutation for its rows
5017: - col - column permutation, each processor supplies only the permutation for its columns
5019: Output Parameters:
5020: . B - the permuted matrix
5022: Level: advanced
5024: Note:
5025: The index sets map from row/col of permuted matrix to row/col of original matrix.
5026: The index sets should be on the same communicator as Mat and have the same local sizes.
5028: .seealso: MatGetOrdering(), ISAllGather()
5030: @*/
5031: PetscErrorCode MatPermute(Mat mat,IS row,IS col,Mat *B)
5032: {
5041: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
5042: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
5043: if (!mat->ops->permute) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"MatPermute not available for Mat type %s",((PetscObject)mat)->type_name);
5044: MatCheckPreallocated(mat,1);
5046: (*mat->ops->permute)(mat,row,col,B);
5047: PetscObjectStateIncrease((PetscObject)*B);
5048: return(0);
5049: }
5051: /*@
5052: MatEqual - Compares two matrices.
5054: Collective on Mat
5056: Input Parameters:
5057: + A - the first matrix
5058: - B - the second matrix
5060: Output Parameter:
5061: . flg - PETSC_TRUE if the matrices are equal; PETSC_FALSE otherwise.
5063: Level: intermediate
5065: @*/
5066: PetscErrorCode MatEqual(Mat A,Mat B,PetscBool *flg)
5067: {
5077: MatCheckPreallocated(B,2);
5078: if (!A->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
5079: if (!B->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
5080: if (A->rmap->N != B->rmap->N || A->cmap->N != B->cmap->N) SETERRQ4(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Mat A,Mat B: global dim %D %D %D %D",A->rmap->N,B->rmap->N,A->cmap->N,B->cmap->N);
5081: if (!A->ops->equal) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Mat type %s",((PetscObject)A)->type_name);
5082: if (!B->ops->equal) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Mat type %s",((PetscObject)B)->type_name);
5083: if (A->ops->equal != B->ops->equal) SETERRQ2(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_INCOMP,"A is type: %s\nB is type: %s",((PetscObject)A)->type_name,((PetscObject)B)->type_name);
5084: MatCheckPreallocated(A,1);
5086: (*A->ops->equal)(A,B,flg);
5087: return(0);
5088: }
5090: /*@
5091: MatDiagonalScale - Scales a matrix on the left and right by diagonal
5092: matrices that are stored as vectors. Either of the two scaling
5093: matrices can be NULL.
5095: Collective on Mat
5097: Input Parameters:
5098: + mat - the matrix to be scaled
5099: . l - the left scaling vector (or NULL)
5100: - r - the right scaling vector (or NULL)
5102: Notes:
5103: MatDiagonalScale() computes A = LAR, where
5104: L = a diagonal matrix (stored as a vector), R = a diagonal matrix (stored as a vector)
5105: The L scales the rows of the matrix, the R scales the columns of the matrix.
5107: Level: intermediate
5110: .seealso: MatScale(), MatShift(), MatDiagonalSet()
5111: @*/
5112: PetscErrorCode MatDiagonalScale(Mat mat,Vec l,Vec r)
5113: {
5119: if (!mat->ops->diagonalscale) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
5122: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
5123: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
5124: MatCheckPreallocated(mat,1);
5126: PetscLogEventBegin(MAT_Scale,mat,0,0,0);
5127: (*mat->ops->diagonalscale)(mat,l,r);
5128: PetscLogEventEnd(MAT_Scale,mat,0,0,0);
5129: PetscObjectStateIncrease((PetscObject)mat);
5130: return(0);
5131: }
5133: /*@
5134: MatScale - Scales all elements of a matrix by a given number.
5136: Logically Collective on Mat
5138: Input Parameters:
5139: + mat - the matrix to be scaled
5140: - a - the scaling value
5142: Output Parameter:
5143: . mat - the scaled matrix
5145: Level: intermediate
5147: .seealso: MatDiagonalScale()
5148: @*/
5149: PetscErrorCode MatScale(Mat mat,PetscScalar a)
5150: {
5156: if (a != (PetscScalar)1.0 && !mat->ops->scale) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
5157: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
5158: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
5160: MatCheckPreallocated(mat,1);
5162: PetscLogEventBegin(MAT_Scale,mat,0,0,0);
5163: if (a != (PetscScalar)1.0) {
5164: (*mat->ops->scale)(mat,a);
5165: PetscObjectStateIncrease((PetscObject)mat);
5166: }
5167: PetscLogEventEnd(MAT_Scale,mat,0,0,0);
5168: return(0);
5169: }
5171: /*@
5172: MatNorm - Calculates various norms of a matrix.
5174: Collective on Mat
5176: Input Parameters:
5177: + mat - the matrix
5178: - type - the type of norm, NORM_1, NORM_FROBENIUS, NORM_INFINITY
5180: Output Parameters:
5181: . nrm - the resulting norm
5183: Level: intermediate
5185: @*/
5186: PetscErrorCode MatNorm(Mat mat,NormType type,PetscReal *nrm)
5187: {
5195: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
5196: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
5197: if (!mat->ops->norm) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
5198: MatCheckPreallocated(mat,1);
5200: (*mat->ops->norm)(mat,type,nrm);
5201: return(0);
5202: }
5204: /*
5205: This variable is used to prevent counting of MatAssemblyBegin() that
5206: are called from within a MatAssemblyEnd().
5207: */
5208: static PetscInt MatAssemblyEnd_InUse = 0;
5209: /*@
5210: MatAssemblyBegin - Begins assembling the matrix. This routine should
5211: be called after completing all calls to MatSetValues().
5213: Collective on Mat
5215: Input Parameters:
5216: + mat - the matrix
5217: - type - type of assembly, either MAT_FLUSH_ASSEMBLY or MAT_FINAL_ASSEMBLY
5219: Notes:
5220: MatSetValues() generally caches the values. The matrix is ready to
5221: use only after MatAssemblyBegin() and MatAssemblyEnd() have been called.
5222: Use MAT_FLUSH_ASSEMBLY when switching between ADD_VALUES and INSERT_VALUES
5223: in MatSetValues(); use MAT_FINAL_ASSEMBLY for the final assembly before
5224: using the matrix.
5226: ALL processes that share a matrix MUST call MatAssemblyBegin() and MatAssemblyEnd() the SAME NUMBER of times, and each time with the
5227: 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
5228: a global collective operation requring all processes that share the matrix.
5230: Space for preallocated nonzeros that is not filled by a call to MatSetValues() or a related routine are compressed
5231: out by assembly. If you intend to use that extra space on a subsequent assembly, be sure to insert explicit zeros
5232: before MAT_FINAL_ASSEMBLY so the space is not compressed out.
5234: Level: beginner
5236: .seealso: MatAssemblyEnd(), MatSetValues(), MatAssembled()
5237: @*/
5238: PetscErrorCode MatAssemblyBegin(Mat mat,MatAssemblyType type)
5239: {
5245: MatCheckPreallocated(mat,1);
5246: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix.\nDid you forget to call MatSetUnfactored()?");
5247: if (mat->assembled) {
5248: mat->was_assembled = PETSC_TRUE;
5249: mat->assembled = PETSC_FALSE;
5250: }
5252: if (!MatAssemblyEnd_InUse) {
5253: PetscLogEventBegin(MAT_AssemblyBegin,mat,0,0,0);
5254: if (mat->ops->assemblybegin) {(*mat->ops->assemblybegin)(mat,type);}
5255: PetscLogEventEnd(MAT_AssemblyBegin,mat,0,0,0);
5256: } else if (mat->ops->assemblybegin) {
5257: (*mat->ops->assemblybegin)(mat,type);
5258: }
5259: return(0);
5260: }
5262: /*@
5263: MatAssembled - Indicates if a matrix has been assembled and is ready for
5264: use; for example, in matrix-vector product.
5266: Not Collective
5268: Input Parameter:
5269: . mat - the matrix
5271: Output Parameter:
5272: . assembled - PETSC_TRUE or PETSC_FALSE
5274: Level: advanced
5276: .seealso: MatAssemblyEnd(), MatSetValues(), MatAssemblyBegin()
5277: @*/
5278: PetscErrorCode MatAssembled(Mat mat,PetscBool *assembled)
5279: {
5283: *assembled = mat->assembled;
5284: return(0);
5285: }
5287: /*@
5288: MatAssemblyEnd - Completes assembling the matrix. This routine should
5289: be called after MatAssemblyBegin().
5291: Collective on Mat
5293: Input Parameters:
5294: + mat - the matrix
5295: - type - type of assembly, either MAT_FLUSH_ASSEMBLY or MAT_FINAL_ASSEMBLY
5297: Options Database Keys:
5298: + -mat_view ::ascii_info - Prints info on matrix at conclusion of MatEndAssembly()
5299: . -mat_view ::ascii_info_detail - Prints more detailed info
5300: . -mat_view - Prints matrix in ASCII format
5301: . -mat_view ::ascii_matlab - Prints matrix in Matlab format
5302: . -mat_view draw - PetscDraws nonzero structure of matrix, using MatView() and PetscDrawOpenX().
5303: . -display <name> - Sets display name (default is host)
5304: . -draw_pause <sec> - Sets number of seconds to pause after display
5305: . -mat_view socket - Sends matrix to socket, can be accessed from Matlab (See Users-Manual: Chapter 12 Using MATLAB with PETSc )
5306: . -viewer_socket_machine <machine> - Machine to use for socket
5307: . -viewer_socket_port <port> - Port number to use for socket
5308: - -mat_view binary:filename[:append] - Save matrix to file in binary format
5310: Notes:
5311: MatSetValues() generally caches the values. The matrix is ready to
5312: use only after MatAssemblyBegin() and MatAssemblyEnd() have been called.
5313: Use MAT_FLUSH_ASSEMBLY when switching between ADD_VALUES and INSERT_VALUES
5314: in MatSetValues(); use MAT_FINAL_ASSEMBLY for the final assembly before
5315: using the matrix.
5317: Space for preallocated nonzeros that is not filled by a call to MatSetValues() or a related routine are compressed
5318: out by assembly. If you intend to use that extra space on a subsequent assembly, be sure to insert explicit zeros
5319: before MAT_FINAL_ASSEMBLY so the space is not compressed out.
5321: Level: beginner
5323: .seealso: MatAssemblyBegin(), MatSetValues(), PetscDrawOpenX(), PetscDrawCreate(), MatView(), MatAssembled(), PetscViewerSocketOpen()
5324: @*/
5325: PetscErrorCode MatAssemblyEnd(Mat mat,MatAssemblyType type)
5326: {
5327: PetscErrorCode ierr;
5328: static PetscInt inassm = 0;
5329: PetscBool flg = PETSC_FALSE;
5335: inassm++;
5336: MatAssemblyEnd_InUse++;
5337: if (MatAssemblyEnd_InUse == 1) { /* Do the logging only the first time through */
5338: PetscLogEventBegin(MAT_AssemblyEnd,mat,0,0,0);
5339: if (mat->ops->assemblyend) {
5340: (*mat->ops->assemblyend)(mat,type);
5341: }
5342: PetscLogEventEnd(MAT_AssemblyEnd,mat,0,0,0);
5343: } else if (mat->ops->assemblyend) {
5344: (*mat->ops->assemblyend)(mat,type);
5345: }
5347: /* Flush assembly is not a true assembly */
5348: if (type != MAT_FLUSH_ASSEMBLY) {
5349: mat->num_ass++;
5350: mat->assembled = PETSC_TRUE;
5351: mat->ass_nonzerostate = mat->nonzerostate;
5352: }
5354: mat->insertmode = NOT_SET_VALUES;
5355: MatAssemblyEnd_InUse--;
5356: PetscObjectStateIncrease((PetscObject)mat);
5357: if (!mat->symmetric_eternal) {
5358: mat->symmetric_set = PETSC_FALSE;
5359: mat->hermitian_set = PETSC_FALSE;
5360: mat->structurally_symmetric_set = PETSC_FALSE;
5361: }
5362: if (inassm == 1 && type != MAT_FLUSH_ASSEMBLY) {
5363: MatViewFromOptions(mat,NULL,"-mat_view");
5365: if (mat->checksymmetryonassembly) {
5366: MatIsSymmetric(mat,mat->checksymmetrytol,&flg);
5367: if (flg) {
5368: PetscPrintf(PetscObjectComm((PetscObject)mat),"Matrix is symmetric (tolerance %g)\n",(double)mat->checksymmetrytol);
5369: } else {
5370: PetscPrintf(PetscObjectComm((PetscObject)mat),"Matrix is not symmetric (tolerance %g)\n",(double)mat->checksymmetrytol);
5371: }
5372: }
5373: if (mat->nullsp && mat->checknullspaceonassembly) {
5374: MatNullSpaceTest(mat->nullsp,mat,NULL);
5375: }
5376: }
5377: inassm--;
5378: return(0);
5379: }
5381: /*@
5382: MatSetOption - Sets a parameter option for a matrix. Some options
5383: may be specific to certain storage formats. Some options
5384: determine how values will be inserted (or added). Sorted,
5385: row-oriented input will generally assemble the fastest. The default
5386: is row-oriented.
5388: Logically Collective on Mat for certain operations, such as MAT_SPD, not collective for MAT_ROW_ORIENTED, see MatOption
5390: Input Parameters:
5391: + mat - the matrix
5392: . option - the option, one of those listed below (and possibly others),
5393: - flg - turn the option on (PETSC_TRUE) or off (PETSC_FALSE)
5395: Options Describing Matrix Structure:
5396: + MAT_SPD - symmetric positive definite
5397: . MAT_SYMMETRIC - symmetric in terms of both structure and value
5398: . MAT_HERMITIAN - transpose is the complex conjugation
5399: . MAT_STRUCTURALLY_SYMMETRIC - symmetric nonzero structure
5400: - MAT_SYMMETRY_ETERNAL - if you would like the symmetry/Hermitian flag
5401: you set to be kept with all future use of the matrix
5402: including after MatAssemblyBegin/End() which could
5403: potentially change the symmetry structure, i.e. you
5404: KNOW the matrix will ALWAYS have the property you set.
5405: Note that setting this flag alone implies nothing about whether the matrix is symmetric/Hermitian;
5406: the relevant flags must be set independently.
5409: Options For Use with MatSetValues():
5410: Insert a logically dense subblock, which can be
5411: . MAT_ROW_ORIENTED - row-oriented (default)
5413: Note these options reflect the data you pass in with MatSetValues(); it has
5414: nothing to do with how the data is stored internally in the matrix
5415: data structure.
5417: When (re)assembling a matrix, we can restrict the input for
5418: efficiency/debugging purposes. These options include:
5419: + MAT_NEW_NONZERO_LOCATIONS - additional insertions will be allowed if they generate a new nonzero (slow)
5420: . MAT_NEW_DIAGONALS - new diagonals will be allowed (for block diagonal format only)
5421: . MAT_IGNORE_OFF_PROC_ENTRIES - drops off-processor entries
5422: . MAT_NEW_NONZERO_LOCATION_ERR - generates an error for new matrix entry
5423: . MAT_USE_HASH_TABLE - uses a hash table to speed up matrix assembly
5424: . MAT_NO_OFF_PROC_ENTRIES - you know each process will only set values for its own rows, will generate an error if
5425: any process sets values for another process. This avoids all reductions in the MatAssembly routines and thus improves
5426: performance for very large process counts.
5427: - MAT_SUBSET_OFF_PROC_ENTRIES - you know that the first assembly after setting this flag will set a superset
5428: of the off-process entries required for all subsequent assemblies. This avoids a rendezvous step in the MatAssembly
5429: functions, instead sending only neighbor messages.
5431: Notes:
5432: Except for MAT_UNUSED_NONZERO_LOCATION_ERR and MAT_ROW_ORIENTED all processes that share the matrix must pass the same value in flg!
5434: Some options are relevant only for particular matrix types and
5435: are thus ignored by others. Other options are not supported by
5436: certain matrix types and will generate an error message if set.
5438: If using a Fortran 77 module to compute a matrix, one may need to
5439: use the column-oriented option (or convert to the row-oriented
5440: format).
5442: MAT_NEW_NONZERO_LOCATIONS set to PETSC_FALSE indicates that any add or insertion
5443: that would generate a new entry in the nonzero structure is instead
5444: ignored. Thus, if memory has not alredy been allocated for this particular
5445: data, then the insertion is ignored. For dense matrices, in which
5446: the entire array is allocated, no entries are ever ignored.
5447: Set after the first MatAssemblyEnd(). If this option is set then the MatAssemblyBegin/End() processes has one less global reduction
5449: MAT_NEW_NONZERO_LOCATION_ERR set to PETSC_TRUE indicates that any add or insertion
5450: that would generate a new entry in the nonzero structure instead produces
5451: an error. (Currently supported for AIJ and BAIJ formats only.) If this option is set then the MatAssemblyBegin/End() processes has one less global reduction
5453: MAT_NEW_NONZERO_ALLOCATION_ERR set to PETSC_TRUE indicates that any add or insertion
5454: that would generate a new entry that has not been preallocated will
5455: instead produce an error. (Currently supported for AIJ and BAIJ formats
5456: only.) This is a useful flag when debugging matrix memory preallocation.
5457: If this option is set then the MatAssemblyBegin/End() processes has one less global reduction
5459: MAT_IGNORE_OFF_PROC_ENTRIES set to PETSC_TRUE indicates entries destined for
5460: other processors should be dropped, rather than stashed.
5461: This is useful if you know that the "owning" processor is also
5462: always generating the correct matrix entries, so that PETSc need
5463: not transfer duplicate entries generated on another processor.
5465: MAT_USE_HASH_TABLE indicates that a hash table be used to improve the
5466: searches during matrix assembly. When this flag is set, the hash table
5467: is created during the first Matrix Assembly. This hash table is
5468: used the next time through, during MatSetVaules()/MatSetVaulesBlocked()
5469: to improve the searching of indices. MAT_NEW_NONZERO_LOCATIONS flag
5470: should be used with MAT_USE_HASH_TABLE flag. This option is currently
5471: supported by MATMPIBAIJ format only.
5473: MAT_KEEP_NONZERO_PATTERN indicates when MatZeroRows() is called the zeroed entries
5474: are kept in the nonzero structure
5476: MAT_IGNORE_ZERO_ENTRIES - for AIJ/IS matrices this will stop zero values from creating
5477: a zero location in the matrix
5479: MAT_USE_INODES - indicates using inode version of the code - works with AIJ matrix types
5481: MAT_NO_OFF_PROC_ZERO_ROWS - you know each process will only zero its own rows. This avoids all reductions in the
5482: zero row routines and thus improves performance for very large process counts.
5484: MAT_IGNORE_LOWER_TRIANGULAR - For SBAIJ matrices will ignore any insertions you make in the lower triangular
5485: part of the matrix (since they should match the upper triangular part).
5487: MAT_SORTED_FULL - each process provides exactly its local rows; all column indices for a given row are passed in a
5488: single call to MatSetValues(), preallocation is perfect, row oriented, INSERT_VALUES is used. Common
5489: with finite difference schemes with non-periodic boundary conditions.
5490: Notes:
5491: Can only be called after MatSetSizes() and MatSetType() have been set.
5493: Level: intermediate
5495: .seealso: MatOption, Mat
5497: @*/
5498: PetscErrorCode MatSetOption(Mat mat,MatOption op,PetscBool flg)
5499: {
5505: if (op > 0) {
5508: }
5510: if (((int) op) <= MAT_OPTION_MIN || ((int) op) >= MAT_OPTION_MAX) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_OUTOFRANGE,"Options %d is out of range",(int)op);
5511: if (!((PetscObject)mat)->type_name) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_TYPENOTSET,"Cannot set options until type and size have been set, see MatSetType() and MatSetSizes()");
5513: switch (op) {
5514: case MAT_NO_OFF_PROC_ENTRIES:
5515: mat->nooffprocentries = flg;
5516: return(0);
5517: break;
5518: case MAT_SUBSET_OFF_PROC_ENTRIES:
5519: mat->assembly_subset = flg;
5520: if (!mat->assembly_subset) { /* See the same logic in VecAssembly wrt VEC_SUBSET_OFF_PROC_ENTRIES */
5521: #if !defined(PETSC_HAVE_MPIUNI)
5522: MatStashScatterDestroy_BTS(&mat->stash);
5523: #endif
5524: mat->stash.first_assembly_done = PETSC_FALSE;
5525: }
5526: return(0);
5527: case MAT_NO_OFF_PROC_ZERO_ROWS:
5528: mat->nooffproczerorows = flg;
5529: return(0);
5530: break;
5531: case MAT_SPD:
5532: mat->spd_set = PETSC_TRUE;
5533: mat->spd = flg;
5534: if (flg) {
5535: mat->symmetric = PETSC_TRUE;
5536: mat->structurally_symmetric = PETSC_TRUE;
5537: mat->symmetric_set = PETSC_TRUE;
5538: mat->structurally_symmetric_set = PETSC_TRUE;
5539: }
5540: break;
5541: case MAT_SYMMETRIC:
5542: mat->symmetric = flg;
5543: if (flg) mat->structurally_symmetric = PETSC_TRUE;
5544: mat->symmetric_set = PETSC_TRUE;
5545: mat->structurally_symmetric_set = flg;
5546: #if !defined(PETSC_USE_COMPLEX)
5547: mat->hermitian = flg;
5548: mat->hermitian_set = PETSC_TRUE;
5549: #endif
5550: break;
5551: case MAT_HERMITIAN:
5552: mat->hermitian = flg;
5553: if (flg) mat->structurally_symmetric = PETSC_TRUE;
5554: mat->hermitian_set = PETSC_TRUE;
5555: mat->structurally_symmetric_set = flg;
5556: #if !defined(PETSC_USE_COMPLEX)
5557: mat->symmetric = flg;
5558: mat->symmetric_set = PETSC_TRUE;
5559: #endif
5560: break;
5561: case MAT_STRUCTURALLY_SYMMETRIC:
5562: mat->structurally_symmetric = flg;
5563: mat->structurally_symmetric_set = PETSC_TRUE;
5564: break;
5565: case MAT_SYMMETRY_ETERNAL:
5566: mat->symmetric_eternal = flg;
5567: break;
5568: case MAT_STRUCTURE_ONLY:
5569: mat->structure_only = flg;
5570: break;
5571: case MAT_SORTED_FULL:
5572: mat->sortedfull = flg;
5573: break;
5574: default:
5575: break;
5576: }
5577: if (mat->ops->setoption) {
5578: (*mat->ops->setoption)(mat,op,flg);
5579: }
5580: return(0);
5581: }
5583: /*@
5584: MatGetOption - Gets a parameter option that has been set for a matrix.
5586: Logically Collective on Mat for certain operations, such as MAT_SPD, not collective for MAT_ROW_ORIENTED, see MatOption
5588: Input Parameters:
5589: + mat - the matrix
5590: - option - the option, this only responds to certain options, check the code for which ones
5592: Output Parameter:
5593: . flg - turn the option on (PETSC_TRUE) or off (PETSC_FALSE)
5595: Notes:
5596: Can only be called after MatSetSizes() and MatSetType() have been set.
5598: Level: intermediate
5600: .seealso: MatOption, MatSetOption()
5602: @*/
5603: PetscErrorCode MatGetOption(Mat mat,MatOption op,PetscBool *flg)
5604: {
5609: if (((int) op) <= MAT_OPTION_MIN || ((int) op) >= MAT_OPTION_MAX) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_OUTOFRANGE,"Options %d is out of range",(int)op);
5610: if (!((PetscObject)mat)->type_name) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_TYPENOTSET,"Cannot get options until type and size have been set, see MatSetType() and MatSetSizes()");
5612: switch (op) {
5613: case MAT_NO_OFF_PROC_ENTRIES:
5614: *flg = mat->nooffprocentries;
5615: break;
5616: case MAT_NO_OFF_PROC_ZERO_ROWS:
5617: *flg = mat->nooffproczerorows;
5618: break;
5619: case MAT_SYMMETRIC:
5620: *flg = mat->symmetric;
5621: break;
5622: case MAT_HERMITIAN:
5623: *flg = mat->hermitian;
5624: break;
5625: case MAT_STRUCTURALLY_SYMMETRIC:
5626: *flg = mat->structurally_symmetric;
5627: break;
5628: case MAT_SYMMETRY_ETERNAL:
5629: *flg = mat->symmetric_eternal;
5630: break;
5631: case MAT_SPD:
5632: *flg = mat->spd;
5633: break;
5634: default:
5635: break;
5636: }
5637: return(0);
5638: }
5640: /*@
5641: MatZeroEntries - Zeros all entries of a matrix. For sparse matrices
5642: this routine retains the old nonzero structure.
5644: Logically Collective on Mat
5646: Input Parameters:
5647: . mat - the matrix
5649: Level: intermediate
5651: Notes:
5652: 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.
5653: See the Performance chapter of the users manual for information on preallocating matrices.
5655: .seealso: MatZeroRows()
5656: @*/
5657: PetscErrorCode MatZeroEntries(Mat mat)
5658: {
5664: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
5665: if (mat->insertmode != NOT_SET_VALUES) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for matrices where you have set values but not yet assembled");
5666: if (!mat->ops->zeroentries) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
5667: MatCheckPreallocated(mat,1);
5669: PetscLogEventBegin(MAT_ZeroEntries,mat,0,0,0);
5670: (*mat->ops->zeroentries)(mat);
5671: PetscLogEventEnd(MAT_ZeroEntries,mat,0,0,0);
5672: PetscObjectStateIncrease((PetscObject)mat);
5673: return(0);
5674: }
5676: /*@
5677: MatZeroRowsColumns - Zeros all entries (except possibly the main diagonal)
5678: of a set of rows and columns of a matrix.
5680: Collective on Mat
5682: Input Parameters:
5683: + mat - the matrix
5684: . numRows - the number of rows to remove
5685: . rows - the global row indices
5686: . diag - value put in all diagonals of eliminated rows (0.0 will even eliminate diagonal entry)
5687: . x - optional vector of solutions for zeroed rows (other entries in vector are not used)
5688: - b - optional vector of right hand side, that will be adjusted by provided solution
5690: Notes:
5691: This does not change the nonzero structure of the matrix, it merely zeros those entries in the matrix.
5693: The user can set a value in the diagonal entry (or for the AIJ and
5694: row formats can optionally remove the main diagonal entry from the
5695: nonzero structure as well, by passing 0.0 as the final argument).
5697: For the parallel case, all processes that share the matrix (i.e.,
5698: those in the communicator used for matrix creation) MUST call this
5699: routine, regardless of whether any rows being zeroed are owned by
5700: them.
5702: Each processor can indicate any rows in the entire matrix to be zeroed (i.e. each process does NOT have to
5703: list only rows local to itself).
5705: The option MAT_NO_OFF_PROC_ZERO_ROWS does not apply to this routine.
5707: Level: intermediate
5709: .seealso: MatZeroRowsIS(), MatZeroRows(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
5710: MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
5711: @*/
5712: PetscErrorCode MatZeroRowsColumns(Mat mat,PetscInt numRows,const PetscInt rows[],PetscScalar diag,Vec x,Vec b)
5713: {
5720: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
5721: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
5722: if (!mat->ops->zerorowscolumns) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
5723: MatCheckPreallocated(mat,1);
5725: (*mat->ops->zerorowscolumns)(mat,numRows,rows,diag,x,b);
5726: MatViewFromOptions(mat,NULL,"-mat_view");
5727: PetscObjectStateIncrease((PetscObject)mat);
5728: return(0);
5729: }
5731: /*@
5732: MatZeroRowsColumnsIS - Zeros all entries (except possibly the main diagonal)
5733: of a set of rows and columns of a matrix.
5735: Collective on Mat
5737: Input Parameters:
5738: + mat - the matrix
5739: . is - the rows to zero
5740: . diag - value put in all diagonals of eliminated rows (0.0 will even eliminate diagonal entry)
5741: . x - optional vector of solutions for zeroed rows (other entries in vector are not used)
5742: - b - optional vector of right hand side, that will be adjusted by provided solution
5744: Notes:
5745: This does not change the nonzero structure of the matrix, it merely zeros those entries in the matrix.
5747: The user can set a value in the diagonal entry (or for the AIJ and
5748: row formats can optionally remove the main diagonal entry from the
5749: nonzero structure as well, by passing 0.0 as the final argument).
5751: For the parallel case, all processes that share the matrix (i.e.,
5752: those in the communicator used for matrix creation) MUST call this
5753: routine, regardless of whether any rows being zeroed are owned by
5754: them.
5756: Each processor can indicate any rows in the entire matrix to be zeroed (i.e. each process does NOT have to
5757: list only rows local to itself).
5759: The option MAT_NO_OFF_PROC_ZERO_ROWS does not apply to this routine.
5761: Level: intermediate
5763: .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
5764: MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRows(), MatZeroRowsColumnsStencil()
5765: @*/
5766: PetscErrorCode MatZeroRowsColumnsIS(Mat mat,IS is,PetscScalar diag,Vec x,Vec b)
5767: {
5769: PetscInt numRows;
5770: const PetscInt *rows;
5777: ISGetLocalSize(is,&numRows);
5778: ISGetIndices(is,&rows);
5779: MatZeroRowsColumns(mat,numRows,rows,diag,x,b);
5780: ISRestoreIndices(is,&rows);
5781: return(0);
5782: }
5784: /*@
5785: MatZeroRows - Zeros all entries (except possibly the main diagonal)
5786: of a set of rows of a matrix.
5788: Collective on Mat
5790: Input Parameters:
5791: + mat - the matrix
5792: . numRows - the number of rows to remove
5793: . rows - the global row indices
5794: . diag - value put in all diagonals of eliminated rows (0.0 will even eliminate diagonal entry)
5795: . x - optional vector of solutions for zeroed rows (other entries in vector are not used)
5796: - b - optional vector of right hand side, that will be adjusted by provided solution
5798: Notes:
5799: For the AIJ and BAIJ matrix formats this removes the old nonzero structure,
5800: but does not release memory. For the dense and block diagonal
5801: formats this does not alter the nonzero structure.
5803: If the option MatSetOption(mat,MAT_KEEP_NONZERO_PATTERN,PETSC_TRUE) the nonzero structure
5804: of the matrix is not changed (even for AIJ and BAIJ matrices) the values are
5805: merely zeroed.
5807: The user can set a value in the diagonal entry (or for the AIJ and
5808: row formats can optionally remove the main diagonal entry from the
5809: nonzero structure as well, by passing 0.0 as the final argument).
5811: For the parallel case, all processes that share the matrix (i.e.,
5812: those in the communicator used for matrix creation) MUST call this
5813: routine, regardless of whether any rows being zeroed are owned by
5814: them.
5816: Each processor can indicate any rows in the entire matrix to be zeroed (i.e. each process does NOT have to
5817: list only rows local to itself).
5819: You can call MatSetOption(mat,MAT_NO_OFF_PROC_ZERO_ROWS,PETSC_TRUE) if each process indicates only rows it
5820: owns that are to be zeroed. This saves a global synchronization in the implementation.
5822: Level: intermediate
5824: .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
5825: MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
5826: @*/
5827: PetscErrorCode MatZeroRows(Mat mat,PetscInt numRows,const PetscInt rows[],PetscScalar diag,Vec x,Vec b)
5828: {
5835: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
5836: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
5837: if (!mat->ops->zerorows) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
5838: MatCheckPreallocated(mat,1);
5840: (*mat->ops->zerorows)(mat,numRows,rows,diag,x,b);
5841: MatViewFromOptions(mat,NULL,"-mat_view");
5842: PetscObjectStateIncrease((PetscObject)mat);
5843: return(0);
5844: }
5846: /*@
5847: MatZeroRowsIS - Zeros all entries (except possibly the main diagonal)
5848: of a set of rows of a matrix.
5850: Collective on Mat
5852: Input Parameters:
5853: + mat - the matrix
5854: . is - index set of rows to remove
5855: . diag - value put in all diagonals of eliminated rows
5856: . x - optional vector of solutions for zeroed rows (other entries in vector are not used)
5857: - b - optional vector of right hand side, that will be adjusted by provided solution
5859: Notes:
5860: For the AIJ and BAIJ matrix formats this removes the old nonzero structure,
5861: but does not release memory. For the dense and block diagonal
5862: formats this does not alter the nonzero structure.
5864: If the option MatSetOption(mat,MAT_KEEP_NONZERO_PATTERN,PETSC_TRUE) the nonzero structure
5865: of the matrix is not changed (even for AIJ and BAIJ matrices) the values are
5866: merely zeroed.
5868: The user can set a value in the diagonal entry (or for the AIJ and
5869: row formats can optionally remove the main diagonal entry from the
5870: nonzero structure as well, by passing 0.0 as the final argument).
5872: For the parallel case, all processes that share the matrix (i.e.,
5873: those in the communicator used for matrix creation) MUST call this
5874: routine, regardless of whether any rows being zeroed are owned by
5875: them.
5877: Each processor can indicate any rows in the entire matrix to be zeroed (i.e. each process does NOT have to
5878: list only rows local to itself).
5880: You can call MatSetOption(mat,MAT_NO_OFF_PROC_ZERO_ROWS,PETSC_TRUE) if each process indicates only rows it
5881: owns that are to be zeroed. This saves a global synchronization in the implementation.
5883: Level: intermediate
5885: .seealso: MatZeroRows(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
5886: MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
5887: @*/
5888: PetscErrorCode MatZeroRowsIS(Mat mat,IS is,PetscScalar diag,Vec x,Vec b)
5889: {
5890: PetscInt numRows;
5891: const PetscInt *rows;
5898: ISGetLocalSize(is,&numRows);
5899: ISGetIndices(is,&rows);
5900: MatZeroRows(mat,numRows,rows,diag,x,b);
5901: ISRestoreIndices(is,&rows);
5902: return(0);
5903: }
5905: /*@
5906: MatZeroRowsStencil - Zeros all entries (except possibly the main diagonal)
5907: of a set of rows of a matrix. These rows must be local to the process.
5909: Collective on Mat
5911: Input Parameters:
5912: + mat - the matrix
5913: . numRows - the number of rows to remove
5914: . rows - the grid coordinates (and component number when dof > 1) for matrix rows
5915: . diag - value put in all diagonals of eliminated rows (0.0 will even eliminate diagonal entry)
5916: . x - optional vector of solutions for zeroed rows (other entries in vector are not used)
5917: - b - optional vector of right hand side, that will be adjusted by provided solution
5919: Notes:
5920: For the AIJ and BAIJ matrix formats this removes the old nonzero structure,
5921: but does not release memory. For the dense and block diagonal
5922: formats this does not alter the nonzero structure.
5924: If the option MatSetOption(mat,MAT_KEEP_NONZERO_PATTERN,PETSC_TRUE) the nonzero structure
5925: of the matrix is not changed (even for AIJ and BAIJ matrices) the values are
5926: merely zeroed.
5928: The user can set a value in the diagonal entry (or for the AIJ and
5929: row formats can optionally remove the main diagonal entry from the
5930: nonzero structure as well, by passing 0.0 as the final argument).
5932: For the parallel case, all processes that share the matrix (i.e.,
5933: those in the communicator used for matrix creation) MUST call this
5934: routine, regardless of whether any rows being zeroed are owned by
5935: them.
5937: Each processor can indicate any rows in the entire matrix to be zeroed (i.e. each process does NOT have to
5938: list only rows local to itself).
5940: The grid coordinates are across the entire grid, not just the local portion
5942: In Fortran idxm and idxn should be declared as
5943: $ MatStencil idxm(4,m)
5944: and the values inserted using
5945: $ idxm(MatStencil_i,1) = i
5946: $ idxm(MatStencil_j,1) = j
5947: $ idxm(MatStencil_k,1) = k
5948: $ idxm(MatStencil_c,1) = c
5949: etc
5951: For periodic boundary conditions use negative indices for values to the left (below 0; that are to be
5952: obtained by wrapping values from right edge). For values to the right of the last entry using that index plus one
5953: etc to obtain values that obtained by wrapping the values from the left edge. This does not work for anything but the
5954: DM_BOUNDARY_PERIODIC boundary type.
5956: 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
5957: a single value per point) you can skip filling those indices.
5959: Level: intermediate
5961: .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsl(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
5962: MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
5963: @*/
5964: PetscErrorCode MatZeroRowsStencil(Mat mat,PetscInt numRows,const MatStencil rows[],PetscScalar diag,Vec x,Vec b)
5965: {
5966: PetscInt dim = mat->stencil.dim;
5967: PetscInt sdim = dim - (1 - (PetscInt) mat->stencil.noc);
5968: PetscInt *dims = mat->stencil.dims+1;
5969: PetscInt *starts = mat->stencil.starts;
5970: PetscInt *dxm = (PetscInt*) rows;
5971: PetscInt *jdxm, i, j, tmp, numNewRows = 0;
5979: PetscMalloc1(numRows, &jdxm);
5980: for (i = 0; i < numRows; ++i) {
5981: /* Skip unused dimensions (they are ordered k, j, i, c) */
5982: for (j = 0; j < 3-sdim; ++j) dxm++;
5983: /* Local index in X dir */
5984: tmp = *dxm++ - starts[0];
5985: /* Loop over remaining dimensions */
5986: for (j = 0; j < dim-1; ++j) {
5987: /* If nonlocal, set index to be negative */
5988: if ((*dxm++ - starts[j+1]) < 0 || tmp < 0) tmp = PETSC_MIN_INT;
5989: /* Update local index */
5990: else tmp = tmp*dims[j] + *(dxm-1) - starts[j+1];
5991: }
5992: /* Skip component slot if necessary */
5993: if (mat->stencil.noc) dxm++;
5994: /* Local row number */
5995: if (tmp >= 0) {
5996: jdxm[numNewRows++] = tmp;
5997: }
5998: }
5999: MatZeroRowsLocal(mat,numNewRows,jdxm,diag,x,b);
6000: PetscFree(jdxm);
6001: return(0);
6002: }
6004: /*@
6005: MatZeroRowsColumnsStencil - Zeros all row and column entries (except possibly the main diagonal)
6006: of a set of rows and columns of a matrix.
6008: Collective on Mat
6010: Input Parameters:
6011: + mat - the matrix
6012: . numRows - the number of rows/columns to remove
6013: . rows - the grid coordinates (and component number when dof > 1) for matrix rows
6014: . diag - value put in all diagonals of eliminated rows (0.0 will even eliminate diagonal entry)
6015: . x - optional vector of solutions for zeroed rows (other entries in vector are not used)
6016: - b - optional vector of right hand side, that will be adjusted by provided solution
6018: Notes:
6019: For the AIJ and BAIJ matrix formats this removes the old nonzero structure,
6020: but does not release memory. For the dense and block diagonal
6021: formats this does not alter the nonzero structure.
6023: If the option MatSetOption(mat,MAT_KEEP_NONZERO_PATTERN,PETSC_TRUE) the nonzero structure
6024: of the matrix is not changed (even for AIJ and BAIJ matrices) the values are
6025: merely zeroed.
6027: The user can set a value in the diagonal entry (or for the AIJ and
6028: row formats can optionally remove the main diagonal entry from the
6029: nonzero structure as well, by passing 0.0 as the final argument).
6031: For the parallel case, all processes that share the matrix (i.e.,
6032: those in the communicator used for matrix creation) MUST call this
6033: routine, regardless of whether any rows being zeroed are owned by
6034: them.
6036: Each processor can indicate any rows in the entire matrix to be zeroed (i.e. each process does NOT have to
6037: list only rows local to itself, but the row/column numbers are given in local numbering).
6039: The grid coordinates are across the entire grid, not just the local portion
6041: In Fortran idxm and idxn should be declared as
6042: $ MatStencil idxm(4,m)
6043: and the values inserted using
6044: $ idxm(MatStencil_i,1) = i
6045: $ idxm(MatStencil_j,1) = j
6046: $ idxm(MatStencil_k,1) = k
6047: $ idxm(MatStencil_c,1) = c
6048: etc
6050: For periodic boundary conditions use negative indices for values to the left (below 0; that are to be
6051: obtained by wrapping values from right edge). For values to the right of the last entry using that index plus one
6052: etc to obtain values that obtained by wrapping the values from the left edge. This does not work for anything but the
6053: DM_BOUNDARY_PERIODIC boundary type.
6055: 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
6056: a single value per point) you can skip filling those indices.
6058: Level: intermediate
6060: .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
6061: MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRows()
6062: @*/
6063: PetscErrorCode MatZeroRowsColumnsStencil(Mat mat,PetscInt numRows,const MatStencil rows[],PetscScalar diag,Vec x,Vec b)
6064: {
6065: PetscInt dim = mat->stencil.dim;
6066: PetscInt sdim = dim - (1 - (PetscInt) mat->stencil.noc);
6067: PetscInt *dims = mat->stencil.dims+1;
6068: PetscInt *starts = mat->stencil.starts;
6069: PetscInt *dxm = (PetscInt*) rows;
6070: PetscInt *jdxm, i, j, tmp, numNewRows = 0;
6078: PetscMalloc1(numRows, &jdxm);
6079: for (i = 0; i < numRows; ++i) {
6080: /* Skip unused dimensions (they are ordered k, j, i, c) */
6081: for (j = 0; j < 3-sdim; ++j) dxm++;
6082: /* Local index in X dir */
6083: tmp = *dxm++ - starts[0];
6084: /* Loop over remaining dimensions */
6085: for (j = 0; j < dim-1; ++j) {
6086: /* If nonlocal, set index to be negative */
6087: if ((*dxm++ - starts[j+1]) < 0 || tmp < 0) tmp = PETSC_MIN_INT;
6088: /* Update local index */
6089: else tmp = tmp*dims[j] + *(dxm-1) - starts[j+1];
6090: }
6091: /* Skip component slot if necessary */
6092: if (mat->stencil.noc) dxm++;
6093: /* Local row number */
6094: if (tmp >= 0) {
6095: jdxm[numNewRows++] = tmp;
6096: }
6097: }
6098: MatZeroRowsColumnsLocal(mat,numNewRows,jdxm,diag,x,b);
6099: PetscFree(jdxm);
6100: return(0);
6101: }
6103: /*@C
6104: MatZeroRowsLocal - Zeros all entries (except possibly the main diagonal)
6105: of a set of rows of a matrix; using local numbering of rows.
6107: Collective on Mat
6109: Input Parameters:
6110: + mat - the matrix
6111: . numRows - the number of rows to remove
6112: . rows - the global row indices
6113: . diag - value put in all diagonals of eliminated rows
6114: . x - optional vector of solutions for zeroed rows (other entries in vector are not used)
6115: - b - optional vector of right hand side, that will be adjusted by provided solution
6117: Notes:
6118: Before calling MatZeroRowsLocal(), the user must first set the
6119: local-to-global mapping by calling MatSetLocalToGlobalMapping().
6121: For the AIJ matrix formats this removes the old nonzero structure,
6122: but does not release memory. For the dense and block diagonal
6123: formats this does not alter the nonzero structure.
6125: If the option MatSetOption(mat,MAT_KEEP_NONZERO_PATTERN,PETSC_TRUE) the nonzero structure
6126: of the matrix is not changed (even for AIJ and BAIJ matrices) the values are
6127: merely zeroed.
6129: The user can set a value in the diagonal entry (or for the AIJ and
6130: row formats can optionally remove the main diagonal entry from the
6131: nonzero structure as well, by passing 0.0 as the final argument).
6133: You can call MatSetOption(mat,MAT_NO_OFF_PROC_ZERO_ROWS,PETSC_TRUE) if each process indicates only rows it
6134: owns that are to be zeroed. This saves a global synchronization in the implementation.
6136: Level: intermediate
6138: .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRows(), MatSetOption(),
6139: MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
6140: @*/
6141: PetscErrorCode MatZeroRowsLocal(Mat mat,PetscInt numRows,const PetscInt rows[],PetscScalar diag,Vec x,Vec b)
6142: {
6149: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6150: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6151: MatCheckPreallocated(mat,1);
6153: if (mat->ops->zerorowslocal) {
6154: (*mat->ops->zerorowslocal)(mat,numRows,rows,diag,x,b);
6155: } else {
6156: IS is, newis;
6157: const PetscInt *newRows;
6159: if (!mat->rmap->mapping) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Need to provide local to global mapping to matrix first");
6160: ISCreateGeneral(PETSC_COMM_SELF,numRows,rows,PETSC_COPY_VALUES,&is);
6161: ISLocalToGlobalMappingApplyIS(mat->rmap->mapping,is,&newis);
6162: ISGetIndices(newis,&newRows);
6163: (*mat->ops->zerorows)(mat,numRows,newRows,diag,x,b);
6164: ISRestoreIndices(newis,&newRows);
6165: ISDestroy(&newis);
6166: ISDestroy(&is);
6167: }
6168: PetscObjectStateIncrease((PetscObject)mat);
6169: return(0);
6170: }
6172: /*@
6173: MatZeroRowsLocalIS - Zeros all entries (except possibly the main diagonal)
6174: of a set of rows of a matrix; using local numbering of rows.
6176: Collective on Mat
6178: Input Parameters:
6179: + mat - the matrix
6180: . is - index set of rows to remove
6181: . diag - value put in all diagonals of eliminated rows
6182: . x - optional vector of solutions for zeroed rows (other entries in vector are not used)
6183: - b - optional vector of right hand side, that will be adjusted by provided solution
6185: Notes:
6186: Before calling MatZeroRowsLocalIS(), the user must first set the
6187: local-to-global mapping by calling MatSetLocalToGlobalMapping().
6189: For the AIJ matrix formats this removes the old nonzero structure,
6190: but does not release memory. For the dense and block diagonal
6191: formats this does not alter the nonzero structure.
6193: If the option MatSetOption(mat,MAT_KEEP_NONZERO_PATTERN,PETSC_TRUE) the nonzero structure
6194: of the matrix is not changed (even for AIJ and BAIJ matrices) the values are
6195: merely zeroed.
6197: The user can set a value in the diagonal entry (or for the AIJ and
6198: row formats can optionally remove the main diagonal entry from the
6199: nonzero structure as well, by passing 0.0 as the final argument).
6201: You can call MatSetOption(mat,MAT_NO_OFF_PROC_ZERO_ROWS,PETSC_TRUE) if each process indicates only rows it
6202: owns that are to be zeroed. This saves a global synchronization in the implementation.
6204: Level: intermediate
6206: .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRows(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
6207: MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
6208: @*/
6209: PetscErrorCode MatZeroRowsLocalIS(Mat mat,IS is,PetscScalar diag,Vec x,Vec b)
6210: {
6212: PetscInt numRows;
6213: const PetscInt *rows;
6219: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6220: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6221: MatCheckPreallocated(mat,1);
6223: ISGetLocalSize(is,&numRows);
6224: ISGetIndices(is,&rows);
6225: MatZeroRowsLocal(mat,numRows,rows,diag,x,b);
6226: ISRestoreIndices(is,&rows);
6227: return(0);
6228: }
6230: /*@
6231: MatZeroRowsColumnsLocal - Zeros all entries (except possibly the main diagonal)
6232: of a set of rows and columns of a matrix; using local numbering of rows.
6234: Collective on Mat
6236: Input Parameters:
6237: + mat - the matrix
6238: . numRows - the number of rows to remove
6239: . rows - the global row indices
6240: . diag - value put in all diagonals of eliminated rows
6241: . x - optional vector of solutions for zeroed rows (other entries in vector are not used)
6242: - b - optional vector of right hand side, that will be adjusted by provided solution
6244: Notes:
6245: Before calling MatZeroRowsColumnsLocal(), the user must first set the
6246: local-to-global mapping by calling MatSetLocalToGlobalMapping().
6248: The user can set a value in the diagonal entry (or for the AIJ and
6249: row formats can optionally remove the main diagonal entry from the
6250: nonzero structure as well, by passing 0.0 as the final argument).
6252: Level: intermediate
6254: .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
6255: MatZeroRows(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
6256: @*/
6257: PetscErrorCode MatZeroRowsColumnsLocal(Mat mat,PetscInt numRows,const PetscInt rows[],PetscScalar diag,Vec x,Vec b)
6258: {
6260: IS is, newis;
6261: const PetscInt *newRows;
6267: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6268: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6269: MatCheckPreallocated(mat,1);
6271: if (!mat->cmap->mapping) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Need to provide local to global mapping to matrix first");
6272: ISCreateGeneral(PETSC_COMM_SELF,numRows,rows,PETSC_COPY_VALUES,&is);
6273: ISLocalToGlobalMappingApplyIS(mat->cmap->mapping,is,&newis);
6274: ISGetIndices(newis,&newRows);
6275: (*mat->ops->zerorowscolumns)(mat,numRows,newRows,diag,x,b);
6276: ISRestoreIndices(newis,&newRows);
6277: ISDestroy(&newis);
6278: ISDestroy(&is);
6279: PetscObjectStateIncrease((PetscObject)mat);
6280: return(0);
6281: }
6283: /*@
6284: MatZeroRowsColumnsLocalIS - Zeros all entries (except possibly the main diagonal)
6285: of a set of rows and columns of a matrix; using local numbering of rows.
6287: Collective on Mat
6289: Input Parameters:
6290: + mat - the matrix
6291: . is - index set of rows to remove
6292: . diag - value put in all diagonals of eliminated rows
6293: . x - optional vector of solutions for zeroed rows (other entries in vector are not used)
6294: - b - optional vector of right hand side, that will be adjusted by provided solution
6296: Notes:
6297: Before calling MatZeroRowsColumnsLocalIS(), the user must first set the
6298: local-to-global mapping by calling MatSetLocalToGlobalMapping().
6300: The user can set a value in the diagonal entry (or for the AIJ and
6301: row formats can optionally remove the main diagonal entry from the
6302: nonzero structure as well, by passing 0.0 as the final argument).
6304: Level: intermediate
6306: .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
6307: MatZeroRowsColumnsLocal(), MatZeroRows(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
6308: @*/
6309: PetscErrorCode MatZeroRowsColumnsLocalIS(Mat mat,IS is,PetscScalar diag,Vec x,Vec b)
6310: {
6312: PetscInt numRows;
6313: const PetscInt *rows;
6319: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6320: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6321: MatCheckPreallocated(mat,1);
6323: ISGetLocalSize(is,&numRows);
6324: ISGetIndices(is,&rows);
6325: MatZeroRowsColumnsLocal(mat,numRows,rows,diag,x,b);
6326: ISRestoreIndices(is,&rows);
6327: return(0);
6328: }
6330: /*@C
6331: MatGetSize - Returns the numbers of rows and columns in a matrix.
6333: Not Collective
6335: Input Parameter:
6336: . mat - the matrix
6338: Output Parameters:
6339: + m - the number of global rows
6340: - n - the number of global columns
6342: Note: both output parameters can be NULL on input.
6344: Level: beginner
6346: .seealso: MatGetLocalSize()
6347: @*/
6348: PetscErrorCode MatGetSize(Mat mat,PetscInt *m,PetscInt *n)
6349: {
6352: if (m) *m = mat->rmap->N;
6353: if (n) *n = mat->cmap->N;
6354: return(0);
6355: }
6357: /*@C
6358: MatGetLocalSize - Returns the number of rows and columns in a matrix
6359: stored locally. This information may be implementation dependent, so
6360: use with care.
6362: Not Collective
6364: Input Parameters:
6365: . mat - the matrix
6367: Output Parameters:
6368: + m - the number of local rows
6369: - n - the number of local columns
6371: Note: both output parameters can be NULL on input.
6373: Level: beginner
6375: .seealso: MatGetSize()
6376: @*/
6377: PetscErrorCode MatGetLocalSize(Mat mat,PetscInt *m,PetscInt *n)
6378: {
6383: if (m) *m = mat->rmap->n;
6384: if (n) *n = mat->cmap->n;
6385: return(0);
6386: }
6388: /*@C
6389: MatGetOwnershipRangeColumn - Returns the range of matrix columns associated with rows of a vector one multiplies by that owned by
6390: this processor. (The columns of the "diagonal block")
6392: Not Collective, unless matrix has not been allocated, then collective on Mat
6394: Input Parameters:
6395: . mat - the matrix
6397: Output Parameters:
6398: + m - the global index of the first local column
6399: - n - one more than the global index of the last local column
6401: Notes:
6402: both output parameters can be NULL on input.
6404: Level: developer
6406: .seealso: MatGetOwnershipRange(), MatGetOwnershipRanges(), MatGetOwnershipRangesColumn()
6408: @*/
6409: PetscErrorCode MatGetOwnershipRangeColumn(Mat mat,PetscInt *m,PetscInt *n)
6410: {
6416: MatCheckPreallocated(mat,1);
6417: if (m) *m = mat->cmap->rstart;
6418: if (n) *n = mat->cmap->rend;
6419: return(0);
6420: }
6422: /*@C
6423: MatGetOwnershipRange - Returns the range of matrix rows owned by
6424: this processor, assuming that the matrix is laid out with the first
6425: n1 rows on the first processor, the next n2 rows on the second, etc.
6426: For certain parallel layouts this range may not be well defined.
6428: Not Collective
6430: Input Parameters:
6431: . mat - the matrix
6433: Output Parameters:
6434: + m - the global index of the first local row
6435: - n - one more than the global index of the last local row
6437: Note: Both output parameters can be NULL on input.
6438: $ This function requires that the matrix be preallocated. If you have not preallocated, consider using
6439: $ PetscSplitOwnership(MPI_Comm comm, PetscInt *n, PetscInt *N)
6440: $ and then MPI_Scan() to calculate prefix sums of the local sizes.
6442: Level: beginner
6444: .seealso: MatGetOwnershipRanges(), MatGetOwnershipRangeColumn(), MatGetOwnershipRangesColumn(), PetscSplitOwnership(), PetscSplitOwnershipBlock()
6446: @*/
6447: PetscErrorCode MatGetOwnershipRange(Mat mat,PetscInt *m,PetscInt *n)
6448: {
6454: MatCheckPreallocated(mat,1);
6455: if (m) *m = mat->rmap->rstart;
6456: if (n) *n = mat->rmap->rend;
6457: return(0);
6458: }
6460: /*@C
6461: MatGetOwnershipRanges - Returns the range of matrix rows owned by
6462: each process
6464: Not Collective, unless matrix has not been allocated, then collective on Mat
6466: Input Parameters:
6467: . mat - the matrix
6469: Output Parameters:
6470: . ranges - start of each processors portion plus one more than the total length at the end
6472: Level: beginner
6474: .seealso: MatGetOwnershipRange(), MatGetOwnershipRangeColumn(), MatGetOwnershipRangesColumn()
6476: @*/
6477: PetscErrorCode MatGetOwnershipRanges(Mat mat,const PetscInt **ranges)
6478: {
6484: MatCheckPreallocated(mat,1);
6485: PetscLayoutGetRanges(mat->rmap,ranges);
6486: return(0);
6487: }
6489: /*@C
6490: MatGetOwnershipRangesColumn - Returns the range of matrix columns associated with rows of a vector one multiplies by that owned by
6491: this processor. (The columns of the "diagonal blocks" for each process)
6493: Not Collective, unless matrix has not been allocated, then collective on Mat
6495: Input Parameters:
6496: . mat - the matrix
6498: Output Parameters:
6499: . ranges - start of each processors portion plus one more then the total length at the end
6501: Level: beginner
6503: .seealso: MatGetOwnershipRange(), MatGetOwnershipRangeColumn(), MatGetOwnershipRanges()
6505: @*/
6506: PetscErrorCode MatGetOwnershipRangesColumn(Mat mat,const PetscInt **ranges)
6507: {
6513: MatCheckPreallocated(mat,1);
6514: PetscLayoutGetRanges(mat->cmap,ranges);
6515: return(0);
6516: }
6518: /*@C
6519: MatGetOwnershipIS - Get row and column ownership as index sets
6521: Not Collective
6523: Input Arguments:
6524: . A - matrix of type Elemental
6526: Output Arguments:
6527: + rows - rows in which this process owns elements
6528: - cols - columns in which this process owns elements
6530: Level: intermediate
6532: .seealso: MatGetOwnershipRange(), MatGetOwnershipRangeColumn(), MatSetValues(), MATELEMENTAL
6533: @*/
6534: PetscErrorCode MatGetOwnershipIS(Mat A,IS *rows,IS *cols)
6535: {
6536: PetscErrorCode ierr,(*f)(Mat,IS*,IS*);
6539: MatCheckPreallocated(A,1);
6540: PetscObjectQueryFunction((PetscObject)A,"MatGetOwnershipIS_C",&f);
6541: if (f) {
6542: (*f)(A,rows,cols);
6543: } else { /* Create a standard row-based partition, each process is responsible for ALL columns in their row block */
6544: if (rows) {ISCreateStride(PETSC_COMM_SELF,A->rmap->n,A->rmap->rstart,1,rows);}
6545: if (cols) {ISCreateStride(PETSC_COMM_SELF,A->cmap->N,0,1,cols);}
6546: }
6547: return(0);
6548: }
6550: /*@C
6551: MatILUFactorSymbolic - Performs symbolic ILU factorization of a matrix.
6552: Uses levels of fill only, not drop tolerance. Use MatLUFactorNumeric()
6553: to complete the factorization.
6555: Collective on Mat
6557: Input Parameters:
6558: + mat - the matrix
6559: . row - row permutation
6560: . column - column permutation
6561: - info - structure containing
6562: $ levels - number of levels of fill.
6563: $ expected fill - as ratio of original fill.
6564: $ 1 or 0 - indicating force fill on diagonal (improves robustness for matrices
6565: missing diagonal entries)
6567: Output Parameters:
6568: . fact - new matrix that has been symbolically factored
6570: Notes:
6571: See Users-Manual: ch_mat for additional information about choosing the fill factor for better efficiency.
6573: Most users should employ the simplified KSP interface for linear solvers
6574: instead of working directly with matrix algebra routines such as this.
6575: See, e.g., KSPCreate().
6577: Level: developer
6579: .seealso: MatLUFactorSymbolic(), MatLUFactorNumeric(), MatCholeskyFactor()
6580: MatGetOrdering(), MatFactorInfo
6582: Note: this uses the definition of level of fill as in Y. Saad, 2003
6584: Developer Note: fortran interface is not autogenerated as the f90
6585: interface defintion cannot be generated correctly [due to MatFactorInfo]
6587: References:
6588: Y. Saad, Iterative methods for sparse linear systems Philadelphia: Society for Industrial and Applied Mathematics, 2003
6589: @*/
6590: PetscErrorCode MatILUFactorSymbolic(Mat fact,Mat mat,IS row,IS col,const MatFactorInfo *info)
6591: {
6601: if (info->levels < 0) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_OUTOFRANGE,"Levels of fill negative %D",(PetscInt)info->levels);
6602: if (info->fill < 1.0) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_OUTOFRANGE,"Expected fill less than 1.0 %g",(double)info->fill);
6603: if (!(fact)->ops->ilufactorsymbolic) {
6604: MatSolverType spackage;
6605: MatFactorGetSolverType(fact,&spackage);
6606: SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Matrix type %s symbolic ILU using solver package %s",((PetscObject)mat)->type_name,spackage);
6607: }
6608: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6609: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6610: MatCheckPreallocated(mat,2);
6612: PetscLogEventBegin(MAT_ILUFactorSymbolic,mat,row,col,0);
6613: (fact->ops->ilufactorsymbolic)(fact,mat,row,col,info);
6614: PetscLogEventEnd(MAT_ILUFactorSymbolic,mat,row,col,0);
6615: return(0);
6616: }
6618: /*@C
6619: MatICCFactorSymbolic - Performs symbolic incomplete
6620: Cholesky factorization for a symmetric matrix. Use
6621: MatCholeskyFactorNumeric() to complete the factorization.
6623: Collective on Mat
6625: Input Parameters:
6626: + mat - the matrix
6627: . perm - row and column permutation
6628: - info - structure containing
6629: $ levels - number of levels of fill.
6630: $ expected fill - as ratio of original fill.
6632: Output Parameter:
6633: . fact - the factored matrix
6635: Notes:
6636: Most users should employ the KSP interface for linear solvers
6637: instead of working directly with matrix algebra routines such as this.
6638: See, e.g., KSPCreate().
6640: Level: developer
6642: .seealso: MatCholeskyFactorNumeric(), MatCholeskyFactor(), MatFactorInfo
6644: Note: this uses the definition of level of fill as in Y. Saad, 2003
6646: Developer Note: fortran interface is not autogenerated as the f90
6647: interface defintion cannot be generated correctly [due to MatFactorInfo]
6649: References:
6650: Y. Saad, Iterative methods for sparse linear systems Philadelphia: Society for Industrial and Applied Mathematics, 2003
6651: @*/
6652: PetscErrorCode MatICCFactorSymbolic(Mat fact,Mat mat,IS perm,const MatFactorInfo *info)
6653: {
6662: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6663: if (info->levels < 0) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_OUTOFRANGE,"Levels negative %D",(PetscInt) info->levels);
6664: if (info->fill < 1.0) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_OUTOFRANGE,"Expected fill less than 1.0 %g",(double)info->fill);
6665: if (!(fact)->ops->iccfactorsymbolic) {
6666: MatSolverType spackage;
6667: MatFactorGetSolverType(fact,&spackage);
6668: SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Matrix type %s symbolic ICC using solver package %s",((PetscObject)mat)->type_name,spackage);
6669: }
6670: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6671: MatCheckPreallocated(mat,2);
6673: PetscLogEventBegin(MAT_ICCFactorSymbolic,mat,perm,0,0);
6674: (fact->ops->iccfactorsymbolic)(fact,mat,perm,info);
6675: PetscLogEventEnd(MAT_ICCFactorSymbolic,mat,perm,0,0);
6676: return(0);
6677: }
6679: /*@C
6680: MatCreateSubMatrices - Extracts several submatrices from a matrix. If submat
6681: points to an array of valid matrices, they may be reused to store the new
6682: submatrices.
6684: Collective on Mat
6686: Input Parameters:
6687: + mat - the matrix
6688: . n - the number of submatrixes to be extracted (on this processor, may be zero)
6689: . irow, icol - index sets of rows and columns to extract
6690: - scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
6692: Output Parameter:
6693: . submat - the array of submatrices
6695: Notes:
6696: MatCreateSubMatrices() can extract ONLY sequential submatrices
6697: (from both sequential and parallel matrices). Use MatCreateSubMatrix()
6698: to extract a parallel submatrix.
6700: Some matrix types place restrictions on the row and column
6701: indices, such as that they be sorted or that they be equal to each other.
6703: The index sets may not have duplicate entries.
6705: When extracting submatrices from a parallel matrix, each processor can
6706: form a different submatrix by setting the rows and columns of its
6707: individual index sets according to the local submatrix desired.
6709: When finished using the submatrices, the user should destroy
6710: them with MatDestroySubMatrices().
6712: MAT_REUSE_MATRIX can only be used when the nonzero structure of the
6713: original matrix has not changed from that last call to MatCreateSubMatrices().
6715: This routine creates the matrices in submat; you should NOT create them before
6716: calling it. It also allocates the array of matrix pointers submat.
6718: For BAIJ matrices the index sets must respect the block structure, that is if they
6719: request one row/column in a block, they must request all rows/columns that are in
6720: that block. For example, if the block size is 2 you cannot request just row 0 and
6721: column 0.
6723: Fortran Note:
6724: The Fortran interface is slightly different from that given below; it
6725: requires one to pass in as submat a Mat (integer) array of size at least n+1.
6727: Level: advanced
6730: .seealso: MatDestroySubMatrices(), MatCreateSubMatrix(), MatGetRow(), MatGetDiagonal(), MatReuse
6731: @*/
6732: PetscErrorCode MatCreateSubMatrices(Mat mat,PetscInt n,const IS irow[],const IS icol[],MatReuse scall,Mat *submat[])
6733: {
6735: PetscInt i;
6736: PetscBool eq;
6741: if (n) {
6746: }
6748: if (n && scall == MAT_REUSE_MATRIX) {
6751: }
6752: if (!mat->ops->createsubmatrices) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
6753: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6754: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6755: MatCheckPreallocated(mat,1);
6757: PetscLogEventBegin(MAT_CreateSubMats,mat,0,0,0);
6758: (*mat->ops->createsubmatrices)(mat,n,irow,icol,scall,submat);
6759: PetscLogEventEnd(MAT_CreateSubMats,mat,0,0,0);
6760: for (i=0; i<n; i++) {
6761: (*submat)[i]->factortype = MAT_FACTOR_NONE; /* in case in place factorization was previously done on submatrix */
6762: ISEqualUnsorted(irow[i],icol[i],&eq);
6763: if (eq) {
6764: MatPropagateSymmetryOptions(mat,(*submat)[i]);
6765: }
6766: }
6767: return(0);
6768: }
6770: /*@C
6771: MatCreateSubMatricesMPI - Extracts MPI submatrices across a sub communicator of mat (by pairs of IS that may live on subcomms).
6773: Collective on Mat
6775: Input Parameters:
6776: + mat - the matrix
6777: . n - the number of submatrixes to be extracted
6778: . irow, icol - index sets of rows and columns to extract
6779: - scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
6781: Output Parameter:
6782: . submat - the array of submatrices
6784: Level: advanced
6787: .seealso: MatCreateSubMatrices(), MatCreateSubMatrix(), MatGetRow(), MatGetDiagonal(), MatReuse
6788: @*/
6789: PetscErrorCode MatCreateSubMatricesMPI(Mat mat,PetscInt n,const IS irow[],const IS icol[],MatReuse scall,Mat *submat[])
6790: {
6792: PetscInt i;
6793: PetscBool eq;
6798: if (n) {
6803: }
6805: if (n && scall == MAT_REUSE_MATRIX) {
6808: }
6809: if (!mat->ops->createsubmatricesmpi) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
6810: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6811: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6812: MatCheckPreallocated(mat,1);
6814: PetscLogEventBegin(MAT_CreateSubMats,mat,0,0,0);
6815: (*mat->ops->createsubmatricesmpi)(mat,n,irow,icol,scall,submat);
6816: PetscLogEventEnd(MAT_CreateSubMats,mat,0,0,0);
6817: for (i=0; i<n; i++) {
6818: ISEqualUnsorted(irow[i],icol[i],&eq);
6819: if (eq) {
6820: MatPropagateSymmetryOptions(mat,(*submat)[i]);
6821: }
6822: }
6823: return(0);
6824: }
6826: /*@C
6827: MatDestroyMatrices - Destroys an array of matrices.
6829: Collective on Mat
6831: Input Parameters:
6832: + n - the number of local matrices
6833: - mat - the matrices (note that this is a pointer to the array of matrices)
6835: Level: advanced
6837: Notes:
6838: Frees not only the matrices, but also the array that contains the matrices
6839: In Fortran will not free the array.
6841: .seealso: MatCreateSubMatrices() MatDestroySubMatrices()
6842: @*/
6843: PetscErrorCode MatDestroyMatrices(PetscInt n,Mat *mat[])
6844: {
6846: PetscInt i;
6849: if (!*mat) return(0);
6850: if (n < 0) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Trying to destroy negative number of matrices %D",n);
6853: for (i=0; i<n; i++) {
6854: MatDestroy(&(*mat)[i]);
6855: }
6857: /* memory is allocated even if n = 0 */
6858: PetscFree(*mat);
6859: return(0);
6860: }
6862: /*@C
6863: MatDestroySubMatrices - Destroys a set of matrices obtained with MatCreateSubMatrices().
6865: Collective on Mat
6867: Input Parameters:
6868: + n - the number of local matrices
6869: - mat - the matrices (note that this is a pointer to the array of matrices, just to match the calling
6870: sequence of MatCreateSubMatrices())
6872: Level: advanced
6874: Notes:
6875: Frees not only the matrices, but also the array that contains the matrices
6876: In Fortran will not free the array.
6878: .seealso: MatCreateSubMatrices()
6879: @*/
6880: PetscErrorCode MatDestroySubMatrices(PetscInt n,Mat *mat[])
6881: {
6883: Mat mat0;
6886: if (!*mat) return(0);
6887: /* mat[] is an array of length n+1, see MatCreateSubMatrices_xxx() */
6888: if (n < 0) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Trying to destroy negative number of matrices %D",n);
6891: mat0 = (*mat)[0];
6892: if (mat0 && mat0->ops->destroysubmatrices) {
6893: (mat0->ops->destroysubmatrices)(n,mat);
6894: } else {
6895: MatDestroyMatrices(n,mat);
6896: }
6897: return(0);
6898: }
6900: /*@C
6901: MatGetSeqNonzeroStructure - Extracts the sequential nonzero structure from a matrix.
6903: Collective on Mat
6905: Input Parameters:
6906: . mat - the matrix
6908: Output Parameter:
6909: . matstruct - the sequential matrix with the nonzero structure of mat
6911: Level: intermediate
6913: .seealso: MatDestroySeqNonzeroStructure(), MatCreateSubMatrices(), MatDestroyMatrices()
6914: @*/
6915: PetscErrorCode MatGetSeqNonzeroStructure(Mat mat,Mat *matstruct)
6916: {
6924: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6925: MatCheckPreallocated(mat,1);
6927: if (!mat->ops->getseqnonzerostructure) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Not for matrix type %s\n",((PetscObject)mat)->type_name);
6928: PetscLogEventBegin(MAT_GetSeqNonzeroStructure,mat,0,0,0);
6929: (*mat->ops->getseqnonzerostructure)(mat,matstruct);
6930: PetscLogEventEnd(MAT_GetSeqNonzeroStructure,mat,0,0,0);
6931: return(0);
6932: }
6934: /*@C
6935: MatDestroySeqNonzeroStructure - Destroys matrix obtained with MatGetSeqNonzeroStructure().
6937: Collective on Mat
6939: Input Parameters:
6940: . mat - the matrix (note that this is a pointer to the array of matrices, just to match the calling
6941: sequence of MatGetSequentialNonzeroStructure())
6943: Level: advanced
6945: Notes:
6946: Frees not only the matrices, but also the array that contains the matrices
6948: .seealso: MatGetSeqNonzeroStructure()
6949: @*/
6950: PetscErrorCode MatDestroySeqNonzeroStructure(Mat *mat)
6951: {
6956: MatDestroy(mat);
6957: return(0);
6958: }
6960: /*@
6961: MatIncreaseOverlap - Given a set of submatrices indicated by index sets,
6962: replaces the index sets by larger ones that represent submatrices with
6963: additional overlap.
6965: Collective on Mat
6967: Input Parameters:
6968: + mat - the matrix
6969: . n - the number of index sets
6970: . is - the array of index sets (these index sets will changed during the call)
6971: - ov - the additional overlap requested
6973: Options Database:
6974: . -mat_increase_overlap_scalable - use a scalable algorithm to compute the overlap (supported by MPIAIJ matrix)
6976: Level: developer
6979: .seealso: MatCreateSubMatrices()
6980: @*/
6981: PetscErrorCode MatIncreaseOverlap(Mat mat,PetscInt n,IS is[],PetscInt ov)
6982: {
6988: if (n < 0) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Must have one or more domains, you have %D",n);
6989: if (n) {
6992: }
6993: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6994: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6995: MatCheckPreallocated(mat,1);
6997: if (!ov) return(0);
6998: if (!mat->ops->increaseoverlap) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
6999: PetscLogEventBegin(MAT_IncreaseOverlap,mat,0,0,0);
7000: (*mat->ops->increaseoverlap)(mat,n,is,ov);
7001: PetscLogEventEnd(MAT_IncreaseOverlap,mat,0,0,0);
7002: return(0);
7003: }
7006: PetscErrorCode MatIncreaseOverlapSplit_Single(Mat,IS*,PetscInt);
7008: /*@
7009: MatIncreaseOverlapSplit - Given a set of submatrices indicated by index sets across
7010: a sub communicator, replaces the index sets by larger ones that represent submatrices with
7011: additional overlap.
7013: Collective on Mat
7015: Input Parameters:
7016: + mat - the matrix
7017: . n - the number of index sets
7018: . is - the array of index sets (these index sets will changed during the call)
7019: - ov - the additional overlap requested
7021: Options Database:
7022: . -mat_increase_overlap_scalable - use a scalable algorithm to compute the overlap (supported by MPIAIJ matrix)
7024: Level: developer
7027: .seealso: MatCreateSubMatrices()
7028: @*/
7029: PetscErrorCode MatIncreaseOverlapSplit(Mat mat,PetscInt n,IS is[],PetscInt ov)
7030: {
7031: PetscInt i;
7037: if (n < 0) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Must have one or more domains, you have %D",n);
7038: if (n) {
7041: }
7042: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
7043: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
7044: MatCheckPreallocated(mat,1);
7045: if (!ov) return(0);
7046: PetscLogEventBegin(MAT_IncreaseOverlap,mat,0,0,0);
7047: for(i=0; i<n; i++){
7048: MatIncreaseOverlapSplit_Single(mat,&is[i],ov);
7049: }
7050: PetscLogEventEnd(MAT_IncreaseOverlap,mat,0,0,0);
7051: return(0);
7052: }
7057: /*@
7058: MatGetBlockSize - Returns the matrix block size.
7060: Not Collective
7062: Input Parameter:
7063: . mat - the matrix
7065: Output Parameter:
7066: . bs - block size
7068: Notes:
7069: Block row formats are MATSEQBAIJ, MATMPIBAIJ, MATSEQSBAIJ, MATMPISBAIJ. These formats ALWAYS have square block storage in the matrix.
7071: If the block size has not been set yet this routine returns 1.
7073: Level: intermediate
7075: .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSizes()
7076: @*/
7077: PetscErrorCode MatGetBlockSize(Mat mat,PetscInt *bs)
7078: {
7082: *bs = PetscAbs(mat->rmap->bs);
7083: return(0);
7084: }
7086: /*@
7087: MatGetBlockSizes - Returns the matrix block row and column sizes.
7089: Not Collective
7091: Input Parameter:
7092: . mat - the matrix
7094: Output Parameter:
7095: + rbs - row block size
7096: - cbs - column block size
7098: Notes:
7099: Block row formats are MATSEQBAIJ, MATMPIBAIJ, MATSEQSBAIJ, MATMPISBAIJ. These formats ALWAYS have square block storage in the matrix.
7100: If you pass a different block size for the columns than the rows, the row block size determines the square block storage.
7102: If a block size has not been set yet this routine returns 1.
7104: Level: intermediate
7106: .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSize(), MatSetBlockSize(), MatSetBlockSizes()
7107: @*/
7108: PetscErrorCode MatGetBlockSizes(Mat mat,PetscInt *rbs, PetscInt *cbs)
7109: {
7114: if (rbs) *rbs = PetscAbs(mat->rmap->bs);
7115: if (cbs) *cbs = PetscAbs(mat->cmap->bs);
7116: return(0);
7117: }
7119: /*@
7120: MatSetBlockSize - Sets the matrix block size.
7122: Logically Collective on Mat
7124: Input Parameters:
7125: + mat - the matrix
7126: - bs - block size
7128: Notes:
7129: Block row formats are MATSEQBAIJ, MATMPIBAIJ, MATSEQSBAIJ, MATMPISBAIJ. These formats ALWAYS have square block storage in the matrix.
7130: This must be called before MatSetUp() or MatXXXSetPreallocation() (or will default to 1) and the block size cannot be changed later.
7132: For MATMPIAIJ and MATSEQAIJ matrix formats, this function can be called at a later stage, provided that the specified block size
7133: is compatible with the matrix local sizes.
7135: Level: intermediate
7137: .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSize(), MatSetBlockSizes(), MatGetBlockSizes()
7138: @*/
7139: PetscErrorCode MatSetBlockSize(Mat mat,PetscInt bs)
7140: {
7146: MatSetBlockSizes(mat,bs,bs);
7147: return(0);
7148: }
7150: /*@
7151: MatSetVariableBlockSizes - Sets a diagonal blocks of the matrix that need not be of the same size
7153: Logically Collective on Mat
7155: Input Parameters:
7156: + mat - the matrix
7157: . nblocks - the number of blocks on this process
7158: - bsizes - the block sizes
7160: Notes:
7161: Currently used by PCVPBJACOBI for SeqAIJ matrices
7163: Level: intermediate
7165: .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSize(), MatSetBlockSizes(), MatGetBlockSizes(), MatGetVariableBlockSizes()
7166: @*/
7167: PetscErrorCode MatSetVariableBlockSizes(Mat mat,PetscInt nblocks,PetscInt *bsizes)
7168: {
7170: PetscInt i,ncnt = 0, nlocal;
7174: if (nblocks < 0) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Number of local blocks must be great than or equal to zero");
7175: MatGetLocalSize(mat,&nlocal,NULL);
7176: for (i=0; i<nblocks; i++) ncnt += bsizes[i];
7177: if (ncnt != nlocal) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Sum of local block sizes %D does not equal local size of matrix %D",ncnt,nlocal);
7178: PetscFree(mat->bsizes);
7179: mat->nblocks = nblocks;
7180: PetscMalloc1(nblocks,&mat->bsizes);
7181: PetscArraycpy(mat->bsizes,bsizes,nblocks);
7182: return(0);
7183: }
7185: /*@C
7186: MatGetVariableBlockSizes - Gets a diagonal blocks of the matrix that need not be of the same size
7188: Logically Collective on Mat
7190: Input Parameters:
7191: . mat - the matrix
7193: Output Parameters:
7194: + nblocks - the number of blocks on this process
7195: - bsizes - the block sizes
7197: Notes: Currently not supported from Fortran
7199: Level: intermediate
7201: .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSize(), MatSetBlockSizes(), MatGetBlockSizes(), MatSetVariableBlockSizes()
7202: @*/
7203: PetscErrorCode MatGetVariableBlockSizes(Mat mat,PetscInt *nblocks,const PetscInt **bsizes)
7204: {
7207: *nblocks = mat->nblocks;
7208: *bsizes = mat->bsizes;
7209: return(0);
7210: }
7212: /*@
7213: MatSetBlockSizes - Sets the matrix block row and column sizes.
7215: Logically Collective on Mat
7217: Input Parameters:
7218: + mat - the matrix
7219: . rbs - row block size
7220: - cbs - column block size
7222: Notes:
7223: Block row formats are MATSEQBAIJ, MATMPIBAIJ, MATSEQSBAIJ, MATMPISBAIJ. These formats ALWAYS have square block storage in the matrix.
7224: If you pass a different block size for the columns than the rows, the row block size determines the square block storage.
7225: This must be called before MatSetUp() or MatXXXSetPreallocation() (or will default to 1) and the block size cannot be changed later.
7227: For MATMPIAIJ and MATSEQAIJ matrix formats, this function can be called at a later stage, provided that the specified block sizes
7228: are compatible with the matrix local sizes.
7230: The row and column block size determine the blocksize of the "row" and "column" vectors returned by MatCreateVecs().
7232: Level: intermediate
7234: .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSize(), MatSetBlockSize(), MatGetBlockSizes()
7235: @*/
7236: PetscErrorCode MatSetBlockSizes(Mat mat,PetscInt rbs,PetscInt cbs)
7237: {
7244: if (mat->ops->setblocksizes) {
7245: (*mat->ops->setblocksizes)(mat,rbs,cbs);
7246: }
7247: if (mat->rmap->refcnt) {
7248: ISLocalToGlobalMapping l2g = NULL;
7249: PetscLayout nmap = NULL;
7251: PetscLayoutDuplicate(mat->rmap,&nmap);
7252: if (mat->rmap->mapping) {
7253: ISLocalToGlobalMappingDuplicate(mat->rmap->mapping,&l2g);
7254: }
7255: PetscLayoutDestroy(&mat->rmap);
7256: mat->rmap = nmap;
7257: mat->rmap->mapping = l2g;
7258: }
7259: if (mat->cmap->refcnt) {
7260: ISLocalToGlobalMapping l2g = NULL;
7261: PetscLayout nmap = NULL;
7263: PetscLayoutDuplicate(mat->cmap,&nmap);
7264: if (mat->cmap->mapping) {
7265: ISLocalToGlobalMappingDuplicate(mat->cmap->mapping,&l2g);
7266: }
7267: PetscLayoutDestroy(&mat->cmap);
7268: mat->cmap = nmap;
7269: mat->cmap->mapping = l2g;
7270: }
7271: PetscLayoutSetBlockSize(mat->rmap,rbs);
7272: PetscLayoutSetBlockSize(mat->cmap,cbs);
7273: return(0);
7274: }
7276: /*@
7277: MatSetBlockSizesFromMats - Sets the matrix block row and column sizes to match a pair of matrices
7279: Logically Collective on Mat
7281: Input Parameters:
7282: + mat - the matrix
7283: . fromRow - matrix from which to copy row block size
7284: - fromCol - matrix from which to copy column block size (can be same as fromRow)
7286: Level: developer
7288: .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSize(), MatSetBlockSizes()
7289: @*/
7290: PetscErrorCode MatSetBlockSizesFromMats(Mat mat,Mat fromRow,Mat fromCol)
7291: {
7298: if (fromRow->rmap->bs > 0) {PetscLayoutSetBlockSize(mat->rmap,fromRow->rmap->bs);}
7299: if (fromCol->cmap->bs > 0) {PetscLayoutSetBlockSize(mat->cmap,fromCol->cmap->bs);}
7300: return(0);
7301: }
7303: /*@
7304: MatResidual - Default routine to calculate the residual.
7306: Collective on Mat
7308: Input Parameters:
7309: + mat - the matrix
7310: . b - the right-hand-side
7311: - x - the approximate solution
7313: Output Parameter:
7314: . r - location to store the residual
7316: Level: developer
7318: .seealso: PCMGSetResidual()
7319: @*/
7320: PetscErrorCode MatResidual(Mat mat,Vec b,Vec x,Vec r)
7321: {
7330: MatCheckPreallocated(mat,1);
7331: PetscLogEventBegin(MAT_Residual,mat,0,0,0);
7332: if (!mat->ops->residual) {
7333: MatMult(mat,x,r);
7334: VecAYPX(r,-1.0,b);
7335: } else {
7336: (*mat->ops->residual)(mat,b,x,r);
7337: }
7338: PetscLogEventEnd(MAT_Residual,mat,0,0,0);
7339: return(0);
7340: }
7342: /*@C
7343: MatGetRowIJ - Returns the compressed row storage i and j indices for sequential matrices.
7345: Collective on Mat
7347: Input Parameters:
7348: + mat - the matrix
7349: . shift - 0 or 1 indicating we want the indices starting at 0 or 1
7350: . symmetric - PETSC_TRUE or PETSC_FALSE indicating the matrix data structure should be symmetrized
7351: - inodecompressed - PETSC_TRUE or PETSC_FALSE indicating if the nonzero structure of the
7352: inodes or the nonzero elements is wanted. For BAIJ matrices the compressed version is
7353: always used.
7355: Output Parameters:
7356: + n - number of rows in the (possibly compressed) matrix
7357: . ia - the row pointers; that is ia[0] = 0, ia[row] = ia[row-1] + number of elements in that row of the matrix
7358: . ja - the column indices
7359: - done - indicates if the routine actually worked and returned appropriate ia[] and ja[] arrays; callers
7360: are responsible for handling the case when done == PETSC_FALSE and ia and ja are not set
7362: Level: developer
7364: Notes:
7365: You CANNOT change any of the ia[] or ja[] values.
7367: Use MatRestoreRowIJ() when you are finished accessing the ia[] and ja[] values.
7369: Fortran Notes:
7370: In Fortran use
7371: $
7372: $ PetscInt ia(1), ja(1)
7373: $ PetscOffset iia, jja
7374: $ call MatGetRowIJ(mat,shift,symmetric,inodecompressed,n,ia,iia,ja,jja,done,ierr)
7375: $ ! Access the ith and jth entries via ia(iia + i) and ja(jja + j)
7377: or
7378: $
7379: $ PetscInt, pointer :: ia(:),ja(:)
7380: $ call MatGetRowIJF90(mat,shift,symmetric,inodecompressed,n,ia,ja,done,ierr)
7381: $ ! Access the ith and jth entries via ia(i) and ja(j)
7383: .seealso: MatGetColumnIJ(), MatRestoreRowIJ(), MatSeqAIJGetArray()
7384: @*/
7385: PetscErrorCode MatGetRowIJ(Mat mat,PetscInt shift,PetscBool symmetric,PetscBool inodecompressed,PetscInt *n,const PetscInt *ia[],const PetscInt *ja[],PetscBool *done)
7386: {
7396: MatCheckPreallocated(mat,1);
7397: if (!mat->ops->getrowij) *done = PETSC_FALSE;
7398: else {
7399: *done = PETSC_TRUE;
7400: PetscLogEventBegin(MAT_GetRowIJ,mat,0,0,0);
7401: (*mat->ops->getrowij)(mat,shift,symmetric,inodecompressed,n,ia,ja,done);
7402: PetscLogEventEnd(MAT_GetRowIJ,mat,0,0,0);
7403: }
7404: return(0);
7405: }
7407: /*@C
7408: MatGetColumnIJ - Returns the compressed column storage i and j indices for sequential matrices.
7410: Collective on Mat
7412: Input Parameters:
7413: + mat - the matrix
7414: . shift - 1 or zero indicating we want the indices starting at 0 or 1
7415: . symmetric - PETSC_TRUE or PETSC_FALSE indicating the matrix data structure should be
7416: symmetrized
7417: . inodecompressed - PETSC_TRUE or PETSC_FALSE indicating if the nonzero structure of the
7418: inodes or the nonzero elements is wanted. For BAIJ matrices the compressed version is
7419: always used.
7420: . n - number of columns in the (possibly compressed) matrix
7421: . ia - the column pointers; that is ia[0] = 0, ia[col] = i[col-1] + number of elements in that col of the matrix
7422: - ja - the row indices
7424: Output Parameters:
7425: . done - PETSC_TRUE or PETSC_FALSE, indicating whether the values have been returned
7427: Level: developer
7429: .seealso: MatGetRowIJ(), MatRestoreColumnIJ()
7430: @*/
7431: PetscErrorCode MatGetColumnIJ(Mat mat,PetscInt shift,PetscBool symmetric,PetscBool inodecompressed,PetscInt *n,const PetscInt *ia[],const PetscInt *ja[],PetscBool *done)
7432: {
7442: MatCheckPreallocated(mat,1);
7443: if (!mat->ops->getcolumnij) *done = PETSC_FALSE;
7444: else {
7445: *done = PETSC_TRUE;
7446: (*mat->ops->getcolumnij)(mat,shift,symmetric,inodecompressed,n,ia,ja,done);
7447: }
7448: return(0);
7449: }
7451: /*@C
7452: MatRestoreRowIJ - Call after you are completed with the ia,ja indices obtained with
7453: MatGetRowIJ().
7455: Collective on Mat
7457: Input Parameters:
7458: + mat - the matrix
7459: . shift - 1 or zero indicating we want the indices starting at 0 or 1
7460: . symmetric - PETSC_TRUE or PETSC_FALSE indicating the matrix data structure should be
7461: symmetrized
7462: . inodecompressed - PETSC_TRUE or PETSC_FALSE indicating if the nonzero structure of the
7463: inodes or the nonzero elements is wanted. For BAIJ matrices the compressed version is
7464: always used.
7465: . n - size of (possibly compressed) matrix
7466: . ia - the row pointers
7467: - ja - the column indices
7469: Output Parameters:
7470: . done - PETSC_TRUE or PETSC_FALSE indicated that the values have been returned
7472: Note:
7473: This routine zeros out n, ia, and ja. This is to prevent accidental
7474: us of the array after it has been restored. If you pass NULL, it will
7475: not zero the pointers. Use of ia or ja after MatRestoreRowIJ() is invalid.
7477: Level: developer
7479: .seealso: MatGetRowIJ(), MatRestoreColumnIJ()
7480: @*/
7481: PetscErrorCode MatRestoreRowIJ(Mat mat,PetscInt shift,PetscBool symmetric,PetscBool inodecompressed,PetscInt *n,const PetscInt *ia[],const PetscInt *ja[],PetscBool *done)
7482: {
7491: MatCheckPreallocated(mat,1);
7493: if (!mat->ops->restorerowij) *done = PETSC_FALSE;
7494: else {
7495: *done = PETSC_TRUE;
7496: (*mat->ops->restorerowij)(mat,shift,symmetric,inodecompressed,n,ia,ja,done);
7497: if (n) *n = 0;
7498: if (ia) *ia = NULL;
7499: if (ja) *ja = NULL;
7500: }
7501: return(0);
7502: }
7504: /*@C
7505: MatRestoreColumnIJ - Call after you are completed with the ia,ja indices obtained with
7506: MatGetColumnIJ().
7508: Collective on Mat
7510: Input Parameters:
7511: + mat - the matrix
7512: . shift - 1 or zero indicating we want the indices starting at 0 or 1
7513: - symmetric - PETSC_TRUE or PETSC_FALSE indicating the matrix data structure should be
7514: symmetrized
7515: - inodecompressed - PETSC_TRUE or PETSC_FALSE indicating if the nonzero structure of the
7516: inodes or the nonzero elements is wanted. For BAIJ matrices the compressed version is
7517: always used.
7519: Output Parameters:
7520: + n - size of (possibly compressed) matrix
7521: . ia - the column pointers
7522: . ja - the row indices
7523: - done - PETSC_TRUE or PETSC_FALSE indicated that the values have been returned
7525: Level: developer
7527: .seealso: MatGetColumnIJ(), MatRestoreRowIJ()
7528: @*/
7529: PetscErrorCode MatRestoreColumnIJ(Mat mat,PetscInt shift,PetscBool symmetric,PetscBool inodecompressed,PetscInt *n,const PetscInt *ia[],const PetscInt *ja[],PetscBool *done)
7530: {
7539: MatCheckPreallocated(mat,1);
7541: if (!mat->ops->restorecolumnij) *done = PETSC_FALSE;
7542: else {
7543: *done = PETSC_TRUE;
7544: (*mat->ops->restorecolumnij)(mat,shift,symmetric,inodecompressed,n,ia,ja,done);
7545: if (n) *n = 0;
7546: if (ia) *ia = NULL;
7547: if (ja) *ja = NULL;
7548: }
7549: return(0);
7550: }
7552: /*@C
7553: MatColoringPatch -Used inside matrix coloring routines that
7554: use MatGetRowIJ() and/or MatGetColumnIJ().
7556: Collective on Mat
7558: Input Parameters:
7559: + mat - the matrix
7560: . ncolors - max color value
7561: . n - number of entries in colorarray
7562: - colorarray - array indicating color for each column
7564: Output Parameters:
7565: . iscoloring - coloring generated using colorarray information
7567: Level: developer
7569: .seealso: MatGetRowIJ(), MatGetColumnIJ()
7571: @*/
7572: PetscErrorCode MatColoringPatch(Mat mat,PetscInt ncolors,PetscInt n,ISColoringValue colorarray[],ISColoring *iscoloring)
7573: {
7581: MatCheckPreallocated(mat,1);
7583: if (!mat->ops->coloringpatch) {
7584: ISColoringCreate(PetscObjectComm((PetscObject)mat),ncolors,n,colorarray,PETSC_OWN_POINTER,iscoloring);
7585: } else {
7586: (*mat->ops->coloringpatch)(mat,ncolors,n,colorarray,iscoloring);
7587: }
7588: return(0);
7589: }
7592: /*@
7593: MatSetUnfactored - Resets a factored matrix to be treated as unfactored.
7595: Logically Collective on Mat
7597: Input Parameter:
7598: . mat - the factored matrix to be reset
7600: Notes:
7601: This routine should be used only with factored matrices formed by in-place
7602: factorization via ILU(0) (or by in-place LU factorization for the MATSEQDENSE
7603: format). This option can save memory, for example, when solving nonlinear
7604: systems with a matrix-free Newton-Krylov method and a matrix-based, in-place
7605: ILU(0) preconditioner.
7607: Note that one can specify in-place ILU(0) factorization by calling
7608: .vb
7609: PCType(pc,PCILU);
7610: PCFactorSeUseInPlace(pc);
7611: .ve
7612: or by using the options -pc_type ilu -pc_factor_in_place
7614: In-place factorization ILU(0) can also be used as a local
7615: solver for the blocks within the block Jacobi or additive Schwarz
7616: methods (runtime option: -sub_pc_factor_in_place). See Users-Manual: ch_pc
7617: for details on setting local solver options.
7619: Most users should employ the simplified KSP interface for linear solvers
7620: instead of working directly with matrix algebra routines such as this.
7621: See, e.g., KSPCreate().
7623: Level: developer
7625: .seealso: PCFactorSetUseInPlace(), PCFactorGetUseInPlace()
7627: @*/
7628: PetscErrorCode MatSetUnfactored(Mat mat)
7629: {
7635: MatCheckPreallocated(mat,1);
7636: mat->factortype = MAT_FACTOR_NONE;
7637: if (!mat->ops->setunfactored) return(0);
7638: (*mat->ops->setunfactored)(mat);
7639: return(0);
7640: }
7642: /*MC
7643: MatDenseGetArrayF90 - Accesses a matrix array from Fortran90.
7645: Synopsis:
7646: MatDenseGetArrayF90(Mat x,{Scalar, pointer :: xx_v(:,:)},integer ierr)
7648: Not collective
7650: Input Parameter:
7651: . x - matrix
7653: Output Parameters:
7654: + xx_v - the Fortran90 pointer to the array
7655: - ierr - error code
7657: Example of Usage:
7658: .vb
7659: PetscScalar, pointer xx_v(:,:)
7660: ....
7661: call MatDenseGetArrayF90(x,xx_v,ierr)
7662: a = xx_v(3)
7663: call MatDenseRestoreArrayF90(x,xx_v,ierr)
7664: .ve
7666: Level: advanced
7668: .seealso: MatDenseRestoreArrayF90(), MatDenseGetArray(), MatDenseRestoreArray(), MatSeqAIJGetArrayF90()
7670: M*/
7672: /*MC
7673: MatDenseRestoreArrayF90 - Restores a matrix array that has been
7674: accessed with MatDenseGetArrayF90().
7676: Synopsis:
7677: MatDenseRestoreArrayF90(Mat x,{Scalar, pointer :: xx_v(:,:)},integer ierr)
7679: Not collective
7681: Input Parameters:
7682: + x - matrix
7683: - xx_v - the Fortran90 pointer to the array
7685: Output Parameter:
7686: . ierr - error code
7688: Example of Usage:
7689: .vb
7690: PetscScalar, pointer xx_v(:,:)
7691: ....
7692: call MatDenseGetArrayF90(x,xx_v,ierr)
7693: a = xx_v(3)
7694: call MatDenseRestoreArrayF90(x,xx_v,ierr)
7695: .ve
7697: Level: advanced
7699: .seealso: MatDenseGetArrayF90(), MatDenseGetArray(), MatDenseRestoreArray(), MatSeqAIJRestoreArrayF90()
7701: M*/
7704: /*MC
7705: MatSeqAIJGetArrayF90 - Accesses a matrix array from Fortran90.
7707: Synopsis:
7708: MatSeqAIJGetArrayF90(Mat x,{Scalar, pointer :: xx_v(:)},integer ierr)
7710: Not collective
7712: Input Parameter:
7713: . x - matrix
7715: Output Parameters:
7716: + xx_v - the Fortran90 pointer to the array
7717: - ierr - error code
7719: Example of Usage:
7720: .vb
7721: PetscScalar, pointer xx_v(:)
7722: ....
7723: call MatSeqAIJGetArrayF90(x,xx_v,ierr)
7724: a = xx_v(3)
7725: call MatSeqAIJRestoreArrayF90(x,xx_v,ierr)
7726: .ve
7728: Level: advanced
7730: .seealso: MatSeqAIJRestoreArrayF90(), MatSeqAIJGetArray(), MatSeqAIJRestoreArray(), MatDenseGetArrayF90()
7732: M*/
7734: /*MC
7735: MatSeqAIJRestoreArrayF90 - Restores a matrix array that has been
7736: accessed with MatSeqAIJGetArrayF90().
7738: Synopsis:
7739: MatSeqAIJRestoreArrayF90(Mat x,{Scalar, pointer :: xx_v(:)},integer ierr)
7741: Not collective
7743: Input Parameters:
7744: + x - matrix
7745: - xx_v - the Fortran90 pointer to the array
7747: Output Parameter:
7748: . ierr - error code
7750: Example of Usage:
7751: .vb
7752: PetscScalar, pointer xx_v(:)
7753: ....
7754: call MatSeqAIJGetArrayF90(x,xx_v,ierr)
7755: a = xx_v(3)
7756: call MatSeqAIJRestoreArrayF90(x,xx_v,ierr)
7757: .ve
7759: Level: advanced
7761: .seealso: MatSeqAIJGetArrayF90(), MatSeqAIJGetArray(), MatSeqAIJRestoreArray(), MatDenseRestoreArrayF90()
7763: M*/
7766: /*@
7767: MatCreateSubMatrix - Gets a single submatrix on the same number of processors
7768: as the original matrix.
7770: Collective on Mat
7772: Input Parameters:
7773: + mat - the original matrix
7774: . isrow - parallel IS containing the rows this processor should obtain
7775: . 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.
7776: - cll - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
7778: Output Parameter:
7779: . newmat - the new submatrix, of the same type as the old
7781: Level: advanced
7783: Notes:
7784: The submatrix will be able to be multiplied with vectors using the same layout as iscol.
7786: Some matrix types place restrictions on the row and column indices, such
7787: as that they be sorted or that they be equal to each other.
7789: The index sets may not have duplicate entries.
7791: The first time this is called you should use a cll of MAT_INITIAL_MATRIX,
7792: the MatCreateSubMatrix() routine will create the newmat for you. Any additional calls
7793: to this routine with a mat of the same nonzero structure and with a call of MAT_REUSE_MATRIX
7794: will reuse the matrix generated the first time. You should call MatDestroy() on newmat when
7795: you are finished using it.
7797: The communicator of the newly obtained matrix is ALWAYS the same as the communicator of
7798: the input matrix.
7800: If iscol is NULL then all columns are obtained (not supported in Fortran).
7802: Example usage:
7803: Consider the following 8x8 matrix with 34 non-zero values, that is
7804: assembled across 3 processors. Let's assume that proc0 owns 3 rows,
7805: proc1 owns 3 rows, proc2 owns 2 rows. This division can be shown
7806: as follows:
7808: .vb
7809: 1 2 0 | 0 3 0 | 0 4
7810: Proc0 0 5 6 | 7 0 0 | 8 0
7811: 9 0 10 | 11 0 0 | 12 0
7812: -------------------------------------
7813: 13 0 14 | 15 16 17 | 0 0
7814: Proc1 0 18 0 | 19 20 21 | 0 0
7815: 0 0 0 | 22 23 0 | 24 0
7816: -------------------------------------
7817: Proc2 25 26 27 | 0 0 28 | 29 0
7818: 30 0 0 | 31 32 33 | 0 34
7819: .ve
7821: Suppose isrow = [0 1 | 4 | 6 7] and iscol = [1 2 | 3 4 5 | 6]. The resulting submatrix is
7823: .vb
7824: 2 0 | 0 3 0 | 0
7825: Proc0 5 6 | 7 0 0 | 8
7826: -------------------------------
7827: Proc1 18 0 | 19 20 21 | 0
7828: -------------------------------
7829: Proc2 26 27 | 0 0 28 | 29
7830: 0 0 | 31 32 33 | 0
7831: .ve
7834: .seealso: MatCreateSubMatrices(), MatCreateSubMatricesMPI(), MatCreateSubMatrixVirtual(), MatSubMatrixVirtualUpdate()
7835: @*/
7836: PetscErrorCode MatCreateSubMatrix(Mat mat,IS isrow,IS iscol,MatReuse cll,Mat *newmat)
7837: {
7839: PetscMPIInt size;
7840: Mat *local;
7841: IS iscoltmp;
7842: PetscBool flg;
7851: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
7852: if (cll == MAT_IGNORE_MATRIX) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Cannot use MAT_IGNORE_MATRIX");
7854: MatCheckPreallocated(mat,1);
7855: MPI_Comm_size(PetscObjectComm((PetscObject)mat),&size);
7857: if (!iscol || isrow == iscol) {
7858: PetscBool stride;
7859: PetscMPIInt grabentirematrix = 0,grab;
7860: PetscObjectTypeCompare((PetscObject)isrow,ISSTRIDE,&stride);
7861: if (stride) {
7862: PetscInt first,step,n,rstart,rend;
7863: ISStrideGetInfo(isrow,&first,&step);
7864: if (step == 1) {
7865: MatGetOwnershipRange(mat,&rstart,&rend);
7866: if (rstart == first) {
7867: ISGetLocalSize(isrow,&n);
7868: if (n == rend-rstart) {
7869: grabentirematrix = 1;
7870: }
7871: }
7872: }
7873: }
7874: MPIU_Allreduce(&grabentirematrix,&grab,1,MPI_INT,MPI_MIN,PetscObjectComm((PetscObject)mat));
7875: if (grab) {
7876: PetscInfo(mat,"Getting entire matrix as submatrix\n");
7877: if (cll == MAT_INITIAL_MATRIX) {
7878: *newmat = mat;
7879: PetscObjectReference((PetscObject)mat);
7880: }
7881: return(0);
7882: }
7883: }
7885: if (!iscol) {
7886: ISCreateStride(PetscObjectComm((PetscObject)mat),mat->cmap->n,mat->cmap->rstart,1,&iscoltmp);
7887: } else {
7888: iscoltmp = iscol;
7889: }
7891: /* if original matrix is on just one processor then use submatrix generated */
7892: if (mat->ops->createsubmatrices && !mat->ops->createsubmatrix && size == 1 && cll == MAT_REUSE_MATRIX) {
7893: MatCreateSubMatrices(mat,1,&isrow,&iscoltmp,MAT_REUSE_MATRIX,&newmat);
7894: goto setproperties;
7895: } else if (mat->ops->createsubmatrices && !mat->ops->createsubmatrix && size == 1) {
7896: MatCreateSubMatrices(mat,1,&isrow,&iscoltmp,MAT_INITIAL_MATRIX,&local);
7897: *newmat = *local;
7898: PetscFree(local);
7899: goto setproperties;
7900: } else if (!mat->ops->createsubmatrix) {
7901: /* Create a new matrix type that implements the operation using the full matrix */
7902: PetscLogEventBegin(MAT_CreateSubMat,mat,0,0,0);
7903: switch (cll) {
7904: case MAT_INITIAL_MATRIX:
7905: MatCreateSubMatrixVirtual(mat,isrow,iscoltmp,newmat);
7906: break;
7907: case MAT_REUSE_MATRIX:
7908: MatSubMatrixVirtualUpdate(*newmat,mat,isrow,iscoltmp);
7909: break;
7910: default: SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_OUTOFRANGE,"Invalid MatReuse, must be either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX");
7911: }
7912: PetscLogEventEnd(MAT_CreateSubMat,mat,0,0,0);
7913: goto setproperties;
7914: }
7916: if (!mat->ops->createsubmatrix) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
7917: PetscLogEventBegin(MAT_CreateSubMat,mat,0,0,0);
7918: (*mat->ops->createsubmatrix)(mat,isrow,iscoltmp,cll,newmat);
7919: PetscLogEventEnd(MAT_CreateSubMat,mat,0,0,0);
7921: setproperties:
7922: ISEqualUnsorted(isrow,iscoltmp,&flg);
7923: if (flg) {
7924: MatPropagateSymmetryOptions(mat,*newmat);
7925: }
7926: if (!iscol) {ISDestroy(&iscoltmp);}
7927: if (*newmat && cll == MAT_INITIAL_MATRIX) {PetscObjectStateIncrease((PetscObject)*newmat);}
7928: return(0);
7929: }
7931: /*@
7932: MatPropagateSymmetryOptions - Propagates symmetry options set on a matrix to another matrix
7934: Not Collective
7936: Input Parameters:
7937: + A - the matrix we wish to propagate options from
7938: - B - the matrix we wish to propagate options to
7940: Level: beginner
7942: Notes: Propagates the options associated to MAT_SYMMETRY_ETERNAL, MAT_STRUCTURALLY_SYMMETRIC, MAT_HERMITIAN, MAT_SPD and MAT_SYMMETRIC
7944: .seealso: MatSetOption()
7945: @*/
7946: PetscErrorCode MatPropagateSymmetryOptions(Mat A, Mat B)
7947: {
7953: if (A->symmetric_eternal) { /* symmetric_eternal does not have a corresponding *set flag */
7954: MatSetOption(B,MAT_SYMMETRY_ETERNAL,A->symmetric_eternal);
7955: }
7956: if (A->structurally_symmetric_set) {
7957: MatSetOption(B,MAT_STRUCTURALLY_SYMMETRIC,A->structurally_symmetric);
7958: }
7959: if (A->hermitian_set) {
7960: MatSetOption(B,MAT_HERMITIAN,A->hermitian);
7961: }
7962: if (A->spd_set) {
7963: MatSetOption(B,MAT_SPD,A->spd);
7964: }
7965: if (A->symmetric_set) {
7966: MatSetOption(B,MAT_SYMMETRIC,A->symmetric);
7967: }
7968: return(0);
7969: }
7971: /*@
7972: MatStashSetInitialSize - sets the sizes of the matrix stash, that is
7973: used during the assembly process to store values that belong to
7974: other processors.
7976: Not Collective
7978: Input Parameters:
7979: + mat - the matrix
7980: . size - the initial size of the stash.
7981: - bsize - the initial size of the block-stash(if used).
7983: Options Database Keys:
7984: + -matstash_initial_size <size> or <size0,size1,...sizep-1>
7985: - -matstash_block_initial_size <bsize> or <bsize0,bsize1,...bsizep-1>
7987: Level: intermediate
7989: Notes:
7990: The block-stash is used for values set with MatSetValuesBlocked() while
7991: the stash is used for values set with MatSetValues()
7993: Run with the option -info and look for output of the form
7994: MatAssemblyBegin_MPIXXX:Stash has MM entries, uses nn mallocs.
7995: to determine the appropriate value, MM, to use for size and
7996: MatAssemblyBegin_MPIXXX:Block-Stash has BMM entries, uses nn mallocs.
7997: to determine the value, BMM to use for bsize
8000: .seealso: MatAssemblyBegin(), MatAssemblyEnd(), Mat, MatStashGetInfo()
8002: @*/
8003: PetscErrorCode MatStashSetInitialSize(Mat mat,PetscInt size, PetscInt bsize)
8004: {
8010: MatStashSetInitialSize_Private(&mat->stash,size);
8011: MatStashSetInitialSize_Private(&mat->bstash,bsize);
8012: return(0);
8013: }
8015: /*@
8016: MatInterpolateAdd - w = y + A*x or A'*x depending on the shape of
8017: the matrix
8019: Neighbor-wise Collective on Mat
8021: Input Parameters:
8022: + mat - the matrix
8023: . x,y - the vectors
8024: - w - where the result is stored
8026: Level: intermediate
8028: Notes:
8029: w may be the same vector as y.
8031: This allows one to use either the restriction or interpolation (its transpose)
8032: matrix to do the interpolation
8034: .seealso: MatMultAdd(), MatMultTransposeAdd(), MatRestrict()
8036: @*/
8037: PetscErrorCode MatInterpolateAdd(Mat A,Vec x,Vec y,Vec w)
8038: {
8040: PetscInt M,N,Ny;
8048: MatCheckPreallocated(A,1);
8049: MatGetSize(A,&M,&N);
8050: VecGetSize(y,&Ny);
8051: if (M == Ny) {
8052: MatMultAdd(A,x,y,w);
8053: } else {
8054: MatMultTransposeAdd(A,x,y,w);
8055: }
8056: return(0);
8057: }
8059: /*@
8060: MatInterpolate - y = A*x or A'*x depending on the shape of
8061: the matrix
8063: Neighbor-wise Collective on Mat
8065: Input Parameters:
8066: + mat - the matrix
8067: - x,y - the vectors
8069: Level: intermediate
8071: Notes:
8072: This allows one to use either the restriction or interpolation (its transpose)
8073: matrix to do the interpolation
8075: .seealso: MatMultAdd(), MatMultTransposeAdd(), MatRestrict()
8077: @*/
8078: PetscErrorCode MatInterpolate(Mat A,Vec x,Vec y)
8079: {
8081: PetscInt M,N,Ny;
8088: MatCheckPreallocated(A,1);
8089: MatGetSize(A,&M,&N);
8090: VecGetSize(y,&Ny);
8091: if (M == Ny) {
8092: MatMult(A,x,y);
8093: } else {
8094: MatMultTranspose(A,x,y);
8095: }
8096: return(0);
8097: }
8099: /*@
8100: MatRestrict - y = A*x or A'*x
8102: Neighbor-wise Collective on Mat
8104: Input Parameters:
8105: + mat - the matrix
8106: - x,y - the vectors
8108: Level: intermediate
8110: Notes:
8111: This allows one to use either the restriction or interpolation (its transpose)
8112: matrix to do the restriction
8114: .seealso: MatMultAdd(), MatMultTransposeAdd(), MatInterpolate()
8116: @*/
8117: PetscErrorCode MatRestrict(Mat A,Vec x,Vec y)
8118: {
8120: PetscInt M,N,Ny;
8127: MatCheckPreallocated(A,1);
8129: MatGetSize(A,&M,&N);
8130: VecGetSize(y,&Ny);
8131: if (M == Ny) {
8132: MatMult(A,x,y);
8133: } else {
8134: MatMultTranspose(A,x,y);
8135: }
8136: return(0);
8137: }
8139: /*@
8140: MatGetNullSpace - retrieves the null space of a matrix.
8142: Logically Collective on Mat
8144: Input Parameters:
8145: + mat - the matrix
8146: - nullsp - the null space object
8148: Level: developer
8150: .seealso: MatCreate(), MatNullSpaceCreate(), MatSetNearNullSpace(), MatSetNullSpace()
8151: @*/
8152: PetscErrorCode MatGetNullSpace(Mat mat, MatNullSpace *nullsp)
8153: {
8157: *nullsp = (mat->symmetric_set && mat->symmetric && !mat->nullsp) ? mat->transnullsp : mat->nullsp;
8158: return(0);
8159: }
8161: /*@
8162: MatSetNullSpace - attaches a null space to a matrix.
8164: Logically Collective on Mat
8166: Input Parameters:
8167: + mat - the matrix
8168: - nullsp - the null space object
8170: Level: advanced
8172: Notes:
8173: This null space is used by the linear solvers. Overwrites any previous null space that may have been attached
8175: For inconsistent singular systems (linear systems where the right hand side is not in the range of the operator) you also likely should
8176: call MatSetTransposeNullSpace(). This allows the linear system to be solved in a least squares sense.
8178: You can remove the null space by calling this routine with an nullsp of NULL
8181: The fundamental theorem of linear algebra (Gilbert Strang, Introduction to Applied Mathematics, page 72) states that
8182: the domain of a matrix A (from R^n to R^m (m rows, n columns) R^n = the direct sum of the null space of A, n(A), + the range of A^T, R(A^T).
8183: 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
8184: 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
8185: 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).
8187: Krylov solvers can produce the minimal norm solution to the least squares problem by utilizing MatNullSpaceRemove().
8189: If the matrix is known to be symmetric because it is an SBAIJ matrix or one as called MatSetOption(mat,MAT_SYMMETRIC or MAT_SYMMETRIC_ETERNAL,PETSC_TRUE); this
8190: routine also automatically calls MatSetTransposeNullSpace().
8192: .seealso: MatCreate(), MatNullSpaceCreate(), MatSetNearNullSpace(), MatGetNullSpace(), MatSetTransposeNullSpace(), MatGetTransposeNullSpace(), MatNullSpaceRemove()
8193: @*/
8194: PetscErrorCode MatSetNullSpace(Mat mat,MatNullSpace nullsp)
8195: {
8201: if (nullsp) {PetscObjectReference((PetscObject)nullsp);}
8202: MatNullSpaceDestroy(&mat->nullsp);
8203: mat->nullsp = nullsp;
8204: if (mat->symmetric_set && mat->symmetric) {
8205: MatSetTransposeNullSpace(mat,nullsp);
8206: }
8207: return(0);
8208: }
8210: /*@
8211: MatGetTransposeNullSpace - retrieves the null space of the transpose of a matrix.
8213: Logically Collective on Mat
8215: Input Parameters:
8216: + mat - the matrix
8217: - nullsp - the null space object
8219: Level: developer
8221: .seealso: MatCreate(), MatNullSpaceCreate(), MatSetNearNullSpace(), MatSetTransposeNullSpace(), MatSetNullSpace(), MatGetNullSpace()
8222: @*/
8223: PetscErrorCode MatGetTransposeNullSpace(Mat mat, MatNullSpace *nullsp)
8224: {
8229: *nullsp = (mat->symmetric_set && mat->symmetric && !mat->transnullsp) ? mat->nullsp : mat->transnullsp;
8230: return(0);
8231: }
8233: /*@
8234: MatSetTransposeNullSpace - attaches a null space to a matrix.
8236: Logically Collective on Mat
8238: Input Parameters:
8239: + mat - the matrix
8240: - nullsp - the null space object
8242: Level: advanced
8244: Notes:
8245: For inconsistent singular systems (linear systems where the right hand side is not in the range of the operator) this allows the linear system to be solved in a least squares sense.
8246: You must also call MatSetNullSpace()
8249: The fundamental theorem of linear algebra (Gilbert Strang, Introduction to Applied Mathematics, page 72) states that
8250: the domain of a matrix A (from R^n to R^m (m rows, n columns) R^n = the direct sum of the null space of A, n(A), + the range of A^T, R(A^T).
8251: 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
8252: 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
8253: 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).
8255: Krylov solvers can produce the minimal norm solution to the least squares problem by utilizing MatNullSpaceRemove().
8257: .seealso: MatCreate(), MatNullSpaceCreate(), MatSetNearNullSpace(), MatGetNullSpace(), MatSetNullSpace(), MatGetTransposeNullSpace(), MatNullSpaceRemove()
8258: @*/
8259: PetscErrorCode MatSetTransposeNullSpace(Mat mat,MatNullSpace nullsp)
8260: {
8266: if (nullsp) {PetscObjectReference((PetscObject)nullsp);}
8267: MatNullSpaceDestroy(&mat->transnullsp);
8268: mat->transnullsp = nullsp;
8269: return(0);
8270: }
8272: /*@
8273: MatSetNearNullSpace - attaches a null space to a matrix, which is often the null space (rigid body modes) of the operator without boundary conditions
8274: This null space will be used to provide near null space vectors to a multigrid preconditioner built from this matrix.
8276: Logically Collective on Mat
8278: Input Parameters:
8279: + mat - the matrix
8280: - nullsp - the null space object
8282: Level: advanced
8284: Notes:
8285: Overwrites any previous near null space that may have been attached
8287: You can remove the null space by calling this routine with an nullsp of NULL
8289: .seealso: MatCreate(), MatNullSpaceCreate(), MatSetNullSpace(), MatNullSpaceCreateRigidBody(), MatGetNearNullSpace()
8290: @*/
8291: PetscErrorCode MatSetNearNullSpace(Mat mat,MatNullSpace nullsp)
8292: {
8299: MatCheckPreallocated(mat,1);
8300: if (nullsp) {PetscObjectReference((PetscObject)nullsp);}
8301: MatNullSpaceDestroy(&mat->nearnullsp);
8302: mat->nearnullsp = nullsp;
8303: return(0);
8304: }
8306: /*@
8307: MatGetNearNullSpace - Get null space attached with MatSetNearNullSpace()
8309: Not Collective
8311: Input Parameter:
8312: . mat - the matrix
8314: Output Parameter:
8315: . nullsp - the null space object, NULL if not set
8317: Level: developer
8319: .seealso: MatSetNearNullSpace(), MatGetNullSpace(), MatNullSpaceCreate()
8320: @*/
8321: PetscErrorCode MatGetNearNullSpace(Mat mat,MatNullSpace *nullsp)
8322: {
8327: MatCheckPreallocated(mat,1);
8328: *nullsp = mat->nearnullsp;
8329: return(0);
8330: }
8332: /*@C
8333: MatICCFactor - Performs in-place incomplete Cholesky factorization of matrix.
8335: Collective on Mat
8337: Input Parameters:
8338: + mat - the matrix
8339: . row - row/column permutation
8340: . fill - expected fill factor >= 1.0
8341: - level - level of fill, for ICC(k)
8343: Notes:
8344: Probably really in-place only when level of fill is zero, otherwise allocates
8345: new space to store factored matrix and deletes previous memory.
8347: Most users should employ the simplified KSP interface for linear solvers
8348: instead of working directly with matrix algebra routines such as this.
8349: See, e.g., KSPCreate().
8351: Level: developer
8354: .seealso: MatICCFactorSymbolic(), MatLUFactorNumeric(), MatCholeskyFactor()
8356: Developer Note: fortran interface is not autogenerated as the f90
8357: interface defintion cannot be generated correctly [due to MatFactorInfo]
8359: @*/
8360: PetscErrorCode MatICCFactor(Mat mat,IS row,const MatFactorInfo *info)
8361: {
8369: if (mat->rmap->N != mat->cmap->N) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONG,"matrix must be square");
8370: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
8371: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
8372: if (!mat->ops->iccfactor) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
8373: MatCheckPreallocated(mat,1);
8374: (*mat->ops->iccfactor)(mat,row,info);
8375: PetscObjectStateIncrease((PetscObject)mat);
8376: return(0);
8377: }
8379: /*@
8380: MatDiagonalScaleLocal - Scales columns of a matrix given the scaling values including the
8381: ghosted ones.
8383: Not Collective
8385: Input Parameters:
8386: + mat - the matrix
8387: - diag = the diagonal values, including ghost ones
8389: Level: developer
8391: Notes:
8392: Works only for MPIAIJ and MPIBAIJ matrices
8394: .seealso: MatDiagonalScale()
8395: @*/
8396: PetscErrorCode MatDiagonalScaleLocal(Mat mat,Vec diag)
8397: {
8399: PetscMPIInt size;
8406: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Matrix must be already assembled");
8407: PetscLogEventBegin(MAT_Scale,mat,0,0,0);
8408: MPI_Comm_size(PetscObjectComm((PetscObject)mat),&size);
8409: if (size == 1) {
8410: PetscInt n,m;
8411: VecGetSize(diag,&n);
8412: MatGetSize(mat,0,&m);
8413: if (m == n) {
8414: MatDiagonalScale(mat,0,diag);
8415: } else SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"Only supported for sequential matrices when no ghost points/periodic conditions");
8416: } else {
8417: PetscUseMethod(mat,"MatDiagonalScaleLocal_C",(Mat,Vec),(mat,diag));
8418: }
8419: PetscLogEventEnd(MAT_Scale,mat,0,0,0);
8420: PetscObjectStateIncrease((PetscObject)mat);
8421: return(0);
8422: }
8424: /*@
8425: MatGetInertia - Gets the inertia from a factored matrix
8427: Collective on Mat
8429: Input Parameter:
8430: . mat - the matrix
8432: Output Parameters:
8433: + nneg - number of negative eigenvalues
8434: . nzero - number of zero eigenvalues
8435: - npos - number of positive eigenvalues
8437: Level: advanced
8439: Notes:
8440: Matrix must have been factored by MatCholeskyFactor()
8443: @*/
8444: PetscErrorCode MatGetInertia(Mat mat,PetscInt *nneg,PetscInt *nzero,PetscInt *npos)
8445: {
8451: if (!mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
8452: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Numeric factor mat is not assembled");
8453: if (!mat->ops->getinertia) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
8454: (*mat->ops->getinertia)(mat,nneg,nzero,npos);
8455: return(0);
8456: }
8458: /* ----------------------------------------------------------------*/
8459: /*@C
8460: MatSolves - Solves A x = b, given a factored matrix, for a collection of vectors
8462: Neighbor-wise Collective on Mats
8464: Input Parameters:
8465: + mat - the factored matrix
8466: - b - the right-hand-side vectors
8468: Output Parameter:
8469: . x - the result vectors
8471: Notes:
8472: The vectors b and x cannot be the same. I.e., one cannot
8473: call MatSolves(A,x,x).
8475: Notes:
8476: Most users should employ the simplified KSP interface for linear solvers
8477: instead of working directly with matrix algebra routines such as this.
8478: See, e.g., KSPCreate().
8480: Level: developer
8482: .seealso: MatSolveAdd(), MatSolveTranspose(), MatSolveTransposeAdd(), MatSolve()
8483: @*/
8484: PetscErrorCode MatSolves(Mat mat,Vecs b,Vecs x)
8485: {
8491: if (x == b) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"x and b must be different vectors");
8492: if (!mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
8493: if (!mat->rmap->N && !mat->cmap->N) return(0);
8495: if (!mat->ops->solves) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
8496: MatCheckPreallocated(mat,1);
8497: PetscLogEventBegin(MAT_Solves,mat,0,0,0);
8498: (*mat->ops->solves)(mat,b,x);
8499: PetscLogEventEnd(MAT_Solves,mat,0,0,0);
8500: return(0);
8501: }
8503: /*@
8504: MatIsSymmetric - Test whether a matrix is symmetric
8506: Collective on Mat
8508: Input Parameter:
8509: + A - the matrix to test
8510: - tol - difference between value and its transpose less than this amount counts as equal (use 0.0 for exact transpose)
8512: Output Parameters:
8513: . flg - the result
8515: Notes:
8516: For real numbers MatIsSymmetric() and MatIsHermitian() return identical results
8518: Level: intermediate
8520: .seealso: MatTranspose(), MatIsTranspose(), MatIsHermitian(), MatIsStructurallySymmetric(), MatSetOption(), MatIsSymmetricKnown()
8521: @*/
8522: PetscErrorCode MatIsSymmetric(Mat A,PetscReal tol,PetscBool *flg)
8523: {
8530: if (!A->symmetric_set) {
8531: if (!A->ops->issymmetric) {
8532: MatType mattype;
8533: MatGetType(A,&mattype);
8534: SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Matrix of type %s does not support checking for symmetric",mattype);
8535: }
8536: (*A->ops->issymmetric)(A,tol,flg);
8537: if (!tol) {
8538: MatSetOption(A,MAT_SYMMETRIC,*flg);
8539: }
8540: } else if (A->symmetric) {
8541: *flg = PETSC_TRUE;
8542: } else if (!tol) {
8543: *flg = PETSC_FALSE;
8544: } else {
8545: if (!A->ops->issymmetric) {
8546: MatType mattype;
8547: MatGetType(A,&mattype);
8548: SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Matrix of type %s does not support checking for symmetric",mattype);
8549: }
8550: (*A->ops->issymmetric)(A,tol,flg);
8551: }
8552: return(0);
8553: }
8555: /*@
8556: MatIsHermitian - Test whether a matrix is Hermitian
8558: Collective on Mat
8560: Input Parameter:
8561: + A - the matrix to test
8562: - tol - difference between value and its transpose less than this amount counts as equal (use 0.0 for exact Hermitian)
8564: Output Parameters:
8565: . flg - the result
8567: Level: intermediate
8569: .seealso: MatTranspose(), MatIsTranspose(), MatIsHermitian(), MatIsStructurallySymmetric(), MatSetOption(),
8570: MatIsSymmetricKnown(), MatIsSymmetric()
8571: @*/
8572: PetscErrorCode MatIsHermitian(Mat A,PetscReal tol,PetscBool *flg)
8573: {
8580: if (!A->hermitian_set) {
8581: if (!A->ops->ishermitian) {
8582: MatType mattype;
8583: MatGetType(A,&mattype);
8584: SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Matrix of type %s does not support checking for hermitian",mattype);
8585: }
8586: (*A->ops->ishermitian)(A,tol,flg);
8587: if (!tol) {
8588: MatSetOption(A,MAT_HERMITIAN,*flg);
8589: }
8590: } else if (A->hermitian) {
8591: *flg = PETSC_TRUE;
8592: } else if (!tol) {
8593: *flg = PETSC_FALSE;
8594: } else {
8595: if (!A->ops->ishermitian) {
8596: MatType mattype;
8597: MatGetType(A,&mattype);
8598: SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Matrix of type %s does not support checking for hermitian",mattype);
8599: }
8600: (*A->ops->ishermitian)(A,tol,flg);
8601: }
8602: return(0);
8603: }
8605: /*@
8606: MatIsSymmetricKnown - Checks the flag on the matrix to see if it is symmetric.
8608: Not Collective
8610: Input Parameter:
8611: . A - the matrix to check
8613: Output Parameters:
8614: + set - if the symmetric flag is set (this tells you if the next flag is valid)
8615: - flg - the result
8617: Level: advanced
8619: Note: Does not check the matrix values directly, so this may return unknown (set = PETSC_FALSE). Use MatIsSymmetric()
8620: if you want it explicitly checked
8622: .seealso: MatTranspose(), MatIsTranspose(), MatIsHermitian(), MatIsStructurallySymmetric(), MatSetOption(), MatIsSymmetric()
8623: @*/
8624: PetscErrorCode MatIsSymmetricKnown(Mat A,PetscBool *set,PetscBool *flg)
8625: {
8630: if (A->symmetric_set) {
8631: *set = PETSC_TRUE;
8632: *flg = A->symmetric;
8633: } else {
8634: *set = PETSC_FALSE;
8635: }
8636: return(0);
8637: }
8639: /*@
8640: MatIsHermitianKnown - Checks the flag on the matrix to see if it is hermitian.
8642: Not Collective
8644: Input Parameter:
8645: . A - the matrix to check
8647: Output Parameters:
8648: + set - if the hermitian flag is set (this tells you if the next flag is valid)
8649: - flg - the result
8651: Level: advanced
8653: Note: Does not check the matrix values directly, so this may return unknown (set = PETSC_FALSE). Use MatIsHermitian()
8654: if you want it explicitly checked
8656: .seealso: MatTranspose(), MatIsTranspose(), MatIsHermitian(), MatIsStructurallySymmetric(), MatSetOption(), MatIsSymmetric()
8657: @*/
8658: PetscErrorCode MatIsHermitianKnown(Mat A,PetscBool *set,PetscBool *flg)
8659: {
8664: if (A->hermitian_set) {
8665: *set = PETSC_TRUE;
8666: *flg = A->hermitian;
8667: } else {
8668: *set = PETSC_FALSE;
8669: }
8670: return(0);
8671: }
8673: /*@
8674: MatIsStructurallySymmetric - Test whether a matrix is structurally symmetric
8676: Collective on Mat
8678: Input Parameter:
8679: . A - the matrix to test
8681: Output Parameters:
8682: . flg - the result
8684: Level: intermediate
8686: .seealso: MatTranspose(), MatIsTranspose(), MatIsHermitian(), MatIsSymmetric(), MatSetOption()
8687: @*/
8688: PetscErrorCode MatIsStructurallySymmetric(Mat A,PetscBool *flg)
8689: {
8695: if (!A->structurally_symmetric_set) {
8696: if (!A->ops->isstructurallysymmetric) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Matrix of type %s does not support checking for structural symmetric",((PetscObject)A)->type_name);
8697: (*A->ops->isstructurallysymmetric)(A,flg);
8698: MatSetOption(A,MAT_STRUCTURALLY_SYMMETRIC,*flg);
8699: } else *flg = A->structurally_symmetric;
8700: return(0);
8701: }
8703: /*@
8704: MatStashGetInfo - Gets how many values are currently in the matrix stash, i.e. need
8705: to be communicated to other processors during the MatAssemblyBegin/End() process
8707: Not collective
8709: Input Parameter:
8710: . vec - the vector
8712: Output Parameters:
8713: + nstash - the size of the stash
8714: . reallocs - the number of additional mallocs incurred.
8715: . bnstash - the size of the block stash
8716: - breallocs - the number of additional mallocs incurred.in the block stash
8718: Level: advanced
8720: .seealso: MatAssemblyBegin(), MatAssemblyEnd(), Mat, MatStashSetInitialSize()
8722: @*/
8723: PetscErrorCode MatStashGetInfo(Mat mat,PetscInt *nstash,PetscInt *reallocs,PetscInt *bnstash,PetscInt *breallocs)
8724: {
8728: MatStashGetInfo_Private(&mat->stash,nstash,reallocs);
8729: MatStashGetInfo_Private(&mat->bstash,bnstash,breallocs);
8730: return(0);
8731: }
8733: /*@C
8734: MatCreateVecs - Get vector(s) compatible with the matrix, i.e. with the same
8735: parallel layout
8737: Collective on Mat
8739: Input Parameter:
8740: . mat - the matrix
8742: Output Parameter:
8743: + right - (optional) vector that the matrix can be multiplied against
8744: - left - (optional) vector that the matrix vector product can be stored in
8746: Notes:
8747: 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().
8749: Notes:
8750: These are new vectors which are not owned by the Mat, they should be destroyed in VecDestroy() when no longer needed
8752: Level: advanced
8754: .seealso: MatCreate(), VecDestroy()
8755: @*/
8756: PetscErrorCode MatCreateVecs(Mat mat,Vec *right,Vec *left)
8757: {
8763: if (mat->ops->getvecs) {
8764: (*mat->ops->getvecs)(mat,right,left);
8765: } else {
8766: PetscInt rbs,cbs;
8767: MatGetBlockSizes(mat,&rbs,&cbs);
8768: if (right) {
8769: if (mat->cmap->n < 0) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"PetscLayout for columns not yet setup");
8770: VecCreate(PetscObjectComm((PetscObject)mat),right);
8771: VecSetSizes(*right,mat->cmap->n,PETSC_DETERMINE);
8772: VecSetBlockSize(*right,cbs);
8773: VecSetType(*right,mat->defaultvectype);
8774: PetscLayoutReference(mat->cmap,&(*right)->map);
8775: }
8776: if (left) {
8777: if (mat->rmap->n < 0) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"PetscLayout for rows not yet setup");
8778: VecCreate(PetscObjectComm((PetscObject)mat),left);
8779: VecSetSizes(*left,mat->rmap->n,PETSC_DETERMINE);
8780: VecSetBlockSize(*left,rbs);
8781: VecSetType(*left,mat->defaultvectype);
8782: PetscLayoutReference(mat->rmap,&(*left)->map);
8783: }
8784: }
8785: return(0);
8786: }
8788: /*@C
8789: MatFactorInfoInitialize - Initializes a MatFactorInfo data structure
8790: with default values.
8792: Not Collective
8794: Input Parameters:
8795: . info - the MatFactorInfo data structure
8798: Notes:
8799: The solvers are generally used through the KSP and PC objects, for example
8800: PCLU, PCILU, PCCHOLESKY, PCICC
8802: Level: developer
8804: .seealso: MatFactorInfo
8806: Developer Note: fortran interface is not autogenerated as the f90
8807: interface defintion cannot be generated correctly [due to MatFactorInfo]
8809: @*/
8811: PetscErrorCode MatFactorInfoInitialize(MatFactorInfo *info)
8812: {
8816: PetscMemzero(info,sizeof(MatFactorInfo));
8817: return(0);
8818: }
8820: /*@
8821: MatFactorSetSchurIS - Set indices corresponding to the Schur complement you wish to have computed
8823: Collective on Mat
8825: Input Parameters:
8826: + mat - the factored matrix
8827: - is - the index set defining the Schur indices (0-based)
8829: Notes:
8830: Call MatFactorSolveSchurComplement() or MatFactorSolveSchurComplementTranspose() after this call to solve a Schur complement system.
8832: You can call MatFactorGetSchurComplement() or MatFactorCreateSchurComplement() after this call.
8834: Level: developer
8836: .seealso: MatGetFactor(), MatFactorGetSchurComplement(), MatFactorRestoreSchurComplement(), MatFactorCreateSchurComplement(), MatFactorSolveSchurComplement(),
8837: MatFactorSolveSchurComplementTranspose(), MatFactorSolveSchurComplement()
8839: @*/
8840: PetscErrorCode MatFactorSetSchurIS(Mat mat,IS is)
8841: {
8842: PetscErrorCode ierr,(*f)(Mat,IS);
8850: if (!mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Only for factored matrix");
8851: PetscObjectQueryFunction((PetscObject)mat,"MatFactorSetSchurIS_C",&f);
8852: if (!f) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"The selected MatSolverType does not support Schur complement computation. You should use MATSOLVERMUMPS or MATSOLVERMKL_PARDISO");
8853: MatDestroy(&mat->schur);
8854: (*f)(mat,is);
8855: if (!mat->schur) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_PLIB,"Schur complement has not been created");
8856: return(0);
8857: }
8859: /*@
8860: MatFactorCreateSchurComplement - Create a Schur complement matrix object using Schur data computed during the factorization step
8862: Logically Collective on Mat
8864: Input Parameters:
8865: + F - the factored matrix obtained by calling MatGetFactor() from PETSc-MUMPS interface
8866: . S - location where to return the Schur complement, can be NULL
8867: - status - the status of the Schur complement matrix, can be NULL
8869: Notes:
8870: You must call MatFactorSetSchurIS() before calling this routine.
8872: The routine provides a copy of the Schur matrix stored within the solver data structures.
8873: The caller must destroy the object when it is no longer needed.
8874: If MatFactorInvertSchurComplement() has been called, the routine gets back the inverse.
8876: 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)
8878: Developer Notes:
8879: The reason this routine exists is because the representation of the Schur complement within the factor matrix may be different than a standard PETSc
8880: matrix representation and we normally do not want to use the time or memory to make a copy as a regular PETSc matrix.
8882: See MatCreateSchurComplement() or MatGetSchurComplement() for ways to create virtual or approximate Schur complements.
8884: Level: advanced
8886: References:
8888: .seealso: MatGetFactor(), MatFactorSetSchurIS(), MatFactorGetSchurComplement(), MatFactorSchurStatus
8889: @*/
8890: PetscErrorCode MatFactorCreateSchurComplement(Mat F,Mat* S,MatFactorSchurStatus* status)
8891: {
8898: if (S) {
8899: PetscErrorCode (*f)(Mat,Mat*);
8901: PetscObjectQueryFunction((PetscObject)F,"MatFactorCreateSchurComplement_C",&f);
8902: if (f) {
8903: (*f)(F,S);
8904: } else {
8905: MatDuplicate(F->schur,MAT_COPY_VALUES,S);
8906: }
8907: }
8908: if (status) *status = F->schur_status;
8909: return(0);
8910: }
8912: /*@
8913: MatFactorGetSchurComplement - Gets access to a Schur complement matrix using the current Schur data within a factored matrix
8915: Logically Collective on Mat
8917: Input Parameters:
8918: + F - the factored matrix obtained by calling MatGetFactor()
8919: . *S - location where to return the Schur complement, can be NULL
8920: - status - the status of the Schur complement matrix, can be NULL
8922: Notes:
8923: You must call MatFactorSetSchurIS() before calling this routine.
8925: Schur complement mode is currently implemented for sequential matrices.
8926: The routine returns a the Schur Complement stored within the data strutures of the solver.
8927: If MatFactorInvertSchurComplement() has previously been called, the returned matrix is actually the inverse of the Schur complement.
8928: The returned matrix should not be destroyed; the caller should call MatFactorRestoreSchurComplement() when the object is no longer needed.
8930: Use MatFactorCreateSchurComplement() to create a copy of the Schur complement matrix that is within a factored matrix
8932: See MatCreateSchurComplement() or MatGetSchurComplement() for ways to create virtual or approximate Schur complements.
8934: Level: advanced
8936: References:
8938: .seealso: MatGetFactor(), MatFactorSetSchurIS(), MatFactorRestoreSchurComplement(), MatFactorCreateSchurComplement(), MatFactorSchurStatus
8939: @*/
8940: PetscErrorCode MatFactorGetSchurComplement(Mat F,Mat* S,MatFactorSchurStatus* status)
8941: {
8946: if (S) *S = F->schur;
8947: if (status) *status = F->schur_status;
8948: return(0);
8949: }
8951: /*@
8952: MatFactorRestoreSchurComplement - Restore the Schur complement matrix object obtained from a call to MatFactorGetSchurComplement
8954: Logically Collective on Mat
8956: Input Parameters:
8957: + F - the factored matrix obtained by calling MatGetFactor()
8958: . *S - location where the Schur complement is stored
8959: - status - the status of the Schur complement matrix (see MatFactorSchurStatus)
8961: Notes:
8963: Level: advanced
8965: References:
8967: .seealso: MatGetFactor(), MatFactorSetSchurIS(), MatFactorRestoreSchurComplement(), MatFactorCreateSchurComplement(), MatFactorSchurStatus
8968: @*/
8969: PetscErrorCode MatFactorRestoreSchurComplement(Mat F,Mat* S,MatFactorSchurStatus status)
8970: {
8975: if (S) {
8977: *S = NULL;
8978: }
8979: F->schur_status = status;
8980: MatFactorUpdateSchurStatus_Private(F);
8981: return(0);
8982: }
8984: /*@
8985: MatFactorSolveSchurComplementTranspose - Solve the transpose of the Schur complement system computed during the factorization step
8987: Logically Collective on Mat
8989: Input Parameters:
8990: + F - the factored matrix obtained by calling MatGetFactor()
8991: . rhs - location where the right hand side of the Schur complement system is stored
8992: - sol - location where the solution of the Schur complement system has to be returned
8994: Notes:
8995: The sizes of the vectors should match the size of the Schur complement
8997: Must be called after MatFactorSetSchurIS()
8999: Level: advanced
9001: References:
9003: .seealso: MatGetFactor(), MatFactorSetSchurIS(), MatFactorSolveSchurComplement()
9004: @*/
9005: PetscErrorCode MatFactorSolveSchurComplementTranspose(Mat F, Vec rhs, Vec sol)
9006: {
9018: MatFactorFactorizeSchurComplement(F);
9019: switch (F->schur_status) {
9020: case MAT_FACTOR_SCHUR_FACTORED:
9021: MatSolveTranspose(F->schur,rhs,sol);
9022: break;
9023: case MAT_FACTOR_SCHUR_INVERTED:
9024: MatMultTranspose(F->schur,rhs,sol);
9025: break;
9026: default:
9027: SETERRQ1(PetscObjectComm((PetscObject)F),PETSC_ERR_SUP,"Unhandled MatFactorSchurStatus %D",F->schur_status);
9028: break;
9029: }
9030: return(0);
9031: }
9033: /*@
9034: MatFactorSolveSchurComplement - Solve the Schur complement system computed during the factorization step
9036: Logically Collective on Mat
9038: Input Parameters:
9039: + F - the factored matrix obtained by calling MatGetFactor()
9040: . rhs - location where the right hand side of the Schur complement system is stored
9041: - sol - location where the solution of the Schur complement system has to be returned
9043: Notes:
9044: The sizes of the vectors should match the size of the Schur complement
9046: Must be called after MatFactorSetSchurIS()
9048: Level: advanced
9050: References:
9052: .seealso: MatGetFactor(), MatFactorSetSchurIS(), MatFactorSolveSchurComplementTranspose()
9053: @*/
9054: PetscErrorCode MatFactorSolveSchurComplement(Mat F, Vec rhs, Vec sol)
9055: {
9067: MatFactorFactorizeSchurComplement(F);
9068: switch (F->schur_status) {
9069: case MAT_FACTOR_SCHUR_FACTORED:
9070: MatSolve(F->schur,rhs,sol);
9071: break;
9072: case MAT_FACTOR_SCHUR_INVERTED:
9073: MatMult(F->schur,rhs,sol);
9074: break;
9075: default:
9076: SETERRQ1(PetscObjectComm((PetscObject)F),PETSC_ERR_SUP,"Unhandled MatFactorSchurStatus %D",F->schur_status);
9077: break;
9078: }
9079: return(0);
9080: }
9082: /*@
9083: MatFactorInvertSchurComplement - Invert the Schur complement matrix computed during the factorization step
9085: Logically Collective on Mat
9087: Input Parameters:
9088: . F - the factored matrix obtained by calling MatGetFactor()
9090: Notes:
9091: Must be called after MatFactorSetSchurIS().
9093: Call MatFactorGetSchurComplement() or MatFactorCreateSchurComplement() AFTER this call to actually compute the inverse and get access to it.
9095: Level: advanced
9097: References:
9099: .seealso: MatGetFactor(), MatFactorSetSchurIS(), MatFactorGetSchurComplement(), MatFactorCreateSchurComplement()
9100: @*/
9101: PetscErrorCode MatFactorInvertSchurComplement(Mat F)
9102: {
9108: if (F->schur_status == MAT_FACTOR_SCHUR_INVERTED) return(0);
9109: MatFactorFactorizeSchurComplement(F);
9110: MatFactorInvertSchurComplement_Private(F);
9111: F->schur_status = MAT_FACTOR_SCHUR_INVERTED;
9112: return(0);
9113: }
9115: /*@
9116: MatFactorFactorizeSchurComplement - Factorize the Schur complement matrix computed during the factorization step
9118: Logically Collective on Mat
9120: Input Parameters:
9121: . F - the factored matrix obtained by calling MatGetFactor()
9123: Notes:
9124: Must be called after MatFactorSetSchurIS().
9126: Level: advanced
9128: References:
9130: .seealso: MatGetFactor(), MatFactorSetSchurIS(), MatFactorInvertSchurComplement()
9131: @*/
9132: PetscErrorCode MatFactorFactorizeSchurComplement(Mat F)
9133: {
9139: if (F->schur_status == MAT_FACTOR_SCHUR_INVERTED || F->schur_status == MAT_FACTOR_SCHUR_FACTORED) return(0);
9140: MatFactorFactorizeSchurComplement_Private(F);
9141: F->schur_status = MAT_FACTOR_SCHUR_FACTORED;
9142: return(0);
9143: }
9145: /*@
9146: MatPtAP - Creates the matrix product C = P^T * A * P
9148: Neighbor-wise Collective on Mat
9150: Input Parameters:
9151: + A - the matrix
9152: . P - the projection matrix
9153: . scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
9154: - fill - expected fill as ratio of nnz(C)/(nnz(A) + nnz(P)), use PETSC_DEFAULT if you do not have a good estimate
9155: if the result is a dense matrix this is irrelevent
9157: Output Parameters:
9158: . C - the product matrix
9160: Notes:
9161: C will be created and must be destroyed by the user with MatDestroy().
9163: For matrix types without special implementation the function fallbacks to MatMatMult() followed by MatTransposeMatMult().
9165: Level: intermediate
9167: .seealso: MatMatMult(), MatRARt()
9168: @*/
9169: PetscErrorCode MatPtAP(Mat A,Mat P,MatReuse scall,PetscReal fill,Mat *C)
9170: {
9174: if (scall == MAT_INPLACE_MATRIX) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Inplace product not supported");
9176: if (scall == MAT_INITIAL_MATRIX) {
9177: MatProductCreate(A,P,NULL,C);
9178: MatProductSetType(*C,MATPRODUCT_PtAP);
9179: MatProductSetAlgorithm(*C,"default");
9180: MatProductSetFill(*C,fill);
9182: (*C)->product->api_user = PETSC_TRUE;
9183: MatProductSetFromOptions(*C);
9184: MatProductSymbolic(*C);
9185: } else {
9186: Mat_Product *product = (*C)->product;
9187: if (product) { /* user may chage input matrices A or B when REUSE */
9188: MatProductReplaceMats(A,P,NULL,*C);
9189: } else SETERRQ(PetscObjectComm((PetscObject)(*C)),PETSC_ERR_SUP,"Call MatProductCreate() or MatProductReplaceProduct() first");
9190: }
9192: MatProductNumeric(*C);
9193: if (A->symmetric_set && A->symmetric) {
9194: MatSetOption(*C,MAT_SYMMETRIC,PETSC_TRUE);
9195: }
9196: return(0);
9197: }
9199: /*@
9200: MatRARt - Creates the matrix product C = R * A * R^T
9202: Neighbor-wise Collective on Mat
9204: Input Parameters:
9205: + A - the matrix
9206: . R - the projection matrix
9207: . scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
9208: - fill - expected fill as ratio of nnz(C)/nnz(A), use PETSC_DEFAULT if you do not have a good estimate
9209: if the result is a dense matrix this is irrelevent
9211: Output Parameters:
9212: . C - the product matrix
9214: Notes:
9215: C will be created and must be destroyed by the user with MatDestroy().
9217: This routine is currently only implemented for pairs of AIJ matrices and classes
9218: which inherit from AIJ. Due to PETSc sparse matrix block row distribution among processes,
9219: parallel MatRARt is implemented via explicit transpose of R, which could be very expensive.
9220: We recommend using MatPtAP().
9222: Level: intermediate
9224: .seealso: MatMatMult(), MatPtAP()
9225: @*/
9226: PetscErrorCode MatRARt(Mat A,Mat R,MatReuse scall,PetscReal fill,Mat *C)
9227: {
9231: if (scall == MAT_INPLACE_MATRIX) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Inplace product not supported");
9233: if (scall == MAT_INITIAL_MATRIX) {
9234: MatProductCreate(A,R,NULL,C);
9235: MatProductSetType(*C,MATPRODUCT_RARt);
9236: MatProductSetAlgorithm(*C,"default");
9237: MatProductSetFill(*C,fill);
9239: (*C)->product->api_user = PETSC_TRUE;
9240: MatProductSetFromOptions(*C);
9241: MatProductSymbolic(*C);
9242: } else { /* scall == MAT_REUSE_MATRIX */
9243: Mat_Product *product = (*C)->product;
9244: if (product) {
9245: /* user may chage input matrices A or R when REUSE */
9246: MatProductReplaceMats(A,R,NULL,*C);
9247: } else SETERRQ(PetscObjectComm((PetscObject)(*C)),PETSC_ERR_SUP,"Call MatProductCreate() or MatProductReplaceProduct() first");
9248: }
9250: MatProductNumeric(*C);
9251: return(0);
9252: }
9254: /*@
9255: MatMatMult - Performs Matrix-Matrix Multiplication C=A*B.
9257: Neighbor-wise Collective on Mat
9259: Input Parameters:
9260: + A - the left matrix
9261: . B - the right matrix
9262: . scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
9263: - fill - expected fill as ratio of nnz(C)/(nnz(A) + nnz(B)), use PETSC_DEFAULT if you do not have a good estimate
9264: if the result is a dense matrix this is irrelevent
9266: Output Parameters:
9267: . C - the product matrix
9269: Notes:
9270: Unless scall is MAT_REUSE_MATRIX C will be created.
9272: 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
9273: call to this function with MAT_INITIAL_MATRIX.
9275: To determine the correct fill value, run with -info and search for the string "Fill ratio" to see the value actually needed.
9277: If you have many matrices with the same non-zero structure to multiply, you should use MatProductCreate()/MatProductSymbolic(C)/ReplaceMats(), and call MatProductNumeric() repeatedly.
9279: 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, rather than first having MatMatMult() create it for you. You can NEVER do this if the matrix C is sparse.
9281: Level: intermediate
9283: .seealso: MatTransposeMatMult(), MatMatTransposeMult(), MatPtAP()
9284: @*/
9285: PetscErrorCode MatMatMult(Mat A,Mat B,MatReuse scall,PetscReal fill,Mat *C)
9286: {
9290: if (scall == MAT_INPLACE_MATRIX) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Inplace product not supported");
9292: if (scall == MAT_INITIAL_MATRIX) {
9293: MatProductCreate(A,B,NULL,C);
9294: MatProductSetType(*C,MATPRODUCT_AB);
9295: MatProductSetAlgorithm(*C,"default");
9296: MatProductSetFill(*C,fill);
9298: (*C)->product->api_user = PETSC_TRUE;
9299: MatProductSetFromOptions(*C);
9300: MatProductSymbolic(*C);
9301: } else { /* scall == MAT_REUSE_MATRIX */
9302: Mat_Product *product = (*C)->product;
9303: if (!product) {
9304: /* user provide the dense matrix *C without calling MatProductCreate() */
9305: PetscBool seqdense,mpidense,dense;
9306: #if defined(PETSC_HAVE_CUDA)
9307: PetscBool seqdensecuda;
9308: #endif
9309: PetscObjectTypeCompare((PetscObject)(*C),MATSEQDENSE,&seqdense);
9310: PetscObjectTypeCompare((PetscObject)(*C),MATMPIDENSE,&mpidense);
9311: PetscObjectTypeCompare((PetscObject)(*C),MATDENSE,&dense);
9312: #if defined(PETSC_HAVE_CUDA)
9313: PetscObjectTypeCompare((PetscObject)(*C),MATSEQDENSECUDA,&seqdensecuda);
9314: if (seqdense || mpidense || dense || seqdensecuda) {
9315: #else
9316: if (seqdense || mpidense || dense) {
9317: #endif
9318: /* user wants to reuse an assembled dense matrix */
9319: /* Create product -- see MatCreateProduct() */
9320: MatProductCreate_Private(A,B,NULL,*C);
9321: product = (*C)->product;
9322: product->fill = fill;
9323: product->api_user = PETSC_TRUE;
9325: MatProductSetType(*C,MATPRODUCT_AB);
9326: MatProductSetFromOptions(*C);
9327: if (!(*C)->assembled) {
9328: MatProductSymbolic(*C);
9329: }
9330: } else SETERRQ(PetscObjectComm((PetscObject)(*C)),PETSC_ERR_SUP,"Call MatProductCreate() or MatProductReplaceProduct() first");
9331: } else { /* user may chage input matrices A or B when REUSE */
9332: MatProductReplaceMats(A,B,NULL,*C);
9333: }
9334: }
9335: MatProductNumeric(*C);
9336: return(0);
9337: }
9339: /*@
9340: MatMatTransposeMult - Performs Matrix-Matrix Multiplication C=A*B^T.
9342: Neighbor-wise Collective on Mat
9344: Input Parameters:
9345: + A - the left matrix
9346: . B - the right matrix
9347: . scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
9348: - fill - expected fill as ratio of nnz(C)/(nnz(A) + nnz(B)), use PETSC_DEFAULT if not known
9350: Output Parameters:
9351: . C - the product matrix
9353: Notes:
9354: C will be created if MAT_INITIAL_MATRIX and must be destroyed by the user with MatDestroy().
9356: MAT_REUSE_MATRIX can only be used if the matrices A and B have the same nonzero pattern as in the previous call
9358: To determine the correct fill value, run with -info and search for the string "Fill ratio" to see the value
9359: actually needed.
9361: This routine is currently only implemented for pairs of SeqAIJ matrices, for the SeqDense class,
9362: and for pairs of MPIDense matrices.
9364: Options Database Keys:
9365: . -matmattransmult_mpidense_mpidense_via {allgatherv,cyclic} - Choose between algorthims for MPIDense matrices: the
9366: first redundantly copies the transposed B matrix on each process and requiers O(log P) communication complexity;
9367: the second never stores more than one portion of the B matrix at a time by requires O(P) communication complexity.
9369: Level: intermediate
9371: .seealso: MatMatMult(), MatTransposeMatMult() MatPtAP()
9372: @*/
9373: PetscErrorCode MatMatTransposeMult(Mat A,Mat B,MatReuse scall,PetscReal fill,Mat *C)
9374: {
9378: if (scall == MAT_INPLACE_MATRIX) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Inplace product not supported");
9380: if (scall == MAT_INITIAL_MATRIX) {
9381: MatProductCreate(A,B,NULL,C);
9382: MatProductSetType(*C, MATPRODUCT_ABt);
9383: MatProductSetAlgorithm(*C,"default");
9384: MatProductSetFill(*C,fill);
9386: (*C)->product->api_user = PETSC_TRUE;
9387: MatProductSetFromOptions(*C);
9388: MatProductSymbolic(*C);
9389: } else {
9390: Mat_Product *product = (*C)->product;
9391: if (!product) {
9392: PetscBool seqdense,mpidense,dense;
9393: PetscObjectTypeCompare((PetscObject)(*C),MATSEQDENSE,&seqdense);
9394: PetscObjectTypeCompare((PetscObject)(*C),MATMPIDENSE,&mpidense);
9395: PetscObjectTypeCompare((PetscObject)(*C),MATDENSE,&dense);
9396: if ((*C)->assembled && (seqdense || mpidense || dense)) {
9397: /* user wants to reuse an assembled dense matrix */
9398: /* Create product -- see MatCreateProduct() */
9399: MatProductCreate_Private(A,B,NULL,*C);
9400: product = (*C)->product;
9401: product->fill = fill;
9402: product->api_user = PETSC_TRUE;
9404: MatProductSetType(*C,MATPRODUCT_ABt);
9405: MatProductSetFromOptions(*C);
9406: MatProductSymbolic(*C);
9407: } else SETERRQ(PetscObjectComm((PetscObject)(*C)),PETSC_ERR_SUP,"Call MatProductCreate() first");
9408: } else { /* user may chage input matrices A or B when REUSE */
9409: MatProductReplaceMats(A,B,NULL,*C);
9410: }
9411: }
9412: MatProductNumeric(*C);
9413: return(0);
9414: }
9416: /*@
9417: MatTransposeMatMult - Performs Matrix-Matrix Multiplication C=A^T*B.
9419: Neighbor-wise Collective on Mat
9421: Input Parameters:
9422: + A - the left matrix
9423: . B - the right matrix
9424: . scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
9425: - fill - expected fill as ratio of nnz(C)/(nnz(A) + nnz(B)), use PETSC_DEFAULT if not known
9427: Output Parameters:
9428: . C - the product matrix
9430: Notes:
9431: C will be created if MAT_INITIAL_MATRIX and must be destroyed by the user with MatDestroy().
9433: MAT_REUSE_MATRIX can only be used if the matrices A and B have the same nonzero pattern as in the previous call.
9435: To determine the correct fill value, run with -info and search for the string "Fill ratio" to see the value
9436: actually needed.
9438: This routine is currently implemented for pairs of AIJ matrices and pairs of SeqDense matrices and classes
9439: which inherit from SeqAIJ. C will be of same type as the input matrices.
9441: Level: intermediate
9443: .seealso: MatMatMult(), MatMatTransposeMult(), MatPtAP()
9444: @*/
9445: PetscErrorCode MatTransposeMatMult(Mat A,Mat B,MatReuse scall,PetscReal fill,Mat *C)
9446: {
9450: if (scall == MAT_INPLACE_MATRIX) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Inplace product not supported");
9452: if (scall == MAT_INITIAL_MATRIX) {
9453: MatProductCreate(A,B,NULL,C);
9454: MatProductSetType(*C,MATPRODUCT_AtB);
9455: MatProductSetAlgorithm(*C,"default");
9456: MatProductSetFill(*C,fill);
9458: (*C)->product->api_user = PETSC_TRUE;
9459: MatProductSetFromOptions(*C);
9460: MatProductSymbolic(*C);
9461: } else {
9462: Mat_Product *product = (*C)->product;
9463: if (!product) {
9464: PetscBool seqdense,mpidense,dense;
9465: PetscObjectTypeCompare((PetscObject)(*C),MATSEQDENSE,&seqdense);
9466: PetscObjectTypeCompare((PetscObject)(*C),MATMPIDENSE,&mpidense);
9467: PetscObjectTypeCompare((PetscObject)(*C),MATDENSE,&dense);
9468: if ((*C)->assembled && (seqdense || mpidense || dense)) {
9469: /* user wants to reuse an assembled dense matrix */
9470: /* Create product -- see MatCreateProduct() */
9471: MatProductCreate_Private(A,B,NULL,*C);
9472: product = (*C)->product;
9473: product->fill = fill;
9474: product->api_user = PETSC_TRUE;
9476: MatProductSetType(*C,MATPRODUCT_AtB);
9477: MatProductSetFromOptions(*C);
9478: } else SETERRQ(PetscObjectComm((PetscObject)(*C)),PETSC_ERR_SUP,"Call MatProductCreate() first");
9479: } else { /* user may chage input matrices A or B when REUSE */
9480: MatProductReplaceMats(A,B,NULL,*C);
9481: }
9482: }
9483: MatProductNumeric(*C);
9484: return(0);
9485: }
9487: /*@
9488: MatMatMatMult - Performs Matrix-Matrix-Matrix Multiplication D=A*B*C.
9490: Neighbor-wise Collective on Mat
9492: Input Parameters:
9493: + A - the left matrix
9494: . B - the middle matrix
9495: . C - the right matrix
9496: . scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
9497: - fill - expected fill as ratio of nnz(D)/(nnz(A) + nnz(B)+nnz(C)), use PETSC_DEFAULT if you do not have a good estimate
9498: if the result is a dense matrix this is irrelevent
9500: Output Parameters:
9501: . D - the product matrix
9503: Notes:
9504: Unless scall is MAT_REUSE_MATRIX D will be created.
9506: MAT_REUSE_MATRIX can only be used if the matrices A, B and C have the same nonzero pattern as in the previous call
9508: To determine the correct fill value, run with -info and search for the string "Fill ratio" to see the value
9509: actually needed.
9511: If you have many matrices with the same non-zero structure to multiply, you
9512: should use MAT_REUSE_MATRIX in all calls but the first or
9514: Level: intermediate
9516: .seealso: MatMatMult, MatPtAP()
9517: @*/
9518: PetscErrorCode MatMatMatMult(Mat A,Mat B,Mat C,MatReuse scall,PetscReal fill,Mat *D)
9519: {
9523: if (scall == MAT_INPLACE_MATRIX) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Inplace product not supported");
9525: if (scall == MAT_INITIAL_MATRIX) {
9526: MatProductCreate(A,B,C,D);
9527: MatProductSetType(*D,MATPRODUCT_ABC);
9528: MatProductSetAlgorithm(*D,"default");
9529: MatProductSetFill(*D,fill);
9531: (*D)->product->api_user = PETSC_TRUE;
9532: MatProductSetFromOptions(*D);
9534: MatProductSymbolic(*D);
9535: } else { /* user may chage input matrices when REUSE */
9536: MatProductReplaceMats(A,B,C,*D);
9537: }
9539: MatProductNumeric(*D);
9540: return(0);
9541: }
9543: /*@
9544: MatCreateRedundantMatrix - Create redundant matrices and put them into processors of subcommunicators.
9546: Collective on Mat
9548: Input Parameters:
9549: + mat - the matrix
9550: . nsubcomm - the number of subcommunicators (= number of redundant parallel or sequential matrices)
9551: . subcomm - MPI communicator split from the communicator where mat resides in (or MPI_COMM_NULL if nsubcomm is used)
9552: - reuse - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
9554: Output Parameter:
9555: . matredundant - redundant matrix
9557: Notes:
9558: MAT_REUSE_MATRIX can only be used when the nonzero structure of the
9559: original matrix has not changed from that last call to MatCreateRedundantMatrix().
9561: This routine creates the duplicated matrices in subcommunicators; you should NOT create them before
9562: calling it.
9564: Level: advanced
9567: .seealso: MatDestroy()
9568: @*/
9569: PetscErrorCode MatCreateRedundantMatrix(Mat mat,PetscInt nsubcomm,MPI_Comm subcomm,MatReuse reuse,Mat *matredundant)
9570: {
9572: MPI_Comm comm;
9573: PetscMPIInt size;
9574: PetscInt mloc_sub,nloc_sub,rstart,rend,M=mat->rmap->N,N=mat->cmap->N,bs=mat->rmap->bs;
9575: Mat_Redundant *redund=NULL;
9576: PetscSubcomm psubcomm=NULL;
9577: MPI_Comm subcomm_in=subcomm;
9578: Mat *matseq;
9579: IS isrow,iscol;
9580: PetscBool newsubcomm=PETSC_FALSE;
9584: if (nsubcomm && reuse == MAT_REUSE_MATRIX) {
9587: }
9589: MPI_Comm_size(PetscObjectComm((PetscObject)mat),&size);
9590: if (size == 1 || nsubcomm == 1) {
9591: if (reuse == MAT_INITIAL_MATRIX) {
9592: MatDuplicate(mat,MAT_COPY_VALUES,matredundant);
9593: } else {
9594: if (*matredundant == mat) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONG,"MAT_REUSE_MATRIX means reuse the matrix passed in as the final argument, not the original matrix");
9595: MatCopy(mat,*matredundant,SAME_NONZERO_PATTERN);
9596: }
9597: return(0);
9598: }
9600: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
9601: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
9602: MatCheckPreallocated(mat,1);
9604: PetscLogEventBegin(MAT_RedundantMat,mat,0,0,0);
9605: if (subcomm_in == MPI_COMM_NULL && reuse == MAT_INITIAL_MATRIX) { /* get subcomm if user does not provide subcomm */
9606: /* create psubcomm, then get subcomm */
9607: PetscObjectGetComm((PetscObject)mat,&comm);
9608: MPI_Comm_size(comm,&size);
9609: if (nsubcomm < 1 || nsubcomm > size) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"nsubcomm must between 1 and %D",size);
9611: PetscSubcommCreate(comm,&psubcomm);
9612: PetscSubcommSetNumber(psubcomm,nsubcomm);
9613: PetscSubcommSetType(psubcomm,PETSC_SUBCOMM_CONTIGUOUS);
9614: PetscSubcommSetFromOptions(psubcomm);
9615: PetscCommDuplicate(PetscSubcommChild(psubcomm),&subcomm,NULL);
9616: newsubcomm = PETSC_TRUE;
9617: PetscSubcommDestroy(&psubcomm);
9618: }
9620: /* get isrow, iscol and a local sequential matrix matseq[0] */
9621: if (reuse == MAT_INITIAL_MATRIX) {
9622: mloc_sub = PETSC_DECIDE;
9623: nloc_sub = PETSC_DECIDE;
9624: if (bs < 1) {
9625: PetscSplitOwnership(subcomm,&mloc_sub,&M);
9626: PetscSplitOwnership(subcomm,&nloc_sub,&N);
9627: } else {
9628: PetscSplitOwnershipBlock(subcomm,bs,&mloc_sub,&M);
9629: PetscSplitOwnershipBlock(subcomm,bs,&nloc_sub,&N);
9630: }
9631: MPI_Scan(&mloc_sub,&rend,1,MPIU_INT,MPI_SUM,subcomm);
9632: rstart = rend - mloc_sub;
9633: ISCreateStride(PETSC_COMM_SELF,mloc_sub,rstart,1,&isrow);
9634: ISCreateStride(PETSC_COMM_SELF,N,0,1,&iscol);
9635: } else { /* reuse == MAT_REUSE_MATRIX */
9636: if (*matredundant == mat) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONG,"MAT_REUSE_MATRIX means reuse the matrix passed in as the final argument, not the original matrix");
9637: /* retrieve subcomm */
9638: PetscObjectGetComm((PetscObject)(*matredundant),&subcomm);
9639: redund = (*matredundant)->redundant;
9640: isrow = redund->isrow;
9641: iscol = redund->iscol;
9642: matseq = redund->matseq;
9643: }
9644: MatCreateSubMatrices(mat,1,&isrow,&iscol,reuse,&matseq);
9646: /* get matredundant over subcomm */
9647: if (reuse == MAT_INITIAL_MATRIX) {
9648: MatCreateMPIMatConcatenateSeqMat(subcomm,matseq[0],nloc_sub,reuse,matredundant);
9650: /* create a supporting struct and attach it to C for reuse */
9651: PetscNewLog(*matredundant,&redund);
9652: (*matredundant)->redundant = redund;
9653: redund->isrow = isrow;
9654: redund->iscol = iscol;
9655: redund->matseq = matseq;
9656: if (newsubcomm) {
9657: redund->subcomm = subcomm;
9658: } else {
9659: redund->subcomm = MPI_COMM_NULL;
9660: }
9661: } else {
9662: MatCreateMPIMatConcatenateSeqMat(subcomm,matseq[0],PETSC_DECIDE,reuse,matredundant);
9663: }
9664: PetscLogEventEnd(MAT_RedundantMat,mat,0,0,0);
9665: return(0);
9666: }
9668: /*@C
9669: MatGetMultiProcBlock - Create multiple [bjacobi] 'parallel submatrices' from
9670: a given 'mat' object. Each submatrix can span multiple procs.
9672: Collective on Mat
9674: Input Parameters:
9675: + mat - the matrix
9676: . subcomm - the subcommunicator obtained by com_split(comm)
9677: - scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
9679: Output Parameter:
9680: . subMat - 'parallel submatrices each spans a given subcomm
9682: Notes:
9683: The submatrix partition across processors is dictated by 'subComm' a
9684: communicator obtained by com_split(comm). The comm_split
9685: is not restriced to be grouped with consecutive original ranks.
9687: Due the comm_split() usage, the parallel layout of the submatrices
9688: map directly to the layout of the original matrix [wrt the local
9689: row,col partitioning]. So the original 'DiagonalMat' naturally maps
9690: into the 'DiagonalMat' of the subMat, hence it is used directly from
9691: the subMat. However the offDiagMat looses some columns - and this is
9692: reconstructed with MatSetValues()
9694: Level: advanced
9697: .seealso: MatCreateSubMatrices()
9698: @*/
9699: PetscErrorCode MatGetMultiProcBlock(Mat mat, MPI_Comm subComm, MatReuse scall,Mat *subMat)
9700: {
9702: PetscMPIInt commsize,subCommSize;
9705: MPI_Comm_size(PetscObjectComm((PetscObject)mat),&commsize);
9706: MPI_Comm_size(subComm,&subCommSize);
9707: if (subCommSize > commsize) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_OUTOFRANGE,"CommSize %D < SubCommZize %D",commsize,subCommSize);
9709: if (scall == MAT_REUSE_MATRIX && *subMat == mat) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONG,"MAT_REUSE_MATRIX means reuse the matrix passed in as the final argument, not the original matrix");
9710: PetscLogEventBegin(MAT_GetMultiProcBlock,mat,0,0,0);
9711: (*mat->ops->getmultiprocblock)(mat,subComm,scall,subMat);
9712: PetscLogEventEnd(MAT_GetMultiProcBlock,mat,0,0,0);
9713: return(0);
9714: }
9716: /*@
9717: MatGetLocalSubMatrix - Gets a reference to a submatrix specified in local numbering
9719: Not Collective
9721: Input Arguments:
9722: + mat - matrix to extract local submatrix from
9723: . isrow - local row indices for submatrix
9724: - iscol - local column indices for submatrix
9726: Output Arguments:
9727: . submat - the submatrix
9729: Level: intermediate
9731: Notes:
9732: The submat should be returned with MatRestoreLocalSubMatrix().
9734: Depending on the format of mat, the returned submat may not implement MatMult(). Its communicator may be
9735: the same as mat, it may be PETSC_COMM_SELF, or some other subcomm of mat's.
9737: The submat always implements MatSetValuesLocal(). If isrow and iscol have the same block size, then
9738: MatSetValuesBlockedLocal() will also be implemented.
9740: The mat must have had a ISLocalToGlobalMapping provided to it with MatSetLocalToGlobalMapping(). Note that
9741: matrices obtained with DMCreateMatrix() generally already have the local to global mapping provided.
9743: .seealso: MatRestoreLocalSubMatrix(), MatCreateLocalRef(), MatSetLocalToGlobalMapping()
9744: @*/
9745: PetscErrorCode MatGetLocalSubMatrix(Mat mat,IS isrow,IS iscol,Mat *submat)
9746: {
9755: if (!mat->rmap->mapping) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Matrix must have local to global mapping provided before this call");
9757: if (mat->ops->getlocalsubmatrix) {
9758: (*mat->ops->getlocalsubmatrix)(mat,isrow,iscol,submat);
9759: } else {
9760: MatCreateLocalRef(mat,isrow,iscol,submat);
9761: }
9762: return(0);
9763: }
9765: /*@
9766: MatRestoreLocalSubMatrix - Restores a reference to a submatrix specified in local numbering
9768: Not Collective
9770: Input Arguments:
9771: mat - matrix to extract local submatrix from
9772: isrow - local row indices for submatrix
9773: iscol - local column indices for submatrix
9774: submat - the submatrix
9776: Level: intermediate
9778: .seealso: MatGetLocalSubMatrix()
9779: @*/
9780: PetscErrorCode MatRestoreLocalSubMatrix(Mat mat,IS isrow,IS iscol,Mat *submat)
9781: {
9790: if (*submat) {
9792: }
9794: if (mat->ops->restorelocalsubmatrix) {
9795: (*mat->ops->restorelocalsubmatrix)(mat,isrow,iscol,submat);
9796: } else {
9797: MatDestroy(submat);
9798: }
9799: *submat = NULL;
9800: return(0);
9801: }
9803: /* --------------------------------------------------------*/
9804: /*@
9805: MatFindZeroDiagonals - Finds all the rows of a matrix that have zero or no diagonal entry in the matrix
9807: Collective on Mat
9809: Input Parameter:
9810: . mat - the matrix
9812: Output Parameter:
9813: . is - if any rows have zero diagonals this contains the list of them
9815: Level: developer
9817: .seealso: MatMultTranspose(), MatMultAdd(), MatMultTransposeAdd()
9818: @*/
9819: PetscErrorCode MatFindZeroDiagonals(Mat mat,IS *is)
9820: {
9826: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
9827: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
9829: if (!mat->ops->findzerodiagonals) {
9830: Vec diag;
9831: const PetscScalar *a;
9832: PetscInt *rows;
9833: PetscInt rStart, rEnd, r, nrow = 0;
9835: MatCreateVecs(mat, &diag, NULL);
9836: MatGetDiagonal(mat, diag);
9837: MatGetOwnershipRange(mat, &rStart, &rEnd);
9838: VecGetArrayRead(diag, &a);
9839: for (r = 0; r < rEnd-rStart; ++r) if (a[r] == 0.0) ++nrow;
9840: PetscMalloc1(nrow, &rows);
9841: nrow = 0;
9842: for (r = 0; r < rEnd-rStart; ++r) if (a[r] == 0.0) rows[nrow++] = r+rStart;
9843: VecRestoreArrayRead(diag, &a);
9844: VecDestroy(&diag);
9845: ISCreateGeneral(PetscObjectComm((PetscObject) mat), nrow, rows, PETSC_OWN_POINTER, is);
9846: } else {
9847: (*mat->ops->findzerodiagonals)(mat, is);
9848: }
9849: return(0);
9850: }
9852: /*@
9853: MatFindOffBlockDiagonalEntries - Finds all the rows of a matrix that have entries outside of the main diagonal block (defined by the matrix block size)
9855: Collective on Mat
9857: Input Parameter:
9858: . mat - the matrix
9860: Output Parameter:
9861: . is - contains the list of rows with off block diagonal entries
9863: Level: developer
9865: .seealso: MatMultTranspose(), MatMultAdd(), MatMultTransposeAdd()
9866: @*/
9867: PetscErrorCode MatFindOffBlockDiagonalEntries(Mat mat,IS *is)
9868: {
9874: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
9875: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
9877: if (!mat->ops->findoffblockdiagonalentries) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Matrix type %s does not have a find off block diagonal entries defined",((PetscObject)mat)->type_name);
9878: (*mat->ops->findoffblockdiagonalentries)(mat,is);
9879: return(0);
9880: }
9882: /*@C
9883: MatInvertBlockDiagonal - Inverts the block diagonal entries.
9885: Collective on Mat
9887: Input Parameters:
9888: . mat - the matrix
9890: Output Parameters:
9891: . values - the block inverses in column major order (FORTRAN-like)
9893: Note:
9894: This routine is not available from Fortran.
9896: Level: advanced
9898: .seealso: MatInvertBockDiagonalMat
9899: @*/
9900: PetscErrorCode MatInvertBlockDiagonal(Mat mat,const PetscScalar **values)
9901: {
9906: if (!mat->assembled) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
9907: if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
9908: if (!mat->ops->invertblockdiagonal) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Not supported for type %s",((PetscObject)mat)->type_name);
9909: (*mat->ops->invertblockdiagonal)(mat,values);
9910: return(0);
9911: }
9913: /*@C
9914: MatInvertVariableBlockDiagonal - Inverts the block diagonal entries.
9916: Collective on Mat
9918: Input Parameters:
9919: + mat - the matrix
9920: . nblocks - the number of blocks
9921: - bsizes - the size of each block
9923: Output Parameters:
9924: . values - the block inverses in column major order (FORTRAN-like)
9926: Note:
9927: This routine is not available from Fortran.
9929: Level: advanced
9931: .seealso: MatInvertBockDiagonal()
9932: @*/
9933: PetscErrorCode MatInvertVariableBlockDiagonal(Mat mat,PetscInt nblocks,const PetscInt *bsizes,PetscScalar *values)
9934: {
9939: if (!mat->assembled) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
9940: if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
9941: if (!mat->ops->invertvariableblockdiagonal) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Not supported for type",((PetscObject)mat)->type_name);
9942: (*mat->ops->invertvariableblockdiagonal)(mat,nblocks,bsizes,values);
9943: return(0);
9944: }
9946: /*@
9947: MatInvertBlockDiagonalMat - set matrix C to be the inverted block diagonal of matrix A
9949: Collective on Mat
9951: Input Parameters:
9952: . A - the matrix
9954: Output Parameters:
9955: . C - matrix with inverted block diagonal of A. This matrix should be created and may have its type set.
9957: Notes: the blocksize of the matrix is used to determine the blocks on the diagonal of C
9959: Level: advanced
9961: .seealso: MatInvertBockDiagonal()
9962: @*/
9963: PetscErrorCode MatInvertBlockDiagonalMat(Mat A,Mat C)
9964: {
9965: PetscErrorCode ierr;
9966: const PetscScalar *vals;
9967: PetscInt *dnnz;
9968: PetscInt M,N,m,n,rstart,rend,bs,i,j;
9971: MatInvertBlockDiagonal(A,&vals);
9972: MatGetBlockSize(A,&bs);
9973: MatGetSize(A,&M,&N);
9974: MatGetLocalSize(A,&m,&n);
9975: MatSetSizes(C,m,n,M,N);
9976: MatSetBlockSize(C,bs);
9977: PetscMalloc1(m/bs,&dnnz);
9978: for (j = 0; j < m/bs; j++) dnnz[j] = 1;
9979: MatXAIJSetPreallocation(C,bs,dnnz,NULL,NULL,NULL);
9980: PetscFree(dnnz);
9981: MatGetOwnershipRange(C,&rstart,&rend);
9982: MatSetOption(C,MAT_ROW_ORIENTED,PETSC_FALSE);
9983: for (i = rstart/bs; i < rend/bs; i++) {
9984: MatSetValuesBlocked(C,1,&i,1,&i,&vals[(i-rstart/bs)*bs*bs],INSERT_VALUES);
9985: }
9986: MatAssemblyBegin(C,MAT_FINAL_ASSEMBLY);
9987: MatAssemblyEnd(C,MAT_FINAL_ASSEMBLY);
9988: MatSetOption(C,MAT_ROW_ORIENTED,PETSC_TRUE);
9989: return(0);
9990: }
9992: /*@C
9993: MatTransposeColoringDestroy - Destroys a coloring context for matrix product C=A*B^T that was created
9994: via MatTransposeColoringCreate().
9996: Collective on MatTransposeColoring
9998: Input Parameter:
9999: . c - coloring context
10001: Level: intermediate
10003: .seealso: MatTransposeColoringCreate()
10004: @*/
10005: PetscErrorCode MatTransposeColoringDestroy(MatTransposeColoring *c)
10006: {
10007: PetscErrorCode ierr;
10008: MatTransposeColoring matcolor=*c;
10011: if (!matcolor) return(0);
10012: if (--((PetscObject)matcolor)->refct > 0) {matcolor = 0; return(0);}
10014: PetscFree3(matcolor->ncolumns,matcolor->nrows,matcolor->colorforrow);
10015: PetscFree(matcolor->rows);
10016: PetscFree(matcolor->den2sp);
10017: PetscFree(matcolor->colorforcol);
10018: PetscFree(matcolor->columns);
10019: if (matcolor->brows>0) {
10020: PetscFree(matcolor->lstart);
10021: }
10022: PetscHeaderDestroy(c);
10023: return(0);
10024: }
10026: /*@C
10027: MatTransColoringApplySpToDen - Given a symbolic matrix product C=A*B^T for which
10028: a MatTransposeColoring context has been created, computes a dense B^T by Apply
10029: MatTransposeColoring to sparse B.
10031: Collective on MatTransposeColoring
10033: Input Parameters:
10034: + B - sparse matrix B
10035: . Btdense - symbolic dense matrix B^T
10036: - coloring - coloring context created with MatTransposeColoringCreate()
10038: Output Parameter:
10039: . Btdense - dense matrix B^T
10041: Level: advanced
10043: Notes:
10044: These are used internally for some implementations of MatRARt()
10046: .seealso: MatTransposeColoringCreate(), MatTransposeColoringDestroy(), MatTransColoringApplyDenToSp()
10048: @*/
10049: PetscErrorCode MatTransColoringApplySpToDen(MatTransposeColoring coloring,Mat B,Mat Btdense)
10050: {
10058: if (!B->ops->transcoloringapplysptoden) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Not supported for this matrix type %s",((PetscObject)B)->type_name);
10059: (B->ops->transcoloringapplysptoden)(coloring,B,Btdense);
10060: return(0);
10061: }
10063: /*@C
10064: MatTransColoringApplyDenToSp - Given a symbolic matrix product Csp=A*B^T for which
10065: a MatTransposeColoring context has been created and a dense matrix Cden=A*Btdense
10066: in which Btdens is obtained from MatTransColoringApplySpToDen(), recover sparse matrix
10067: Csp from Cden.
10069: Collective on MatTransposeColoring
10071: Input Parameters:
10072: + coloring - coloring context created with MatTransposeColoringCreate()
10073: - Cden - matrix product of a sparse matrix and a dense matrix Btdense
10075: Output Parameter:
10076: . Csp - sparse matrix
10078: Level: advanced
10080: Notes:
10081: These are used internally for some implementations of MatRARt()
10083: .seealso: MatTransposeColoringCreate(), MatTransposeColoringDestroy(), MatTransColoringApplySpToDen()
10085: @*/
10086: PetscErrorCode MatTransColoringApplyDenToSp(MatTransposeColoring matcoloring,Mat Cden,Mat Csp)
10087: {
10095: if (!Csp->ops->transcoloringapplydentosp) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Not supported for this matrix type %s",((PetscObject)Csp)->type_name);
10096: (Csp->ops->transcoloringapplydentosp)(matcoloring,Cden,Csp);
10097: return(0);
10098: }
10100: /*@C
10101: MatTransposeColoringCreate - Creates a matrix coloring context for matrix product C=A*B^T.
10103: Collective on Mat
10105: Input Parameters:
10106: + mat - the matrix product C
10107: - iscoloring - the coloring of the matrix; usually obtained with MatColoringCreate() or DMCreateColoring()
10109: Output Parameter:
10110: . color - the new coloring context
10112: Level: intermediate
10114: .seealso: MatTransposeColoringDestroy(), MatTransColoringApplySpToDen(),
10115: MatTransColoringApplyDenToSp()
10116: @*/
10117: PetscErrorCode MatTransposeColoringCreate(Mat mat,ISColoring iscoloring,MatTransposeColoring *color)
10118: {
10119: MatTransposeColoring c;
10120: MPI_Comm comm;
10121: PetscErrorCode ierr;
10124: PetscLogEventBegin(MAT_TransposeColoringCreate,mat,0,0,0);
10125: PetscObjectGetComm((PetscObject)mat,&comm);
10126: PetscHeaderCreate(c,MAT_TRANSPOSECOLORING_CLASSID,"MatTransposeColoring","Matrix product C=A*B^T via coloring","Mat",comm,MatTransposeColoringDestroy,NULL);
10128: c->ctype = iscoloring->ctype;
10129: if (mat->ops->transposecoloringcreate) {
10130: (*mat->ops->transposecoloringcreate)(mat,iscoloring,c);
10131: } else SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Code not yet written for matrix type %s",((PetscObject)mat)->type_name);
10133: *color = c;
10134: PetscLogEventEnd(MAT_TransposeColoringCreate,mat,0,0,0);
10135: return(0);
10136: }
10138: /*@
10139: MatGetNonzeroState - Returns a 64 bit integer representing the current state of nonzeros in the matrix. If the
10140: matrix has had no new nonzero locations added to the matrix since the previous call then the value will be the
10141: same, otherwise it will be larger
10143: Not Collective
10145: Input Parameter:
10146: . A - the matrix
10148: Output Parameter:
10149: . state - the current state
10151: Notes:
10152: You can only compare states from two different calls to the SAME matrix, you cannot compare calls between
10153: different matrices
10155: Level: intermediate
10157: @*/
10158: PetscErrorCode MatGetNonzeroState(Mat mat,PetscObjectState *state)
10159: {
10162: *state = mat->nonzerostate;
10163: return(0);
10164: }
10166: /*@
10167: MatCreateMPIMatConcatenateSeqMat - Creates a single large PETSc matrix by concatenating sequential
10168: matrices from each processor
10170: Collective
10172: Input Parameters:
10173: + comm - the communicators the parallel matrix will live on
10174: . seqmat - the input sequential matrices
10175: . n - number of local columns (or PETSC_DECIDE)
10176: - reuse - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
10178: Output Parameter:
10179: . mpimat - the parallel matrix generated
10181: Level: advanced
10183: Notes:
10184: The number of columns of the matrix in EACH processor MUST be the same.
10186: @*/
10187: PetscErrorCode MatCreateMPIMatConcatenateSeqMat(MPI_Comm comm,Mat seqmat,PetscInt n,MatReuse reuse,Mat *mpimat)
10188: {
10192: if (!seqmat->ops->creatempimatconcatenateseqmat) SETERRQ1(PetscObjectComm((PetscObject)seqmat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)seqmat)->type_name);
10193: if (reuse == MAT_REUSE_MATRIX && seqmat == *mpimat) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONG,"MAT_REUSE_MATRIX means reuse the matrix passed in as the final argument, not the original matrix");
10195: PetscLogEventBegin(MAT_Merge,seqmat,0,0,0);
10196: (*seqmat->ops->creatempimatconcatenateseqmat)(comm,seqmat,n,reuse,mpimat);
10197: PetscLogEventEnd(MAT_Merge,seqmat,0,0,0);
10198: return(0);
10199: }
10201: /*@
10202: MatSubdomainsCreateCoalesce - Creates index subdomains by coalescing adjacent
10203: ranks' ownership ranges.
10205: Collective on A
10207: Input Parameters:
10208: + A - the matrix to create subdomains from
10209: - N - requested number of subdomains
10212: Output Parameters:
10213: + n - number of subdomains resulting on this rank
10214: - iss - IS list with indices of subdomains on this rank
10216: Level: advanced
10218: Notes:
10219: number of subdomains must be smaller than the communicator size
10220: @*/
10221: PetscErrorCode MatSubdomainsCreateCoalesce(Mat A,PetscInt N,PetscInt *n,IS *iss[])
10222: {
10223: MPI_Comm comm,subcomm;
10224: PetscMPIInt size,rank,color;
10225: PetscInt rstart,rend,k;
10226: PetscErrorCode ierr;
10229: PetscObjectGetComm((PetscObject)A,&comm);
10230: MPI_Comm_size(comm,&size);
10231: MPI_Comm_rank(comm,&rank);
10232: if (N < 1 || N >= (PetscInt)size) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONG,"number of subdomains must be > 0 and < %D, got N = %D",size,N);
10233: *n = 1;
10234: k = ((PetscInt)size)/N + ((PetscInt)size%N>0); /* There are up to k ranks to a color */
10235: color = rank/k;
10236: MPI_Comm_split(comm,color,rank,&subcomm);
10237: PetscMalloc1(1,iss);
10238: MatGetOwnershipRange(A,&rstart,&rend);
10239: ISCreateStride(subcomm,rend-rstart,rstart,1,iss[0]);
10240: MPI_Comm_free(&subcomm);
10241: return(0);
10242: }
10244: /*@
10245: MatGalerkin - Constructs the coarse grid problem via Galerkin projection.
10247: If the interpolation and restriction operators are the same, uses MatPtAP.
10248: If they are not the same, use MatMatMatMult.
10250: Once the coarse grid problem is constructed, correct for interpolation operators
10251: that are not of full rank, which can legitimately happen in the case of non-nested
10252: geometric multigrid.
10254: Input Parameters:
10255: + restrct - restriction operator
10256: . dA - fine grid matrix
10257: . interpolate - interpolation operator
10258: . reuse - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
10259: - fill - expected fill, use PETSC_DEFAULT if you do not have a good estimate
10261: Output Parameters:
10262: . A - the Galerkin coarse matrix
10264: Options Database Key:
10265: . -pc_mg_galerkin <both,pmat,mat,none>
10267: Level: developer
10269: .seealso: MatPtAP(), MatMatMatMult()
10270: @*/
10271: PetscErrorCode MatGalerkin(Mat restrct, Mat dA, Mat interpolate, MatReuse reuse, PetscReal fill, Mat *A)
10272: {
10274: IS zerorows;
10275: Vec diag;
10278: if (reuse == MAT_INPLACE_MATRIX) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Inplace product not supported");
10279: /* Construct the coarse grid matrix */
10280: if (interpolate == restrct) {
10281: MatPtAP(dA,interpolate,reuse,fill,A);
10282: } else {
10283: MatMatMatMult(restrct,dA,interpolate,reuse,fill,A);
10284: }
10286: /* If the interpolation matrix is not of full rank, A will have zero rows.
10287: This can legitimately happen in the case of non-nested geometric multigrid.
10288: In that event, we set the rows of the matrix to the rows of the identity,
10289: ignoring the equations (as the RHS will also be zero). */
10291: MatFindZeroRows(*A, &zerorows);
10293: if (zerorows != NULL) { /* if there are any zero rows */
10294: MatCreateVecs(*A, &diag, NULL);
10295: MatGetDiagonal(*A, diag);
10296: VecISSet(diag, zerorows, 1.0);
10297: MatDiagonalSet(*A, diag, INSERT_VALUES);
10298: VecDestroy(&diag);
10299: ISDestroy(&zerorows);
10300: }
10301: return(0);
10302: }
10304: /*@C
10305: MatSetOperation - Allows user to set a matrix operation for any matrix type
10307: Logically Collective on Mat
10309: Input Parameters:
10310: + mat - the matrix
10311: . op - the name of the operation
10312: - f - the function that provides the operation
10314: Level: developer
10316: Usage:
10317: $ extern PetscErrorCode usermult(Mat,Vec,Vec);
10318: $ MatCreateXXX(comm,...&A);
10319: $ MatSetOperation(A,MATOP_MULT,(void(*)(void))usermult);
10321: Notes:
10322: See the file include/petscmat.h for a complete list of matrix
10323: operations, which all have the form MATOP_<OPERATION>, where
10324: <OPERATION> is the name (in all capital letters) of the
10325: user interface routine (e.g., MatMult() -> MATOP_MULT).
10327: All user-provided functions (except for MATOP_DESTROY) should have the same calling
10328: sequence as the usual matrix interface routines, since they
10329: are intended to be accessed via the usual matrix interface
10330: routines, e.g.,
10331: $ MatMult(Mat,Vec,Vec) -> usermult(Mat,Vec,Vec)
10333: In particular each function MUST return an error code of 0 on success and
10334: nonzero on failure.
10336: This routine is distinct from MatShellSetOperation() in that it can be called on any matrix type.
10338: .seealso: MatGetOperation(), MatCreateShell(), MatShellSetContext(), MatShellSetOperation()
10339: @*/
10340: PetscErrorCode MatSetOperation(Mat mat,MatOperation op,void (*f)(void))
10341: {
10344: if (op == MATOP_VIEW && !mat->ops->viewnative && f != (void (*)(void))(mat->ops->view)) {
10345: mat->ops->viewnative = mat->ops->view;
10346: }
10347: (((void(**)(void))mat->ops)[op]) = f;
10348: return(0);
10349: }
10351: /*@C
10352: MatGetOperation - Gets a matrix operation for any matrix type.
10354: Not Collective
10356: Input Parameters:
10357: + mat - the matrix
10358: - op - the name of the operation
10360: Output Parameter:
10361: . f - the function that provides the operation
10363: Level: developer
10365: Usage:
10366: $ PetscErrorCode (*usermult)(Mat,Vec,Vec);
10367: $ MatGetOperation(A,MATOP_MULT,(void(**)(void))&usermult);
10369: Notes:
10370: See the file include/petscmat.h for a complete list of matrix
10371: operations, which all have the form MATOP_<OPERATION>, where
10372: <OPERATION> is the name (in all capital letters) of the
10373: user interface routine (e.g., MatMult() -> MATOP_MULT).
10375: This routine is distinct from MatShellGetOperation() in that it can be called on any matrix type.
10377: .seealso: MatSetOperation(), MatCreateShell(), MatShellGetContext(), MatShellGetOperation()
10378: @*/
10379: PetscErrorCode MatGetOperation(Mat mat,MatOperation op,void(**f)(void))
10380: {
10383: *f = (((void (**)(void))mat->ops)[op]);
10384: return(0);
10385: }
10387: /*@
10388: MatHasOperation - Determines whether the given matrix supports the particular
10389: operation.
10391: Not Collective
10393: Input Parameters:
10394: + mat - the matrix
10395: - op - the operation, for example, MATOP_GET_DIAGONAL
10397: Output Parameter:
10398: . has - either PETSC_TRUE or PETSC_FALSE
10400: Level: advanced
10402: Notes:
10403: See the file include/petscmat.h for a complete list of matrix
10404: operations, which all have the form MATOP_<OPERATION>, where
10405: <OPERATION> is the name (in all capital letters) of the
10406: user-level routine. E.g., MatNorm() -> MATOP_NORM.
10408: .seealso: MatCreateShell()
10409: @*/
10410: PetscErrorCode MatHasOperation(Mat mat,MatOperation op,PetscBool *has)
10411: {
10418: if (mat->ops->hasoperation) {
10419: (*mat->ops->hasoperation)(mat,op,has);
10420: } else {
10421: if (((void**)mat->ops)[op]) *has = PETSC_TRUE;
10422: else {
10423: *has = PETSC_FALSE;
10424: if (op == MATOP_CREATE_SUBMATRIX) {
10425: PetscMPIInt size;
10427: MPI_Comm_size(PetscObjectComm((PetscObject)mat),&size);
10428: if (size == 1) {
10429: MatHasOperation(mat,MATOP_CREATE_SUBMATRICES,has);
10430: }
10431: }
10432: }
10433: }
10434: return(0);
10435: }
10437: /*@
10438: MatHasCongruentLayouts - Determines whether the rows and columns layouts
10439: of the matrix are congruent
10441: Collective on mat
10443: Input Parameters:
10444: . mat - the matrix
10446: Output Parameter:
10447: . cong - either PETSC_TRUE or PETSC_FALSE
10449: Level: beginner
10451: Notes:
10453: .seealso: MatCreate(), MatSetSizes()
10454: @*/
10455: PetscErrorCode MatHasCongruentLayouts(Mat mat,PetscBool *cong)
10456: {
10463: if (!mat->rmap || !mat->cmap) {
10464: *cong = mat->rmap == mat->cmap ? PETSC_TRUE : PETSC_FALSE;
10465: return(0);
10466: }
10467: if (mat->congruentlayouts == PETSC_DECIDE) { /* first time we compare rows and cols layouts */
10468: PetscLayoutCompare(mat->rmap,mat->cmap,cong);
10469: if (*cong) mat->congruentlayouts = 1;
10470: else mat->congruentlayouts = 0;
10471: } else *cong = mat->congruentlayouts ? PETSC_TRUE : PETSC_FALSE;
10472: return(0);
10473: }
10475: /*@
10476: MatFreeIntermediateDataStructures - Free intermediate data structures created for reuse,
10477: e.g., matrx product of MatPtAP.
10479: Collective on mat
10481: Input Parameters:
10482: . mat - the matrix
10484: Output Parameter:
10485: . mat - the matrix with intermediate data structures released
10487: Level: advanced
10489: Notes:
10491: .seealso: MatPtAP(), MatMatMult()
10492: @*/
10493: PetscErrorCode MatFreeIntermediateDataStructures(Mat mat)
10494: {
10500: if (mat->ops->freeintermediatedatastructures) {
10501: (*mat->ops->freeintermediatedatastructures)(mat);
10502: }
10503: return(0);
10504: }