Actual source code: matrix.c
petsc-3.11.4 2019-09-28
2: /*
3: This is where the abstract matrix operations are defined
4: */
6: #include <petsc/private/matimpl.h>
7: #include <petsc/private/isimpl.h>
8: #include <petsc/private/vecimpl.h>
10: /* Logging support */
11: PetscClassId MAT_CLASSID;
12: PetscClassId MAT_COLORING_CLASSID;
13: PetscClassId MAT_FDCOLORING_CLASSID;
14: PetscClassId MAT_TRANSPOSECOLORING_CLASSID;
16: PetscLogEvent MAT_Mult, MAT_Mults, MAT_MultConstrained, MAT_MultAdd, MAT_MultTranspose;
17: PetscLogEvent MAT_MultTransposeConstrained, MAT_MultTransposeAdd, MAT_Solve, MAT_Solves, MAT_SolveAdd, MAT_SolveTranspose, MAT_MatSolve,MAT_MatTrSolve;
18: PetscLogEvent MAT_SolveTransposeAdd, MAT_SOR, MAT_ForwardSolve, MAT_BackwardSolve, MAT_LUFactor, MAT_LUFactorSymbolic;
19: PetscLogEvent MAT_LUFactorNumeric, MAT_CholeskyFactor, MAT_CholeskyFactorSymbolic, MAT_CholeskyFactorNumeric, MAT_ILUFactor;
20: PetscLogEvent MAT_ILUFactorSymbolic, MAT_ICCFactorSymbolic, MAT_Copy, MAT_Convert, MAT_Scale, MAT_AssemblyBegin;
21: PetscLogEvent MAT_AssemblyEnd, MAT_SetValues, MAT_GetValues, MAT_GetRow, MAT_GetRowIJ, MAT_CreateSubMats, MAT_GetOrdering, MAT_RedundantMat, MAT_GetSeqNonzeroStructure;
22: PetscLogEvent MAT_IncreaseOverlap, MAT_Partitioning, MAT_PartitioningND, MAT_Coarsen, MAT_ZeroEntries, MAT_Load, MAT_View, MAT_AXPY, MAT_FDColoringCreate;
23: PetscLogEvent MAT_FDColoringSetUp, MAT_FDColoringApply,MAT_Transpose,MAT_FDColoringFunction, MAT_CreateSubMat;
24: PetscLogEvent MAT_TransposeColoringCreate;
25: PetscLogEvent MAT_MatMult, MAT_MatMultSymbolic, MAT_MatMultNumeric;
26: PetscLogEvent MAT_PtAP, MAT_PtAPSymbolic, MAT_PtAPNumeric,MAT_RARt, MAT_RARtSymbolic, MAT_RARtNumeric;
27: PetscLogEvent MAT_MatTransposeMult, MAT_MatTransposeMultSymbolic, MAT_MatTransposeMultNumeric;
28: PetscLogEvent MAT_TransposeMatMult, MAT_TransposeMatMultSymbolic, MAT_TransposeMatMultNumeric;
29: PetscLogEvent MAT_MatMatMult, MAT_MatMatMultSymbolic, MAT_MatMatMultNumeric;
30: PetscLogEvent MAT_MultHermitianTranspose,MAT_MultHermitianTransposeAdd;
31: PetscLogEvent MAT_Getsymtranspose, MAT_Getsymtransreduced, MAT_Transpose_SeqAIJ, MAT_GetBrowsOfAcols;
32: PetscLogEvent MAT_GetBrowsOfAocols, MAT_Getlocalmat, MAT_Getlocalmatcondensed, MAT_Seqstompi, MAT_Seqstompinum, MAT_Seqstompisym;
33: PetscLogEvent MAT_Applypapt, MAT_Applypapt_numeric, MAT_Applypapt_symbolic, MAT_GetSequentialNonzeroStructure;
34: PetscLogEvent MAT_GetMultiProcBlock;
35: PetscLogEvent MAT_CUSPARSECopyToGPU, MAT_SetValuesBatch;
36: PetscLogEvent MAT_ViennaCLCopyToGPU;
37: PetscLogEvent MAT_Merge,MAT_Residual,MAT_SetRandom;
38: PetscLogEvent MATCOLORING_Apply,MATCOLORING_Comm,MATCOLORING_Local,MATCOLORING_ISCreate,MATCOLORING_SetUp,MATCOLORING_Weights;
40: const char *const MatFactorTypes[] = {"NONE","LU","CHOLESKY","ILU","ICC","ILUDT","MatFactorType","MAT_FACTOR_",0};
42: /*@
43: 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: Logically Collective on Mat
47: Input Parameters:
48: + x - the matrix
49: - rctx - the random number context, formed by PetscRandomCreate(), or NULL and
50: it will create one internally.
52: Output Parameter:
53: . x - the matrix
55: Example of Usage:
56: .vb
57: PetscRandomCreate(PETSC_COMM_WORLD,&rctx);
58: MatSetRandom(x,rctx);
59: PetscRandomDestroy(rctx);
60: .ve
62: Level: intermediate
64: Concepts: matrix^setting to random
65: Concepts: random^matrix
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 SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Not coded for this matrix type");
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: #if defined(PETSC_HAVE_VIENNACL) || defined(PETSC_HAVE_CUDA)
392: if (mat->valid_GPU_matrix != PETSC_OFFLOAD_UNALLOCATED) {
393: mat->valid_GPU_matrix = PETSC_OFFLOAD_CPU;
394: }
395: #endif
396: return(0);
397: }
399: /*@C
400: MatGetGhosts - Get the global index of all ghost nodes defined by the sparse matrix
402: Collective on Mat
404: Input Parameter:
405: . mat - the matrix
407: Output Parameters:
408: + nghosts - number of ghosts (note for BAIJ matrices there is one ghost for each block)
409: - ghosts - the global indices of the ghost points
411: Notes:
412: the nghosts and ghosts are suitable to pass into VecCreateGhost()
414: Level: advanced
416: @*/
417: PetscErrorCode MatGetGhosts(Mat mat,PetscInt *nghosts,const PetscInt *ghosts[])
418: {
424: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
425: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
426: if (!mat->ops->getghosts) {
427: if (nghosts) *nghosts = 0;
428: if (ghosts) *ghosts = 0;
429: } else {
430: (*mat->ops->getghosts)(mat,nghosts,ghosts);
431: }
432: return(0);
433: }
436: /*@
437: MatImaginaryPart - Moves the imaginary part of the matrix to the real part and zeros the imaginary part
439: Logically Collective on Mat
441: Input Parameters:
442: . mat - the matrix
444: Level: advanced
447: .seealso: MatRealPart()
448: @*/
449: PetscErrorCode MatImaginaryPart(Mat mat)
450: {
456: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
457: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
458: if (!mat->ops->imaginarypart) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
459: MatCheckPreallocated(mat,1);
460: (*mat->ops->imaginarypart)(mat);
461: #if defined(PETSC_HAVE_VIENNACL) || defined(PETSC_HAVE_CUDA)
462: if (mat->valid_GPU_matrix != PETSC_OFFLOAD_UNALLOCATED) {
463: mat->valid_GPU_matrix = PETSC_OFFLOAD_CPU;
464: }
465: #endif
466: return(0);
467: }
469: /*@
470: MatMissingDiagonal - Determine if sparse matrix is missing a diagonal entry (or block entry for BAIJ matrices)
472: Not Collective
474: Input Parameter:
475: . mat - the matrix
477: Output Parameters:
478: + missing - is any diagonal missing
479: - dd - first diagonal entry that is missing (optional) on this process
481: Level: advanced
484: .seealso: MatRealPart()
485: @*/
486: PetscErrorCode MatMissingDiagonal(Mat mat,PetscBool *missing,PetscInt *dd)
487: {
493: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
494: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
495: if (!mat->ops->missingdiagonal) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
496: (*mat->ops->missingdiagonal)(mat,missing,dd);
497: return(0);
498: }
500: /*@C
501: MatGetRow - Gets a row of a matrix. You MUST call MatRestoreRow()
502: for each row that you get to ensure that your application does
503: not bleed memory.
505: Not Collective
507: Input Parameters:
508: + mat - the matrix
509: - row - the row to get
511: Output Parameters:
512: + ncols - if not NULL, the number of nonzeros in the row
513: . cols - if not NULL, the column numbers
514: - vals - if not NULL, the values
516: Notes:
517: This routine is provided for people who need to have direct access
518: to the structure of a matrix. We hope that we provide enough
519: high-level matrix routines that few users will need it.
521: MatGetRow() always returns 0-based column indices, regardless of
522: whether the internal representation is 0-based (default) or 1-based.
524: For better efficiency, set cols and/or vals to NULL if you do
525: not wish to extract these quantities.
527: The user can only examine the values extracted with MatGetRow();
528: the values cannot be altered. To change the matrix entries, one
529: must use MatSetValues().
531: You can only have one call to MatGetRow() outstanding for a particular
532: matrix at a time, per processor. MatGetRow() can only obtain rows
533: associated with the given processor, it cannot get rows from the
534: other processors; for that we suggest using MatCreateSubMatrices(), then
535: MatGetRow() on the submatrix. The row index passed to MatGetRow()
536: is in the global number of rows.
538: Fortran Notes:
539: The calling sequence from Fortran is
540: .vb
541: MatGetRow(matrix,row,ncols,cols,values,ierr)
542: Mat matrix (input)
543: integer row (input)
544: integer ncols (output)
545: integer cols(maxcols) (output)
546: double precision (or double complex) values(maxcols) output
547: .ve
548: where maxcols >= maximum nonzeros in any row of the matrix.
551: Caution:
552: Do not try to change the contents of the output arrays (cols and vals).
553: In some cases, this may corrupt the matrix.
555: Level: advanced
557: Concepts: matrices^row access
559: .seealso: MatRestoreRow(), MatSetValues(), MatGetValues(), MatCreateSubMatrices(), MatGetDiagonal()
560: @*/
561: PetscErrorCode MatGetRow(Mat mat,PetscInt row,PetscInt *ncols,const PetscInt *cols[],const PetscScalar *vals[])
562: {
564: PetscInt incols;
569: if (!mat->assembled) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
570: if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
571: if (!mat->ops->getrow) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
572: MatCheckPreallocated(mat,1);
573: PetscLogEventBegin(MAT_GetRow,mat,0,0,0);
574: (*mat->ops->getrow)(mat,row,&incols,(PetscInt**)cols,(PetscScalar**)vals);
575: if (ncols) *ncols = incols;
576: PetscLogEventEnd(MAT_GetRow,mat,0,0,0);
577: return(0);
578: }
580: /*@
581: MatConjugate - replaces the matrix values with their complex conjugates
583: Logically Collective on Mat
585: Input Parameters:
586: . mat - the matrix
588: Level: advanced
590: .seealso: VecConjugate()
591: @*/
592: PetscErrorCode MatConjugate(Mat mat)
593: {
594: #if defined(PETSC_USE_COMPLEX)
599: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
600: if (!mat->ops->conjugate) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Not provided for this matrix format, send email to petsc-maint@mcs.anl.gov");
601: (*mat->ops->conjugate)(mat);
602: #if defined(PETSC_HAVE_VIENNACL) || defined(PETSC_HAVE_CUDA)
603: if (mat->valid_GPU_matrix != PETSC_OFFLOAD_UNALLOCATED) {
604: mat->valid_GPU_matrix = PETSC_OFFLOAD_CPU;
605: }
606: #endif
607: return(0);
608: #else
609: return 0;
610: #endif
611: }
613: /*@C
614: MatRestoreRow - Frees any temporary space allocated by MatGetRow().
616: Not Collective
618: Input Parameters:
619: + mat - the matrix
620: . row - the row to get
621: . ncols, cols - the number of nonzeros and their columns
622: - vals - if nonzero the column values
624: Notes:
625: This routine should be called after you have finished examining the entries.
627: This routine zeros out ncols, cols, and vals. This is to prevent accidental
628: us of the array after it has been restored. If you pass NULL, it will
629: not zero the pointers. Use of cols or vals after MatRestoreRow is invalid.
631: Fortran Notes:
632: The calling sequence from Fortran is
633: .vb
634: MatRestoreRow(matrix,row,ncols,cols,values,ierr)
635: Mat matrix (input)
636: integer row (input)
637: integer ncols (output)
638: integer cols(maxcols) (output)
639: double precision (or double complex) values(maxcols) output
640: .ve
641: Where maxcols >= maximum nonzeros in any row of the matrix.
643: In Fortran MatRestoreRow() MUST be called after MatGetRow()
644: before another call to MatGetRow() can be made.
646: Level: advanced
648: .seealso: MatGetRow()
649: @*/
650: PetscErrorCode MatRestoreRow(Mat mat,PetscInt row,PetscInt *ncols,const PetscInt *cols[],const PetscScalar *vals[])
651: {
657: if (!mat->assembled) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
658: if (!mat->ops->restorerow) return(0);
659: (*mat->ops->restorerow)(mat,row,ncols,(PetscInt **)cols,(PetscScalar **)vals);
660: if (ncols) *ncols = 0;
661: if (cols) *cols = NULL;
662: if (vals) *vals = NULL;
663: return(0);
664: }
666: /*@
667: MatGetRowUpperTriangular - Sets a flag to enable calls to MatGetRow() for matrix in MATSBAIJ format.
668: You should call MatRestoreRowUpperTriangular() after calling MatGetRow/MatRestoreRow() to disable the flag.
670: Not Collective
672: Input Parameters:
673: + mat - the matrix
675: Notes:
676: The flag is to ensure that users are aware of MatGetRow() only provides the upper trianglular part of the row for the matrices in MATSBAIJ format.
678: Level: advanced
680: Concepts: matrices^row access
682: .seealso: MatRestoreRowRowUpperTriangular()
683: @*/
684: PetscErrorCode MatGetRowUpperTriangular(Mat mat)
685: {
691: if (!mat->assembled) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
692: if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
693: MatCheckPreallocated(mat,1);
694: if (!mat->ops->getrowuppertriangular) return(0);
695: (*mat->ops->getrowuppertriangular)(mat);
696: return(0);
697: }
699: /*@
700: MatRestoreRowUpperTriangular - Disable calls to MatGetRow() for matrix in MATSBAIJ format.
702: Not Collective
704: Input Parameters:
705: + mat - the matrix
707: Notes:
708: This routine should be called after you have finished MatGetRow/MatRestoreRow().
711: Level: advanced
713: .seealso: MatGetRowUpperTriangular()
714: @*/
715: PetscErrorCode MatRestoreRowUpperTriangular(Mat mat)
716: {
722: if (!mat->assembled) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
723: if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
724: MatCheckPreallocated(mat,1);
725: if (!mat->ops->restorerowuppertriangular) return(0);
726: (*mat->ops->restorerowuppertriangular)(mat);
727: return(0);
728: }
730: /*@C
731: MatSetOptionsPrefix - Sets the prefix used for searching for all
732: Mat options in the database.
734: Logically Collective on Mat
736: Input Parameter:
737: + A - the Mat context
738: - prefix - the prefix to prepend to all option names
740: Notes:
741: A hyphen (-) must NOT be given at the beginning of the prefix name.
742: The first character of all runtime options is AUTOMATICALLY the hyphen.
744: Level: advanced
746: .keywords: Mat, set, options, prefix, database
748: .seealso: MatSetFromOptions()
749: @*/
750: PetscErrorCode MatSetOptionsPrefix(Mat A,const char prefix[])
751: {
756: PetscObjectSetOptionsPrefix((PetscObject)A,prefix);
757: return(0);
758: }
760: /*@C
761: MatAppendOptionsPrefix - Appends to the prefix used for searching for all
762: Mat options in the database.
764: Logically Collective on Mat
766: Input Parameters:
767: + A - the Mat context
768: - prefix - the prefix to prepend to all option names
770: Notes:
771: A hyphen (-) must NOT be given at the beginning of the prefix name.
772: The first character of all runtime options is AUTOMATICALLY the hyphen.
774: Level: advanced
776: .keywords: Mat, append, options, prefix, database
778: .seealso: MatGetOptionsPrefix()
779: @*/
780: PetscErrorCode MatAppendOptionsPrefix(Mat A,const char prefix[])
781: {
786: PetscObjectAppendOptionsPrefix((PetscObject)A,prefix);
787: return(0);
788: }
790: /*@C
791: MatGetOptionsPrefix - Sets the prefix used for searching for all
792: Mat options in the database.
794: Not Collective
796: Input Parameter:
797: . A - the Mat context
799: Output Parameter:
800: . prefix - pointer to the prefix string used
802: Notes:
803: On the fortran side, the user should pass in a string 'prefix' of
804: sufficient length to hold the prefix.
806: Level: advanced
808: .keywords: Mat, get, options, prefix, database
810: .seealso: MatAppendOptionsPrefix()
811: @*/
812: PetscErrorCode MatGetOptionsPrefix(Mat A,const char *prefix[])
813: {
818: PetscObjectGetOptionsPrefix((PetscObject)A,prefix);
819: return(0);
820: }
822: /*@
823: MatResetPreallocation - Reset mat to use the original nonzero pattern provided by users.
825: Collective on Mat
827: Input Parameters:
828: . A - the Mat context
830: Notes:
831: The allocated memory will be shrunk after calling MatAssembly with MAT_FINAL_ASSEMBLY. Users can reset the preallocation to access the original memory.
832: Currently support MPIAIJ and SEQAIJ.
834: Level: beginner
836: .keywords: Mat, ResetPreallocation
838: .seealso: MatSeqAIJSetPreallocation(), MatMPIAIJSetPreallocation(), MatXAIJSetPreallocation()
839: @*/
840: PetscErrorCode MatResetPreallocation(Mat A)
841: {
847: PetscUseMethod(A,"MatResetPreallocation_C",(Mat),(A));
848: return(0);
849: }
852: /*@
853: MatSetUp - Sets up the internal matrix data structures for the later use.
855: Collective on Mat
857: Input Parameters:
858: . A - the Mat context
860: Notes:
861: If the user has not set preallocation for this matrix then a default preallocation that is likely to be inefficient is used.
863: If a suitable preallocation routine is used, this function does not need to be called.
865: See the Performance chapter of the PETSc users manual for how to preallocate matrices
867: Level: beginner
869: .keywords: Mat, setup
871: .seealso: MatCreate(), MatDestroy()
872: @*/
873: PetscErrorCode MatSetUp(Mat A)
874: {
875: PetscMPIInt size;
880: if (!((PetscObject)A)->type_name) {
881: MPI_Comm_size(PetscObjectComm((PetscObject)A), &size);
882: if (size == 1) {
883: MatSetType(A, MATSEQAIJ);
884: } else {
885: MatSetType(A, MATMPIAIJ);
886: }
887: }
888: if (!A->preallocated && A->ops->setup) {
889: PetscInfo(A,"Warning not preallocating matrix storage\n");
890: (*A->ops->setup)(A);
891: }
892: PetscLayoutSetUp(A->rmap);
893: PetscLayoutSetUp(A->cmap);
894: A->preallocated = PETSC_TRUE;
895: return(0);
896: }
898: #if defined(PETSC_HAVE_SAWS)
899: #include <petscviewersaws.h>
900: #endif
901: /*@C
902: MatView - Visualizes a matrix object.
904: Collective on Mat
906: Input Parameters:
907: + mat - the matrix
908: - viewer - visualization context
910: Notes:
911: The available visualization contexts include
912: + PETSC_VIEWER_STDOUT_SELF - for sequential matrices
913: . PETSC_VIEWER_STDOUT_WORLD - for parallel matrices created on PETSC_COMM_WORLD
914: . PETSC_VIEWER_STDOUT_(comm) - for matrices created on MPI communicator comm
915: - PETSC_VIEWER_DRAW_WORLD - graphical display of nonzero structure
917: The user can open alternative visualization contexts with
918: + PetscViewerASCIIOpen() - Outputs matrix to a specified file
919: . PetscViewerBinaryOpen() - Outputs matrix in binary to a
920: specified file; corresponding input uses MatLoad()
921: . PetscViewerDrawOpen() - Outputs nonzero matrix structure to
922: an X window display
923: - PetscViewerSocketOpen() - Outputs matrix to Socket viewer.
924: Currently only the sequential dense and AIJ
925: matrix types support the Socket viewer.
927: The user can call PetscViewerPushFormat() to specify the output
928: format of ASCII printed objects (when using PETSC_VIEWER_STDOUT_SELF,
929: PETSC_VIEWER_STDOUT_WORLD and PetscViewerASCIIOpen). Available formats include
930: + PETSC_VIEWER_DEFAULT - default, prints matrix contents
931: . PETSC_VIEWER_ASCII_MATLAB - prints matrix contents in Matlab format
932: . PETSC_VIEWER_ASCII_DENSE - prints entire matrix including zeros
933: . PETSC_VIEWER_ASCII_COMMON - prints matrix contents, using a sparse
934: format common among all matrix types
935: . PETSC_VIEWER_ASCII_IMPL - prints matrix contents, using an implementation-specific
936: format (which is in many cases the same as the default)
937: . PETSC_VIEWER_ASCII_INFO - prints basic information about the matrix
938: size and structure (not the matrix entries)
939: - PETSC_VIEWER_ASCII_INFO_DETAIL - prints more detailed information about
940: the matrix structure
942: Options Database Keys:
943: + -mat_view ::ascii_info - Prints info on matrix at conclusion of MatAssemblyEnd()
944: . -mat_view ::ascii_info_detail - Prints more detailed info
945: . -mat_view - Prints matrix in ASCII format
946: . -mat_view ::ascii_matlab - Prints matrix in Matlab format
947: . -mat_view draw - PetscDraws nonzero structure of matrix, using MatView() and PetscDrawOpenX().
948: . -display <name> - Sets display name (default is host)
949: . -draw_pause <sec> - Sets number of seconds to pause after display
950: . -mat_view socket - Sends matrix to socket, can be accessed from Matlab (see Users-Manual: Chapter 12 Using MATLAB with PETSc for details)
951: . -viewer_socket_machine <machine> -
952: . -viewer_socket_port <port> -
953: . -mat_view binary - save matrix to file in binary format
954: - -viewer_binary_filename <name> -
955: Level: beginner
957: Notes:
958: The ASCII viewers are only recommended for small matrices on at most a moderate number of processes,
959: the program will seemingly hang and take hours for larger matrices, for larger matrices one should use the binary format.
961: See the manual page for MatLoad() for the exact format of the binary file when the binary
962: viewer is used.
964: See share/petsc/matlab/PetscBinaryRead.m for a Matlab code that can read in the binary file when the binary
965: viewer is used.
967: One can use '-mat_view draw -draw_pause -1' to pause the graphical display of matrix nonzero structure,
968: and then use the following mouse functions.
969: + left mouse: zoom in
970: . middle mouse: zoom out
971: - right mouse: continue with the simulation
973: Concepts: matrices^viewing
974: Concepts: matrices^plotting
975: Concepts: matrices^printing
977: .seealso: PetscViewerPushFormat(), PetscViewerASCIIOpen(), PetscViewerDrawOpen(),
978: PetscViewerSocketOpen(), PetscViewerBinaryOpen(), MatLoad()
979: @*/
980: PetscErrorCode MatView(Mat mat,PetscViewer viewer)
981: {
982: PetscErrorCode ierr;
983: PetscInt rows,cols,rbs,cbs;
984: PetscBool iascii,ibinary;
985: PetscViewerFormat format;
986: PetscMPIInt size;
987: #if defined(PETSC_HAVE_SAWS)
988: PetscBool issaws;
989: #endif
994: if (!viewer) {
995: PetscViewerASCIIGetStdout(PetscObjectComm((PetscObject)mat),&viewer);
996: }
999: MatCheckPreallocated(mat,1);
1000: PetscViewerGetFormat(viewer,&format);
1001: MPI_Comm_size(PetscObjectComm((PetscObject)mat),&size);
1002: if (size == 1 && format == PETSC_VIEWER_LOAD_BALANCE) return(0);
1003: PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERBINARY,&ibinary);
1004: if (ibinary) {
1005: PetscBool mpiio;
1006: PetscViewerBinaryGetUseMPIIO(viewer,&mpiio);
1007: if (mpiio) SETERRQ(PetscObjectComm((PetscObject)viewer),PETSC_ERR_SUP,"PETSc matrix viewers do not support using MPI-IO, turn off that flag");
1008: }
1010: PetscLogEventBegin(MAT_View,mat,viewer,0,0);
1011: PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERASCII,&iascii);
1012: if ((!iascii || (format != PETSC_VIEWER_ASCII_INFO || format == PETSC_VIEWER_ASCII_INFO_DETAIL)) && mat->factortype) {
1013: SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"No viewers for factored matrix except ASCII info or info_detailed");
1014: }
1016: #if defined(PETSC_HAVE_SAWS)
1017: PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERSAWS,&issaws);
1018: #endif
1019: if (iascii) {
1020: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ORDER,"Must call MatAssemblyBegin/End() before viewing matrix");
1021: PetscObjectPrintClassNamePrefixType((PetscObject)mat,viewer);
1022: if (format == PETSC_VIEWER_ASCII_INFO || format == PETSC_VIEWER_ASCII_INFO_DETAIL) {
1023: MatNullSpace nullsp,transnullsp;
1025: PetscViewerASCIIPushTab(viewer);
1026: MatGetSize(mat,&rows,&cols);
1027: MatGetBlockSizes(mat,&rbs,&cbs);
1028: if (rbs != 1 || cbs != 1) {
1029: if (rbs != cbs) {PetscViewerASCIIPrintf(viewer,"rows=%D, cols=%D, rbs=%D, cbs = %D\n",rows,cols,rbs,cbs);}
1030: else {PetscViewerASCIIPrintf(viewer,"rows=%D, cols=%D, bs=%D\n",rows,cols,rbs);}
1031: } else {
1032: PetscViewerASCIIPrintf(viewer,"rows=%D, cols=%D\n",rows,cols);
1033: }
1034: if (mat->factortype) {
1035: MatSolverType solver;
1036: MatFactorGetSolverType(mat,&solver);
1037: PetscViewerASCIIPrintf(viewer,"package used to perform factorization: %s\n",solver);
1038: }
1039: if (mat->ops->getinfo) {
1040: MatInfo info;
1041: MatGetInfo(mat,MAT_GLOBAL_SUM,&info);
1042: PetscViewerASCIIPrintf(viewer,"total: nonzeros=%.f, allocated nonzeros=%.f\n",info.nz_used,info.nz_allocated);
1043: PetscViewerASCIIPrintf(viewer,"total number of mallocs used during MatSetValues calls =%D\n",(PetscInt)info.mallocs);
1044: }
1045: MatGetNullSpace(mat,&nullsp);
1046: MatGetTransposeNullSpace(mat,&transnullsp);
1047: if (nullsp) {PetscViewerASCIIPrintf(viewer," has attached null space\n");}
1048: if (transnullsp && transnullsp != nullsp) {PetscViewerASCIIPrintf(viewer," has attached transposed null space\n");}
1049: MatGetNearNullSpace(mat,&nullsp);
1050: if (nullsp) {PetscViewerASCIIPrintf(viewer," has attached near null space\n");}
1051: }
1052: #if defined(PETSC_HAVE_SAWS)
1053: } else if (issaws) {
1054: PetscMPIInt rank;
1056: PetscObjectName((PetscObject)mat);
1057: MPI_Comm_rank(PETSC_COMM_WORLD,&rank);
1058: if (!((PetscObject)mat)->amsmem && !rank) {
1059: PetscObjectViewSAWs((PetscObject)mat,viewer);
1060: }
1061: #endif
1062: }
1063: if ((format == PETSC_VIEWER_NATIVE || format == PETSC_VIEWER_LOAD_BALANCE) && mat->ops->viewnative) {
1064: PetscViewerASCIIPushTab(viewer);
1065: (*mat->ops->viewnative)(mat,viewer);
1066: PetscViewerASCIIPopTab(viewer);
1067: } else if (mat->ops->view) {
1068: PetscViewerASCIIPushTab(viewer);
1069: (*mat->ops->view)(mat,viewer);
1070: PetscViewerASCIIPopTab(viewer);
1071: }
1072: if (iascii) {
1073: PetscViewerGetFormat(viewer,&format);
1074: if (format == PETSC_VIEWER_ASCII_INFO || format == PETSC_VIEWER_ASCII_INFO_DETAIL) {
1075: PetscViewerASCIIPopTab(viewer);
1076: }
1077: }
1078: PetscLogEventEnd(MAT_View,mat,viewer,0,0);
1079: return(0);
1080: }
1082: #if defined(PETSC_USE_DEBUG)
1083: #include <../src/sys/totalview/tv_data_display.h>
1084: PETSC_UNUSED static int TV_display_type(const struct _p_Mat *mat)
1085: {
1086: TV_add_row("Local rows", "int", &mat->rmap->n);
1087: TV_add_row("Local columns", "int", &mat->cmap->n);
1088: TV_add_row("Global rows", "int", &mat->rmap->N);
1089: TV_add_row("Global columns", "int", &mat->cmap->N);
1090: TV_add_row("Typename", TV_ascii_string_type, ((PetscObject)mat)->type_name);
1091: return TV_format_OK;
1092: }
1093: #endif
1095: /*@C
1096: MatLoad - Loads a matrix that has been stored in binary/HDF5 format
1097: with MatView(). The matrix format is determined from the options database.
1098: Generates a parallel MPI matrix if the communicator has more than one
1099: processor. The default matrix type is AIJ.
1101: Collective on PetscViewer
1103: Input Parameters:
1104: + newmat - the newly loaded matrix, this needs to have been created with MatCreate()
1105: or some related function before a call to MatLoad()
1106: - viewer - binary/HDF5 file viewer
1108: Options Database Keys:
1109: Used with block matrix formats (MATSEQBAIJ, ...) to specify
1110: block size
1111: . -matload_block_size <bs>
1113: Level: beginner
1115: Notes:
1116: If the Mat type has not yet been given then MATAIJ is used, call MatSetFromOptions() on the
1117: Mat before calling this routine if you wish to set it from the options database.
1119: MatLoad() automatically loads into the options database any options
1120: given in the file filename.info where filename is the name of the file
1121: that was passed to the PetscViewerBinaryOpen(). The options in the info
1122: file will be ignored if you use the -viewer_binary_skip_info option.
1124: If the type or size of newmat is not set before a call to MatLoad, PETSc
1125: sets the default matrix type AIJ and sets the local and global sizes.
1126: If type and/or size is already set, then the same are used.
1128: In parallel, each processor can load a subset of rows (or the
1129: entire matrix). This routine is especially useful when a large
1130: matrix is stored on disk and only part of it is desired on each
1131: processor. For example, a parallel solver may access only some of
1132: the rows from each processor. The algorithm used here reads
1133: relatively small blocks of data rather than reading the entire
1134: matrix and then subsetting it.
1136: Viewer's PetscViewerType must be either PETSCVIEWERBINARY or PETSCVIEWERHDF5.
1137: Such viewer can be created using PetscViewerBinaryOpen()/PetscViewerHDF5Open(),
1138: or the sequence like
1139: $ PetscViewer v;
1140: $ PetscViewerCreate(PETSC_COMM_WORLD,&v);
1141: $ PetscViewerSetType(v,PETSCVIEWERBINARY);
1142: $ PetscViewerSetFromOptions(v);
1143: $ PetscViewerFileSetMode(v,FILE_MODE_READ);
1144: $ PetscViewerFileSetName(v,"datafile");
1145: The optional PetscViewerSetFromOptions() call allows to override PetscViewerSetType() using option
1146: $ -viewer_type {binary,hdf5}
1148: See the example src/ksp/ksp/examples/tutorials/ex27.c with the first approach,
1149: and src/mat/examples/tutorials/ex10.c with the second approach.
1151: Notes about the PETSc binary format:
1152: In case of PETSCVIEWERBINARY, a native PETSc binary format is used. Each of the blocks
1153: is read onto rank 0 and then shipped to its destination rank, one after another.
1154: Multiple objects, both matrices and vectors, can be stored within the same file.
1155: Their PetscObject name is ignored; they are loaded in the order of their storage.
1157: Most users should not need to know the details of the binary storage
1158: format, since MatLoad() and MatView() completely hide these details.
1159: But for anyone who's interested, the standard binary matrix storage
1160: format is
1162: $ int MAT_FILE_CLASSID
1163: $ int number of rows
1164: $ int number of columns
1165: $ int total number of nonzeros
1166: $ int *number nonzeros in each row
1167: $ int *column indices of all nonzeros (starting index is zero)
1168: $ PetscScalar *values of all nonzeros
1170: PETSc automatically does the byte swapping for
1171: machines that store the bytes reversed, e.g. DEC alpha, freebsd,
1172: linux, Windows and the paragon; thus if you write your own binary
1173: read/write routines you have to swap the bytes; see PetscBinaryRead()
1174: and PetscBinaryWrite() to see how this may be done.
1176: Notes about the HDF5 (MATLAB MAT-File Version 7.3) format:
1177: In case of PETSCVIEWERHDF5, a parallel HDF5 reader is used.
1178: Each processor's chunk is loaded independently by its owning rank.
1179: Multiple objects, both matrices and vectors, can be stored within the same file.
1180: They are looked up by their PetscObject name.
1182: As the MATLAB MAT-File Version 7.3 format is also a HDF5 flavor, we decided to use
1183: by default the same structure and naming of the AIJ arrays and column count
1184: (see PetscViewerHDF5SetAIJNames())
1185: within the HDF5 file. This means that a MAT file saved with -v7.3 flag, e.g.
1186: $ save example.mat A b -v7.3
1187: can be directly read by this routine (see Reference 1 for details).
1188: Note that depending on your MATLAB version, this format might be a default,
1189: otherwise you can set it as default in Preferences.
1191: Unless -nocompression flag is used to save the file in MATLAB,
1192: PETSc must be configured with ZLIB package.
1194: See also examples src/mat/examples/tutorials/ex10.c and src/ksp/ksp/examples/tutorials/ex27.c
1196: Current HDF5 (MAT-File) limitations:
1197: This reader currently supports only real MATSEQAIJ and MATMPIAIJ matrices.
1199: Corresponding MatView() is not yet implemented.
1201: The loaded matrix is actually a transpose of the original one in MATLAB,
1202: unless you push PETSC_VIEWER_HDF5_MAT format (see examples above).
1203: With this format, matrix is automatically transposed by PETSc,
1204: unless the matrix is marked as SPD or symmetric
1205: (see MatSetOption(), MAT_SPD, MAT_SYMMETRIC).
1207: References:
1208: 1. MATLAB(R) Documentation, manual page of save(), https://www.mathworks.com/help/matlab/ref/save.html#btox10b-1-version
1210: .keywords: matrix, load, binary, input, HDF5
1212: .seealso: PetscViewerBinaryOpen(), PetscViewerSetType(), PetscViewerHDF5SetAIJNames(), MatView(), VecLoad()
1214: @*/
1215: PetscErrorCode MatLoad(Mat newmat,PetscViewer viewer)
1216: {
1218: PetscBool flg;
1224: if (!((PetscObject)newmat)->type_name) {
1225: MatSetType(newmat,MATAIJ);
1226: }
1228: flg = PETSC_FALSE;
1229: PetscOptionsGetBool(((PetscObject)newmat)->options,((PetscObject)newmat)->prefix,"-matload_symmetric",&flg,NULL);
1230: if (flg) {
1231: MatSetOption(newmat,MAT_SYMMETRIC,PETSC_TRUE);
1232: MatSetOption(newmat,MAT_SYMMETRY_ETERNAL,PETSC_TRUE);
1233: }
1234: flg = PETSC_FALSE;
1235: PetscOptionsGetBool(((PetscObject)newmat)->options,((PetscObject)newmat)->prefix,"-matload_spd",&flg,NULL);
1236: if (flg) {
1237: MatSetOption(newmat,MAT_SPD,PETSC_TRUE);
1238: }
1240: if (!newmat->ops->load) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"MatLoad is not supported for type");
1241: PetscLogEventBegin(MAT_Load,viewer,0,0,0);
1242: (*newmat->ops->load)(newmat,viewer);
1243: PetscLogEventEnd(MAT_Load,viewer,0,0,0);
1244: return(0);
1245: }
1247: PetscErrorCode MatDestroy_Redundant(Mat_Redundant **redundant)
1248: {
1250: Mat_Redundant *redund = *redundant;
1251: PetscInt i;
1254: if (redund){
1255: if (redund->matseq) { /* via MatCreateSubMatrices() */
1256: ISDestroy(&redund->isrow);
1257: ISDestroy(&redund->iscol);
1258: MatDestroySubMatrices(1,&redund->matseq);
1259: } else {
1260: PetscFree2(redund->send_rank,redund->recv_rank);
1261: PetscFree(redund->sbuf_j);
1262: PetscFree(redund->sbuf_a);
1263: for (i=0; i<redund->nrecvs; i++) {
1264: PetscFree(redund->rbuf_j[i]);
1265: PetscFree(redund->rbuf_a[i]);
1266: }
1267: PetscFree4(redund->sbuf_nz,redund->rbuf_nz,redund->rbuf_j,redund->rbuf_a);
1268: }
1270: if (redund->subcomm) {
1271: PetscCommDestroy(&redund->subcomm);
1272: }
1273: PetscFree(redund);
1274: }
1275: return(0);
1276: }
1278: /*@
1279: MatDestroy - Frees space taken by a matrix.
1281: Collective on Mat
1283: Input Parameter:
1284: . A - the matrix
1286: Level: beginner
1288: @*/
1289: PetscErrorCode MatDestroy(Mat *A)
1290: {
1294: if (!*A) return(0);
1296: if (--((PetscObject)(*A))->refct > 0) {*A = NULL; return(0);}
1298: /* if memory was published with SAWs then destroy it */
1299: PetscObjectSAWsViewOff((PetscObject)*A);
1300: if ((*A)->ops->destroy) {
1301: (*(*A)->ops->destroy)(*A);
1302: }
1304: PetscFree((*A)->defaultvectype);
1305: PetscFree((*A)->bsizes);
1306: PetscFree((*A)->solvertype);
1307: MatDestroy_Redundant(&(*A)->redundant);
1308: MatNullSpaceDestroy(&(*A)->nullsp);
1309: MatNullSpaceDestroy(&(*A)->transnullsp);
1310: MatNullSpaceDestroy(&(*A)->nearnullsp);
1311: MatDestroy(&(*A)->schur);
1312: PetscLayoutDestroy(&(*A)->rmap);
1313: PetscLayoutDestroy(&(*A)->cmap);
1314: PetscHeaderDestroy(A);
1315: return(0);
1316: }
1318: /*@C
1319: MatSetValues - Inserts or adds a block of values into a matrix.
1320: These values may be cached, so MatAssemblyBegin() and MatAssemblyEnd()
1321: MUST be called after all calls to MatSetValues() have been completed.
1323: Not Collective
1325: Input Parameters:
1326: + mat - the matrix
1327: . v - a logically two-dimensional array of values
1328: . m, idxm - the number of rows and their global indices
1329: . n, idxn - the number of columns and their global indices
1330: - addv - either ADD_VALUES or INSERT_VALUES, where
1331: ADD_VALUES adds values to any existing entries, and
1332: INSERT_VALUES replaces existing entries with new values
1334: Notes:
1335: If you create the matrix yourself (that is not with a call to DMCreateMatrix()) then you MUST call MatXXXXSetPreallocation() or
1336: MatSetUp() before using this routine
1338: By default the values, v, are row-oriented. See MatSetOption() for other options.
1340: Calls to MatSetValues() with the INSERT_VALUES and ADD_VALUES
1341: options cannot be mixed without intervening calls to the assembly
1342: routines.
1344: MatSetValues() uses 0-based row and column numbers in Fortran
1345: as well as in C.
1347: Negative indices may be passed in idxm and idxn, these rows and columns are
1348: simply ignored. This allows easily inserting element stiffness matrices
1349: with homogeneous Dirchlet boundary conditions that you don't want represented
1350: in the matrix.
1352: Efficiency Alert:
1353: The routine MatSetValuesBlocked() may offer much better efficiency
1354: for users of block sparse formats (MATSEQBAIJ and MATMPIBAIJ).
1356: Level: beginner
1358: Developer Notes:
1359: This is labeled with C so does not automatically generate Fortran stubs and interfaces
1360: because it requires multiple Fortran interfaces depending on which arguments are scalar or arrays.
1362: Concepts: matrices^putting entries in
1364: .seealso: MatSetOption(), MatAssemblyBegin(), MatAssemblyEnd(), MatSetValuesBlocked(), MatSetValuesLocal(),
1365: InsertMode, INSERT_VALUES, ADD_VALUES
1366: @*/
1367: PetscErrorCode MatSetValues(Mat mat,PetscInt m,const PetscInt idxm[],PetscInt n,const PetscInt idxn[],const PetscScalar v[],InsertMode addv)
1368: {
1370: #if defined(PETSC_USE_DEBUG)
1371: PetscInt i,j;
1372: #endif
1377: if (!m || !n) return(0); /* no values to insert */
1381: MatCheckPreallocated(mat,1);
1382: if (mat->insertmode == NOT_SET_VALUES) {
1383: mat->insertmode = addv;
1384: }
1385: #if defined(PETSC_USE_DEBUG)
1386: else if (mat->insertmode != addv) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Cannot mix add values and insert values");
1387: if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
1388: if (!mat->ops->setvalues) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
1390: for (i=0; i<m; i++) {
1391: for (j=0; j<n; j++) {
1392: if (mat->erroriffailure && PetscIsInfOrNanScalar(v[i*n+j]))
1393: #if defined(PETSC_USE_COMPLEX)
1394: 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]);
1395: #else
1396: SETERRQ3(PETSC_COMM_SELF,PETSC_ERR_FP,"Inserting %g at matrix entry (%D,%D)",(double)v[i*n+j],idxm[i],idxn[j]);
1397: #endif
1398: }
1399: }
1400: #endif
1402: if (mat->assembled) {
1403: mat->was_assembled = PETSC_TRUE;
1404: mat->assembled = PETSC_FALSE;
1405: }
1406: PetscLogEventBegin(MAT_SetValues,mat,0,0,0);
1407: (*mat->ops->setvalues)(mat,m,idxm,n,idxn,v,addv);
1408: PetscLogEventEnd(MAT_SetValues,mat,0,0,0);
1409: #if defined(PETSC_HAVE_VIENNACL) || defined(PETSC_HAVE_CUDA)
1410: if (mat->valid_GPU_matrix != PETSC_OFFLOAD_UNALLOCATED) {
1411: mat->valid_GPU_matrix = PETSC_OFFLOAD_CPU;
1412: }
1413: #endif
1414: return(0);
1415: }
1418: /*@
1419: MatSetValuesRowLocal - Inserts a row (block row for BAIJ matrices) of nonzero
1420: values into a matrix
1422: Not Collective
1424: Input Parameters:
1425: + mat - the matrix
1426: . row - the (block) row to set
1427: - v - a logically two-dimensional array of values
1429: Notes:
1430: By the values, v, are column-oriented (for the block version) and sorted
1432: All the nonzeros in the row must be provided
1434: The matrix must have previously had its column indices set
1436: The row must belong to this process
1438: Level: intermediate
1440: Concepts: matrices^putting entries in
1442: .seealso: MatSetOption(), MatAssemblyBegin(), MatAssemblyEnd(), MatSetValuesBlocked(), MatSetValuesLocal(),
1443: InsertMode, INSERT_VALUES, ADD_VALUES, MatSetValues(), MatSetValuesRow(), MatSetLocalToGlobalMapping()
1444: @*/
1445: PetscErrorCode MatSetValuesRowLocal(Mat mat,PetscInt row,const PetscScalar v[])
1446: {
1448: PetscInt globalrow;
1454: ISLocalToGlobalMappingApply(mat->rmap->mapping,1,&row,&globalrow);
1455: MatSetValuesRow(mat,globalrow,v);
1456: #if defined(PETSC_HAVE_VIENNACL) || defined(PETSC_HAVE_CUDA)
1457: if (mat->valid_GPU_matrix != PETSC_OFFLOAD_UNALLOCATED) {
1458: mat->valid_GPU_matrix = PETSC_OFFLOAD_CPU;
1459: }
1460: #endif
1461: return(0);
1462: }
1464: /*@
1465: MatSetValuesRow - Inserts a row (block row for BAIJ matrices) of nonzero
1466: values into a matrix
1468: Not Collective
1470: Input Parameters:
1471: + mat - the matrix
1472: . row - the (block) row to set
1473: - 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
1475: Notes:
1476: The values, v, are column-oriented for the block version.
1478: All the nonzeros in the row must be provided
1480: THE MATRIX MUST HAVE PREVIOUSLY HAD ITS COLUMN INDICES SET. IT IS RARE THAT THIS ROUTINE IS USED, usually MatSetValues() is used.
1482: The row must belong to this process
1484: Level: advanced
1486: Concepts: matrices^putting entries in
1488: .seealso: MatSetOption(), MatAssemblyBegin(), MatAssemblyEnd(), MatSetValuesBlocked(), MatSetValuesLocal(),
1489: InsertMode, INSERT_VALUES, ADD_VALUES, MatSetValues()
1490: @*/
1491: PetscErrorCode MatSetValuesRow(Mat mat,PetscInt row,const PetscScalar v[])
1492: {
1498: MatCheckPreallocated(mat,1);
1500: #if defined(PETSC_USE_DEBUG)
1501: if (mat->insertmode == ADD_VALUES) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Cannot mix add and insert values");
1502: if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
1503: #endif
1504: mat->insertmode = INSERT_VALUES;
1506: if (mat->assembled) {
1507: mat->was_assembled = PETSC_TRUE;
1508: mat->assembled = PETSC_FALSE;
1509: }
1510: PetscLogEventBegin(MAT_SetValues,mat,0,0,0);
1511: if (!mat->ops->setvaluesrow) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
1512: (*mat->ops->setvaluesrow)(mat,row,v);
1513: PetscLogEventEnd(MAT_SetValues,mat,0,0,0);
1514: #if defined(PETSC_HAVE_VIENNACL) || defined(PETSC_HAVE_CUDA)
1515: if (mat->valid_GPU_matrix != PETSC_OFFLOAD_UNALLOCATED) {
1516: mat->valid_GPU_matrix = PETSC_OFFLOAD_CPU;
1517: }
1518: #endif
1519: return(0);
1520: }
1522: /*@
1523: MatSetValuesStencil - Inserts or adds a block of values into a matrix.
1524: Using structured grid indexing
1526: Not Collective
1528: Input Parameters:
1529: + mat - the matrix
1530: . m - number of rows being entered
1531: . idxm - grid coordinates (and component number when dof > 1) for matrix rows being entered
1532: . n - number of columns being entered
1533: . idxn - grid coordinates (and component number when dof > 1) for matrix columns being entered
1534: . v - a logically two-dimensional array of values
1535: - addv - either ADD_VALUES or INSERT_VALUES, where
1536: ADD_VALUES adds values to any existing entries, and
1537: INSERT_VALUES replaces existing entries with new values
1539: Notes:
1540: By default the values, v, are row-oriented. See MatSetOption() for other options.
1542: Calls to MatSetValuesStencil() with the INSERT_VALUES and ADD_VALUES
1543: options cannot be mixed without intervening calls to the assembly
1544: routines.
1546: The grid coordinates are across the entire grid, not just the local portion
1548: MatSetValuesStencil() uses 0-based row and column numbers in Fortran
1549: as well as in C.
1551: For setting/accessing vector values via array coordinates you can use the DMDAVecGetArray() routine
1553: In order to use this routine you must either obtain the matrix with DMCreateMatrix()
1554: or call MatSetLocalToGlobalMapping() and MatSetStencil() first.
1556: The columns and rows in the stencil passed in MUST be contained within the
1557: ghost region of the given process as set with DMDACreateXXX() or MatSetStencil(). For example,
1558: if you create a DMDA with an overlap of one grid level and on a particular process its first
1559: local nonghost x logical coordinate is 6 (so its first ghost x logical coordinate is 5) the
1560: first i index you can use in your column and row indices in MatSetStencil() is 5.
1562: In Fortran idxm and idxn should be declared as
1563: $ MatStencil idxm(4,m),idxn(4,n)
1564: and the values inserted using
1565: $ idxm(MatStencil_i,1) = i
1566: $ idxm(MatStencil_j,1) = j
1567: $ idxm(MatStencil_k,1) = k
1568: $ idxm(MatStencil_c,1) = c
1569: etc
1571: For periodic boundary conditions use negative indices for values to the left (below 0; that are to be
1572: obtained by wrapping values from right edge). For values to the right of the last entry using that index plus one
1573: etc to obtain values that obtained by wrapping the values from the left edge. This does not work for anything but the
1574: DM_BOUNDARY_PERIODIC boundary type.
1576: 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
1577: a single value per point) you can skip filling those indices.
1579: Inspired by the structured grid interface to the HYPRE package
1580: (http://www.llnl.gov/CASC/hypre)
1582: Efficiency Alert:
1583: The routine MatSetValuesBlockedStencil() may offer much better efficiency
1584: for users of block sparse formats (MATSEQBAIJ and MATMPIBAIJ).
1586: Level: beginner
1588: Concepts: matrices^putting entries in
1590: .seealso: MatSetOption(), MatAssemblyBegin(), MatAssemblyEnd(), MatSetValuesBlocked(), MatSetValuesLocal()
1591: MatSetValues(), MatSetValuesBlockedStencil(), MatSetStencil(), DMCreateMatrix(), DMDAVecGetArray(), MatStencil
1592: @*/
1593: PetscErrorCode MatSetValuesStencil(Mat mat,PetscInt m,const MatStencil idxm[],PetscInt n,const MatStencil idxn[],const PetscScalar v[],InsertMode addv)
1594: {
1596: PetscInt buf[8192],*bufm=0,*bufn=0,*jdxm,*jdxn;
1597: PetscInt j,i,dim = mat->stencil.dim,*dims = mat->stencil.dims+1,tmp;
1598: PetscInt *starts = mat->stencil.starts,*dxm = (PetscInt*)idxm,*dxn = (PetscInt*)idxn,sdim = dim - (1 - (PetscInt)mat->stencil.noc);
1601: if (!m || !n) return(0); /* no values to insert */
1608: if ((m+n) <= (PetscInt)(sizeof(buf)/sizeof(PetscInt))) {
1609: jdxm = buf; jdxn = buf+m;
1610: } else {
1611: PetscMalloc2(m,&bufm,n,&bufn);
1612: jdxm = bufm; jdxn = bufn;
1613: }
1614: for (i=0; i<m; i++) {
1615: for (j=0; j<3-sdim; j++) dxm++;
1616: tmp = *dxm++ - starts[0];
1617: for (j=0; j<dim-1; j++) {
1618: if ((*dxm++ - starts[j+1]) < 0 || tmp < 0) tmp = -1;
1619: else tmp = tmp*dims[j] + *(dxm-1) - starts[j+1];
1620: }
1621: if (mat->stencil.noc) dxm++;
1622: jdxm[i] = tmp;
1623: }
1624: for (i=0; i<n; i++) {
1625: for (j=0; j<3-sdim; j++) dxn++;
1626: tmp = *dxn++ - starts[0];
1627: for (j=0; j<dim-1; j++) {
1628: if ((*dxn++ - starts[j+1]) < 0 || tmp < 0) tmp = -1;
1629: else tmp = tmp*dims[j] + *(dxn-1) - starts[j+1];
1630: }
1631: if (mat->stencil.noc) dxn++;
1632: jdxn[i] = tmp;
1633: }
1634: MatSetValuesLocal(mat,m,jdxm,n,jdxn,v,addv);
1635: PetscFree2(bufm,bufn);
1636: return(0);
1637: }
1639: /*@
1640: MatSetValuesBlockedStencil - Inserts or adds a block of values into a matrix.
1641: Using structured grid indexing
1643: Not Collective
1645: Input Parameters:
1646: + mat - the matrix
1647: . m - number of rows being entered
1648: . idxm - grid coordinates for matrix rows being entered
1649: . n - number of columns being entered
1650: . idxn - grid coordinates for matrix columns being entered
1651: . v - a logically two-dimensional array of values
1652: - addv - either ADD_VALUES or INSERT_VALUES, where
1653: ADD_VALUES adds values to any existing entries, and
1654: INSERT_VALUES replaces existing entries with new values
1656: Notes:
1657: By default the values, v, are row-oriented and unsorted.
1658: See MatSetOption() for other options.
1660: Calls to MatSetValuesBlockedStencil() with the INSERT_VALUES and ADD_VALUES
1661: options cannot be mixed without intervening calls to the assembly
1662: routines.
1664: The grid coordinates are across the entire grid, not just the local portion
1666: MatSetValuesBlockedStencil() uses 0-based row and column numbers in Fortran
1667: as well as in C.
1669: For setting/accessing vector values via array coordinates you can use the DMDAVecGetArray() routine
1671: In order to use this routine you must either obtain the matrix with DMCreateMatrix()
1672: or call MatSetBlockSize(), MatSetLocalToGlobalMapping() and MatSetStencil() first.
1674: The columns and rows in the stencil passed in MUST be contained within the
1675: ghost region of the given process as set with DMDACreateXXX() or MatSetStencil(). For example,
1676: if you create a DMDA with an overlap of one grid level and on a particular process its first
1677: local nonghost x logical coordinate is 6 (so its first ghost x logical coordinate is 5) the
1678: first i index you can use in your column and row indices in MatSetStencil() is 5.
1680: In Fortran idxm and idxn should be declared as
1681: $ MatStencil idxm(4,m),idxn(4,n)
1682: and the values inserted using
1683: $ idxm(MatStencil_i,1) = i
1684: $ idxm(MatStencil_j,1) = j
1685: $ idxm(MatStencil_k,1) = k
1686: etc
1688: Negative indices may be passed in idxm and idxn, these rows and columns are
1689: simply ignored. This allows easily inserting element stiffness matrices
1690: with homogeneous Dirchlet boundary conditions that you don't want represented
1691: in the matrix.
1693: Inspired by the structured grid interface to the HYPRE package
1694: (http://www.llnl.gov/CASC/hypre)
1696: Level: beginner
1698: Concepts: matrices^putting entries in
1700: .seealso: MatSetOption(), MatAssemblyBegin(), MatAssemblyEnd(), MatSetValuesBlocked(), MatSetValuesLocal()
1701: MatSetValues(), MatSetValuesStencil(), MatSetStencil(), DMCreateMatrix(), DMDAVecGetArray(), MatStencil,
1702: MatSetBlockSize(), MatSetLocalToGlobalMapping()
1703: @*/
1704: PetscErrorCode MatSetValuesBlockedStencil(Mat mat,PetscInt m,const MatStencil idxm[],PetscInt n,const MatStencil idxn[],const PetscScalar v[],InsertMode addv)
1705: {
1707: PetscInt buf[8192],*bufm=0,*bufn=0,*jdxm,*jdxn;
1708: PetscInt j,i,dim = mat->stencil.dim,*dims = mat->stencil.dims+1,tmp;
1709: PetscInt *starts = mat->stencil.starts,*dxm = (PetscInt*)idxm,*dxn = (PetscInt*)idxn,sdim = dim - (1 - (PetscInt)mat->stencil.noc);
1712: if (!m || !n) return(0); /* no values to insert */
1719: if ((m+n) <= (PetscInt)(sizeof(buf)/sizeof(PetscInt))) {
1720: jdxm = buf; jdxn = buf+m;
1721: } else {
1722: PetscMalloc2(m,&bufm,n,&bufn);
1723: jdxm = bufm; jdxn = bufn;
1724: }
1725: for (i=0; i<m; i++) {
1726: for (j=0; j<3-sdim; j++) dxm++;
1727: tmp = *dxm++ - starts[0];
1728: for (j=0; j<sdim-1; j++) {
1729: if ((*dxm++ - starts[j+1]) < 0 || tmp < 0) tmp = -1;
1730: else tmp = tmp*dims[j] + *(dxm-1) - starts[j+1];
1731: }
1732: dxm++;
1733: jdxm[i] = tmp;
1734: }
1735: for (i=0; i<n; i++) {
1736: for (j=0; j<3-sdim; j++) dxn++;
1737: tmp = *dxn++ - starts[0];
1738: for (j=0; j<sdim-1; j++) {
1739: if ((*dxn++ - starts[j+1]) < 0 || tmp < 0) tmp = -1;
1740: else tmp = tmp*dims[j] + *(dxn-1) - starts[j+1];
1741: }
1742: dxn++;
1743: jdxn[i] = tmp;
1744: }
1745: MatSetValuesBlockedLocal(mat,m,jdxm,n,jdxn,v,addv);
1746: PetscFree2(bufm,bufn);
1747: #if defined(PETSC_HAVE_VIENNACL) || defined(PETSC_HAVE_CUDA)
1748: if (mat->valid_GPU_matrix != PETSC_OFFLOAD_UNALLOCATED) {
1749: mat->valid_GPU_matrix = PETSC_OFFLOAD_CPU;
1750: }
1751: #endif
1752: return(0);
1753: }
1755: /*@
1756: MatSetStencil - Sets the grid information for setting values into a matrix via
1757: MatSetValuesStencil()
1759: Not Collective
1761: Input Parameters:
1762: + mat - the matrix
1763: . dim - dimension of the grid 1, 2, or 3
1764: . dims - number of grid points in x, y, and z direction, including ghost points on your processor
1765: . starts - starting point of ghost nodes on your processor in x, y, and z direction
1766: - dof - number of degrees of freedom per node
1769: Inspired by the structured grid interface to the HYPRE package
1770: (www.llnl.gov/CASC/hyper)
1772: For matrices generated with DMCreateMatrix() this routine is automatically called and so not needed by the
1773: user.
1775: Level: beginner
1777: Concepts: matrices^putting entries in
1779: .seealso: MatSetOption(), MatAssemblyBegin(), MatAssemblyEnd(), MatSetValuesBlocked(), MatSetValuesLocal()
1780: MatSetValues(), MatSetValuesBlockedStencil(), MatSetValuesStencil()
1781: @*/
1782: PetscErrorCode MatSetStencil(Mat mat,PetscInt dim,const PetscInt dims[],const PetscInt starts[],PetscInt dof)
1783: {
1784: PetscInt i;
1791: mat->stencil.dim = dim + (dof > 1);
1792: for (i=0; i<dim; i++) {
1793: mat->stencil.dims[i] = dims[dim-i-1]; /* copy the values in backwards */
1794: mat->stencil.starts[i] = starts[dim-i-1];
1795: }
1796: mat->stencil.dims[dim] = dof;
1797: mat->stencil.starts[dim] = 0;
1798: mat->stencil.noc = (PetscBool)(dof == 1);
1799: return(0);
1800: }
1802: /*@C
1803: MatSetValuesBlocked - Inserts or adds a block of values into a matrix.
1805: Not Collective
1807: Input Parameters:
1808: + mat - the matrix
1809: . v - a logically two-dimensional array of values
1810: . m, idxm - the number of block rows and their global block indices
1811: . n, idxn - the number of block columns and their global block indices
1812: - addv - either ADD_VALUES or INSERT_VALUES, where
1813: ADD_VALUES adds values to any existing entries, and
1814: INSERT_VALUES replaces existing entries with new values
1816: Notes:
1817: If you create the matrix yourself (that is not with a call to DMCreateMatrix()) then you MUST call
1818: MatXXXXSetPreallocation() or MatSetUp() before using this routine.
1820: The m and n count the NUMBER of blocks in the row direction and column direction,
1821: NOT the total number of rows/columns; for example, if the block size is 2 and
1822: you are passing in values for rows 2,3,4,5 then m would be 2 (not 4).
1823: The values in idxm would be 1 2; that is the first index for each block divided by
1824: the block size.
1826: Note that you must call MatSetBlockSize() when constructing this matrix (before
1827: preallocating it).
1829: By default the values, v, are row-oriented, so the layout of
1830: v is the same as for MatSetValues(). See MatSetOption() for other options.
1832: Calls to MatSetValuesBlocked() with the INSERT_VALUES and ADD_VALUES
1833: options cannot be mixed without intervening calls to the assembly
1834: routines.
1836: MatSetValuesBlocked() uses 0-based row and column numbers in Fortran
1837: as well as in C.
1839: Negative indices may be passed in idxm and idxn, these rows and columns are
1840: simply ignored. This allows easily inserting element stiffness matrices
1841: with homogeneous Dirchlet boundary conditions that you don't want represented
1842: in the matrix.
1844: Each time an entry is set within a sparse matrix via MatSetValues(),
1845: internal searching must be done to determine where to place the
1846: data in the matrix storage space. By instead inserting blocks of
1847: entries via MatSetValuesBlocked(), the overhead of matrix assembly is
1848: reduced.
1850: Example:
1851: $ Suppose m=n=2 and block size(bs) = 2 The array is
1852: $
1853: $ 1 2 | 3 4
1854: $ 5 6 | 7 8
1855: $ - - - | - - -
1856: $ 9 10 | 11 12
1857: $ 13 14 | 15 16
1858: $
1859: $ v[] should be passed in like
1860: $ v[] = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]
1861: $
1862: $ If you are not using row oriented storage of v (that is you called MatSetOption(mat,MAT_ROW_ORIENTED,PETSC_FALSE)) then
1863: $ v[] = [1,5,9,13,2,6,10,14,3,7,11,15,4,8,12,16]
1865: Level: intermediate
1867: Concepts: matrices^putting entries in blocked
1869: .seealso: MatSetBlockSize(), MatSetOption(), MatAssemblyBegin(), MatAssemblyEnd(), MatSetValues(), MatSetValuesBlockedLocal()
1870: @*/
1871: PetscErrorCode MatSetValuesBlocked(Mat mat,PetscInt m,const PetscInt idxm[],PetscInt n,const PetscInt idxn[],const PetscScalar v[],InsertMode addv)
1872: {
1878: if (!m || !n) return(0); /* no values to insert */
1882: MatCheckPreallocated(mat,1);
1883: if (mat->insertmode == NOT_SET_VALUES) {
1884: mat->insertmode = addv;
1885: }
1886: #if defined(PETSC_USE_DEBUG)
1887: else if (mat->insertmode != addv) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Cannot mix add values and insert values");
1888: if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
1889: if (!mat->ops->setvaluesblocked && !mat->ops->setvalues) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
1890: #endif
1892: if (mat->assembled) {
1893: mat->was_assembled = PETSC_TRUE;
1894: mat->assembled = PETSC_FALSE;
1895: }
1896: PetscLogEventBegin(MAT_SetValues,mat,0,0,0);
1897: if (mat->ops->setvaluesblocked) {
1898: (*mat->ops->setvaluesblocked)(mat,m,idxm,n,idxn,v,addv);
1899: } else {
1900: PetscInt buf[8192],*bufr=0,*bufc=0,*iidxm,*iidxn;
1901: PetscInt i,j,bs,cbs;
1902: MatGetBlockSizes(mat,&bs,&cbs);
1903: if (m*bs+n*cbs <= (PetscInt)(sizeof(buf)/sizeof(PetscInt))) {
1904: iidxm = buf; iidxn = buf + m*bs;
1905: } else {
1906: PetscMalloc2(m*bs,&bufr,n*cbs,&bufc);
1907: iidxm = bufr; iidxn = bufc;
1908: }
1909: for (i=0; i<m; i++) {
1910: for (j=0; j<bs; j++) {
1911: iidxm[i*bs+j] = bs*idxm[i] + j;
1912: }
1913: }
1914: for (i=0; i<n; i++) {
1915: for (j=0; j<cbs; j++) {
1916: iidxn[i*cbs+j] = cbs*idxn[i] + j;
1917: }
1918: }
1919: MatSetValues(mat,m*bs,iidxm,n*cbs,iidxn,v,addv);
1920: PetscFree2(bufr,bufc);
1921: }
1922: PetscLogEventEnd(MAT_SetValues,mat,0,0,0);
1923: #if defined(PETSC_HAVE_VIENNACL) || defined(PETSC_HAVE_CUDA)
1924: if (mat->valid_GPU_matrix != PETSC_OFFLOAD_UNALLOCATED) {
1925: mat->valid_GPU_matrix = PETSC_OFFLOAD_CPU;
1926: }
1927: #endif
1928: return(0);
1929: }
1931: /*@
1932: MatGetValues - Gets a block of values from a matrix.
1934: Not Collective; currently only returns a local block
1936: Input Parameters:
1937: + mat - the matrix
1938: . v - a logically two-dimensional array for storing the values
1939: . m, idxm - the number of rows and their global indices
1940: - n, idxn - the number of columns and their global indices
1942: Notes:
1943: The user must allocate space (m*n PetscScalars) for the values, v.
1944: The values, v, are then returned in a row-oriented format,
1945: analogous to that used by default in MatSetValues().
1947: MatGetValues() uses 0-based row and column numbers in
1948: Fortran as well as in C.
1950: MatGetValues() requires that the matrix has been assembled
1951: with MatAssemblyBegin()/MatAssemblyEnd(). Thus, calls to
1952: MatSetValues() and MatGetValues() CANNOT be made in succession
1953: without intermediate matrix assembly.
1955: Negative row or column indices will be ignored and those locations in v[] will be
1956: left unchanged.
1958: Level: advanced
1960: Concepts: matrices^accessing values
1962: .seealso: MatGetRow(), MatCreateSubMatrices(), MatSetValues()
1963: @*/
1964: PetscErrorCode MatGetValues(Mat mat,PetscInt m,const PetscInt idxm[],PetscInt n,const PetscInt idxn[],PetscScalar v[])
1965: {
1971: if (!m || !n) return(0);
1975: if (!mat->assembled) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
1976: if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
1977: if (!mat->ops->getvalues) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
1978: MatCheckPreallocated(mat,1);
1980: PetscLogEventBegin(MAT_GetValues,mat,0,0,0);
1981: (*mat->ops->getvalues)(mat,m,idxm,n,idxn,v);
1982: PetscLogEventEnd(MAT_GetValues,mat,0,0,0);
1983: return(0);
1984: }
1986: /*@
1987: MatSetValuesBatch - Adds (ADD_VALUES) many blocks of values into a matrix at once. The blocks must all be square and
1988: the same size. Currently, this can only be called once and creates the given matrix.
1990: Not Collective
1992: Input Parameters:
1993: + mat - the matrix
1994: . nb - the number of blocks
1995: . bs - the number of rows (and columns) in each block
1996: . rows - a concatenation of the rows for each block
1997: - v - a concatenation of logically two-dimensional arrays of values
1999: Notes:
2000: In the future, we will extend this routine to handle rectangular blocks, and to allow multiple calls for a given matrix.
2002: Level: advanced
2004: Concepts: matrices^putting entries in
2006: .seealso: MatSetOption(), MatAssemblyBegin(), MatAssemblyEnd(), MatSetValuesBlocked(), MatSetValuesLocal(),
2007: InsertMode, INSERT_VALUES, ADD_VALUES, MatSetValues()
2008: @*/
2009: PetscErrorCode MatSetValuesBatch(Mat mat, PetscInt nb, PetscInt bs, PetscInt rows[], const PetscScalar v[])
2010: {
2018: #if defined(PETSC_USE_DEBUG)
2019: if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2020: #endif
2022: PetscLogEventBegin(MAT_SetValuesBatch,mat,0,0,0);
2023: if (mat->ops->setvaluesbatch) {
2024: (*mat->ops->setvaluesbatch)(mat,nb,bs,rows,v);
2025: } else {
2026: PetscInt b;
2027: for (b = 0; b < nb; ++b) {
2028: MatSetValues(mat, bs, &rows[b*bs], bs, &rows[b*bs], &v[b*bs*bs], ADD_VALUES);
2029: }
2030: }
2031: PetscLogEventEnd(MAT_SetValuesBatch,mat,0,0,0);
2032: return(0);
2033: }
2035: /*@
2036: MatSetLocalToGlobalMapping - Sets a local-to-global numbering for use by
2037: the routine MatSetValuesLocal() to allow users to insert matrix entries
2038: using a local (per-processor) numbering.
2040: Not Collective
2042: Input Parameters:
2043: + x - the matrix
2044: . rmapping - row mapping created with ISLocalToGlobalMappingCreate() or ISLocalToGlobalMappingCreateIS()
2045: - cmapping - column mapping
2047: Level: intermediate
2049: Concepts: matrices^local to global mapping
2050: Concepts: local to global mapping^for matrices
2052: .seealso: MatAssemblyBegin(), MatAssemblyEnd(), MatSetValues(), MatSetValuesLocal()
2053: @*/
2054: PetscErrorCode MatSetLocalToGlobalMapping(Mat x,ISLocalToGlobalMapping rmapping,ISLocalToGlobalMapping cmapping)
2055: {
2064: if (x->ops->setlocaltoglobalmapping) {
2065: (*x->ops->setlocaltoglobalmapping)(x,rmapping,cmapping);
2066: } else {
2067: PetscLayoutSetISLocalToGlobalMapping(x->rmap,rmapping);
2068: PetscLayoutSetISLocalToGlobalMapping(x->cmap,cmapping);
2069: }
2070: return(0);
2071: }
2074: /*@
2075: MatGetLocalToGlobalMapping - Gets the local-to-global numbering set by MatSetLocalToGlobalMapping()
2077: Not Collective
2079: Input Parameters:
2080: . A - the matrix
2082: Output Parameters:
2083: + rmapping - row mapping
2084: - cmapping - column mapping
2086: Level: advanced
2088: Concepts: matrices^local to global mapping
2089: Concepts: local to global mapping^for matrices
2091: .seealso: MatSetValuesLocal()
2092: @*/
2093: PetscErrorCode MatGetLocalToGlobalMapping(Mat A,ISLocalToGlobalMapping *rmapping,ISLocalToGlobalMapping *cmapping)
2094: {
2100: if (rmapping) *rmapping = A->rmap->mapping;
2101: if (cmapping) *cmapping = A->cmap->mapping;
2102: return(0);
2103: }
2105: /*@
2106: MatGetLayouts - Gets the PetscLayout objects for rows and columns
2108: Not Collective
2110: Input Parameters:
2111: . A - the matrix
2113: Output Parameters:
2114: + rmap - row layout
2115: - cmap - column layout
2117: Level: advanced
2119: .seealso: MatCreateVecs(), MatGetLocalToGlobalMapping()
2120: @*/
2121: PetscErrorCode MatGetLayouts(Mat A,PetscLayout *rmap,PetscLayout *cmap)
2122: {
2128: if (rmap) *rmap = A->rmap;
2129: if (cmap) *cmap = A->cmap;
2130: return(0);
2131: }
2133: /*@C
2134: MatSetValuesLocal - Inserts or adds values into certain locations of a matrix,
2135: using a local ordering of the nodes.
2137: Not Collective
2139: Input Parameters:
2140: + mat - the matrix
2141: . nrow, irow - number of rows and their local indices
2142: . ncol, icol - number of columns and their local indices
2143: . y - a logically two-dimensional array of values
2144: - addv - either INSERT_VALUES or ADD_VALUES, where
2145: ADD_VALUES adds values to any existing entries, and
2146: INSERT_VALUES replaces existing entries with new values
2148: Notes:
2149: If you create the matrix yourself (that is not with a call to DMCreateMatrix()) then you MUST call MatXXXXSetPreallocation() or
2150: MatSetUp() before using this routine
2152: If you create the matrix yourself (that is not with a call to DMCreateMatrix()) then you MUST call MatSetLocalToGlobalMapping() before using this routine
2154: Calls to MatSetValuesLocal() with the INSERT_VALUES and ADD_VALUES
2155: options cannot be mixed without intervening calls to the assembly
2156: routines.
2158: These values may be cached, so MatAssemblyBegin() and MatAssemblyEnd()
2159: MUST be called after all calls to MatSetValuesLocal() have been completed.
2161: Level: intermediate
2163: Concepts: matrices^putting entries in with local numbering
2165: Developer Notes:
2166: This is labeled with C so does not automatically generate Fortran stubs and interfaces
2167: because it requires multiple Fortran interfaces depending on which arguments are scalar or arrays.
2169: .seealso: MatAssemblyBegin(), MatAssemblyEnd(), MatSetValues(), MatSetLocalToGlobalMapping(),
2170: MatSetValueLocal()
2171: @*/
2172: PetscErrorCode MatSetValuesLocal(Mat mat,PetscInt nrow,const PetscInt irow[],PetscInt ncol,const PetscInt icol[],const PetscScalar y[],InsertMode addv)
2173: {
2179: MatCheckPreallocated(mat,1);
2180: if (!nrow || !ncol) return(0); /* no values to insert */
2184: if (mat->insertmode == NOT_SET_VALUES) {
2185: mat->insertmode = addv;
2186: }
2187: #if defined(PETSC_USE_DEBUG)
2188: else if (mat->insertmode != addv) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Cannot mix add values and insert values");
2189: if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2190: if (!mat->ops->setvalueslocal && !mat->ops->setvalues) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
2191: #endif
2193: if (mat->assembled) {
2194: mat->was_assembled = PETSC_TRUE;
2195: mat->assembled = PETSC_FALSE;
2196: }
2197: PetscLogEventBegin(MAT_SetValues,mat,0,0,0);
2198: if (mat->ops->setvalueslocal) {
2199: (*mat->ops->setvalueslocal)(mat,nrow,irow,ncol,icol,y,addv);
2200: } else {
2201: PetscInt buf[8192],*bufr=0,*bufc=0,*irowm,*icolm;
2202: if ((nrow+ncol) <= (PetscInt)(sizeof(buf)/sizeof(PetscInt))) {
2203: irowm = buf; icolm = buf+nrow;
2204: } else {
2205: PetscMalloc2(nrow,&bufr,ncol,&bufc);
2206: irowm = bufr; icolm = bufc;
2207: }
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: #if defined(PETSC_HAVE_VIENNACL) || defined(PETSC_HAVE_CUDA)
2215: if (mat->valid_GPU_matrix != PETSC_OFFLOAD_UNALLOCATED) {
2216: mat->valid_GPU_matrix = PETSC_OFFLOAD_CPU;
2217: }
2218: #endif
2219: return(0);
2220: }
2222: /*@C
2223: MatSetValuesBlockedLocal - Inserts or adds values into certain locations of a matrix,
2224: using a local ordering of the nodes a block at a time.
2226: Not Collective
2228: Input Parameters:
2229: + x - the matrix
2230: . nrow, irow - number of rows and their local indices
2231: . ncol, icol - number of columns and their local indices
2232: . y - a logically two-dimensional array of values
2233: - addv - either INSERT_VALUES or ADD_VALUES, where
2234: ADD_VALUES adds values to any existing entries, and
2235: INSERT_VALUES replaces existing entries with new values
2237: Notes:
2238: If you create the matrix yourself (that is not with a call to DMCreateMatrix()) then you MUST call MatXXXXSetPreallocation() or
2239: MatSetUp() before using this routine
2241: If you create the matrix yourself (that is not with a call to DMCreateMatrix()) then you MUST call MatSetBlockSize() and MatSetLocalToGlobalMapping()
2242: before using this routineBefore calling MatSetValuesLocal(), the user must first set the
2244: Calls to MatSetValuesBlockedLocal() with the INSERT_VALUES and ADD_VALUES
2245: options cannot be mixed without intervening calls to the assembly
2246: routines.
2248: These values may be cached, so MatAssemblyBegin() and MatAssemblyEnd()
2249: MUST be called after all calls to MatSetValuesBlockedLocal() have been completed.
2251: Level: intermediate
2253: Developer Notes:
2254: This is labeled with C so does not automatically generate Fortran stubs and interfaces
2255: because it requires multiple Fortran interfaces depending on which arguments are scalar or arrays.
2257: Concepts: matrices^putting blocked values in with local numbering
2259: .seealso: MatSetBlockSize(), MatSetLocalToGlobalMapping(), MatAssemblyBegin(), MatAssemblyEnd(),
2260: MatSetValuesLocal(), MatSetValuesBlocked()
2261: @*/
2262: PetscErrorCode MatSetValuesBlockedLocal(Mat mat,PetscInt nrow,const PetscInt irow[],PetscInt ncol,const PetscInt icol[],const PetscScalar y[],InsertMode addv)
2263: {
2269: MatCheckPreallocated(mat,1);
2270: if (!nrow || !ncol) return(0); /* no values to insert */
2274: if (mat->insertmode == NOT_SET_VALUES) {
2275: mat->insertmode = addv;
2276: }
2277: #if defined(PETSC_USE_DEBUG)
2278: else if (mat->insertmode != addv) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Cannot mix add values and insert values");
2279: if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2280: 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);
2281: #endif
2283: if (mat->assembled) {
2284: mat->was_assembled = PETSC_TRUE;
2285: mat->assembled = PETSC_FALSE;
2286: }
2287: PetscLogEventBegin(MAT_SetValues,mat,0,0,0);
2288: if (mat->ops->setvaluesblockedlocal) {
2289: (*mat->ops->setvaluesblockedlocal)(mat,nrow,irow,ncol,icol,y,addv);
2290: } else {
2291: PetscInt buf[8192],*bufr=0,*bufc=0,*irowm,*icolm;
2292: if ((nrow+ncol) <= (PetscInt)(sizeof(buf)/sizeof(PetscInt))) {
2293: irowm = buf; icolm = buf + nrow;
2294: } else {
2295: PetscMalloc2(nrow,&bufr,ncol,&bufc);
2296: irowm = bufr; icolm = bufc;
2297: }
2298: ISLocalToGlobalMappingApplyBlock(mat->rmap->mapping,nrow,irow,irowm);
2299: ISLocalToGlobalMappingApplyBlock(mat->cmap->mapping,ncol,icol,icolm);
2300: MatSetValuesBlocked(mat,nrow,irowm,ncol,icolm,y,addv);
2301: PetscFree2(bufr,bufc);
2302: }
2303: PetscLogEventEnd(MAT_SetValues,mat,0,0,0);
2304: #if defined(PETSC_HAVE_VIENNACL) || defined(PETSC_HAVE_CUDA)
2305: if (mat->valid_GPU_matrix != PETSC_OFFLOAD_UNALLOCATED) {
2306: mat->valid_GPU_matrix = PETSC_OFFLOAD_CPU;
2307: }
2308: #endif
2309: return(0);
2310: }
2312: /*@
2313: MatMultDiagonalBlock - Computes the matrix-vector product, y = Dx. Where D is defined by the inode or block structure of the diagonal
2315: Collective on Mat and Vec
2317: Input Parameters:
2318: + mat - the matrix
2319: - x - the vector to be multiplied
2321: Output Parameters:
2322: . y - the result
2324: Notes:
2325: The vectors x and y cannot be the same. I.e., one cannot
2326: call MatMult(A,y,y).
2328: Level: developer
2330: Concepts: matrix-vector product
2332: .seealso: MatMultTranspose(), MatMultAdd(), MatMultTransposeAdd()
2333: @*/
2334: PetscErrorCode MatMultDiagonalBlock(Mat mat,Vec x,Vec y)
2335: {
2344: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2345: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2346: if (x == y) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"x and y must be different vectors");
2347: MatCheckPreallocated(mat,1);
2349: if (!mat->ops->multdiagonalblock) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"This matrix type does not have a multiply defined");
2350: (*mat->ops->multdiagonalblock)(mat,x,y);
2351: PetscObjectStateIncrease((PetscObject)y);
2352: return(0);
2353: }
2355: /* --------------------------------------------------------*/
2356: /*@
2357: MatMult - Computes the matrix-vector product, y = Ax.
2359: Neighbor-wise Collective on Mat and Vec
2361: Input Parameters:
2362: + mat - the matrix
2363: - x - the vector to be multiplied
2365: Output Parameters:
2366: . y - the result
2368: Notes:
2369: The vectors x and y cannot be the same. I.e., one cannot
2370: call MatMult(A,y,y).
2372: Level: beginner
2374: Concepts: matrix-vector product
2376: .seealso: MatMultTranspose(), MatMultAdd(), MatMultTransposeAdd()
2377: @*/
2378: PetscErrorCode MatMult(Mat mat,Vec x,Vec y)
2379: {
2387: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2388: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2389: if (x == y) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"x and y must be different vectors");
2390: #if !defined(PETSC_HAVE_CONSTRAINTS)
2391: 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);
2392: 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);
2393: 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);
2394: #endif
2395: VecSetErrorIfLocked(y,3);
2396: if (mat->erroriffailure) {VecValidValues(x,2,PETSC_TRUE);}
2397: MatCheckPreallocated(mat,1);
2399: VecLockReadPush(x);
2400: if (!mat->ops->mult) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"This matrix type does not have a multiply defined");
2401: PetscLogEventBegin(MAT_Mult,mat,x,y,0);
2402: (*mat->ops->mult)(mat,x,y);
2403: PetscLogEventEnd(MAT_Mult,mat,x,y,0);
2404: if (mat->erroriffailure) {VecValidValues(y,3,PETSC_FALSE);}
2405: VecLockReadPop(x);
2406: return(0);
2407: }
2409: /*@
2410: MatMultTranspose - Computes matrix transpose times a vector y = A^T * x.
2412: Neighbor-wise Collective on Mat and Vec
2414: Input Parameters:
2415: + mat - the matrix
2416: - x - the vector to be multiplied
2418: Output Parameters:
2419: . y - the result
2421: Notes:
2422: The vectors x and y cannot be the same. I.e., one cannot
2423: call MatMultTranspose(A,y,y).
2425: For complex numbers this does NOT compute the Hermitian (complex conjugate) transpose multiple,
2426: use MatMultHermitianTranspose()
2428: Level: beginner
2430: Concepts: matrix vector product^transpose
2432: .seealso: MatMult(), MatMultAdd(), MatMultTransposeAdd(), MatMultHermitianTranspose(), MatTranspose()
2433: @*/
2434: PetscErrorCode MatMultTranspose(Mat mat,Vec x,Vec y)
2435: {
2444: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2445: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2446: if (x == y) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"x and y must be different vectors");
2447: #if !defined(PETSC_HAVE_CONSTRAINTS)
2448: 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);
2449: 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);
2450: #endif
2451: if (mat->erroriffailure) {VecValidValues(x,2,PETSC_TRUE);}
2452: MatCheckPreallocated(mat,1);
2454: if (!mat->ops->multtranspose) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"This matrix type does not have a multiply transpose defined");
2455: PetscLogEventBegin(MAT_MultTranspose,mat,x,y,0);
2456: VecLockReadPush(x);
2457: (*mat->ops->multtranspose)(mat,x,y);
2458: VecLockReadPop(x);
2459: PetscLogEventEnd(MAT_MultTranspose,mat,x,y,0);
2460: PetscObjectStateIncrease((PetscObject)y);
2461: if (mat->erroriffailure) {VecValidValues(y,3,PETSC_FALSE);}
2462: return(0);
2463: }
2465: /*@
2466: MatMultHermitianTranspose - Computes matrix Hermitian transpose times a vector.
2468: Neighbor-wise Collective on Mat and Vec
2470: Input Parameters:
2471: + mat - the matrix
2472: - x - the vector to be multilplied
2474: Output Parameters:
2475: . y - the result
2477: Notes:
2478: The vectors x and y cannot be the same. I.e., one cannot
2479: call MatMultHermitianTranspose(A,y,y).
2481: Also called the conjugate transpose, complex conjugate transpose, or adjoint.
2483: For real numbers MatMultTranspose() and MatMultHermitianTranspose() are identical.
2485: Level: beginner
2487: Concepts: matrix vector product^transpose
2489: .seealso: MatMult(), MatMultAdd(), MatMultHermitianTransposeAdd(), MatMultTranspose()
2490: @*/
2491: PetscErrorCode MatMultHermitianTranspose(Mat mat,Vec x,Vec y)
2492: {
2494: Vec w;
2502: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2503: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2504: if (x == y) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"x and y must be different vectors");
2505: #if !defined(PETSC_HAVE_CONSTRAINTS)
2506: 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);
2507: 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);
2508: #endif
2509: MatCheckPreallocated(mat,1);
2511: PetscLogEventBegin(MAT_MultHermitianTranspose,mat,x,y,0);
2512: if (mat->ops->multhermitiantranspose) {
2513: VecLockReadPush(x);
2514: (*mat->ops->multhermitiantranspose)(mat,x,y);
2515: VecLockReadPop(x);
2516: } else {
2517: VecDuplicate(x,&w);
2518: VecCopy(x,w);
2519: VecConjugate(w);
2520: MatMultTranspose(mat,w,y);
2521: VecDestroy(&w);
2522: VecConjugate(y);
2523: }
2524: PetscLogEventEnd(MAT_MultHermitianTranspose,mat,x,y,0);
2525: PetscObjectStateIncrease((PetscObject)y);
2526: return(0);
2527: }
2529: /*@
2530: MatMultAdd - Computes v3 = v2 + A * v1.
2532: Neighbor-wise Collective on Mat and Vec
2534: Input Parameters:
2535: + mat - the matrix
2536: - v1, v2 - the vectors
2538: Output Parameters:
2539: . v3 - the result
2541: Notes:
2542: The vectors v1 and v3 cannot be the same. I.e., one cannot
2543: call MatMultAdd(A,v1,v2,v1).
2545: Level: beginner
2547: Concepts: matrix vector product^addition
2549: .seealso: MatMultTranspose(), MatMult(), MatMultTransposeAdd()
2550: @*/
2551: PetscErrorCode MatMultAdd(Mat mat,Vec v1,Vec v2,Vec v3)
2552: {
2562: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2563: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2564: 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);
2565: /* 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);
2566: 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); */
2567: 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);
2568: 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);
2569: if (v1 == v3) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"v1 and v3 must be different vectors");
2570: MatCheckPreallocated(mat,1);
2572: if (!mat->ops->multadd) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"No MatMultAdd() for matrix type '%s'",((PetscObject)mat)->type_name);
2573: PetscLogEventBegin(MAT_MultAdd,mat,v1,v2,v3);
2574: VecLockReadPush(v1);
2575: (*mat->ops->multadd)(mat,v1,v2,v3);
2576: VecLockReadPop(v1);
2577: PetscLogEventEnd(MAT_MultAdd,mat,v1,v2,v3);
2578: PetscObjectStateIncrease((PetscObject)v3);
2579: return(0);
2580: }
2582: /*@
2583: MatMultTransposeAdd - Computes v3 = v2 + A' * v1.
2585: Neighbor-wise Collective on Mat and Vec
2587: Input Parameters:
2588: + mat - the matrix
2589: - v1, v2 - the vectors
2591: Output Parameters:
2592: . v3 - the result
2594: Notes:
2595: The vectors v1 and v3 cannot be the same. I.e., one cannot
2596: call MatMultTransposeAdd(A,v1,v2,v1).
2598: Level: beginner
2600: Concepts: matrix vector product^transpose and addition
2602: .seealso: MatMultTranspose(), MatMultAdd(), MatMult()
2603: @*/
2604: PetscErrorCode MatMultTransposeAdd(Mat mat,Vec v1,Vec v2,Vec v3)
2605: {
2615: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2616: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2617: if (!mat->ops->multtransposeadd) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
2618: if (v1 == v3) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"v1 and v3 must be different vectors");
2619: 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);
2620: 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);
2621: 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);
2622: MatCheckPreallocated(mat,1);
2624: PetscLogEventBegin(MAT_MultTransposeAdd,mat,v1,v2,v3);
2625: VecLockReadPush(v1);
2626: (*mat->ops->multtransposeadd)(mat,v1,v2,v3);
2627: VecLockReadPop(v1);
2628: PetscLogEventEnd(MAT_MultTransposeAdd,mat,v1,v2,v3);
2629: PetscObjectStateIncrease((PetscObject)v3);
2630: return(0);
2631: }
2633: /*@
2634: MatMultHermitianTransposeAdd - Computes v3 = v2 + A^H * v1.
2636: Neighbor-wise Collective on Mat and Vec
2638: Input Parameters:
2639: + mat - the matrix
2640: - v1, v2 - the vectors
2642: Output Parameters:
2643: . v3 - the result
2645: Notes:
2646: The vectors v1 and v3 cannot be the same. I.e., one cannot
2647: call MatMultHermitianTransposeAdd(A,v1,v2,v1).
2649: Level: beginner
2651: Concepts: matrix vector product^transpose and addition
2653: .seealso: MatMultHermitianTranspose(), MatMultTranspose(), MatMultAdd(), MatMult()
2654: @*/
2655: PetscErrorCode MatMultHermitianTransposeAdd(Mat mat,Vec v1,Vec v2,Vec v3)
2656: {
2666: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2667: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2668: if (v1 == v3) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"v1 and v3 must be different vectors");
2669: 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);
2670: 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);
2671: 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);
2672: MatCheckPreallocated(mat,1);
2674: PetscLogEventBegin(MAT_MultHermitianTransposeAdd,mat,v1,v2,v3);
2675: VecLockReadPush(v1);
2676: if (mat->ops->multhermitiantransposeadd) {
2677: (*mat->ops->multhermitiantransposeadd)(mat,v1,v2,v3);
2678: } else {
2679: Vec w,z;
2680: VecDuplicate(v1,&w);
2681: VecCopy(v1,w);
2682: VecConjugate(w);
2683: VecDuplicate(v3,&z);
2684: MatMultTranspose(mat,w,z);
2685: VecDestroy(&w);
2686: VecConjugate(z);
2687: if (v2 != v3) {
2688: VecWAXPY(v3,1.0,v2,z);
2689: } else {
2690: VecAXPY(v3,1.0,z);
2691: }
2692: VecDestroy(&z);
2693: }
2694: VecLockReadPop(v1);
2695: PetscLogEventEnd(MAT_MultHermitianTransposeAdd,mat,v1,v2,v3);
2696: PetscObjectStateIncrease((PetscObject)v3);
2697: return(0);
2698: }
2700: /*@
2701: MatMultConstrained - The inner multiplication routine for a
2702: constrained matrix P^T A P.
2704: Neighbor-wise Collective on Mat and Vec
2706: Input Parameters:
2707: + mat - the matrix
2708: - x - the vector to be multilplied
2710: Output Parameters:
2711: . y - the result
2713: Notes:
2714: The vectors x and y cannot be the same. I.e., one cannot
2715: call MatMult(A,y,y).
2717: Level: beginner
2719: .keywords: matrix, multiply, matrix-vector product, constraint
2720: .seealso: MatMult(), MatMultTranspose(), MatMultAdd(), MatMultTransposeAdd()
2721: @*/
2722: PetscErrorCode MatMultConstrained(Mat mat,Vec x,Vec y)
2723: {
2730: if (!mat->assembled) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2731: if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2732: if (x == y) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"x and y must be different vectors");
2733: 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);
2734: 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);
2735: 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);
2737: PetscLogEventBegin(MAT_MultConstrained,mat,x,y,0);
2738: VecLockReadPush(x);
2739: (*mat->ops->multconstrained)(mat,x,y);
2740: VecLockReadPop(x);
2741: PetscLogEventEnd(MAT_MultConstrained,mat,x,y,0);
2742: PetscObjectStateIncrease((PetscObject)y);
2743: return(0);
2744: }
2746: /*@
2747: MatMultTransposeConstrained - The inner multiplication routine for a
2748: constrained matrix P^T A^T P.
2750: Neighbor-wise Collective on Mat and Vec
2752: Input Parameters:
2753: + mat - the matrix
2754: - x - the vector to be multilplied
2756: Output Parameters:
2757: . y - the result
2759: Notes:
2760: The vectors x and y cannot be the same. I.e., one cannot
2761: call MatMult(A,y,y).
2763: Level: beginner
2765: .keywords: matrix, multiply, matrix-vector product, constraint
2766: .seealso: MatMult(), MatMultTranspose(), MatMultAdd(), MatMultTransposeAdd()
2767: @*/
2768: PetscErrorCode MatMultTransposeConstrained(Mat mat,Vec x,Vec y)
2769: {
2776: if (!mat->assembled) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2777: if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2778: if (x == y) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"x and y must be different vectors");
2779: 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);
2780: 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);
2782: PetscLogEventBegin(MAT_MultConstrained,mat,x,y,0);
2783: (*mat->ops->multtransposeconstrained)(mat,x,y);
2784: PetscLogEventEnd(MAT_MultConstrained,mat,x,y,0);
2785: PetscObjectStateIncrease((PetscObject)y);
2786: return(0);
2787: }
2789: /*@C
2790: MatGetFactorType - gets the type of factorization it is
2792: Not Collective
2794: Input Parameters:
2795: . mat - the matrix
2797: Output Parameters:
2798: . t - the type, one of MAT_FACTOR_NONE, MAT_FACTOR_LU, MAT_FACTOR_CHOLESKY, MAT_FACTOR_ILU, MAT_FACTOR_ICC,MAT_FACTOR_ILUDT
2800: Level: intermediate
2802: .seealso: MatFactorType, MatGetFactor(), MatSetFactorType()
2803: @*/
2804: PetscErrorCode MatGetFactorType(Mat mat,MatFactorType *t)
2805: {
2810: *t = mat->factortype;
2811: return(0);
2812: }
2814: /*@C
2815: MatSetFactorType - sets the type of factorization it is
2817: Logically Collective on Mat
2819: Input Parameters:
2820: + mat - the matrix
2821: - t - the type, one of MAT_FACTOR_NONE, MAT_FACTOR_LU, MAT_FACTOR_CHOLESKY, MAT_FACTOR_ILU, MAT_FACTOR_ICC,MAT_FACTOR_ILUDT
2823: Level: intermediate
2825: .seealso: MatFactorType, MatGetFactor(), MatGetFactorType()
2826: @*/
2827: PetscErrorCode MatSetFactorType(Mat mat, MatFactorType t)
2828: {
2832: mat->factortype = t;
2833: return(0);
2834: }
2836: /* ------------------------------------------------------------*/
2837: /*@C
2838: MatGetInfo - Returns information about matrix storage (number of
2839: nonzeros, memory, etc.).
2841: Collective on Mat if MAT_GLOBAL_MAX or MAT_GLOBAL_SUM is used as the flag
2843: Input Parameters:
2844: . mat - the matrix
2846: Output Parameters:
2847: + flag - flag indicating the type of parameters to be returned
2848: (MAT_LOCAL - local matrix, MAT_GLOBAL_MAX - maximum over all processors,
2849: MAT_GLOBAL_SUM - sum over all processors)
2850: - info - matrix information context
2852: Notes:
2853: The MatInfo context contains a variety of matrix data, including
2854: number of nonzeros allocated and used, number of mallocs during
2855: matrix assembly, etc. Additional information for factored matrices
2856: is provided (such as the fill ratio, number of mallocs during
2857: factorization, etc.). Much of this info is printed to PETSC_STDOUT
2858: when using the runtime options
2859: $ -info -mat_view ::ascii_info
2861: Example for C/C++ Users:
2862: See the file ${PETSC_DIR}/include/petscmat.h for a complete list of
2863: data within the MatInfo context. For example,
2864: .vb
2865: MatInfo info;
2866: Mat A;
2867: double mal, nz_a, nz_u;
2869: MatGetInfo(A,MAT_LOCAL,&info);
2870: mal = info.mallocs;
2871: nz_a = info.nz_allocated;
2872: .ve
2874: Example for Fortran Users:
2875: Fortran users should declare info as a double precision
2876: array of dimension MAT_INFO_SIZE, and then extract the parameters
2877: of interest. See the file ${PETSC_DIR}/include/petsc/finclude/petscmat.h
2878: a complete list of parameter names.
2879: .vb
2880: double precision info(MAT_INFO_SIZE)
2881: double precision mal, nz_a
2882: Mat A
2883: integer ierr
2885: call MatGetInfo(A,MAT_LOCAL,info,ierr)
2886: mal = info(MAT_INFO_MALLOCS)
2887: nz_a = info(MAT_INFO_NZ_ALLOCATED)
2888: .ve
2890: Level: intermediate
2892: Concepts: matrices^getting information on
2894: Developer Note: fortran interface is not autogenerated as the f90
2895: interface defintion cannot be generated correctly [due to MatInfo]
2897: .seealso: MatStashGetInfo()
2899: @*/
2900: PetscErrorCode MatGetInfo(Mat mat,MatInfoType flag,MatInfo *info)
2901: {
2908: if (!mat->ops->getinfo) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
2909: MatCheckPreallocated(mat,1);
2910: (*mat->ops->getinfo)(mat,flag,info);
2911: return(0);
2912: }
2914: /*
2915: This is used by external packages where it is not easy to get the info from the actual
2916: matrix factorization.
2917: */
2918: PetscErrorCode MatGetInfo_External(Mat A,MatInfoType flag,MatInfo *info)
2919: {
2923: PetscMemzero(info,sizeof(MatInfo));
2924: return(0);
2925: }
2927: /* ----------------------------------------------------------*/
2929: /*@C
2930: MatLUFactor - Performs in-place LU factorization of matrix.
2932: Collective on Mat
2934: Input Parameters:
2935: + mat - the matrix
2936: . row - row permutation
2937: . col - column permutation
2938: - info - options for factorization, includes
2939: $ fill - expected fill as ratio of original fill.
2940: $ dtcol - pivot tolerance (0 no pivot, 1 full column pivoting)
2941: $ Run with the option -info to determine an optimal value to use
2943: Notes:
2944: Most users should employ the simplified KSP interface for linear solvers
2945: instead of working directly with matrix algebra routines such as this.
2946: See, e.g., KSPCreate().
2948: This changes the state of the matrix to a factored matrix; it cannot be used
2949: for example with MatSetValues() unless one first calls MatSetUnfactored().
2951: Level: developer
2953: Concepts: matrices^LU factorization
2955: .seealso: MatLUFactorSymbolic(), MatLUFactorNumeric(), MatCholeskyFactor(),
2956: MatGetOrdering(), MatSetUnfactored(), MatFactorInfo, MatGetFactor()
2958: Developer Note: fortran interface is not autogenerated as the f90
2959: interface defintion cannot be generated correctly [due to MatFactorInfo]
2961: @*/
2962: PetscErrorCode MatLUFactor(Mat mat,IS row,IS col,const MatFactorInfo *info)
2963: {
2965: MatFactorInfo tinfo;
2973: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2974: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2975: if (!mat->ops->lufactor) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
2976: MatCheckPreallocated(mat,1);
2977: if (!info) {
2978: MatFactorInfoInitialize(&tinfo);
2979: info = &tinfo;
2980: }
2982: PetscLogEventBegin(MAT_LUFactor,mat,row,col,0);
2983: (*mat->ops->lufactor)(mat,row,col,info);
2984: PetscLogEventEnd(MAT_LUFactor,mat,row,col,0);
2985: PetscObjectStateIncrease((PetscObject)mat);
2986: return(0);
2987: }
2989: /*@C
2990: MatILUFactor - Performs in-place ILU factorization of matrix.
2992: Collective on Mat
2994: Input Parameters:
2995: + mat - the matrix
2996: . row - row permutation
2997: . col - column permutation
2998: - info - structure containing
2999: $ levels - number of levels of fill.
3000: $ expected fill - as ratio of original fill.
3001: $ 1 or 0 - indicating force fill on diagonal (improves robustness for matrices
3002: missing diagonal entries)
3004: Notes:
3005: Probably really in-place only when level of fill is zero, otherwise allocates
3006: new space to store factored matrix and deletes previous memory.
3008: Most users should employ the simplified KSP interface for linear solvers
3009: instead of working directly with matrix algebra routines such as this.
3010: See, e.g., KSPCreate().
3012: Level: developer
3014: Concepts: matrices^ILU factorization
3016: .seealso: MatILUFactorSymbolic(), MatLUFactorNumeric(), MatCholeskyFactor(), MatFactorInfo
3018: Developer Note: fortran interface is not autogenerated as the f90
3019: interface defintion cannot be generated correctly [due to MatFactorInfo]
3021: @*/
3022: PetscErrorCode MatILUFactor(Mat mat,IS row,IS col,const MatFactorInfo *info)
3023: {
3032: if (mat->rmap->N != mat->cmap->N) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONG,"matrix must be square");
3033: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
3034: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
3035: if (!mat->ops->ilufactor) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
3036: MatCheckPreallocated(mat,1);
3038: PetscLogEventBegin(MAT_ILUFactor,mat,row,col,0);
3039: (*mat->ops->ilufactor)(mat,row,col,info);
3040: PetscLogEventEnd(MAT_ILUFactor,mat,row,col,0);
3041: PetscObjectStateIncrease((PetscObject)mat);
3042: return(0);
3043: }
3045: /*@C
3046: MatLUFactorSymbolic - Performs symbolic LU factorization of matrix.
3047: Call this routine before calling MatLUFactorNumeric().
3049: Collective on Mat
3051: Input Parameters:
3052: + fact - the factor matrix obtained with MatGetFactor()
3053: . mat - the matrix
3054: . row, col - row and column permutations
3055: - info - options for factorization, includes
3056: $ fill - expected fill as ratio of original fill.
3057: $ dtcol - pivot tolerance (0 no pivot, 1 full column pivoting)
3058: $ Run with the option -info to determine an optimal value to use
3061: Notes:
3062: See Users-Manual: ch_mat for additional information about choosing the fill factor for better efficiency.
3064: Most users should employ the simplified KSP interface for linear solvers
3065: instead of working directly with matrix algebra routines such as this.
3066: See, e.g., KSPCreate().
3068: Level: developer
3070: Concepts: matrices^LU symbolic factorization
3072: .seealso: MatLUFactor(), MatLUFactorNumeric(), MatCholeskyFactor(), MatFactorInfo, MatFactorInfoInitialize()
3074: Developer Note: fortran interface is not autogenerated as the f90
3075: interface defintion cannot be generated correctly [due to MatFactorInfo]
3077: @*/
3078: PetscErrorCode MatLUFactorSymbolic(Mat fact,Mat mat,IS row,IS col,const MatFactorInfo *info)
3079: {
3089: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
3090: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
3091: if (!(fact)->ops->lufactorsymbolic) {
3092: MatSolverType spackage;
3093: MatFactorGetSolverType(fact,&spackage);
3094: SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Matrix type %s symbolic LU using solver package %s",((PetscObject)mat)->type_name,spackage);
3095: }
3096: MatCheckPreallocated(mat,2);
3098: PetscLogEventBegin(MAT_LUFactorSymbolic,mat,row,col,0);
3099: (fact->ops->lufactorsymbolic)(fact,mat,row,col,info);
3100: PetscLogEventEnd(MAT_LUFactorSymbolic,mat,row,col,0);
3101: PetscObjectStateIncrease((PetscObject)fact);
3102: return(0);
3103: }
3105: /*@C
3106: MatLUFactorNumeric - Performs numeric LU factorization of a matrix.
3107: Call this routine after first calling MatLUFactorSymbolic().
3109: Collective on Mat
3111: Input Parameters:
3112: + fact - the factor matrix obtained with MatGetFactor()
3113: . mat - the matrix
3114: - info - options for factorization
3116: Notes:
3117: See MatLUFactor() for in-place factorization. See
3118: MatCholeskyFactorNumeric() for the symmetric, positive definite case.
3120: Most users should employ the simplified KSP interface for linear solvers
3121: instead of working directly with matrix algebra routines such as this.
3122: See, e.g., KSPCreate().
3124: Level: developer
3126: Concepts: matrices^LU numeric factorization
3128: .seealso: MatLUFactorSymbolic(), MatLUFactor(), MatCholeskyFactor()
3130: Developer Note: fortran interface is not autogenerated as the f90
3131: interface defintion cannot be generated correctly [due to MatFactorInfo]
3133: @*/
3134: PetscErrorCode MatLUFactorNumeric(Mat fact,Mat mat,const MatFactorInfo *info)
3135: {
3143: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
3144: 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);
3146: if (!(fact)->ops->lufactornumeric) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s numeric LU",((PetscObject)mat)->type_name);
3147: MatCheckPreallocated(mat,2);
3148: PetscLogEventBegin(MAT_LUFactorNumeric,mat,fact,0,0);
3149: (fact->ops->lufactornumeric)(fact,mat,info);
3150: PetscLogEventEnd(MAT_LUFactorNumeric,mat,fact,0,0);
3151: MatViewFromOptions(fact,NULL,"-mat_factor_view");
3152: PetscObjectStateIncrease((PetscObject)fact);
3153: return(0);
3154: }
3156: /*@C
3157: MatCholeskyFactor - Performs in-place Cholesky factorization of a
3158: symmetric matrix.
3160: Collective on Mat
3162: Input Parameters:
3163: + mat - the matrix
3164: . perm - row and column permutations
3165: - f - expected fill as ratio of original fill
3167: Notes:
3168: See MatLUFactor() for the nonsymmetric case. See also
3169: MatCholeskyFactorSymbolic(), and MatCholeskyFactorNumeric().
3171: Most users should employ the simplified KSP interface for linear solvers
3172: instead of working directly with matrix algebra routines such as this.
3173: See, e.g., KSPCreate().
3175: Level: developer
3177: Concepts: matrices^Cholesky factorization
3179: .seealso: MatLUFactor(), MatCholeskyFactorSymbolic(), MatCholeskyFactorNumeric()
3180: MatGetOrdering()
3182: Developer Note: fortran interface is not autogenerated as the f90
3183: interface defintion cannot be generated correctly [due to MatFactorInfo]
3185: @*/
3186: PetscErrorCode MatCholeskyFactor(Mat mat,IS perm,const MatFactorInfo *info)
3187: {
3195: if (mat->rmap->N != mat->cmap->N) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONG,"Matrix must be square");
3196: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
3197: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
3198: 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);
3199: MatCheckPreallocated(mat,1);
3201: PetscLogEventBegin(MAT_CholeskyFactor,mat,perm,0,0);
3202: (*mat->ops->choleskyfactor)(mat,perm,info);
3203: PetscLogEventEnd(MAT_CholeskyFactor,mat,perm,0,0);
3204: PetscObjectStateIncrease((PetscObject)mat);
3205: return(0);
3206: }
3208: /*@C
3209: MatCholeskyFactorSymbolic - Performs symbolic Cholesky factorization
3210: of a symmetric matrix.
3212: Collective on Mat
3214: Input Parameters:
3215: + fact - the factor matrix obtained with MatGetFactor()
3216: . mat - the matrix
3217: . perm - row and column permutations
3218: - info - options for factorization, includes
3219: $ fill - expected fill as ratio of original fill.
3220: $ dtcol - pivot tolerance (0 no pivot, 1 full column pivoting)
3221: $ Run with the option -info to determine an optimal value to use
3223: Notes:
3224: See MatLUFactorSymbolic() for the nonsymmetric case. See also
3225: MatCholeskyFactor() and MatCholeskyFactorNumeric().
3227: Most users should employ the simplified KSP interface for linear solvers
3228: instead of working directly with matrix algebra routines such as this.
3229: See, e.g., KSPCreate().
3231: Level: developer
3233: Concepts: matrices^Cholesky symbolic factorization
3235: .seealso: MatLUFactorSymbolic(), MatCholeskyFactor(), MatCholeskyFactorNumeric()
3236: MatGetOrdering()
3238: Developer Note: fortran interface is not autogenerated as the f90
3239: interface defintion cannot be generated correctly [due to MatFactorInfo]
3241: @*/
3242: PetscErrorCode MatCholeskyFactorSymbolic(Mat fact,Mat mat,IS perm,const MatFactorInfo *info)
3243: {
3252: if (mat->rmap->N != mat->cmap->N) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONG,"Matrix must be square");
3253: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
3254: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
3255: if (!(fact)->ops->choleskyfactorsymbolic) {
3256: MatSolverType spackage;
3257: MatFactorGetSolverType(fact,&spackage);
3258: SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s symbolic factor Cholesky using solver package %s",((PetscObject)mat)->type_name,spackage);
3259: }
3260: MatCheckPreallocated(mat,2);
3262: PetscLogEventBegin(MAT_CholeskyFactorSymbolic,mat,perm,0,0);
3263: (fact->ops->choleskyfactorsymbolic)(fact,mat,perm,info);
3264: PetscLogEventEnd(MAT_CholeskyFactorSymbolic,mat,perm,0,0);
3265: PetscObjectStateIncrease((PetscObject)fact);
3266: return(0);
3267: }
3269: /*@C
3270: MatCholeskyFactorNumeric - Performs numeric Cholesky factorization
3271: of a symmetric matrix. Call this routine after first calling
3272: MatCholeskyFactorSymbolic().
3274: Collective on Mat
3276: Input Parameters:
3277: + fact - the factor matrix obtained with MatGetFactor()
3278: . mat - the initial matrix
3279: . info - options for factorization
3280: - fact - the symbolic factor of mat
3283: Notes:
3284: Most users should employ the simplified KSP interface for linear solvers
3285: instead of working directly with matrix algebra routines such as this.
3286: See, e.g., KSPCreate().
3288: Level: developer
3290: Concepts: matrices^Cholesky numeric factorization
3292: .seealso: MatCholeskyFactorSymbolic(), MatCholeskyFactor(), MatLUFactorNumeric()
3294: Developer Note: fortran interface is not autogenerated as the f90
3295: interface defintion cannot be generated correctly [due to MatFactorInfo]
3297: @*/
3298: PetscErrorCode MatCholeskyFactorNumeric(Mat fact,Mat mat,const MatFactorInfo *info)
3299: {
3307: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
3308: if (!(fact)->ops->choleskyfactornumeric) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s numeric factor Cholesky",((PetscObject)mat)->type_name);
3309: 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);
3310: MatCheckPreallocated(mat,2);
3312: PetscLogEventBegin(MAT_CholeskyFactorNumeric,mat,fact,0,0);
3313: (fact->ops->choleskyfactornumeric)(fact,mat,info);
3314: PetscLogEventEnd(MAT_CholeskyFactorNumeric,mat,fact,0,0);
3315: MatViewFromOptions(fact,NULL,"-mat_factor_view");
3316: PetscObjectStateIncrease((PetscObject)fact);
3317: return(0);
3318: }
3320: /* ----------------------------------------------------------------*/
3321: /*@
3322: MatSolve - Solves A x = b, given a factored matrix.
3324: Neighbor-wise Collective on Mat and Vec
3326: Input Parameters:
3327: + mat - the factored matrix
3328: - b - the right-hand-side vector
3330: Output Parameter:
3331: . x - the result vector
3333: Notes:
3334: The vectors b and x cannot be the same. I.e., one cannot
3335: call MatSolve(A,x,x).
3337: Notes:
3338: Most users should employ the simplified KSP interface for linear solvers
3339: instead of working directly with matrix algebra routines such as this.
3340: See, e.g., KSPCreate().
3342: Level: developer
3344: Concepts: matrices^triangular solves
3346: .seealso: MatSolveAdd(), MatSolveTranspose(), MatSolveTransposeAdd()
3347: @*/
3348: PetscErrorCode MatSolve(Mat mat,Vec b,Vec x)
3349: {
3359: if (x == b) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"x and b must be different vectors");
3360: 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);
3361: 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);
3362: 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);
3363: if (!mat->rmap->N && !mat->cmap->N) return(0);
3364: if (!mat->ops->solve) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
3365: MatCheckPreallocated(mat,1);
3367: PetscLogEventBegin(MAT_Solve,mat,b,x,0);
3368: if (mat->factorerrortype) {
3369: PetscInfo1(mat,"MatFactorError %D\n",mat->factorerrortype);
3370: VecSetInf(x);
3371: } else {
3372: if (!mat->ops->solve) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
3373: (*mat->ops->solve)(mat,b,x);
3374: }
3375: PetscLogEventEnd(MAT_Solve,mat,b,x,0);
3376: PetscObjectStateIncrease((PetscObject)x);
3377: return(0);
3378: }
3380: static PetscErrorCode MatMatSolve_Basic(Mat A,Mat B,Mat X, PetscBool trans)
3381: {
3383: Vec b,x;
3384: PetscInt m,N,i;
3385: PetscScalar *bb,*xx;
3386: PetscBool flg;
3389: PetscObjectTypeCompareAny((PetscObject)B,&flg,MATSEQDENSE,MATMPIDENSE,NULL);
3390: if (!flg) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONG,"Matrix B must be MATDENSE matrix");
3391: PetscObjectTypeCompareAny((PetscObject)X,&flg,MATSEQDENSE,MATMPIDENSE,NULL);
3392: if (!flg) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONG,"Matrix X must be MATDENSE matrix");
3394: MatDenseGetArray(B,&bb);
3395: MatDenseGetArray(X,&xx);
3396: MatGetLocalSize(B,&m,NULL); /* number local rows */
3397: MatGetSize(B,NULL,&N); /* total columns in dense matrix */
3398: MatCreateVecs(A,&x,&b);
3399: for (i=0; i<N; i++) {
3400: VecPlaceArray(b,bb + i*m);
3401: VecPlaceArray(x,xx + i*m);
3402: if (trans) {
3403: MatSolveTranspose(A,b,x);
3404: } else {
3405: MatSolve(A,b,x);
3406: }
3407: VecResetArray(x);
3408: VecResetArray(b);
3409: }
3410: VecDestroy(&b);
3411: VecDestroy(&x);
3412: MatDenseRestoreArray(B,&bb);
3413: MatDenseRestoreArray(X,&xx);
3414: return(0);
3415: }
3417: /*@
3418: MatMatSolve - Solves A X = B, given a factored matrix.
3420: Neighbor-wise Collective on Mat
3422: Input Parameters:
3423: + A - the factored matrix
3424: - B - the right-hand-side matrix (dense matrix)
3426: Output Parameter:
3427: . X - the result matrix (dense matrix)
3429: Notes:
3430: The matrices b and x cannot be the same. I.e., one cannot
3431: call MatMatSolve(A,x,x).
3433: Notes:
3434: Most users should usually employ the simplified KSP interface for linear solvers
3435: instead of working directly with matrix algebra routines such as this.
3436: See, e.g., KSPCreate(). However KSP can only solve for one vector (column of X)
3437: at a time.
3439: When using SuperLU_Dist as a parallel solver PETSc will use the SuperLU_Dist functionality to solve multiple right hand sides simultaneously. For MUMPS
3440: it calls a separate solve for each right hand side since MUMPS does not yet support distributed right hand sides.
3442: Since the resulting matrix X must always be dense we do not support sparse representation of the matrix B.
3444: Level: developer
3446: Concepts: matrices^triangular solves
3448: .seealso: MatMatSolveTranspose(), MatLUFactor(), MatCholeskyFactor()
3449: @*/
3450: PetscErrorCode MatMatSolve(Mat A,Mat B,Mat X)
3451: {
3461: if (X == B) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_IDN,"X and B must be different matrices");
3462: 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);
3463: 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);
3464: 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");
3465: if (!A->rmap->N && !A->cmap->N) return(0);
3466: if (!A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
3467: MatCheckPreallocated(A,1);
3469: PetscLogEventBegin(MAT_MatSolve,A,B,X,0);
3470: if (!A->ops->matsolve) {
3471: PetscInfo1(A,"Mat type %s using basic MatMatSolve\n",((PetscObject)A)->type_name);
3472: MatMatSolve_Basic(A,B,X,PETSC_FALSE);
3473: } else {
3474: (*A->ops->matsolve)(A,B,X);
3475: }
3476: PetscLogEventEnd(MAT_MatSolve,A,B,X,0);
3477: PetscObjectStateIncrease((PetscObject)X);
3478: return(0);
3479: }
3481: /*@
3482: MatMatSolveTranspose - Solves A^T X = B, given a factored matrix.
3484: Neighbor-wise Collective on Mat
3486: Input Parameters:
3487: + A - the factored matrix
3488: - B - the right-hand-side matrix (dense matrix)
3490: Output Parameter:
3491: . X - the result matrix (dense matrix)
3493: Notes:
3494: The matrices B and X cannot be the same. I.e., one cannot
3495: call MatMatSolveTranspose(A,X,X).
3497: Notes:
3498: Most users should usually employ the simplified KSP interface for linear solvers
3499: instead of working directly with matrix algebra routines such as this.
3500: See, e.g., KSPCreate(). However KSP can only solve for one vector (column of X)
3501: at a time.
3503: When using SuperLU_Dist or MUMPS as a parallel solver, PETSc will use their functionality to solve multiple right hand sides simultaneously.
3505: Level: developer
3507: Concepts: matrices^triangular solves
3509: .seealso: MatMatSolve(), MatLUFactor(), MatCholeskyFactor()
3510: @*/
3511: PetscErrorCode MatMatSolveTranspose(Mat A,Mat B,Mat X)
3512: {
3522: if (X == B) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_IDN,"X and B must be different matrices");
3523: 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);
3524: 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);
3525: 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);
3526: 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");
3527: if (!A->rmap->N && !A->cmap->N) return(0);
3528: if (!A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
3529: MatCheckPreallocated(A,1);
3531: PetscLogEventBegin(MAT_MatSolve,A,B,X,0);
3532: if (!A->ops->matsolvetranspose) {
3533: PetscInfo1(A,"Mat type %s using basic MatMatSolveTranspose\n",((PetscObject)A)->type_name);
3534: MatMatSolve_Basic(A,B,X,PETSC_TRUE);
3535: } else {
3536: (*A->ops->matsolvetranspose)(A,B,X);
3537: }
3538: PetscLogEventEnd(MAT_MatSolve,A,B,X,0);
3539: PetscObjectStateIncrease((PetscObject)X);
3540: return(0);
3541: }
3543: /*@
3544: MatMatTransposeSolve - Solves A X = B^T, given a factored matrix.
3546: Neighbor-wise Collective on Mat
3548: Input Parameters:
3549: + A - the factored matrix
3550: - Bt - the transpose of right-hand-side matrix
3552: Output Parameter:
3553: . X - the result matrix (dense matrix)
3555: Notes:
3556: Most users should usually employ the simplified KSP interface for linear solvers
3557: instead of working directly with matrix algebra routines such as this.
3558: See, e.g., KSPCreate(). However KSP can only solve for one vector (column of X)
3559: at a time.
3561: 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().
3563: Level: developer
3565: Concepts: matrices^triangular solves
3567: .seealso: MatMatSolve(), MatMatSolveTranspose(), MatLUFactor(), MatCholeskyFactor()
3568: @*/
3569: PetscErrorCode MatMatTransposeSolve(Mat A,Mat Bt,Mat X)
3570: {
3581: if (X == Bt) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_IDN,"X and B must be different matrices");
3582: 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);
3583: 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);
3584: 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");
3585: if (!A->rmap->N && !A->cmap->N) return(0);
3586: if (!A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
3587: MatCheckPreallocated(A,1);
3589: if (!A->ops->mattransposesolve) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Mat type %s",((PetscObject)A)->type_name);
3590: PetscLogEventBegin(MAT_MatTrSolve,A,Bt,X,0);
3591: (*A->ops->mattransposesolve)(A,Bt,X);
3592: PetscLogEventEnd(MAT_MatTrSolve,A,Bt,X,0);
3593: PetscObjectStateIncrease((PetscObject)X);
3594: return(0);
3595: }
3597: /*@
3598: MatForwardSolve - Solves L x = b, given a factored matrix, A = LU, or
3599: U^T*D^(1/2) x = b, given a factored symmetric matrix, A = U^T*D*U,
3601: Neighbor-wise Collective on Mat and Vec
3603: Input Parameters:
3604: + mat - the factored matrix
3605: - b - the right-hand-side vector
3607: Output Parameter:
3608: . x - the result vector
3610: Notes:
3611: MatSolve() should be used for most applications, as it performs
3612: a forward solve followed by a backward solve.
3614: The vectors b and x cannot be the same, i.e., one cannot
3615: call MatForwardSolve(A,x,x).
3617: For matrix in seqsbaij format with block size larger than 1,
3618: the diagonal blocks are not implemented as D = D^(1/2) * D^(1/2) yet.
3619: MatForwardSolve() solves U^T*D y = b, and
3620: MatBackwardSolve() solves U x = y.
3621: Thus they do not provide a symmetric preconditioner.
3623: Most users should employ the simplified KSP interface for linear solvers
3624: instead of working directly with matrix algebra routines such as this.
3625: See, e.g., KSPCreate().
3627: Level: developer
3629: Concepts: matrices^forward solves
3631: .seealso: MatSolve(), MatBackwardSolve()
3632: @*/
3633: PetscErrorCode MatForwardSolve(Mat mat,Vec b,Vec x)
3634: {
3644: if (x == b) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"x and b must be different vectors");
3645: 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);
3646: 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);
3647: 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);
3648: if (!mat->rmap->N && !mat->cmap->N) return(0);
3649: if (!mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
3650: MatCheckPreallocated(mat,1);
3652: if (!mat->ops->forwardsolve) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
3653: PetscLogEventBegin(MAT_ForwardSolve,mat,b,x,0);
3654: (*mat->ops->forwardsolve)(mat,b,x);
3655: PetscLogEventEnd(MAT_ForwardSolve,mat,b,x,0);
3656: PetscObjectStateIncrease((PetscObject)x);
3657: return(0);
3658: }
3660: /*@
3661: MatBackwardSolve - Solves U x = b, given a factored matrix, A = LU.
3662: D^(1/2) U x = b, given a factored symmetric matrix, A = U^T*D*U,
3664: Neighbor-wise Collective on Mat and Vec
3666: Input Parameters:
3667: + mat - the factored matrix
3668: - b - the right-hand-side vector
3670: Output Parameter:
3671: . x - the result vector
3673: Notes:
3674: MatSolve() should be used for most applications, as it performs
3675: a forward solve followed by a backward solve.
3677: The vectors b and x cannot be the same. I.e., one cannot
3678: call MatBackwardSolve(A,x,x).
3680: For matrix in seqsbaij format with block size larger than 1,
3681: the diagonal blocks are not implemented as D = D^(1/2) * D^(1/2) yet.
3682: MatForwardSolve() solves U^T*D y = b, and
3683: MatBackwardSolve() solves U x = y.
3684: Thus they do not provide a symmetric preconditioner.
3686: Most users should employ the simplified KSP interface for linear solvers
3687: instead of working directly with matrix algebra routines such as this.
3688: See, e.g., KSPCreate().
3690: Level: developer
3692: Concepts: matrices^backward solves
3694: .seealso: MatSolve(), MatForwardSolve()
3695: @*/
3696: PetscErrorCode MatBackwardSolve(Mat mat,Vec b,Vec x)
3697: {
3707: if (x == b) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"x and b must be different vectors");
3708: 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);
3709: 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);
3710: 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);
3711: if (!mat->rmap->N && !mat->cmap->N) return(0);
3712: if (!mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
3713: MatCheckPreallocated(mat,1);
3715: if (!mat->ops->backwardsolve) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
3716: PetscLogEventBegin(MAT_BackwardSolve,mat,b,x,0);
3717: (*mat->ops->backwardsolve)(mat,b,x);
3718: PetscLogEventEnd(MAT_BackwardSolve,mat,b,x,0);
3719: PetscObjectStateIncrease((PetscObject)x);
3720: return(0);
3721: }
3723: /*@
3724: MatSolveAdd - Computes x = y + inv(A)*b, given a factored matrix.
3726: Neighbor-wise Collective on Mat and Vec
3728: Input Parameters:
3729: + mat - the factored matrix
3730: . b - the right-hand-side vector
3731: - y - the vector to be added to
3733: Output Parameter:
3734: . x - the result vector
3736: Notes:
3737: The vectors b and x cannot be the same. I.e., one cannot
3738: call MatSolveAdd(A,x,y,x).
3740: Most users should employ the simplified KSP interface for linear solvers
3741: instead of working directly with matrix algebra routines such as this.
3742: See, e.g., KSPCreate().
3744: Level: developer
3746: Concepts: matrices^triangular solves
3748: .seealso: MatSolve(), MatSolveTranspose(), MatSolveTransposeAdd()
3749: @*/
3750: PetscErrorCode MatSolveAdd(Mat mat,Vec b,Vec y,Vec x)
3751: {
3752: PetscScalar one = 1.0;
3753: Vec tmp;
3765: if (x == b) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"x and b must be different vectors");
3766: 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);
3767: 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);
3768: 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);
3769: 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);
3770: 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);
3771: if (!mat->rmap->N && !mat->cmap->N) return(0);
3772: if (!mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
3773: MatCheckPreallocated(mat,1);
3775: PetscLogEventBegin(MAT_SolveAdd,mat,b,x,y);
3776: if (mat->ops->solveadd) {
3777: (*mat->ops->solveadd)(mat,b,y,x);
3778: } else {
3779: /* do the solve then the add manually */
3780: if (x != y) {
3781: MatSolve(mat,b,x);
3782: VecAXPY(x,one,y);
3783: } else {
3784: VecDuplicate(x,&tmp);
3785: PetscLogObjectParent((PetscObject)mat,(PetscObject)tmp);
3786: VecCopy(x,tmp);
3787: MatSolve(mat,b,x);
3788: VecAXPY(x,one,tmp);
3789: VecDestroy(&tmp);
3790: }
3791: }
3792: PetscLogEventEnd(MAT_SolveAdd,mat,b,x,y);
3793: PetscObjectStateIncrease((PetscObject)x);
3794: return(0);
3795: }
3797: /*@
3798: MatSolveTranspose - Solves A' x = b, given a factored matrix.
3800: Neighbor-wise Collective on Mat and Vec
3802: Input Parameters:
3803: + mat - the factored matrix
3804: - b - the right-hand-side vector
3806: Output Parameter:
3807: . x - the result vector
3809: Notes:
3810: The vectors b and x cannot be the same. I.e., one cannot
3811: call MatSolveTranspose(A,x,x).
3813: Most users should employ the simplified KSP interface for linear solvers
3814: instead of working directly with matrix algebra routines such as this.
3815: See, e.g., KSPCreate().
3817: Level: developer
3819: Concepts: matrices^triangular solves
3821: .seealso: MatSolve(), MatSolveAdd(), MatSolveTransposeAdd()
3822: @*/
3823: PetscErrorCode MatSolveTranspose(Mat mat,Vec b,Vec x)
3824: {
3834: if (x == b) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"x and b must be different vectors");
3835: 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);
3836: 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);
3837: if (!mat->rmap->N && !mat->cmap->N) return(0);
3838: if (!mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
3839: MatCheckPreallocated(mat,1);
3840: PetscLogEventBegin(MAT_SolveTranspose,mat,b,x,0);
3841: if (mat->factorerrortype) {
3842: PetscInfo1(mat,"MatFactorError %D\n",mat->factorerrortype);
3843: VecSetInf(x);
3844: } else {
3845: if (!mat->ops->solvetranspose) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Matrix type %s",((PetscObject)mat)->type_name);
3846: (*mat->ops->solvetranspose)(mat,b,x);
3847: }
3848: PetscLogEventEnd(MAT_SolveTranspose,mat,b,x,0);
3849: PetscObjectStateIncrease((PetscObject)x);
3850: return(0);
3851: }
3853: /*@
3854: MatSolveTransposeAdd - Computes x = y + inv(Transpose(A)) b, given a
3855: factored matrix.
3857: Neighbor-wise Collective on Mat and Vec
3859: Input Parameters:
3860: + mat - the factored matrix
3861: . b - the right-hand-side vector
3862: - y - the vector to be added to
3864: Output Parameter:
3865: . x - the result vector
3867: Notes:
3868: The vectors b and x cannot be the same. I.e., one cannot
3869: call MatSolveTransposeAdd(A,x,y,x).
3871: Most users should employ the simplified KSP interface for linear solvers
3872: instead of working directly with matrix algebra routines such as this.
3873: See, e.g., KSPCreate().
3875: Level: developer
3877: Concepts: matrices^triangular solves
3879: .seealso: MatSolve(), MatSolveAdd(), MatSolveTranspose()
3880: @*/
3881: PetscErrorCode MatSolveTransposeAdd(Mat mat,Vec b,Vec y,Vec x)
3882: {
3883: PetscScalar one = 1.0;
3885: Vec tmp;
3896: if (x == b) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"x and b must be different vectors");
3897: 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);
3898: 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);
3899: 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);
3900: 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);
3901: if (!mat->rmap->N && !mat->cmap->N) return(0);
3902: if (!mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
3903: MatCheckPreallocated(mat,1);
3905: PetscLogEventBegin(MAT_SolveTransposeAdd,mat,b,x,y);
3906: if (mat->ops->solvetransposeadd) {
3907: if (mat->factorerrortype) {
3908: PetscInfo1(mat,"MatFactorError %D\n",mat->factorerrortype);
3909: VecSetInf(x);
3910: } else {
3911: (*mat->ops->solvetransposeadd)(mat,b,y,x);
3912: }
3913: } else {
3914: /* do the solve then the add manually */
3915: if (x != y) {
3916: MatSolveTranspose(mat,b,x);
3917: VecAXPY(x,one,y);
3918: } else {
3919: VecDuplicate(x,&tmp);
3920: PetscLogObjectParent((PetscObject)mat,(PetscObject)tmp);
3921: VecCopy(x,tmp);
3922: MatSolveTranspose(mat,b,x);
3923: VecAXPY(x,one,tmp);
3924: VecDestroy(&tmp);
3925: }
3926: }
3927: PetscLogEventEnd(MAT_SolveTransposeAdd,mat,b,x,y);
3928: PetscObjectStateIncrease((PetscObject)x);
3929: return(0);
3930: }
3931: /* ----------------------------------------------------------------*/
3933: /*@
3934: MatSOR - Computes relaxation (SOR, Gauss-Seidel) sweeps.
3936: Neighbor-wise Collective on Mat and Vec
3938: Input Parameters:
3939: + mat - the matrix
3940: . b - the right hand side
3941: . omega - the relaxation factor
3942: . flag - flag indicating the type of SOR (see below)
3943: . shift - diagonal shift
3944: . its - the number of iterations
3945: - lits - the number of local iterations
3947: Output Parameters:
3948: . x - the solution (can contain an initial guess, use option SOR_ZERO_INITIAL_GUESS to indicate no guess)
3950: SOR Flags:
3951: . SOR_FORWARD_SWEEP - forward SOR
3952: . SOR_BACKWARD_SWEEP - backward SOR
3953: . SOR_SYMMETRIC_SWEEP - SSOR (symmetric SOR)
3954: . SOR_LOCAL_FORWARD_SWEEP - local forward SOR
3955: . SOR_LOCAL_BACKWARD_SWEEP - local forward SOR
3956: . SOR_LOCAL_SYMMETRIC_SWEEP - local SSOR
3957: . SOR_APPLY_UPPER, SOR_APPLY_LOWER - applies
3958: upper/lower triangular part of matrix to
3959: vector (with omega)
3960: . SOR_ZERO_INITIAL_GUESS - zero initial guess
3962: Notes:
3963: SOR_LOCAL_FORWARD_SWEEP, SOR_LOCAL_BACKWARD_SWEEP, and
3964: SOR_LOCAL_SYMMETRIC_SWEEP perform separate independent smoothings
3965: on each processor.
3967: Application programmers will not generally use MatSOR() directly,
3968: but instead will employ the KSP/PC interface.
3970: Notes:
3971: for BAIJ, SBAIJ, and AIJ matrices with Inodes this does a block SOR smoothing, otherwise it does a pointwise smoothing
3973: Notes for Advanced Users:
3974: The flags are implemented as bitwise inclusive or operations.
3975: For example, use (SOR_ZERO_INITIAL_GUESS | SOR_SYMMETRIC_SWEEP)
3976: to specify a zero initial guess for SSOR.
3978: Most users should employ the simplified KSP interface for linear solvers
3979: instead of working directly with matrix algebra routines such as this.
3980: See, e.g., KSPCreate().
3982: Vectors x and b CANNOT be the same
3984: Developer Note: We should add block SOR support for AIJ matrices with block size set to great than one and no inodes
3986: Level: developer
3988: Concepts: matrices^relaxation
3989: Concepts: matrices^SOR
3990: Concepts: matrices^Gauss-Seidel
3992: @*/
3993: PetscErrorCode MatSOR(Mat mat,Vec b,PetscReal omega,MatSORType flag,PetscReal shift,PetscInt its,PetscInt lits,Vec x)
3994: {
4004: if (!mat->ops->sor) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
4005: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
4006: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
4007: 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);
4008: 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);
4009: 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);
4010: if (its <= 0) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONG,"Relaxation requires global its %D positive",its);
4011: if (lits <= 0) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONG,"Relaxation requires local its %D positive",lits);
4012: if (b == x) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_IDN,"b and x vector cannot be the same");
4014: MatCheckPreallocated(mat,1);
4015: PetscLogEventBegin(MAT_SOR,mat,b,x,0);
4016: ierr =(*mat->ops->sor)(mat,b,omega,flag,shift,its,lits,x);
4017: PetscLogEventEnd(MAT_SOR,mat,b,x,0);
4018: PetscObjectStateIncrease((PetscObject)x);
4019: return(0);
4020: }
4022: /*
4023: Default matrix copy routine.
4024: */
4025: PetscErrorCode MatCopy_Basic(Mat A,Mat B,MatStructure str)
4026: {
4027: PetscErrorCode ierr;
4028: PetscInt i,rstart = 0,rend = 0,nz;
4029: const PetscInt *cwork;
4030: const PetscScalar *vwork;
4033: if (B->assembled) {
4034: MatZeroEntries(B);
4035: }
4036: if (str == SAME_NONZERO_PATTERN) {
4037: MatGetOwnershipRange(A,&rstart,&rend);
4038: for (i=rstart; i<rend; i++) {
4039: MatGetRow(A,i,&nz,&cwork,&vwork);
4040: MatSetValues(B,1,&i,nz,cwork,vwork,INSERT_VALUES);
4041: MatRestoreRow(A,i,&nz,&cwork,&vwork);
4042: }
4043: } else {
4044: MatAYPX(B,0.0,A,str);
4045: }
4046: MatAssemblyBegin(B,MAT_FINAL_ASSEMBLY);
4047: MatAssemblyEnd(B,MAT_FINAL_ASSEMBLY);
4048: return(0);
4049: }
4051: /*@
4052: MatCopy - Copies a matrix to another matrix.
4054: Collective on Mat
4056: Input Parameters:
4057: + A - the matrix
4058: - str - SAME_NONZERO_PATTERN or DIFFERENT_NONZERO_PATTERN
4060: Output Parameter:
4061: . B - where the copy is put
4063: Notes:
4064: If you use SAME_NONZERO_PATTERN then the two matrices had better have the
4065: same nonzero pattern or the routine will crash.
4067: MatCopy() copies the matrix entries of a matrix to another existing
4068: matrix (after first zeroing the second matrix). A related routine is
4069: MatConvert(), which first creates a new matrix and then copies the data.
4071: Level: intermediate
4073: Concepts: matrices^copying
4075: .seealso: MatConvert(), MatDuplicate()
4077: @*/
4078: PetscErrorCode MatCopy(Mat A,Mat B,MatStructure str)
4079: {
4081: PetscInt i;
4089: MatCheckPreallocated(B,2);
4090: if (!A->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
4091: if (A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
4092: 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);
4093: MatCheckPreallocated(A,1);
4094: if (A == B) return(0);
4096: PetscLogEventBegin(MAT_Copy,A,B,0,0);
4097: if (A->ops->copy) {
4098: (*A->ops->copy)(A,B,str);
4099: } else { /* generic conversion */
4100: MatCopy_Basic(A,B,str);
4101: }
4103: B->stencil.dim = A->stencil.dim;
4104: B->stencil.noc = A->stencil.noc;
4105: for (i=0; i<=A->stencil.dim; i++) {
4106: B->stencil.dims[i] = A->stencil.dims[i];
4107: B->stencil.starts[i] = A->stencil.starts[i];
4108: }
4110: PetscLogEventEnd(MAT_Copy,A,B,0,0);
4111: PetscObjectStateIncrease((PetscObject)B);
4112: return(0);
4113: }
4115: /*@C
4116: MatConvert - Converts a matrix to another matrix, either of the same
4117: or different type.
4119: Collective on Mat
4121: Input Parameters:
4122: + mat - the matrix
4123: . newtype - new matrix type. Use MATSAME to create a new matrix of the
4124: same type as the original matrix.
4125: - reuse - denotes if the destination matrix is to be created or reused.
4126: 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
4127: 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).
4129: Output Parameter:
4130: . M - pointer to place new matrix
4132: Notes:
4133: MatConvert() first creates a new matrix and then copies the data from
4134: the first matrix. A related routine is MatCopy(), which copies the matrix
4135: entries of one matrix to another already existing matrix context.
4137: Cannot be used to convert a sequential matrix to parallel or parallel to sequential,
4138: the MPI communicator of the generated matrix is always the same as the communicator
4139: of the input matrix.
4141: Level: intermediate
4143: Concepts: matrices^converting between storage formats
4145: .seealso: MatCopy(), MatDuplicate()
4146: @*/
4147: PetscErrorCode MatConvert(Mat mat, MatType newtype,MatReuse reuse,Mat *M)
4148: {
4150: PetscBool sametype,issame,flg;
4151: char convname[256],mtype[256];
4152: Mat B;
4158: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
4159: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
4160: MatCheckPreallocated(mat,1);
4162: PetscOptionsGetString(((PetscObject)mat)->options,((PetscObject)mat)->prefix,"-matconvert_type",mtype,256,&flg);
4163: if (flg) {
4164: newtype = mtype;
4165: }
4166: PetscObjectTypeCompare((PetscObject)mat,newtype,&sametype);
4167: PetscStrcmp(newtype,"same",&issame);
4168: if ((reuse == MAT_INPLACE_MATRIX) && (mat != *M)) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"MAT_INPLACE_MATRIX requires same input and output matrix");
4169: 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");
4171: if ((reuse == MAT_INPLACE_MATRIX) && (issame || sametype)) return(0);
4173: if ((sametype || issame) && (reuse==MAT_INITIAL_MATRIX) && mat->ops->duplicate) {
4174: (*mat->ops->duplicate)(mat,MAT_COPY_VALUES,M);
4175: } else {
4176: PetscErrorCode (*conv)(Mat, MatType,MatReuse,Mat*)=NULL;
4177: const char *prefix[3] = {"seq","mpi",""};
4178: PetscInt i;
4179: /*
4180: Order of precedence:
4181: 0) See if newtype is a superclass of the current matrix.
4182: 1) See if a specialized converter is known to the current matrix.
4183: 2) See if a specialized converter is known to the desired matrix class.
4184: 3) See if a good general converter is registered for the desired class
4185: (as of 6/27/03 only MATMPIADJ falls into this category).
4186: 4) See if a good general converter is known for the current matrix.
4187: 5) Use a really basic converter.
4188: */
4190: /* 0) See if newtype is a superclass of the current matrix.
4191: i.e mat is mpiaij and newtype is aij */
4192: for (i=0; i<2; i++) {
4193: PetscStrncpy(convname,prefix[i],sizeof(convname));
4194: PetscStrlcat(convname,newtype,sizeof(convname));
4195: PetscStrcmp(convname,((PetscObject)mat)->type_name,&flg);
4196: PetscInfo3(mat,"Check superclass %s %s -> %d\n",convname,((PetscObject)mat)->type_name,flg);
4197: if (flg) {
4198: if (reuse == MAT_INPLACE_MATRIX) {
4199: return(0);
4200: } else if (reuse == MAT_INITIAL_MATRIX && mat->ops->duplicate) {
4201: (*mat->ops->duplicate)(mat,MAT_COPY_VALUES,M);
4202: return(0);
4203: } else if (reuse == MAT_REUSE_MATRIX && mat->ops->copy) {
4204: MatCopy(mat,*M,SAME_NONZERO_PATTERN);
4205: return(0);
4206: }
4207: }
4208: }
4209: /* 1) See if a specialized converter is known to the current matrix and the desired class */
4210: for (i=0; i<3; i++) {
4211: PetscStrncpy(convname,"MatConvert_",sizeof(convname));
4212: PetscStrlcat(convname,((PetscObject)mat)->type_name,sizeof(convname));
4213: PetscStrlcat(convname,"_",sizeof(convname));
4214: PetscStrlcat(convname,prefix[i],sizeof(convname));
4215: PetscStrlcat(convname,issame ? ((PetscObject)mat)->type_name : newtype,sizeof(convname));
4216: PetscStrlcat(convname,"_C",sizeof(convname));
4217: PetscObjectQueryFunction((PetscObject)mat,convname,&conv);
4218: PetscInfo3(mat,"Check specialized (1) %s (%s) -> %d\n",convname,((PetscObject)mat)->type_name,!!conv);
4219: if (conv) goto foundconv;
4220: }
4222: /* 2) See if a specialized converter is known to the desired matrix class. */
4223: MatCreate(PetscObjectComm((PetscObject)mat),&B);
4224: MatSetSizes(B,mat->rmap->n,mat->cmap->n,mat->rmap->N,mat->cmap->N);
4225: MatSetType(B,newtype);
4226: for (i=0; i<3; i++) {
4227: PetscStrncpy(convname,"MatConvert_",sizeof(convname));
4228: PetscStrlcat(convname,((PetscObject)mat)->type_name,sizeof(convname));
4229: PetscStrlcat(convname,"_",sizeof(convname));
4230: PetscStrlcat(convname,prefix[i],sizeof(convname));
4231: PetscStrlcat(convname,newtype,sizeof(convname));
4232: PetscStrlcat(convname,"_C",sizeof(convname));
4233: PetscObjectQueryFunction((PetscObject)B,convname,&conv);
4234: PetscInfo3(mat,"Check specialized (2) %s (%s) -> %d\n",convname,((PetscObject)B)->type_name,!!conv);
4235: if (conv) {
4236: MatDestroy(&B);
4237: goto foundconv;
4238: }
4239: }
4241: /* 3) See if a good general converter is registered for the desired class */
4242: conv = B->ops->convertfrom;
4243: PetscInfo2(mat,"Check convertfrom (%s) -> %d\n",((PetscObject)B)->type_name,!!conv);
4244: MatDestroy(&B);
4245: if (conv) goto foundconv;
4247: /* 4) See if a good general converter is known for the current matrix */
4248: if (mat->ops->convert) {
4249: conv = mat->ops->convert;
4250: }
4251: PetscInfo2(mat,"Check general convert (%s) -> %d\n",((PetscObject)mat)->type_name,!!conv);
4252: if (conv) goto foundconv;
4254: /* 5) Use a really basic converter. */
4255: PetscInfo(mat,"Using MatConvert_Basic\n");
4256: conv = MatConvert_Basic;
4258: foundconv:
4259: PetscLogEventBegin(MAT_Convert,mat,0,0,0);
4260: (*conv)(mat,newtype,reuse,M);
4261: if (mat->rmap->mapping && mat->cmap->mapping && !(*M)->rmap->mapping && !(*M)->cmap->mapping) {
4262: /* the block sizes must be same if the mappings are copied over */
4263: (*M)->rmap->bs = mat->rmap->bs;
4264: (*M)->cmap->bs = mat->cmap->bs;
4265: PetscObjectReference((PetscObject)mat->rmap->mapping);
4266: PetscObjectReference((PetscObject)mat->cmap->mapping);
4267: (*M)->rmap->mapping = mat->rmap->mapping;
4268: (*M)->cmap->mapping = mat->cmap->mapping;
4269: }
4270: (*M)->stencil.dim = mat->stencil.dim;
4271: (*M)->stencil.noc = mat->stencil.noc;
4272: for (i=0; i<=mat->stencil.dim; i++) {
4273: (*M)->stencil.dims[i] = mat->stencil.dims[i];
4274: (*M)->stencil.starts[i] = mat->stencil.starts[i];
4275: }
4276: PetscLogEventEnd(MAT_Convert,mat,0,0,0);
4277: }
4278: PetscObjectStateIncrease((PetscObject)*M);
4280: /* Copy Mat options */
4281: if (mat->symmetric) {MatSetOption(*M,MAT_SYMMETRIC,PETSC_TRUE);}
4282: if (mat->hermitian) {MatSetOption(*M,MAT_HERMITIAN,PETSC_TRUE);}
4283: return(0);
4284: }
4286: /*@C
4287: MatFactorGetSolverType - Returns name of the package providing the factorization routines
4289: Not Collective
4291: Input Parameter:
4292: . mat - the matrix, must be a factored matrix
4294: Output Parameter:
4295: . type - the string name of the package (do not free this string)
4297: Notes:
4298: In Fortran you pass in a empty string and the package name will be copied into it.
4299: (Make sure the string is long enough)
4301: Level: intermediate
4303: .seealso: MatCopy(), MatDuplicate(), MatGetFactorAvailable(), MatGetFactor()
4304: @*/
4305: PetscErrorCode MatFactorGetSolverType(Mat mat, MatSolverType *type)
4306: {
4307: PetscErrorCode ierr, (*conv)(Mat,MatSolverType*);
4312: if (!mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Only for factored matrix");
4313: PetscObjectQueryFunction((PetscObject)mat,"MatFactorGetSolverType_C",&conv);
4314: if (!conv) {
4315: *type = MATSOLVERPETSC;
4316: } else {
4317: (*conv)(mat,type);
4318: }
4319: return(0);
4320: }
4322: typedef struct _MatSolverTypeForSpecifcType* MatSolverTypeForSpecifcType;
4323: struct _MatSolverTypeForSpecifcType {
4324: MatType mtype;
4325: PetscErrorCode (*getfactor[4])(Mat,MatFactorType,Mat*);
4326: MatSolverTypeForSpecifcType next;
4327: };
4329: typedef struct _MatSolverTypeHolder* MatSolverTypeHolder;
4330: struct _MatSolverTypeHolder {
4331: char *name;
4332: MatSolverTypeForSpecifcType handlers;
4333: MatSolverTypeHolder next;
4334: };
4336: static MatSolverTypeHolder MatSolverTypeHolders = NULL;
4338: /*@C
4339: MatSolvePackageRegister - Registers a MatSolverType that works for a particular matrix type
4341: Input Parameters:
4342: + package - name of the package, for example petsc or superlu
4343: . mtype - the matrix type that works with this package
4344: . ftype - the type of factorization supported by the package
4345: - getfactor - routine that will create the factored matrix ready to be used
4347: Level: intermediate
4349: .seealso: MatCopy(), MatDuplicate(), MatGetFactorAvailable()
4350: @*/
4351: PetscErrorCode MatSolverTypeRegister(MatSolverType package,MatType mtype,MatFactorType ftype,PetscErrorCode (*getfactor)(Mat,MatFactorType,Mat*))
4352: {
4353: PetscErrorCode ierr;
4354: MatSolverTypeHolder next = MatSolverTypeHolders,prev;
4355: PetscBool flg;
4356: MatSolverTypeForSpecifcType inext,iprev = NULL;
4359: MatInitializePackage();
4360: if (!next) {
4361: PetscNew(&MatSolverTypeHolders);
4362: PetscStrallocpy(package,&MatSolverTypeHolders->name);
4363: PetscNew(&MatSolverTypeHolders->handlers);
4364: PetscStrallocpy(mtype,(char **)&MatSolverTypeHolders->handlers->mtype);
4365: MatSolverTypeHolders->handlers->getfactor[(int)ftype-1] = getfactor;
4366: return(0);
4367: }
4368: while (next) {
4369: PetscStrcasecmp(package,next->name,&flg);
4370: if (flg) {
4371: if (!next->handlers) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_PLIB,"MatSolverTypeHolder is missing handlers");
4372: inext = next->handlers;
4373: while (inext) {
4374: PetscStrcasecmp(mtype,inext->mtype,&flg);
4375: if (flg) {
4376: inext->getfactor[(int)ftype-1] = getfactor;
4377: return(0);
4378: }
4379: iprev = inext;
4380: inext = inext->next;
4381: }
4382: PetscNew(&iprev->next);
4383: PetscStrallocpy(mtype,(char **)&iprev->next->mtype);
4384: iprev->next->getfactor[(int)ftype-1] = getfactor;
4385: return(0);
4386: }
4387: prev = next;
4388: next = next->next;
4389: }
4390: PetscNew(&prev->next);
4391: PetscStrallocpy(package,&prev->next->name);
4392: PetscNew(&prev->next->handlers);
4393: PetscStrallocpy(mtype,(char **)&prev->next->handlers->mtype);
4394: prev->next->handlers->getfactor[(int)ftype-1] = getfactor;
4395: return(0);
4396: }
4398: /*@C
4399: MatSolvePackageGet - Get's the function that creates the factor matrix if it exist
4401: Input Parameters:
4402: + package - name of the package, for example petsc or superlu
4403: . ftype - the type of factorization supported by the package
4404: - mtype - the matrix type that works with this package
4406: Output Parameters:
4407: + foundpackage - PETSC_TRUE if the package was registered
4408: . foundmtype - PETSC_TRUE if the package supports the requested mtype
4409: - getfactor - routine that will create the factored matrix ready to be used or NULL if not found
4411: Level: intermediate
4413: .seealso: MatCopy(), MatDuplicate(), MatGetFactorAvailable()
4414: @*/
4415: PetscErrorCode MatSolverTypeGet(MatSolverType package,MatType mtype,MatFactorType ftype,PetscBool *foundpackage,PetscBool *foundmtype,PetscErrorCode (**getfactor)(Mat,MatFactorType,Mat*))
4416: {
4417: PetscErrorCode ierr;
4418: MatSolverTypeHolder next = MatSolverTypeHolders;
4419: PetscBool flg;
4420: MatSolverTypeForSpecifcType inext;
4423: if (foundpackage) *foundpackage = PETSC_FALSE;
4424: if (foundmtype) *foundmtype = PETSC_FALSE;
4425: if (getfactor) *getfactor = NULL;
4427: if (package) {
4428: while (next) {
4429: PetscStrcasecmp(package,next->name,&flg);
4430: if (flg) {
4431: if (foundpackage) *foundpackage = PETSC_TRUE;
4432: inext = next->handlers;
4433: while (inext) {
4434: PetscStrbeginswith(mtype,inext->mtype,&flg);
4435: if (flg) {
4436: if (foundmtype) *foundmtype = PETSC_TRUE;
4437: if (getfactor) *getfactor = inext->getfactor[(int)ftype-1];
4438: return(0);
4439: }
4440: inext = inext->next;
4441: }
4442: }
4443: next = next->next;
4444: }
4445: } else {
4446: while (next) {
4447: inext = next->handlers;
4448: while (inext) {
4449: PetscStrbeginswith(mtype,inext->mtype,&flg);
4450: if (flg && inext->getfactor[(int)ftype-1]) {
4451: if (foundpackage) *foundpackage = PETSC_TRUE;
4452: if (foundmtype) *foundmtype = PETSC_TRUE;
4453: if (getfactor) *getfactor = inext->getfactor[(int)ftype-1];
4454: return(0);
4455: }
4456: inext = inext->next;
4457: }
4458: next = next->next;
4459: }
4460: }
4461: return(0);
4462: }
4464: PetscErrorCode MatSolverTypeDestroy(void)
4465: {
4466: PetscErrorCode ierr;
4467: MatSolverTypeHolder next = MatSolverTypeHolders,prev;
4468: MatSolverTypeForSpecifcType inext,iprev;
4471: while (next) {
4472: PetscFree(next->name);
4473: inext = next->handlers;
4474: while (inext) {
4475: PetscFree(inext->mtype);
4476: iprev = inext;
4477: inext = inext->next;
4478: PetscFree(iprev);
4479: }
4480: prev = next;
4481: next = next->next;
4482: PetscFree(prev);
4483: }
4484: MatSolverTypeHolders = NULL;
4485: return(0);
4486: }
4488: /*@C
4489: MatGetFactor - Returns a matrix suitable to calls to MatXXFactorSymbolic()
4491: Collective on Mat
4493: Input Parameters:
4494: + mat - the matrix
4495: . type - name of solver type, for example, superlu, petsc (to use PETSc's default)
4496: - ftype - factor type, MAT_FACTOR_LU, MAT_FACTOR_CHOLESKY, MAT_FACTOR_ICC, MAT_FACTOR_ILU,
4498: Output Parameters:
4499: . f - the factor matrix used with MatXXFactorSymbolic() calls
4501: Notes:
4502: Some PETSc matrix formats have alternative solvers available that are contained in alternative packages
4503: such as pastix, superlu, mumps etc.
4505: PETSc must have been ./configure to use the external solver, using the option --download-package
4507: Level: intermediate
4509: .seealso: MatCopy(), MatDuplicate(), MatGetFactorAvailable()
4510: @*/
4511: PetscErrorCode MatGetFactor(Mat mat, MatSolverType type,MatFactorType ftype,Mat *f)
4512: {
4513: PetscErrorCode ierr,(*conv)(Mat,MatFactorType,Mat*);
4514: PetscBool foundpackage,foundmtype;
4520: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
4521: MatCheckPreallocated(mat,1);
4523: MatSolverTypeGet(type,((PetscObject)mat)->type_name,ftype,&foundpackage,&foundmtype,&conv);
4524: if (!foundpackage) {
4525: if (type) {
4526: SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_MISSING_FACTOR,"Could not locate solver package %s. Perhaps you must ./configure with --download-%s",type,type);
4527: } else {
4528: SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_MISSING_FACTOR,"Could not locate a solver package. Perhaps you must ./configure with --download-<package>");
4529: }
4530: }
4532: if (!foundmtype) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_MISSING_FACTOR,"MatSolverType %s does not support matrix type %s",type,((PetscObject)mat)->type_name);
4533: 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);
4535: #if defined(PETSC_USE_COMPLEX)
4536: if (mat->hermitian && !mat->symmetric && (ftype == MAT_FACTOR_CHOLESKY||ftype == MAT_FACTOR_ICC)) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"Hermitian CHOLESKY or ICC Factor is not supported");
4537: #endif
4539: (*conv)(mat,ftype,f);
4540: return(0);
4541: }
4543: /*@C
4544: MatGetFactorAvailable - Returns a a flag if matrix supports particular package and factor type
4546: Not Collective
4548: Input Parameters:
4549: + mat - the matrix
4550: . type - name of solver type, for example, superlu, petsc (to use PETSc's default)
4551: - ftype - factor type, MAT_FACTOR_LU, MAT_FACTOR_CHOLESKY, MAT_FACTOR_ICC, MAT_FACTOR_ILU,
4553: Output Parameter:
4554: . flg - PETSC_TRUE if the factorization is available
4556: Notes:
4557: Some PETSc matrix formats have alternative solvers available that are contained in alternative packages
4558: such as pastix, superlu, mumps etc.
4560: PETSc must have been ./configure to use the external solver, using the option --download-package
4562: Level: intermediate
4564: .seealso: MatCopy(), MatDuplicate(), MatGetFactor()
4565: @*/
4566: PetscErrorCode MatGetFactorAvailable(Mat mat, MatSolverType type,MatFactorType ftype,PetscBool *flg)
4567: {
4568: PetscErrorCode ierr, (*gconv)(Mat,MatFactorType,Mat*);
4574: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
4575: MatCheckPreallocated(mat,1);
4577: *flg = PETSC_FALSE;
4578: MatSolverTypeGet(type,((PetscObject)mat)->type_name,ftype,NULL,NULL,&gconv);
4579: if (gconv) {
4580: *flg = PETSC_TRUE;
4581: }
4582: return(0);
4583: }
4585: #include <petscdmtypes.h>
4587: /*@
4588: MatDuplicate - Duplicates a matrix including the non-zero structure.
4590: Collective on Mat
4592: Input Parameters:
4593: + mat - the matrix
4594: - op - One of MAT_DO_NOT_COPY_VALUES, MAT_COPY_VALUES, or MAT_SHARE_NONZERO_PATTERN.
4595: See the manual page for MatDuplicateOption for an explanation of these options.
4597: Output Parameter:
4598: . M - pointer to place new matrix
4600: Level: intermediate
4602: Concepts: matrices^duplicating
4604: Notes:
4605: You cannot change the nonzero pattern for the parent or child matrix if you use MAT_SHARE_NONZERO_PATTERN.
4606: 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.
4608: .seealso: MatCopy(), MatConvert(), MatDuplicateOption
4609: @*/
4610: PetscErrorCode MatDuplicate(Mat mat,MatDuplicateOption op,Mat *M)
4611: {
4613: Mat B;
4614: PetscInt i;
4615: DM dm;
4616: void (*viewf)(void);
4622: if (op == MAT_COPY_VALUES && !mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"MAT_COPY_VALUES not allowed for unassembled matrix");
4623: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
4624: MatCheckPreallocated(mat,1);
4626: *M = 0;
4627: if (!mat->ops->duplicate) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Not written for this matrix type");
4628: PetscLogEventBegin(MAT_Convert,mat,0,0,0);
4629: (*mat->ops->duplicate)(mat,op,M);
4630: B = *M;
4632: MatGetOperation(mat,MATOP_VIEW,&viewf);
4633: if (viewf) {
4634: MatSetOperation(B,MATOP_VIEW,viewf);
4635: }
4637: B->stencil.dim = mat->stencil.dim;
4638: B->stencil.noc = mat->stencil.noc;
4639: for (i=0; i<=mat->stencil.dim; i++) {
4640: B->stencil.dims[i] = mat->stencil.dims[i];
4641: B->stencil.starts[i] = mat->stencil.starts[i];
4642: }
4644: B->nooffproczerorows = mat->nooffproczerorows;
4645: B->nooffprocentries = mat->nooffprocentries;
4647: PetscObjectQuery((PetscObject) mat, "__PETSc_dm", (PetscObject*) &dm);
4648: if (dm) {
4649: PetscObjectCompose((PetscObject) B, "__PETSc_dm", (PetscObject) dm);
4650: }
4651: PetscLogEventEnd(MAT_Convert,mat,0,0,0);
4652: PetscObjectStateIncrease((PetscObject)B);
4653: return(0);
4654: }
4656: /*@
4657: MatGetDiagonal - Gets the diagonal of a matrix.
4659: Logically Collective on Mat and Vec
4661: Input Parameters:
4662: + mat - the matrix
4663: - v - the vector for storing the diagonal
4665: Output Parameter:
4666: . v - the diagonal of the matrix
4668: Level: intermediate
4670: Note:
4671: Currently only correct in parallel for square matrices.
4673: Concepts: matrices^accessing diagonals
4675: .seealso: MatGetRow(), MatCreateSubMatrices(), MatCreateSubMatrix(), MatGetRowMaxAbs()
4676: @*/
4677: PetscErrorCode MatGetDiagonal(Mat mat,Vec v)
4678: {
4685: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
4686: if (!mat->ops->getdiagonal) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
4687: MatCheckPreallocated(mat,1);
4689: (*mat->ops->getdiagonal)(mat,v);
4690: PetscObjectStateIncrease((PetscObject)v);
4691: return(0);
4692: }
4694: /*@C
4695: MatGetRowMin - Gets the minimum value (of the real part) of each
4696: row of the matrix
4698: Logically Collective on Mat and Vec
4700: Input Parameters:
4701: . mat - the matrix
4703: Output Parameter:
4704: + v - the vector for storing the maximums
4705: - idx - the indices of the column found for each row (optional)
4707: Level: intermediate
4709: Notes:
4710: The result of this call are the same as if one converted the matrix to dense format
4711: and found the minimum value in each row (i.e. the implicit zeros are counted as zeros).
4713: This code is only implemented for a couple of matrix formats.
4715: Concepts: matrices^getting row maximums
4717: .seealso: MatGetDiagonal(), MatCreateSubMatrices(), MatCreateSubMatrix(), MatGetRowMaxAbs(),
4718: MatGetRowMax()
4719: @*/
4720: PetscErrorCode MatGetRowMin(Mat mat,Vec v,PetscInt idx[])
4721: {
4728: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
4729: if (!mat->ops->getrowmax) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
4730: MatCheckPreallocated(mat,1);
4732: (*mat->ops->getrowmin)(mat,v,idx);
4733: PetscObjectStateIncrease((PetscObject)v);
4734: return(0);
4735: }
4737: /*@C
4738: MatGetRowMinAbs - Gets the minimum value (in absolute value) of each
4739: row of the matrix
4741: Logically Collective on Mat and Vec
4743: Input Parameters:
4744: . mat - the matrix
4746: Output Parameter:
4747: + v - the vector for storing the minimums
4748: - idx - the indices of the column found for each row (or NULL if not needed)
4750: Level: intermediate
4752: Notes:
4753: if a row is completely empty or has only 0.0 values then the idx[] value for that
4754: row is 0 (the first column).
4756: This code is only implemented for a couple of matrix formats.
4758: Concepts: matrices^getting row maximums
4760: .seealso: MatGetDiagonal(), MatCreateSubMatrices(), MatCreateSubMatrix(), MatGetRowMax(), MatGetRowMaxAbs(), MatGetRowMin()
4761: @*/
4762: PetscErrorCode MatGetRowMinAbs(Mat mat,Vec v,PetscInt idx[])
4763: {
4770: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
4771: if (!mat->ops->getrowminabs) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
4772: MatCheckPreallocated(mat,1);
4773: if (idx) {PetscMemzero(idx,mat->rmap->n*sizeof(PetscInt));}
4775: (*mat->ops->getrowminabs)(mat,v,idx);
4776: PetscObjectStateIncrease((PetscObject)v);
4777: return(0);
4778: }
4780: /*@C
4781: MatGetRowMax - Gets the maximum value (of the real part) of each
4782: row of the matrix
4784: Logically Collective on Mat and Vec
4786: Input Parameters:
4787: . mat - the matrix
4789: Output Parameter:
4790: + v - the vector for storing the maximums
4791: - idx - the indices of the column found for each row (optional)
4793: Level: intermediate
4795: Notes:
4796: The result of this call are the same as if one converted the matrix to dense format
4797: and found the minimum value in each row (i.e. the implicit zeros are counted as zeros).
4799: This code is only implemented for a couple of matrix formats.
4801: Concepts: matrices^getting row maximums
4803: .seealso: MatGetDiagonal(), MatCreateSubMatrices(), MatCreateSubMatrix(), MatGetRowMaxAbs(), MatGetRowMin()
4804: @*/
4805: PetscErrorCode MatGetRowMax(Mat mat,Vec v,PetscInt idx[])
4806: {
4813: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
4814: if (!mat->ops->getrowmax) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
4815: MatCheckPreallocated(mat,1);
4817: (*mat->ops->getrowmax)(mat,v,idx);
4818: PetscObjectStateIncrease((PetscObject)v);
4819: return(0);
4820: }
4822: /*@C
4823: MatGetRowMaxAbs - Gets the maximum value (in absolute value) of each
4824: row of the matrix
4826: Logically Collective on Mat and Vec
4828: Input Parameters:
4829: . mat - the matrix
4831: Output Parameter:
4832: + v - the vector for storing the maximums
4833: - idx - the indices of the column found for each row (or NULL if not needed)
4835: Level: intermediate
4837: Notes:
4838: if a row is completely empty or has only 0.0 values then the idx[] value for that
4839: row is 0 (the first column).
4841: This code is only implemented for a couple of matrix formats.
4843: Concepts: matrices^getting row maximums
4845: .seealso: MatGetDiagonal(), MatCreateSubMatrices(), MatCreateSubMatrix(), MatGetRowMax(), MatGetRowMin()
4846: @*/
4847: PetscErrorCode MatGetRowMaxAbs(Mat mat,Vec v,PetscInt idx[])
4848: {
4855: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
4856: if (!mat->ops->getrowmaxabs) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
4857: MatCheckPreallocated(mat,1);
4858: if (idx) {PetscMemzero(idx,mat->rmap->n*sizeof(PetscInt));}
4860: (*mat->ops->getrowmaxabs)(mat,v,idx);
4861: PetscObjectStateIncrease((PetscObject)v);
4862: return(0);
4863: }
4865: /*@
4866: MatGetRowSum - Gets the sum of each row of the matrix
4868: Logically or Neighborhood Collective on Mat and Vec
4870: Input Parameters:
4871: . mat - the matrix
4873: Output Parameter:
4874: . v - the vector for storing the sum of rows
4876: Level: intermediate
4878: Notes:
4879: This code is slow since it is not currently specialized for different formats
4881: Concepts: matrices^getting row sums
4883: .seealso: MatGetDiagonal(), MatCreateSubMatrices(), MatCreateSubMatrix(), MatGetRowMax(), MatGetRowMin()
4884: @*/
4885: PetscErrorCode MatGetRowSum(Mat mat, Vec v)
4886: {
4887: Vec ones;
4894: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
4895: MatCheckPreallocated(mat,1);
4896: MatCreateVecs(mat,&ones,NULL);
4897: VecSet(ones,1.);
4898: MatMult(mat,ones,v);
4899: VecDestroy(&ones);
4900: return(0);
4901: }
4903: /*@
4904: MatTranspose - Computes an in-place or out-of-place transpose of a matrix.
4906: Collective on Mat
4908: Input Parameter:
4909: + mat - the matrix to transpose
4910: - reuse - either MAT_INITIAL_MATRIX, MAT_REUSE_MATRIX, or MAT_INPLACE_MATRIX
4912: Output Parameters:
4913: . B - the transpose
4915: Notes:
4916: If you use MAT_INPLACE_MATRIX then you must pass in &mat for B
4918: MAT_REUSE_MATRIX causes the B matrix from a previous call to this function with MAT_INITIAL_MATRIX to be used
4920: Consider using MatCreateTranspose() instead if you only need a matrix that behaves like the transpose, but don't need the storage to be changed.
4922: Level: intermediate
4924: Concepts: matrices^transposing
4926: .seealso: MatMultTranspose(), MatMultTransposeAdd(), MatIsTranspose(), MatReuse
4927: @*/
4928: PetscErrorCode MatTranspose(Mat mat,MatReuse reuse,Mat *B)
4929: {
4935: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
4936: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
4937: if (!mat->ops->transpose) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
4938: if (reuse == MAT_INPLACE_MATRIX && mat != *B) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"MAT_INPLACE_MATRIX requires last matrix to match first");
4939: if (reuse == MAT_REUSE_MATRIX && mat == *B) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Perhaps you mean MAT_INPLACE_MATRIX");
4940: MatCheckPreallocated(mat,1);
4942: PetscLogEventBegin(MAT_Transpose,mat,0,0,0);
4943: (*mat->ops->transpose)(mat,reuse,B);
4944: PetscLogEventEnd(MAT_Transpose,mat,0,0,0);
4945: if (B) {PetscObjectStateIncrease((PetscObject)*B);}
4946: return(0);
4947: }
4949: /*@
4950: MatIsTranspose - Test whether a matrix is another one's transpose,
4951: or its own, in which case it tests symmetry.
4953: Collective on Mat
4955: Input Parameter:
4956: + A - the matrix to test
4957: - B - the matrix to test against, this can equal the first parameter
4959: Output Parameters:
4960: . flg - the result
4962: Notes:
4963: Only available for SeqAIJ/MPIAIJ matrices. The sequential algorithm
4964: has a running time of the order of the number of nonzeros; the parallel
4965: test involves parallel copies of the block-offdiagonal parts of the matrix.
4967: Level: intermediate
4969: Concepts: matrices^transposing, matrix^symmetry
4971: .seealso: MatTranspose(), MatIsSymmetric(), MatIsHermitian()
4972: @*/
4973: PetscErrorCode MatIsTranspose(Mat A,Mat B,PetscReal tol,PetscBool *flg)
4974: {
4975: PetscErrorCode ierr,(*f)(Mat,Mat,PetscReal,PetscBool*),(*g)(Mat,Mat,PetscReal,PetscBool*);
4981: PetscObjectQueryFunction((PetscObject)A,"MatIsTranspose_C",&f);
4982: PetscObjectQueryFunction((PetscObject)B,"MatIsTranspose_C",&g);
4983: *flg = PETSC_FALSE;
4984: if (f && g) {
4985: if (f == g) {
4986: (*f)(A,B,tol,flg);
4987: } else SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_NOTSAMETYPE,"Matrices do not have the same comparator for symmetry test");
4988: } else {
4989: MatType mattype;
4990: if (!f) {
4991: MatGetType(A,&mattype);
4992: } else {
4993: MatGetType(B,&mattype);
4994: }
4995: SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Matrix of type <%s> does not support checking for transpose",mattype);
4996: }
4997: return(0);
4998: }
5000: /*@
5001: MatHermitianTranspose - Computes an in-place or out-of-place transpose of a matrix in complex conjugate.
5003: Collective on Mat
5005: Input Parameter:
5006: + mat - the matrix to transpose and complex conjugate
5007: - reuse - MAT_INITIAL_MATRIX to create a new matrix, MAT_INPLACE_MATRIX to reuse the first argument to store the transpose
5009: Output Parameters:
5010: . B - the Hermitian
5012: Level: intermediate
5014: Concepts: matrices^transposing, complex conjugatex
5016: .seealso: MatTranspose(), MatMultTranspose(), MatMultTransposeAdd(), MatIsTranspose(), MatReuse
5017: @*/
5018: PetscErrorCode MatHermitianTranspose(Mat mat,MatReuse reuse,Mat *B)
5019: {
5023: MatTranspose(mat,reuse,B);
5024: #if defined(PETSC_USE_COMPLEX)
5025: MatConjugate(*B);
5026: #endif
5027: return(0);
5028: }
5030: /*@
5031: MatIsHermitianTranspose - Test whether a matrix is another one's Hermitian transpose,
5033: Collective on Mat
5035: Input Parameter:
5036: + A - the matrix to test
5037: - B - the matrix to test against, this can equal the first parameter
5039: Output Parameters:
5040: . flg - the result
5042: Notes:
5043: Only available for SeqAIJ/MPIAIJ matrices. The sequential algorithm
5044: has a running time of the order of the number of nonzeros; the parallel
5045: test involves parallel copies of the block-offdiagonal parts of the matrix.
5047: Level: intermediate
5049: Concepts: matrices^transposing, matrix^symmetry
5051: .seealso: MatTranspose(), MatIsSymmetric(), MatIsHermitian(), MatIsTranspose()
5052: @*/
5053: PetscErrorCode MatIsHermitianTranspose(Mat A,Mat B,PetscReal tol,PetscBool *flg)
5054: {
5055: PetscErrorCode ierr,(*f)(Mat,Mat,PetscReal,PetscBool*),(*g)(Mat,Mat,PetscReal,PetscBool*);
5061: PetscObjectQueryFunction((PetscObject)A,"MatIsHermitianTranspose_C",&f);
5062: PetscObjectQueryFunction((PetscObject)B,"MatIsHermitianTranspose_C",&g);
5063: if (f && g) {
5064: if (f==g) {
5065: (*f)(A,B,tol,flg);
5066: } else SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_NOTSAMETYPE,"Matrices do not have the same comparator for Hermitian test");
5067: }
5068: return(0);
5069: }
5071: /*@
5072: MatPermute - Creates a new matrix with rows and columns permuted from the
5073: original.
5075: Collective on Mat
5077: Input Parameters:
5078: + mat - the matrix to permute
5079: . row - row permutation, each processor supplies only the permutation for its rows
5080: - col - column permutation, each processor supplies only the permutation for its columns
5082: Output Parameters:
5083: . B - the permuted matrix
5085: Level: advanced
5087: Note:
5088: The index sets map from row/col of permuted matrix to row/col of original matrix.
5089: The index sets should be on the same communicator as Mat and have the same local sizes.
5091: Concepts: matrices^permuting
5093: .seealso: MatGetOrdering(), ISAllGather()
5095: @*/
5096: PetscErrorCode MatPermute(Mat mat,IS row,IS col,Mat *B)
5097: {
5106: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
5107: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
5108: if (!mat->ops->permute) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"MatPermute not available for Mat type %s",((PetscObject)mat)->type_name);
5109: MatCheckPreallocated(mat,1);
5111: (*mat->ops->permute)(mat,row,col,B);
5112: PetscObjectStateIncrease((PetscObject)*B);
5113: return(0);
5114: }
5116: /*@
5117: MatEqual - Compares two matrices.
5119: Collective on Mat
5121: Input Parameters:
5122: + A - the first matrix
5123: - B - the second matrix
5125: Output Parameter:
5126: . flg - PETSC_TRUE if the matrices are equal; PETSC_FALSE otherwise.
5128: Level: intermediate
5130: Concepts: matrices^equality between
5131: @*/
5132: PetscErrorCode MatEqual(Mat A,Mat B,PetscBool *flg)
5133: {
5143: MatCheckPreallocated(B,2);
5144: if (!A->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
5145: if (!B->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
5146: 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);
5147: if (!A->ops->equal) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Mat type %s",((PetscObject)A)->type_name);
5148: if (!B->ops->equal) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Mat type %s",((PetscObject)B)->type_name);
5149: 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);
5150: MatCheckPreallocated(A,1);
5152: (*A->ops->equal)(A,B,flg);
5153: return(0);
5154: }
5156: /*@
5157: MatDiagonalScale - Scales a matrix on the left and right by diagonal
5158: matrices that are stored as vectors. Either of the two scaling
5159: matrices can be NULL.
5161: Collective on Mat
5163: Input Parameters:
5164: + mat - the matrix to be scaled
5165: . l - the left scaling vector (or NULL)
5166: - r - the right scaling vector (or NULL)
5168: Notes:
5169: MatDiagonalScale() computes A = LAR, where
5170: L = a diagonal matrix (stored as a vector), R = a diagonal matrix (stored as a vector)
5171: The L scales the rows of the matrix, the R scales the columns of the matrix.
5173: Level: intermediate
5175: Concepts: matrices^diagonal scaling
5176: Concepts: diagonal scaling of matrices
5178: .seealso: MatScale(), MatShift(), MatDiagonalSet()
5179: @*/
5180: PetscErrorCode MatDiagonalScale(Mat mat,Vec l,Vec r)
5181: {
5187: if (!mat->ops->diagonalscale) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
5190: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
5191: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
5192: MatCheckPreallocated(mat,1);
5194: PetscLogEventBegin(MAT_Scale,mat,0,0,0);
5195: (*mat->ops->diagonalscale)(mat,l,r);
5196: PetscLogEventEnd(MAT_Scale,mat,0,0,0);
5197: PetscObjectStateIncrease((PetscObject)mat);
5198: #if defined(PETSC_HAVE_VIENNACL) || defined(PETSC_HAVE_CUDA)
5199: if (mat->valid_GPU_matrix != PETSC_OFFLOAD_UNALLOCATED) {
5200: mat->valid_GPU_matrix = PETSC_OFFLOAD_CPU;
5201: }
5202: #endif
5203: return(0);
5204: }
5206: /*@
5207: MatScale - Scales all elements of a matrix by a given number.
5209: Logically Collective on Mat
5211: Input Parameters:
5212: + mat - the matrix to be scaled
5213: - a - the scaling value
5215: Output Parameter:
5216: . mat - the scaled matrix
5218: Level: intermediate
5220: Concepts: matrices^scaling all entries
5222: .seealso: MatDiagonalScale()
5223: @*/
5224: PetscErrorCode MatScale(Mat mat,PetscScalar a)
5225: {
5231: if (a != (PetscScalar)1.0 && !mat->ops->scale) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
5232: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
5233: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
5235: MatCheckPreallocated(mat,1);
5237: PetscLogEventBegin(MAT_Scale,mat,0,0,0);
5238: if (a != (PetscScalar)1.0) {
5239: (*mat->ops->scale)(mat,a);
5240: PetscObjectStateIncrease((PetscObject)mat);
5241: #if defined(PETSC_HAVE_VIENNACL) || defined(PETSC_HAVE_CUDA)
5242: if (mat->valid_GPU_matrix != PETSC_OFFLOAD_UNALLOCATED) {
5243: mat->valid_GPU_matrix = PETSC_OFFLOAD_CPU;
5244: }
5245: #endif
5246: }
5247: PetscLogEventEnd(MAT_Scale,mat,0,0,0);
5248: return(0);
5249: }
5251: /*@
5252: MatNorm - Calculates various norms of a matrix.
5254: Collective on Mat
5256: Input Parameters:
5257: + mat - the matrix
5258: - type - the type of norm, NORM_1, NORM_FROBENIUS, NORM_INFINITY
5260: Output Parameters:
5261: . nrm - the resulting norm
5263: Level: intermediate
5265: Concepts: matrices^norm
5266: Concepts: norm^of matrix
5267: @*/
5268: PetscErrorCode MatNorm(Mat mat,NormType type,PetscReal *nrm)
5269: {
5277: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
5278: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
5279: if (!mat->ops->norm) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
5280: MatCheckPreallocated(mat,1);
5282: (*mat->ops->norm)(mat,type,nrm);
5283: return(0);
5284: }
5286: /*
5287: This variable is used to prevent counting of MatAssemblyBegin() that
5288: are called from within a MatAssemblyEnd().
5289: */
5290: static PetscInt MatAssemblyEnd_InUse = 0;
5291: /*@
5292: MatAssemblyBegin - Begins assembling the matrix. This routine should
5293: be called after completing all calls to MatSetValues().
5295: Collective on Mat
5297: Input Parameters:
5298: + mat - the matrix
5299: - type - type of assembly, either MAT_FLUSH_ASSEMBLY or MAT_FINAL_ASSEMBLY
5301: Notes:
5302: MatSetValues() generally caches the values. The matrix is ready to
5303: use only after MatAssemblyBegin() and MatAssemblyEnd() have been called.
5304: Use MAT_FLUSH_ASSEMBLY when switching between ADD_VALUES and INSERT_VALUES
5305: in MatSetValues(); use MAT_FINAL_ASSEMBLY for the final assembly before
5306: using the matrix.
5308: ALL processes that share a matrix MUST call MatAssemblyBegin() and MatAssemblyEnd() the SAME NUMBER of times, and each time with the
5309: 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
5310: a global collective operation requring all processes that share the matrix.
5312: Space for preallocated nonzeros that is not filled by a call to MatSetValues() or a related routine are compressed
5313: out by assembly. If you intend to use that extra space on a subsequent assembly, be sure to insert explicit zeros
5314: before MAT_FINAL_ASSEMBLY so the space is not compressed out.
5316: Level: beginner
5318: Concepts: matrices^assembling
5320: .seealso: MatAssemblyEnd(), MatSetValues(), MatAssembled()
5321: @*/
5322: PetscErrorCode MatAssemblyBegin(Mat mat,MatAssemblyType type)
5323: {
5329: MatCheckPreallocated(mat,1);
5330: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix.\nDid you forget to call MatSetUnfactored()?");
5331: if (mat->assembled) {
5332: mat->was_assembled = PETSC_TRUE;
5333: mat->assembled = PETSC_FALSE;
5334: }
5335: if (!MatAssemblyEnd_InUse) {
5336: PetscLogEventBegin(MAT_AssemblyBegin,mat,0,0,0);
5337: if (mat->ops->assemblybegin) {(*mat->ops->assemblybegin)(mat,type);}
5338: PetscLogEventEnd(MAT_AssemblyBegin,mat,0,0,0);
5339: } else if (mat->ops->assemblybegin) {
5340: (*mat->ops->assemblybegin)(mat,type);
5341: }
5342: return(0);
5343: }
5345: /*@
5346: MatAssembled - Indicates if a matrix has been assembled and is ready for
5347: use; for example, in matrix-vector product.
5349: Not Collective
5351: Input Parameter:
5352: . mat - the matrix
5354: Output Parameter:
5355: . assembled - PETSC_TRUE or PETSC_FALSE
5357: Level: advanced
5359: Concepts: matrices^assembled?
5361: .seealso: MatAssemblyEnd(), MatSetValues(), MatAssemblyBegin()
5362: @*/
5363: PetscErrorCode MatAssembled(Mat mat,PetscBool *assembled)
5364: {
5368: *assembled = mat->assembled;
5369: return(0);
5370: }
5372: /*@
5373: MatAssemblyEnd - Completes assembling the matrix. This routine should
5374: be called after MatAssemblyBegin().
5376: Collective on Mat
5378: Input Parameters:
5379: + mat - the matrix
5380: - type - type of assembly, either MAT_FLUSH_ASSEMBLY or MAT_FINAL_ASSEMBLY
5382: Options Database Keys:
5383: + -mat_view ::ascii_info - Prints info on matrix at conclusion of MatEndAssembly()
5384: . -mat_view ::ascii_info_detail - Prints more detailed info
5385: . -mat_view - Prints matrix in ASCII format
5386: . -mat_view ::ascii_matlab - Prints matrix in Matlab format
5387: . -mat_view draw - PetscDraws nonzero structure of matrix, using MatView() and PetscDrawOpenX().
5388: . -display <name> - Sets display name (default is host)
5389: . -draw_pause <sec> - Sets number of seconds to pause after display
5390: . -mat_view socket - Sends matrix to socket, can be accessed from Matlab (See Users-Manual: Chapter 12 Using MATLAB with PETSc )
5391: . -viewer_socket_machine <machine> - Machine to use for socket
5392: . -viewer_socket_port <port> - Port number to use for socket
5393: - -mat_view binary:filename[:append] - Save matrix to file in binary format
5395: Notes:
5396: MatSetValues() generally caches the values. The matrix is ready to
5397: use only after MatAssemblyBegin() and MatAssemblyEnd() have been called.
5398: Use MAT_FLUSH_ASSEMBLY when switching between ADD_VALUES and INSERT_VALUES
5399: in MatSetValues(); use MAT_FINAL_ASSEMBLY for the final assembly before
5400: using the matrix.
5402: Space for preallocated nonzeros that is not filled by a call to MatSetValues() or a related routine are compressed
5403: out by assembly. If you intend to use that extra space on a subsequent assembly, be sure to insert explicit zeros
5404: before MAT_FINAL_ASSEMBLY so the space is not compressed out.
5406: Level: beginner
5408: .seealso: MatAssemblyBegin(), MatSetValues(), PetscDrawOpenX(), PetscDrawCreate(), MatView(), MatAssembled(), PetscViewerSocketOpen()
5409: @*/
5410: PetscErrorCode MatAssemblyEnd(Mat mat,MatAssemblyType type)
5411: {
5412: PetscErrorCode ierr;
5413: static PetscInt inassm = 0;
5414: PetscBool flg = PETSC_FALSE;
5420: inassm++;
5421: MatAssemblyEnd_InUse++;
5422: if (MatAssemblyEnd_InUse == 1) { /* Do the logging only the first time through */
5423: PetscLogEventBegin(MAT_AssemblyEnd,mat,0,0,0);
5424: if (mat->ops->assemblyend) {
5425: (*mat->ops->assemblyend)(mat,type);
5426: }
5427: PetscLogEventEnd(MAT_AssemblyEnd,mat,0,0,0);
5428: } else if (mat->ops->assemblyend) {
5429: (*mat->ops->assemblyend)(mat,type);
5430: }
5432: /* Flush assembly is not a true assembly */
5433: if (type != MAT_FLUSH_ASSEMBLY) {
5434: mat->assembled = PETSC_TRUE; mat->num_ass++;
5435: }
5436: mat->insertmode = NOT_SET_VALUES;
5437: MatAssemblyEnd_InUse--;
5438: PetscObjectStateIncrease((PetscObject)mat);
5439: if (!mat->symmetric_eternal) {
5440: mat->symmetric_set = PETSC_FALSE;
5441: mat->hermitian_set = PETSC_FALSE;
5442: mat->structurally_symmetric_set = PETSC_FALSE;
5443: }
5444: #if defined(PETSC_HAVE_VIENNACL) || defined(PETSC_HAVE_CUDA)
5445: if (mat->valid_GPU_matrix != PETSC_OFFLOAD_UNALLOCATED) {
5446: mat->valid_GPU_matrix = PETSC_OFFLOAD_CPU;
5447: }
5448: #endif
5449: if (inassm == 1 && type != MAT_FLUSH_ASSEMBLY) {
5450: MatViewFromOptions(mat,NULL,"-mat_view");
5452: if (mat->checksymmetryonassembly) {
5453: MatIsSymmetric(mat,mat->checksymmetrytol,&flg);
5454: if (flg) {
5455: PetscPrintf(PetscObjectComm((PetscObject)mat),"Matrix is symmetric (tolerance %g)\n",(double)mat->checksymmetrytol);
5456: } else {
5457: PetscPrintf(PetscObjectComm((PetscObject)mat),"Matrix is not symmetric (tolerance %g)\n",(double)mat->checksymmetrytol);
5458: }
5459: }
5460: if (mat->nullsp && mat->checknullspaceonassembly) {
5461: MatNullSpaceTest(mat->nullsp,mat,NULL);
5462: }
5463: }
5464: inassm--;
5465: return(0);
5466: }
5468: /*@
5469: MatSetOption - Sets a parameter option for a matrix. Some options
5470: may be specific to certain storage formats. Some options
5471: determine how values will be inserted (or added). Sorted,
5472: row-oriented input will generally assemble the fastest. The default
5473: is row-oriented.
5475: Logically Collective on Mat for certain operations, such as MAT_SPD, not collective for MAT_ROW_ORIENTED, see MatOption
5477: Input Parameters:
5478: + mat - the matrix
5479: . option - the option, one of those listed below (and possibly others),
5480: - flg - turn the option on (PETSC_TRUE) or off (PETSC_FALSE)
5482: Options Describing Matrix Structure:
5483: + MAT_SPD - symmetric positive definite
5484: . MAT_SYMMETRIC - symmetric in terms of both structure and value
5485: . MAT_HERMITIAN - transpose is the complex conjugation
5486: . MAT_STRUCTURALLY_SYMMETRIC - symmetric nonzero structure
5487: - MAT_SYMMETRY_ETERNAL - if you would like the symmetry/Hermitian flag
5488: you set to be kept with all future use of the matrix
5489: including after MatAssemblyBegin/End() which could
5490: potentially change the symmetry structure, i.e. you
5491: KNOW the matrix will ALWAYS have the property you set.
5494: Options For Use with MatSetValues():
5495: Insert a logically dense subblock, which can be
5496: . MAT_ROW_ORIENTED - row-oriented (default)
5498: Note these options reflect the data you pass in with MatSetValues(); it has
5499: nothing to do with how the data is stored internally in the matrix
5500: data structure.
5502: When (re)assembling a matrix, we can restrict the input for
5503: efficiency/debugging purposes. These options include:
5504: + MAT_NEW_NONZERO_LOCATIONS - additional insertions will be allowed if they generate a new nonzero (slow)
5505: . MAT_NEW_DIAGONALS - new diagonals will be allowed (for block diagonal format only)
5506: . MAT_IGNORE_OFF_PROC_ENTRIES - drops off-processor entries
5507: . MAT_NEW_NONZERO_LOCATION_ERR - generates an error for new matrix entry
5508: . MAT_USE_HASH_TABLE - uses a hash table to speed up matrix assembly
5509: . MAT_NO_OFF_PROC_ENTRIES - you know each process will only set values for its own rows, will generate an error if
5510: any process sets values for another process. This avoids all reductions in the MatAssembly routines and thus improves
5511: performance for very large process counts.
5512: - MAT_SUBSET_OFF_PROC_ENTRIES - you know that the first assembly after setting this flag will set a superset
5513: of the off-process entries required for all subsequent assemblies. This avoids a rendezvous step in the MatAssembly
5514: functions, instead sending only neighbor messages.
5516: Notes:
5517: Except for MAT_UNUSED_NONZERO_LOCATION_ERR and MAT_ROW_ORIENTED all processes that share the matrix must pass the same value in flg!
5519: Some options are relevant only for particular matrix types and
5520: are thus ignored by others. Other options are not supported by
5521: certain matrix types and will generate an error message if set.
5523: If using a Fortran 77 module to compute a matrix, one may need to
5524: use the column-oriented option (or convert to the row-oriented
5525: format).
5527: MAT_NEW_NONZERO_LOCATIONS set to PETSC_FALSE indicates that any add or insertion
5528: that would generate a new entry in the nonzero structure is instead
5529: ignored. Thus, if memory has not alredy been allocated for this particular
5530: data, then the insertion is ignored. For dense matrices, in which
5531: the entire array is allocated, no entries are ever ignored.
5532: Set after the first MatAssemblyEnd(). If this option is set then the MatAssemblyBegin/End() processes has one less global reduction
5534: MAT_NEW_NONZERO_LOCATION_ERR set to PETSC_TRUE indicates that any add or insertion
5535: that would generate a new entry in the nonzero structure instead produces
5536: 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
5538: MAT_NEW_NONZERO_ALLOCATION_ERR set to PETSC_TRUE indicates that any add or insertion
5539: that would generate a new entry that has not been preallocated will
5540: instead produce an error. (Currently supported for AIJ and BAIJ formats
5541: only.) This is a useful flag when debugging matrix memory preallocation.
5542: If this option is set then the MatAssemblyBegin/End() processes has one less global reduction
5544: MAT_IGNORE_OFF_PROC_ENTRIES set to PETSC_TRUE indicates entries destined for
5545: other processors should be dropped, rather than stashed.
5546: This is useful if you know that the "owning" processor is also
5547: always generating the correct matrix entries, so that PETSc need
5548: not transfer duplicate entries generated on another processor.
5550: MAT_USE_HASH_TABLE indicates that a hash table be used to improve the
5551: searches during matrix assembly. When this flag is set, the hash table
5552: is created during the first Matrix Assembly. This hash table is
5553: used the next time through, during MatSetVaules()/MatSetVaulesBlocked()
5554: to improve the searching of indices. MAT_NEW_NONZERO_LOCATIONS flag
5555: should be used with MAT_USE_HASH_TABLE flag. This option is currently
5556: supported by MATMPIBAIJ format only.
5558: MAT_KEEP_NONZERO_PATTERN indicates when MatZeroRows() is called the zeroed entries
5559: are kept in the nonzero structure
5561: MAT_IGNORE_ZERO_ENTRIES - for AIJ/IS matrices this will stop zero values from creating
5562: a zero location in the matrix
5564: MAT_USE_INODES - indicates using inode version of the code - works with AIJ matrix types
5566: MAT_NO_OFF_PROC_ZERO_ROWS - you know each process will only zero its own rows. This avoids all reductions in the
5567: zero row routines and thus improves performance for very large process counts.
5569: MAT_IGNORE_LOWER_TRIANGULAR - For SBAIJ matrices will ignore any insertions you make in the lower triangular
5570: part of the matrix (since they should match the upper triangular part).
5572: Notes:
5573: Can only be called after MatSetSizes() and MatSetType() have been set.
5575: Level: intermediate
5577: Concepts: matrices^setting options
5579: .seealso: MatOption, Mat
5581: @*/
5582: PetscErrorCode MatSetOption(Mat mat,MatOption op,PetscBool flg)
5583: {
5589: if (op > 0) {
5592: }
5594: 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);
5595: 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()");
5597: switch (op) {
5598: case MAT_NO_OFF_PROC_ENTRIES:
5599: mat->nooffprocentries = flg;
5600: return(0);
5601: break;
5602: case MAT_SUBSET_OFF_PROC_ENTRIES:
5603: mat->assembly_subset = flg;
5604: if (!mat->assembly_subset) { /* See the same logic in VecAssembly wrt VEC_SUBSET_OFF_PROC_ENTRIES */
5605: #if !defined(PETSC_HAVE_MPIUNI)
5606: MatStashScatterDestroy_BTS(&mat->stash);
5607: #endif
5608: mat->stash.first_assembly_done = PETSC_FALSE;
5609: }
5610: return(0);
5611: case MAT_NO_OFF_PROC_ZERO_ROWS:
5612: mat->nooffproczerorows = flg;
5613: return(0);
5614: break;
5615: case MAT_SPD:
5616: mat->spd_set = PETSC_TRUE;
5617: mat->spd = flg;
5618: if (flg) {
5619: mat->symmetric = PETSC_TRUE;
5620: mat->structurally_symmetric = PETSC_TRUE;
5621: mat->symmetric_set = PETSC_TRUE;
5622: mat->structurally_symmetric_set = PETSC_TRUE;
5623: }
5624: break;
5625: case MAT_SYMMETRIC:
5626: mat->symmetric = flg;
5627: if (flg) mat->structurally_symmetric = PETSC_TRUE;
5628: mat->symmetric_set = PETSC_TRUE;
5629: mat->structurally_symmetric_set = flg;
5630: #if !defined(PETSC_USE_COMPLEX)
5631: mat->hermitian = flg;
5632: mat->hermitian_set = PETSC_TRUE;
5633: #endif
5634: break;
5635: case MAT_HERMITIAN:
5636: mat->hermitian = flg;
5637: if (flg) mat->structurally_symmetric = PETSC_TRUE;
5638: mat->hermitian_set = PETSC_TRUE;
5639: mat->structurally_symmetric_set = flg;
5640: #if !defined(PETSC_USE_COMPLEX)
5641: mat->symmetric = flg;
5642: mat->symmetric_set = PETSC_TRUE;
5643: #endif
5644: break;
5645: case MAT_STRUCTURALLY_SYMMETRIC:
5646: mat->structurally_symmetric = flg;
5647: mat->structurally_symmetric_set = PETSC_TRUE;
5648: break;
5649: case MAT_SYMMETRY_ETERNAL:
5650: mat->symmetric_eternal = flg;
5651: break;
5652: case MAT_STRUCTURE_ONLY:
5653: mat->structure_only = flg;
5654: break;
5655: default:
5656: break;
5657: }
5658: if (mat->ops->setoption) {
5659: (*mat->ops->setoption)(mat,op,flg);
5660: }
5661: return(0);
5662: }
5664: /*@
5665: MatGetOption - Gets a parameter option that has been set for a matrix.
5667: Logically Collective on Mat for certain operations, such as MAT_SPD, not collective for MAT_ROW_ORIENTED, see MatOption
5669: Input Parameters:
5670: + mat - the matrix
5671: - option - the option, this only responds to certain options, check the code for which ones
5673: Output Parameter:
5674: . flg - turn the option on (PETSC_TRUE) or off (PETSC_FALSE)
5676: Notes:
5677: Can only be called after MatSetSizes() and MatSetType() have been set.
5679: Level: intermediate
5681: Concepts: matrices^setting options
5683: .seealso: MatOption, MatSetOption()
5685: @*/
5686: PetscErrorCode MatGetOption(Mat mat,MatOption op,PetscBool *flg)
5687: {
5692: 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);
5693: 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()");
5695: switch (op) {
5696: case MAT_NO_OFF_PROC_ENTRIES:
5697: *flg = mat->nooffprocentries;
5698: break;
5699: case MAT_NO_OFF_PROC_ZERO_ROWS:
5700: *flg = mat->nooffproczerorows;
5701: break;
5702: case MAT_SYMMETRIC:
5703: *flg = mat->symmetric;
5704: break;
5705: case MAT_HERMITIAN:
5706: *flg = mat->hermitian;
5707: break;
5708: case MAT_STRUCTURALLY_SYMMETRIC:
5709: *flg = mat->structurally_symmetric;
5710: break;
5711: case MAT_SYMMETRY_ETERNAL:
5712: *flg = mat->symmetric_eternal;
5713: break;
5714: case MAT_SPD:
5715: *flg = mat->spd;
5716: break;
5717: default:
5718: break;
5719: }
5720: return(0);
5721: }
5723: /*@
5724: MatZeroEntries - Zeros all entries of a matrix. For sparse matrices
5725: this routine retains the old nonzero structure.
5727: Logically Collective on Mat
5729: Input Parameters:
5730: . mat - the matrix
5732: Level: intermediate
5734: Notes:
5735: 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.
5736: See the Performance chapter of the users manual for information on preallocating matrices.
5738: Concepts: matrices^zeroing
5740: .seealso: MatZeroRows()
5741: @*/
5742: PetscErrorCode MatZeroEntries(Mat mat)
5743: {
5749: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
5750: 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");
5751: if (!mat->ops->zeroentries) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
5752: MatCheckPreallocated(mat,1);
5754: PetscLogEventBegin(MAT_ZeroEntries,mat,0,0,0);
5755: (*mat->ops->zeroentries)(mat);
5756: PetscLogEventEnd(MAT_ZeroEntries,mat,0,0,0);
5757: PetscObjectStateIncrease((PetscObject)mat);
5758: #if defined(PETSC_HAVE_VIENNACL) || defined(PETSC_HAVE_CUDA)
5759: if (mat->valid_GPU_matrix != PETSC_OFFLOAD_UNALLOCATED) {
5760: mat->valid_GPU_matrix = PETSC_OFFLOAD_CPU;
5761: }
5762: #endif
5763: return(0);
5764: }
5766: /*@
5767: MatZeroRowsColumns - Zeros all entries (except possibly the main diagonal)
5768: of a set of rows and columns of a matrix.
5770: Collective on Mat
5772: Input Parameters:
5773: + mat - the matrix
5774: . numRows - the number of rows to remove
5775: . rows - the global row indices
5776: . diag - value put in all diagonals of eliminated rows (0.0 will even eliminate diagonal entry)
5777: . x - optional vector of solutions for zeroed rows (other entries in vector are not used)
5778: - b - optional vector of right hand side, that will be adjusted by provided solution
5780: Notes:
5781: This does not change the nonzero structure of the matrix, it merely zeros those entries in the matrix.
5783: The user can set a value in the diagonal entry (or for the AIJ and
5784: row formats can optionally remove the main diagonal entry from the
5785: nonzero structure as well, by passing 0.0 as the final argument).
5787: For the parallel case, all processes that share the matrix (i.e.,
5788: those in the communicator used for matrix creation) MUST call this
5789: routine, regardless of whether any rows being zeroed are owned by
5790: them.
5792: Each processor can indicate any rows in the entire matrix to be zeroed (i.e. each process does NOT have to
5793: list only rows local to itself).
5795: The option MAT_NO_OFF_PROC_ZERO_ROWS does not apply to this routine.
5797: Level: intermediate
5799: Concepts: matrices^zeroing rows
5801: .seealso: MatZeroRowsIS(), MatZeroRows(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
5802: MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
5803: @*/
5804: PetscErrorCode MatZeroRowsColumns(Mat mat,PetscInt numRows,const PetscInt rows[],PetscScalar diag,Vec x,Vec b)
5805: {
5812: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
5813: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
5814: if (!mat->ops->zerorowscolumns) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
5815: MatCheckPreallocated(mat,1);
5817: (*mat->ops->zerorowscolumns)(mat,numRows,rows,diag,x,b);
5818: MatViewFromOptions(mat,NULL,"-mat_view");
5819: PetscObjectStateIncrease((PetscObject)mat);
5820: #if defined(PETSC_HAVE_VIENNACL) || defined(PETSC_HAVE_CUDA)
5821: if (mat->valid_GPU_matrix != PETSC_OFFLOAD_UNALLOCATED) {
5822: mat->valid_GPU_matrix = PETSC_OFFLOAD_CPU;
5823: }
5824: #endif
5825: return(0);
5826: }
5828: /*@
5829: MatZeroRowsColumnsIS - Zeros all entries (except possibly the main diagonal)
5830: of a set of rows and columns of a matrix.
5832: Collective on Mat
5834: Input Parameters:
5835: + mat - the matrix
5836: . is - the rows to zero
5837: . diag - value put in all diagonals of eliminated rows (0.0 will even eliminate diagonal entry)
5838: . x - optional vector of solutions for zeroed rows (other entries in vector are not used)
5839: - b - optional vector of right hand side, that will be adjusted by provided solution
5841: Notes:
5842: This does not change the nonzero structure of the matrix, it merely zeros those entries in the matrix.
5844: The user can set a value in the diagonal entry (or for the AIJ and
5845: row formats can optionally remove the main diagonal entry from the
5846: nonzero structure as well, by passing 0.0 as the final argument).
5848: For the parallel case, all processes that share the matrix (i.e.,
5849: those in the communicator used for matrix creation) MUST call this
5850: routine, regardless of whether any rows being zeroed are owned by
5851: them.
5853: Each processor can indicate any rows in the entire matrix to be zeroed (i.e. each process does NOT have to
5854: list only rows local to itself).
5856: The option MAT_NO_OFF_PROC_ZERO_ROWS does not apply to this routine.
5858: Level: intermediate
5860: Concepts: matrices^zeroing rows
5862: .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
5863: MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRows(), MatZeroRowsColumnsStencil()
5864: @*/
5865: PetscErrorCode MatZeroRowsColumnsIS(Mat mat,IS is,PetscScalar diag,Vec x,Vec b)
5866: {
5868: PetscInt numRows;
5869: const PetscInt *rows;
5876: ISGetLocalSize(is,&numRows);
5877: ISGetIndices(is,&rows);
5878: MatZeroRowsColumns(mat,numRows,rows,diag,x,b);
5879: ISRestoreIndices(is,&rows);
5880: return(0);
5881: }
5883: /*@
5884: MatZeroRows - Zeros all entries (except possibly the main diagonal)
5885: of a set of rows of a matrix.
5887: Collective on Mat
5889: Input Parameters:
5890: + mat - the matrix
5891: . numRows - the number of rows to remove
5892: . rows - the global row indices
5893: . diag - value put in all diagonals of eliminated rows (0.0 will even eliminate diagonal entry)
5894: . x - optional vector of solutions for zeroed rows (other entries in vector are not used)
5895: - b - optional vector of right hand side, that will be adjusted by provided solution
5897: Notes:
5898: For the AIJ and BAIJ matrix formats this removes the old nonzero structure,
5899: but does not release memory. For the dense and block diagonal
5900: formats this does not alter the nonzero structure.
5902: If the option MatSetOption(mat,MAT_KEEP_NONZERO_PATTERN,PETSC_TRUE) the nonzero structure
5903: of the matrix is not changed (even for AIJ and BAIJ matrices) the values are
5904: merely zeroed.
5906: The user can set a value in the diagonal entry (or for the AIJ and
5907: row formats can optionally remove the main diagonal entry from the
5908: nonzero structure as well, by passing 0.0 as the final argument).
5910: For the parallel case, all processes that share the matrix (i.e.,
5911: those in the communicator used for matrix creation) MUST call this
5912: routine, regardless of whether any rows being zeroed are owned by
5913: them.
5915: Each processor can indicate any rows in the entire matrix to be zeroed (i.e. each process does NOT have to
5916: list only rows local to itself).
5918: You can call MatSetOption(mat,MAT_NO_OFF_PROC_ZERO_ROWS,PETSC_TRUE) if each process indicates only rows it
5919: owns that are to be zeroed. This saves a global synchronization in the implementation.
5921: Level: intermediate
5923: Concepts: matrices^zeroing rows
5925: .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
5926: MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
5927: @*/
5928: PetscErrorCode MatZeroRows(Mat mat,PetscInt numRows,const PetscInt rows[],PetscScalar diag,Vec x,Vec b)
5929: {
5936: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
5937: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
5938: if (!mat->ops->zerorows) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
5939: MatCheckPreallocated(mat,1);
5941: (*mat->ops->zerorows)(mat,numRows,rows,diag,x,b);
5942: MatViewFromOptions(mat,NULL,"-mat_view");
5943: PetscObjectStateIncrease((PetscObject)mat);
5944: #if defined(PETSC_HAVE_VIENNACL) || defined(PETSC_HAVE_CUDA)
5945: if (mat->valid_GPU_matrix != PETSC_OFFLOAD_UNALLOCATED) {
5946: mat->valid_GPU_matrix = PETSC_OFFLOAD_CPU;
5947: }
5948: #endif
5949: return(0);
5950: }
5952: /*@
5953: MatZeroRowsIS - Zeros all entries (except possibly the main diagonal)
5954: of a set of rows of a matrix.
5956: Collective on Mat
5958: Input Parameters:
5959: + mat - the matrix
5960: . is - index set of rows to remove
5961: . diag - value put in all diagonals of eliminated rows
5962: . x - optional vector of solutions for zeroed rows (other entries in vector are not used)
5963: - b - optional vector of right hand side, that will be adjusted by provided solution
5965: Notes:
5966: For the AIJ and BAIJ matrix formats this removes the old nonzero structure,
5967: but does not release memory. For the dense and block diagonal
5968: formats this does not alter the nonzero structure.
5970: If the option MatSetOption(mat,MAT_KEEP_NONZERO_PATTERN,PETSC_TRUE) the nonzero structure
5971: of the matrix is not changed (even for AIJ and BAIJ matrices) the values are
5972: merely zeroed.
5974: The user can set a value in the diagonal entry (or for the AIJ and
5975: row formats can optionally remove the main diagonal entry from the
5976: nonzero structure as well, by passing 0.0 as the final argument).
5978: For the parallel case, all processes that share the matrix (i.e.,
5979: those in the communicator used for matrix creation) MUST call this
5980: routine, regardless of whether any rows being zeroed are owned by
5981: them.
5983: Each processor can indicate any rows in the entire matrix to be zeroed (i.e. each process does NOT have to
5984: list only rows local to itself).
5986: You can call MatSetOption(mat,MAT_NO_OFF_PROC_ZERO_ROWS,PETSC_TRUE) if each process indicates only rows it
5987: owns that are to be zeroed. This saves a global synchronization in the implementation.
5989: Level: intermediate
5991: Concepts: matrices^zeroing rows
5993: .seealso: MatZeroRows(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
5994: MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
5995: @*/
5996: PetscErrorCode MatZeroRowsIS(Mat mat,IS is,PetscScalar diag,Vec x,Vec b)
5997: {
5998: PetscInt numRows;
5999: const PetscInt *rows;
6006: ISGetLocalSize(is,&numRows);
6007: ISGetIndices(is,&rows);
6008: MatZeroRows(mat,numRows,rows,diag,x,b);
6009: ISRestoreIndices(is,&rows);
6010: return(0);
6011: }
6013: /*@
6014: MatZeroRowsStencil - Zeros all entries (except possibly the main diagonal)
6015: of a set of rows of a matrix. These rows must be local to the process.
6017: Collective on Mat
6019: Input Parameters:
6020: + mat - the matrix
6021: . numRows - the number of rows to remove
6022: . rows - the grid coordinates (and component number when dof > 1) for matrix rows
6023: . diag - value put in all diagonals of eliminated rows (0.0 will even eliminate diagonal entry)
6024: . x - optional vector of solutions for zeroed rows (other entries in vector are not used)
6025: - b - optional vector of right hand side, that will be adjusted by provided solution
6027: Notes:
6028: For the AIJ and BAIJ matrix formats this removes the old nonzero structure,
6029: but does not release memory. For the dense and block diagonal
6030: formats this does not alter the nonzero structure.
6032: If the option MatSetOption(mat,MAT_KEEP_NONZERO_PATTERN,PETSC_TRUE) the nonzero structure
6033: of the matrix is not changed (even for AIJ and BAIJ matrices) the values are
6034: merely zeroed.
6036: The user can set a value in the diagonal entry (or for the AIJ and
6037: row formats can optionally remove the main diagonal entry from the
6038: nonzero structure as well, by passing 0.0 as the final argument).
6040: For the parallel case, all processes that share the matrix (i.e.,
6041: those in the communicator used for matrix creation) MUST call this
6042: routine, regardless of whether any rows being zeroed are owned by
6043: them.
6045: Each processor can indicate any rows in the entire matrix to be zeroed (i.e. each process does NOT have to
6046: list only rows local to itself).
6048: The grid coordinates are across the entire grid, not just the local portion
6050: In Fortran idxm and idxn should be declared as
6051: $ MatStencil idxm(4,m)
6052: and the values inserted using
6053: $ idxm(MatStencil_i,1) = i
6054: $ idxm(MatStencil_j,1) = j
6055: $ idxm(MatStencil_k,1) = k
6056: $ idxm(MatStencil_c,1) = c
6057: etc
6059: For periodic boundary conditions use negative indices for values to the left (below 0; that are to be
6060: obtained by wrapping values from right edge). For values to the right of the last entry using that index plus one
6061: etc to obtain values that obtained by wrapping the values from the left edge. This does not work for anything but the
6062: DM_BOUNDARY_PERIODIC boundary type.
6064: 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
6065: a single value per point) you can skip filling those indices.
6067: Level: intermediate
6069: Concepts: matrices^zeroing rows
6071: .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsl(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
6072: MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
6073: @*/
6074: PetscErrorCode MatZeroRowsStencil(Mat mat,PetscInt numRows,const MatStencil rows[],PetscScalar diag,Vec x,Vec b)
6075: {
6076: PetscInt dim = mat->stencil.dim;
6077: PetscInt sdim = dim - (1 - (PetscInt) mat->stencil.noc);
6078: PetscInt *dims = mat->stencil.dims+1;
6079: PetscInt *starts = mat->stencil.starts;
6080: PetscInt *dxm = (PetscInt*) rows;
6081: PetscInt *jdxm, i, j, tmp, numNewRows = 0;
6089: PetscMalloc1(numRows, &jdxm);
6090: for (i = 0; i < numRows; ++i) {
6091: /* Skip unused dimensions (they are ordered k, j, i, c) */
6092: for (j = 0; j < 3-sdim; ++j) dxm++;
6093: /* Local index in X dir */
6094: tmp = *dxm++ - starts[0];
6095: /* Loop over remaining dimensions */
6096: for (j = 0; j < dim-1; ++j) {
6097: /* If nonlocal, set index to be negative */
6098: if ((*dxm++ - starts[j+1]) < 0 || tmp < 0) tmp = PETSC_MIN_INT;
6099: /* Update local index */
6100: else tmp = tmp*dims[j] + *(dxm-1) - starts[j+1];
6101: }
6102: /* Skip component slot if necessary */
6103: if (mat->stencil.noc) dxm++;
6104: /* Local row number */
6105: if (tmp >= 0) {
6106: jdxm[numNewRows++] = tmp;
6107: }
6108: }
6109: MatZeroRowsLocal(mat,numNewRows,jdxm,diag,x,b);
6110: PetscFree(jdxm);
6111: return(0);
6112: }
6114: /*@
6115: MatZeroRowsColumnsStencil - Zeros all row and column entries (except possibly the main diagonal)
6116: of a set of rows and columns of a matrix.
6118: Collective on Mat
6120: Input Parameters:
6121: + mat - the matrix
6122: . numRows - the number of rows/columns to remove
6123: . rows - the grid coordinates (and component number when dof > 1) for matrix rows
6124: . diag - value put in all diagonals of eliminated rows (0.0 will even eliminate diagonal entry)
6125: . x - optional vector of solutions for zeroed rows (other entries in vector are not used)
6126: - b - optional vector of right hand side, that will be adjusted by provided solution
6128: Notes:
6129: For the AIJ and BAIJ matrix formats this removes the old nonzero structure,
6130: but does not release memory. For the dense and block diagonal
6131: formats this does not alter the nonzero structure.
6133: If the option MatSetOption(mat,MAT_KEEP_NONZERO_PATTERN,PETSC_TRUE) the nonzero structure
6134: of the matrix is not changed (even for AIJ and BAIJ matrices) the values are
6135: merely zeroed.
6137: The user can set a value in the diagonal entry (or for the AIJ and
6138: row formats can optionally remove the main diagonal entry from the
6139: nonzero structure as well, by passing 0.0 as the final argument).
6141: For the parallel case, all processes that share the matrix (i.e.,
6142: those in the communicator used for matrix creation) MUST call this
6143: routine, regardless of whether any rows being zeroed are owned by
6144: them.
6146: Each processor can indicate any rows in the entire matrix to be zeroed (i.e. each process does NOT have to
6147: list only rows local to itself, but the row/column numbers are given in local numbering).
6149: The grid coordinates are across the entire grid, not just the local portion
6151: In Fortran idxm and idxn should be declared as
6152: $ MatStencil idxm(4,m)
6153: and the values inserted using
6154: $ idxm(MatStencil_i,1) = i
6155: $ idxm(MatStencil_j,1) = j
6156: $ idxm(MatStencil_k,1) = k
6157: $ idxm(MatStencil_c,1) = c
6158: etc
6160: For periodic boundary conditions use negative indices for values to the left (below 0; that are to be
6161: obtained by wrapping values from right edge). For values to the right of the last entry using that index plus one
6162: etc to obtain values that obtained by wrapping the values from the left edge. This does not work for anything but the
6163: DM_BOUNDARY_PERIODIC boundary type.
6165: 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
6166: a single value per point) you can skip filling those indices.
6168: Level: intermediate
6170: Concepts: matrices^zeroing rows
6172: .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
6173: MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRows()
6174: @*/
6175: PetscErrorCode MatZeroRowsColumnsStencil(Mat mat,PetscInt numRows,const MatStencil rows[],PetscScalar diag,Vec x,Vec b)
6176: {
6177: PetscInt dim = mat->stencil.dim;
6178: PetscInt sdim = dim - (1 - (PetscInt) mat->stencil.noc);
6179: PetscInt *dims = mat->stencil.dims+1;
6180: PetscInt *starts = mat->stencil.starts;
6181: PetscInt *dxm = (PetscInt*) rows;
6182: PetscInt *jdxm, i, j, tmp, numNewRows = 0;
6190: PetscMalloc1(numRows, &jdxm);
6191: for (i = 0; i < numRows; ++i) {
6192: /* Skip unused dimensions (they are ordered k, j, i, c) */
6193: for (j = 0; j < 3-sdim; ++j) dxm++;
6194: /* Local index in X dir */
6195: tmp = *dxm++ - starts[0];
6196: /* Loop over remaining dimensions */
6197: for (j = 0; j < dim-1; ++j) {
6198: /* If nonlocal, set index to be negative */
6199: if ((*dxm++ - starts[j+1]) < 0 || tmp < 0) tmp = PETSC_MIN_INT;
6200: /* Update local index */
6201: else tmp = tmp*dims[j] + *(dxm-1) - starts[j+1];
6202: }
6203: /* Skip component slot if necessary */
6204: if (mat->stencil.noc) dxm++;
6205: /* Local row number */
6206: if (tmp >= 0) {
6207: jdxm[numNewRows++] = tmp;
6208: }
6209: }
6210: MatZeroRowsColumnsLocal(mat,numNewRows,jdxm,diag,x,b);
6211: PetscFree(jdxm);
6212: return(0);
6213: }
6215: /*@C
6216: MatZeroRowsLocal - Zeros all entries (except possibly the main diagonal)
6217: of a set of rows of a matrix; using local numbering of rows.
6219: Collective on Mat
6221: Input Parameters:
6222: + mat - the matrix
6223: . numRows - the number of rows to remove
6224: . rows - the global row indices
6225: . diag - value put in all diagonals of eliminated rows
6226: . x - optional vector of solutions for zeroed rows (other entries in vector are not used)
6227: - b - optional vector of right hand side, that will be adjusted by provided solution
6229: Notes:
6230: Before calling MatZeroRowsLocal(), the user must first set the
6231: local-to-global mapping by calling MatSetLocalToGlobalMapping().
6233: For the AIJ matrix formats this removes the old nonzero structure,
6234: but does not release memory. For the dense and block diagonal
6235: formats this does not alter the nonzero structure.
6237: If the option MatSetOption(mat,MAT_KEEP_NONZERO_PATTERN,PETSC_TRUE) the nonzero structure
6238: of the matrix is not changed (even for AIJ and BAIJ matrices) the values are
6239: merely zeroed.
6241: The user can set a value in the diagonal entry (or for the AIJ and
6242: row formats can optionally remove the main diagonal entry from the
6243: nonzero structure as well, by passing 0.0 as the final argument).
6245: You can call MatSetOption(mat,MAT_NO_OFF_PROC_ZERO_ROWS,PETSC_TRUE) if each process indicates only rows it
6246: owns that are to be zeroed. This saves a global synchronization in the implementation.
6248: Level: intermediate
6250: Concepts: matrices^zeroing
6252: .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRows(), MatSetOption(),
6253: MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
6254: @*/
6255: PetscErrorCode MatZeroRowsLocal(Mat mat,PetscInt numRows,const PetscInt rows[],PetscScalar diag,Vec x,Vec b)
6256: {
6263: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6264: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6265: MatCheckPreallocated(mat,1);
6267: if (mat->ops->zerorowslocal) {
6268: (*mat->ops->zerorowslocal)(mat,numRows,rows,diag,x,b);
6269: } else {
6270: IS is, newis;
6271: const PetscInt *newRows;
6273: if (!mat->rmap->mapping) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Need to provide local to global mapping to matrix first");
6274: ISCreateGeneral(PETSC_COMM_SELF,numRows,rows,PETSC_COPY_VALUES,&is);
6275: ISLocalToGlobalMappingApplyIS(mat->rmap->mapping,is,&newis);
6276: ISGetIndices(newis,&newRows);
6277: (*mat->ops->zerorows)(mat,numRows,newRows,diag,x,b);
6278: ISRestoreIndices(newis,&newRows);
6279: ISDestroy(&newis);
6280: ISDestroy(&is);
6281: }
6282: PetscObjectStateIncrease((PetscObject)mat);
6283: #if defined(PETSC_HAVE_VIENNACL) || defined(PETSC_HAVE_CUDA)
6284: if (mat->valid_GPU_matrix != PETSC_OFFLOAD_UNALLOCATED) {
6285: mat->valid_GPU_matrix = PETSC_OFFLOAD_CPU;
6286: }
6287: #endif
6288: return(0);
6289: }
6291: /*@
6292: MatZeroRowsLocalIS - Zeros all entries (except possibly the main diagonal)
6293: of a set of rows of a matrix; using local numbering of rows.
6295: Collective on Mat
6297: Input Parameters:
6298: + mat - the matrix
6299: . is - index set of rows to remove
6300: . diag - value put in all diagonals of eliminated rows
6301: . x - optional vector of solutions for zeroed rows (other entries in vector are not used)
6302: - b - optional vector of right hand side, that will be adjusted by provided solution
6304: Notes:
6305: Before calling MatZeroRowsLocalIS(), the user must first set the
6306: local-to-global mapping by calling MatSetLocalToGlobalMapping().
6308: For the AIJ matrix formats this removes the old nonzero structure,
6309: but does not release memory. For the dense and block diagonal
6310: formats this does not alter the nonzero structure.
6312: If the option MatSetOption(mat,MAT_KEEP_NONZERO_PATTERN,PETSC_TRUE) the nonzero structure
6313: of the matrix is not changed (even for AIJ and BAIJ matrices) the values are
6314: merely zeroed.
6316: The user can set a value in the diagonal entry (or for the AIJ and
6317: row formats can optionally remove the main diagonal entry from the
6318: nonzero structure as well, by passing 0.0 as the final argument).
6320: You can call MatSetOption(mat,MAT_NO_OFF_PROC_ZERO_ROWS,PETSC_TRUE) if each process indicates only rows it
6321: owns that are to be zeroed. This saves a global synchronization in the implementation.
6323: Level: intermediate
6325: Concepts: matrices^zeroing
6327: .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRows(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
6328: MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
6329: @*/
6330: PetscErrorCode MatZeroRowsLocalIS(Mat mat,IS is,PetscScalar diag,Vec x,Vec b)
6331: {
6333: PetscInt numRows;
6334: const PetscInt *rows;
6340: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6341: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6342: MatCheckPreallocated(mat,1);
6344: ISGetLocalSize(is,&numRows);
6345: ISGetIndices(is,&rows);
6346: MatZeroRowsLocal(mat,numRows,rows,diag,x,b);
6347: ISRestoreIndices(is,&rows);
6348: return(0);
6349: }
6351: /*@
6352: MatZeroRowsColumnsLocal - Zeros all entries (except possibly the main diagonal)
6353: of a set of rows and columns of a matrix; using local numbering of rows.
6355: Collective on Mat
6357: Input Parameters:
6358: + mat - the matrix
6359: . numRows - the number of rows to remove
6360: . rows - the global row indices
6361: . diag - value put in all diagonals of eliminated rows
6362: . x - optional vector of solutions for zeroed rows (other entries in vector are not used)
6363: - b - optional vector of right hand side, that will be adjusted by provided solution
6365: Notes:
6366: Before calling MatZeroRowsColumnsLocal(), the user must first set the
6367: local-to-global mapping by calling MatSetLocalToGlobalMapping().
6369: The user can set a value in the diagonal entry (or for the AIJ and
6370: row formats can optionally remove the main diagonal entry from the
6371: nonzero structure as well, by passing 0.0 as the final argument).
6373: Level: intermediate
6375: Concepts: matrices^zeroing
6377: .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
6378: MatZeroRows(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
6379: @*/
6380: PetscErrorCode MatZeroRowsColumnsLocal(Mat mat,PetscInt numRows,const PetscInt rows[],PetscScalar diag,Vec x,Vec b)
6381: {
6383: IS is, newis;
6384: const PetscInt *newRows;
6390: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6391: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6392: MatCheckPreallocated(mat,1);
6394: if (!mat->cmap->mapping) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Need to provide local to global mapping to matrix first");
6395: ISCreateGeneral(PETSC_COMM_SELF,numRows,rows,PETSC_COPY_VALUES,&is);
6396: ISLocalToGlobalMappingApplyIS(mat->cmap->mapping,is,&newis);
6397: ISGetIndices(newis,&newRows);
6398: (*mat->ops->zerorowscolumns)(mat,numRows,newRows,diag,x,b);
6399: ISRestoreIndices(newis,&newRows);
6400: ISDestroy(&newis);
6401: ISDestroy(&is);
6402: PetscObjectStateIncrease((PetscObject)mat);
6403: #if defined(PETSC_HAVE_VIENNACL) || defined(PETSC_HAVE_CUDA)
6404: if (mat->valid_GPU_matrix != PETSC_OFFLOAD_UNALLOCATED) {
6405: mat->valid_GPU_matrix = PETSC_OFFLOAD_CPU;
6406: }
6407: #endif
6408: return(0);
6409: }
6411: /*@
6412: MatZeroRowsColumnsLocalIS - Zeros all entries (except possibly the main diagonal)
6413: of a set of rows and columns of a matrix; using local numbering of rows.
6415: Collective on Mat
6417: Input Parameters:
6418: + mat - the matrix
6419: . is - index set of rows to remove
6420: . diag - value put in all diagonals of eliminated rows
6421: . x - optional vector of solutions for zeroed rows (other entries in vector are not used)
6422: - b - optional vector of right hand side, that will be adjusted by provided solution
6424: Notes:
6425: Before calling MatZeroRowsColumnsLocalIS(), the user must first set the
6426: local-to-global mapping by calling MatSetLocalToGlobalMapping().
6428: The user can set a value in the diagonal entry (or for the AIJ and
6429: row formats can optionally remove the main diagonal entry from the
6430: nonzero structure as well, by passing 0.0 as the final argument).
6432: Level: intermediate
6434: Concepts: matrices^zeroing
6436: .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
6437: MatZeroRowsColumnsLocal(), MatZeroRows(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
6438: @*/
6439: PetscErrorCode MatZeroRowsColumnsLocalIS(Mat mat,IS is,PetscScalar diag,Vec x,Vec b)
6440: {
6442: PetscInt numRows;
6443: const PetscInt *rows;
6449: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6450: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6451: MatCheckPreallocated(mat,1);
6453: ISGetLocalSize(is,&numRows);
6454: ISGetIndices(is,&rows);
6455: MatZeroRowsColumnsLocal(mat,numRows,rows,diag,x,b);
6456: ISRestoreIndices(is,&rows);
6457: return(0);
6458: }
6460: /*@C
6461: MatGetSize - Returns the numbers of rows and columns in a matrix.
6463: Not Collective
6465: Input Parameter:
6466: . mat - the matrix
6468: Output Parameters:
6469: + m - the number of global rows
6470: - n - the number of global columns
6472: Note: both output parameters can be NULL on input.
6474: Level: beginner
6476: Concepts: matrices^size
6478: .seealso: MatGetLocalSize()
6479: @*/
6480: PetscErrorCode MatGetSize(Mat mat,PetscInt *m,PetscInt *n)
6481: {
6484: if (m) *m = mat->rmap->N;
6485: if (n) *n = mat->cmap->N;
6486: return(0);
6487: }
6489: /*@C
6490: MatGetLocalSize - Returns the number of rows and columns in a matrix
6491: stored locally. This information may be implementation dependent, so
6492: use with care.
6494: Not Collective
6496: Input Parameters:
6497: . mat - the matrix
6499: Output Parameters:
6500: + m - the number of local rows
6501: - n - the number of local columns
6503: Note: both output parameters can be NULL on input.
6505: Level: beginner
6507: Concepts: matrices^local size
6509: .seealso: MatGetSize()
6510: @*/
6511: PetscErrorCode MatGetLocalSize(Mat mat,PetscInt *m,PetscInt *n)
6512: {
6517: if (m) *m = mat->rmap->n;
6518: if (n) *n = mat->cmap->n;
6519: return(0);
6520: }
6522: /*@C
6523: MatGetOwnershipRangeColumn - Returns the range of matrix columns associated with rows of a vector one multiplies by that owned by
6524: this processor. (The columns of the "diagonal block")
6526: Not Collective, unless matrix has not been allocated, then collective on Mat
6528: Input Parameters:
6529: . mat - the matrix
6531: Output Parameters:
6532: + m - the global index of the first local column
6533: - n - one more than the global index of the last local column
6535: Notes:
6536: both output parameters can be NULL on input.
6538: Level: developer
6540: Concepts: matrices^column ownership
6542: .seealso: MatGetOwnershipRange(), MatGetOwnershipRanges(), MatGetOwnershipRangesColumn()
6544: @*/
6545: PetscErrorCode MatGetOwnershipRangeColumn(Mat mat,PetscInt *m,PetscInt *n)
6546: {
6552: MatCheckPreallocated(mat,1);
6553: if (m) *m = mat->cmap->rstart;
6554: if (n) *n = mat->cmap->rend;
6555: return(0);
6556: }
6558: /*@C
6559: MatGetOwnershipRange - Returns the range of matrix rows owned by
6560: this processor, assuming that the matrix is laid out with the first
6561: n1 rows on the first processor, the next n2 rows on the second, etc.
6562: For certain parallel layouts this range may not be well defined.
6564: Not Collective
6566: Input Parameters:
6567: . mat - the matrix
6569: Output Parameters:
6570: + m - the global index of the first local row
6571: - n - one more than the global index of the last local row
6573: Note: Both output parameters can be NULL on input.
6574: $ This function requires that the matrix be preallocated. If you have not preallocated, consider using
6575: $ PetscSplitOwnership(MPI_Comm comm, PetscInt *n, PetscInt *N)
6576: $ and then MPI_Scan() to calculate prefix sums of the local sizes.
6578: Level: beginner
6580: Concepts: matrices^row ownership
6582: .seealso: MatGetOwnershipRanges(), MatGetOwnershipRangeColumn(), MatGetOwnershipRangesColumn(), PetscSplitOwnership(), PetscSplitOwnershipBlock()
6584: @*/
6585: PetscErrorCode MatGetOwnershipRange(Mat mat,PetscInt *m,PetscInt *n)
6586: {
6592: MatCheckPreallocated(mat,1);
6593: if (m) *m = mat->rmap->rstart;
6594: if (n) *n = mat->rmap->rend;
6595: return(0);
6596: }
6598: /*@C
6599: MatGetOwnershipRanges - Returns the range of matrix rows owned by
6600: each process
6602: Not Collective, unless matrix has not been allocated, then collective on Mat
6604: Input Parameters:
6605: . mat - the matrix
6607: Output Parameters:
6608: . ranges - start of each processors portion plus one more than the total length at the end
6610: Level: beginner
6612: Concepts: matrices^row ownership
6614: .seealso: MatGetOwnershipRange(), MatGetOwnershipRangeColumn(), MatGetOwnershipRangesColumn()
6616: @*/
6617: PetscErrorCode MatGetOwnershipRanges(Mat mat,const PetscInt **ranges)
6618: {
6624: MatCheckPreallocated(mat,1);
6625: PetscLayoutGetRanges(mat->rmap,ranges);
6626: return(0);
6627: }
6629: /*@C
6630: MatGetOwnershipRangesColumn - Returns the range of matrix columns associated with rows of a vector one multiplies by that owned by
6631: this processor. (The columns of the "diagonal blocks" for each process)
6633: Not Collective, unless matrix has not been allocated, then collective on Mat
6635: Input Parameters:
6636: . mat - the matrix
6638: Output Parameters:
6639: . ranges - start of each processors portion plus one more then the total length at the end
6641: Level: beginner
6643: Concepts: matrices^column ownership
6645: .seealso: MatGetOwnershipRange(), MatGetOwnershipRangeColumn(), MatGetOwnershipRanges()
6647: @*/
6648: PetscErrorCode MatGetOwnershipRangesColumn(Mat mat,const PetscInt **ranges)
6649: {
6655: MatCheckPreallocated(mat,1);
6656: PetscLayoutGetRanges(mat->cmap,ranges);
6657: return(0);
6658: }
6660: /*@C
6661: MatGetOwnershipIS - Get row and column ownership as index sets
6663: Not Collective
6665: Input Arguments:
6666: . A - matrix of type Elemental
6668: Output Arguments:
6669: + rows - rows in which this process owns elements
6670: . cols - columns in which this process owns elements
6672: Level: intermediate
6674: .seealso: MatGetOwnershipRange(), MatGetOwnershipRangeColumn(), MatSetValues(), MATELEMENTAL
6675: @*/
6676: PetscErrorCode MatGetOwnershipIS(Mat A,IS *rows,IS *cols)
6677: {
6678: PetscErrorCode ierr,(*f)(Mat,IS*,IS*);
6681: MatCheckPreallocated(A,1);
6682: PetscObjectQueryFunction((PetscObject)A,"MatGetOwnershipIS_C",&f);
6683: if (f) {
6684: (*f)(A,rows,cols);
6685: } else { /* Create a standard row-based partition, each process is responsible for ALL columns in their row block */
6686: if (rows) {ISCreateStride(PETSC_COMM_SELF,A->rmap->n,A->rmap->rstart,1,rows);}
6687: if (cols) {ISCreateStride(PETSC_COMM_SELF,A->cmap->N,0,1,cols);}
6688: }
6689: return(0);
6690: }
6692: /*@C
6693: MatILUFactorSymbolic - Performs symbolic ILU factorization of a matrix.
6694: Uses levels of fill only, not drop tolerance. Use MatLUFactorNumeric()
6695: to complete the factorization.
6697: Collective on Mat
6699: Input Parameters:
6700: + mat - the matrix
6701: . row - row permutation
6702: . column - column permutation
6703: - info - structure containing
6704: $ levels - number of levels of fill.
6705: $ expected fill - as ratio of original fill.
6706: $ 1 or 0 - indicating force fill on diagonal (improves robustness for matrices
6707: missing diagonal entries)
6709: Output Parameters:
6710: . fact - new matrix that has been symbolically factored
6712: Notes:
6713: See Users-Manual: ch_mat for additional information about choosing the fill factor for better efficiency.
6715: Most users should employ the simplified KSP interface for linear solvers
6716: instead of working directly with matrix algebra routines such as this.
6717: See, e.g., KSPCreate().
6719: Level: developer
6721: Concepts: matrices^symbolic LU factorization
6722: Concepts: matrices^factorization
6723: Concepts: LU^symbolic factorization
6725: .seealso: MatLUFactorSymbolic(), MatLUFactorNumeric(), MatCholeskyFactor()
6726: MatGetOrdering(), MatFactorInfo
6728: Note: this uses the definition of level of fill as in Y. Saad, 2003
6730: Developer Note: fortran interface is not autogenerated as the f90
6731: interface defintion cannot be generated correctly [due to MatFactorInfo]
6733: References:
6734: Y. Saad, Iterative methods for sparse linear systems Philadelphia: Society for Industrial and Applied Mathematics, 2003
6735: @*/
6736: PetscErrorCode MatILUFactorSymbolic(Mat fact,Mat mat,IS row,IS col,const MatFactorInfo *info)
6737: {
6747: if (info->levels < 0) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_OUTOFRANGE,"Levels of fill negative %D",(PetscInt)info->levels);
6748: if (info->fill < 1.0) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_OUTOFRANGE,"Expected fill less than 1.0 %g",(double)info->fill);
6749: if (!(fact)->ops->ilufactorsymbolic) {
6750: MatSolverType spackage;
6751: MatFactorGetSolverType(fact,&spackage);
6752: SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Matrix type %s symbolic ILU using solver package %s",((PetscObject)mat)->type_name,spackage);
6753: }
6754: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6755: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6756: MatCheckPreallocated(mat,2);
6758: PetscLogEventBegin(MAT_ILUFactorSymbolic,mat,row,col,0);
6759: (fact->ops->ilufactorsymbolic)(fact,mat,row,col,info);
6760: PetscLogEventEnd(MAT_ILUFactorSymbolic,mat,row,col,0);
6761: return(0);
6762: }
6764: /*@C
6765: MatICCFactorSymbolic - Performs symbolic incomplete
6766: Cholesky factorization for a symmetric matrix. Use
6767: MatCholeskyFactorNumeric() to complete the factorization.
6769: Collective on Mat
6771: Input Parameters:
6772: + mat - the matrix
6773: . perm - row and column permutation
6774: - info - structure containing
6775: $ levels - number of levels of fill.
6776: $ expected fill - as ratio of original fill.
6778: Output Parameter:
6779: . fact - the factored matrix
6781: Notes:
6782: Most users should employ the KSP interface for linear solvers
6783: instead of working directly with matrix algebra routines such as this.
6784: See, e.g., KSPCreate().
6786: Level: developer
6788: Concepts: matrices^symbolic incomplete Cholesky factorization
6789: Concepts: matrices^factorization
6790: Concepts: Cholsky^symbolic factorization
6792: .seealso: MatCholeskyFactorNumeric(), MatCholeskyFactor(), MatFactorInfo
6794: Note: this uses the definition of level of fill as in Y. Saad, 2003
6796: Developer Note: fortran interface is not autogenerated as the f90
6797: interface defintion cannot be generated correctly [due to MatFactorInfo]
6799: References:
6800: Y. Saad, Iterative methods for sparse linear systems Philadelphia: Society for Industrial and Applied Mathematics, 2003
6801: @*/
6802: PetscErrorCode MatICCFactorSymbolic(Mat fact,Mat mat,IS perm,const MatFactorInfo *info)
6803: {
6812: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6813: if (info->levels < 0) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_OUTOFRANGE,"Levels negative %D",(PetscInt) info->levels);
6814: if (info->fill < 1.0) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_OUTOFRANGE,"Expected fill less than 1.0 %g",(double)info->fill);
6815: if (!(fact)->ops->iccfactorsymbolic) {
6816: MatSolverType spackage;
6817: MatFactorGetSolverType(fact,&spackage);
6818: SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Matrix type %s symbolic ICC using solver package %s",((PetscObject)mat)->type_name,spackage);
6819: }
6820: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6821: MatCheckPreallocated(mat,2);
6823: PetscLogEventBegin(MAT_ICCFactorSymbolic,mat,perm,0,0);
6824: (fact->ops->iccfactorsymbolic)(fact,mat,perm,info);
6825: PetscLogEventEnd(MAT_ICCFactorSymbolic,mat,perm,0,0);
6826: return(0);
6827: }
6829: /*@C
6830: MatCreateSubMatrices - Extracts several submatrices from a matrix. If submat
6831: points to an array of valid matrices, they may be reused to store the new
6832: submatrices.
6834: Collective on Mat
6836: Input Parameters:
6837: + mat - the matrix
6838: . n - the number of submatrixes to be extracted (on this processor, may be zero)
6839: . irow, icol - index sets of rows and columns to extract
6840: - scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
6842: Output Parameter:
6843: . submat - the array of submatrices
6845: Notes:
6846: MatCreateSubMatrices() can extract ONLY sequential submatrices
6847: (from both sequential and parallel matrices). Use MatCreateSubMatrix()
6848: to extract a parallel submatrix.
6850: Some matrix types place restrictions on the row and column
6851: indices, such as that they be sorted or that they be equal to each other.
6853: The index sets may not have duplicate entries.
6855: When extracting submatrices from a parallel matrix, each processor can
6856: form a different submatrix by setting the rows and columns of its
6857: individual index sets according to the local submatrix desired.
6859: When finished using the submatrices, the user should destroy
6860: them with MatDestroySubMatrices().
6862: MAT_REUSE_MATRIX can only be used when the nonzero structure of the
6863: original matrix has not changed from that last call to MatCreateSubMatrices().
6865: This routine creates the matrices in submat; you should NOT create them before
6866: calling it. It also allocates the array of matrix pointers submat.
6868: For BAIJ matrices the index sets must respect the block structure, that is if they
6869: request one row/column in a block, they must request all rows/columns that are in
6870: that block. For example, if the block size is 2 you cannot request just row 0 and
6871: column 0.
6873: Fortran Note:
6874: The Fortran interface is slightly different from that given below; it
6875: requires one to pass in as submat a Mat (integer) array of size at least n+1.
6877: Level: advanced
6879: Concepts: matrices^accessing submatrices
6880: Concepts: submatrices
6882: .seealso: MatDestroySubMatrices(), MatCreateSubMatrix(), MatGetRow(), MatGetDiagonal(), MatReuse
6883: @*/
6884: PetscErrorCode MatCreateSubMatrices(Mat mat,PetscInt n,const IS irow[],const IS icol[],MatReuse scall,Mat *submat[])
6885: {
6887: PetscInt i;
6888: PetscBool eq;
6893: if (n) {
6898: }
6900: if (n && scall == MAT_REUSE_MATRIX) {
6903: }
6904: if (!mat->ops->createsubmatrices) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
6905: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6906: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6907: MatCheckPreallocated(mat,1);
6909: PetscLogEventBegin(MAT_CreateSubMats,mat,0,0,0);
6910: (*mat->ops->createsubmatrices)(mat,n,irow,icol,scall,submat);
6911: PetscLogEventEnd(MAT_CreateSubMats,mat,0,0,0);
6912: for (i=0; i<n; i++) {
6913: (*submat)[i]->factortype = MAT_FACTOR_NONE; /* in case in place factorization was previously done on submatrix */
6914: if (mat->symmetric || mat->structurally_symmetric || mat->hermitian) {
6915: ISEqual(irow[i],icol[i],&eq);
6916: if (eq) {
6917: if (mat->symmetric) {
6918: MatSetOption((*submat)[i],MAT_SYMMETRIC,PETSC_TRUE);
6919: } else if (mat->hermitian) {
6920: MatSetOption((*submat)[i],MAT_HERMITIAN,PETSC_TRUE);
6921: } else if (mat->structurally_symmetric) {
6922: MatSetOption((*submat)[i],MAT_STRUCTURALLY_SYMMETRIC,PETSC_TRUE);
6923: }
6924: }
6925: }
6926: }
6927: return(0);
6928: }
6930: /*@C
6931: MatCreateSubMatricesMPI - Extracts MPI submatrices across a sub communicator of mat (by pairs of IS that may live on subcomms).
6933: Collective on Mat
6935: Input Parameters:
6936: + mat - the matrix
6937: . n - the number of submatrixes to be extracted
6938: . irow, icol - index sets of rows and columns to extract
6939: - scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
6941: Output Parameter:
6942: . submat - the array of submatrices
6944: Level: advanced
6946: Concepts: matrices^accessing submatrices
6947: Concepts: submatrices
6949: .seealso: MatCreateSubMatrices(), MatCreateSubMatrix(), MatGetRow(), MatGetDiagonal(), MatReuse
6950: @*/
6951: PetscErrorCode MatCreateSubMatricesMPI(Mat mat,PetscInt n,const IS irow[],const IS icol[],MatReuse scall,Mat *submat[])
6952: {
6954: PetscInt i;
6955: PetscBool eq;
6960: if (n) {
6965: }
6967: if (n && scall == MAT_REUSE_MATRIX) {
6970: }
6971: if (!mat->ops->createsubmatricesmpi) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
6972: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6973: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6974: MatCheckPreallocated(mat,1);
6976: PetscLogEventBegin(MAT_CreateSubMats,mat,0,0,0);
6977: (*mat->ops->createsubmatricesmpi)(mat,n,irow,icol,scall,submat);
6978: PetscLogEventEnd(MAT_CreateSubMats,mat,0,0,0);
6979: for (i=0; i<n; i++) {
6980: if (mat->symmetric || mat->structurally_symmetric || mat->hermitian) {
6981: ISEqual(irow[i],icol[i],&eq);
6982: if (eq) {
6983: if (mat->symmetric) {
6984: MatSetOption((*submat)[i],MAT_SYMMETRIC,PETSC_TRUE);
6985: } else if (mat->hermitian) {
6986: MatSetOption((*submat)[i],MAT_HERMITIAN,PETSC_TRUE);
6987: } else if (mat->structurally_symmetric) {
6988: MatSetOption((*submat)[i],MAT_STRUCTURALLY_SYMMETRIC,PETSC_TRUE);
6989: }
6990: }
6991: }
6992: }
6993: return(0);
6994: }
6996: /*@C
6997: MatDestroyMatrices - Destroys an array of matrices.
6999: Collective on Mat
7001: Input Parameters:
7002: + n - the number of local matrices
7003: - mat - the matrices (note that this is a pointer to the array of matrices)
7005: Level: advanced
7007: Notes:
7008: Frees not only the matrices, but also the array that contains the matrices
7009: In Fortran will not free the array.
7011: .seealso: MatCreateSubMatrices() MatDestroySubMatrices()
7012: @*/
7013: PetscErrorCode MatDestroyMatrices(PetscInt n,Mat *mat[])
7014: {
7016: PetscInt i;
7019: if (!*mat) return(0);
7020: if (n < 0) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Trying to destroy negative number of matrices %D",n);
7023: for (i=0; i<n; i++) {
7024: MatDestroy(&(*mat)[i]);
7025: }
7027: /* memory is allocated even if n = 0 */
7028: PetscFree(*mat);
7029: return(0);
7030: }
7032: /*@C
7033: MatDestroySubMatrices - Destroys a set of matrices obtained with MatCreateSubMatrices().
7035: Collective on Mat
7037: Input Parameters:
7038: + n - the number of local matrices
7039: - mat - the matrices (note that this is a pointer to the array of matrices, just to match the calling
7040: sequence of MatCreateSubMatrices())
7042: Level: advanced
7044: Notes:
7045: Frees not only the matrices, but also the array that contains the matrices
7046: In Fortran will not free the array.
7048: .seealso: MatCreateSubMatrices()
7049: @*/
7050: PetscErrorCode MatDestroySubMatrices(PetscInt n,Mat *mat[])
7051: {
7053: Mat mat0;
7056: if (!*mat) return(0);
7057: /* mat[] is an array of length n+1, see MatCreateSubMatrices_xxx() */
7058: if (n < 0) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Trying to destroy negative number of matrices %D",n);
7061: mat0 = (*mat)[0];
7062: if (mat0 && mat0->ops->destroysubmatrices) {
7063: (mat0->ops->destroysubmatrices)(n,mat);
7064: } else {
7065: MatDestroyMatrices(n,mat);
7066: }
7067: return(0);
7068: }
7070: /*@C
7071: MatGetSeqNonzeroStructure - Extracts the sequential nonzero structure from a matrix.
7073: Collective on Mat
7075: Input Parameters:
7076: . mat - the matrix
7078: Output Parameter:
7079: . matstruct - the sequential matrix with the nonzero structure of mat
7081: Level: intermediate
7083: .seealso: MatDestroySeqNonzeroStructure(), MatCreateSubMatrices(), MatDestroyMatrices()
7084: @*/
7085: PetscErrorCode MatGetSeqNonzeroStructure(Mat mat,Mat *matstruct)
7086: {
7094: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
7095: MatCheckPreallocated(mat,1);
7097: if (!mat->ops->getseqnonzerostructure) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Not for matrix type %s\n",((PetscObject)mat)->type_name);
7098: PetscLogEventBegin(MAT_GetSeqNonzeroStructure,mat,0,0,0);
7099: (*mat->ops->getseqnonzerostructure)(mat,matstruct);
7100: PetscLogEventEnd(MAT_GetSeqNonzeroStructure,mat,0,0,0);
7101: return(0);
7102: }
7104: /*@C
7105: MatDestroySeqNonzeroStructure - Destroys matrix obtained with MatGetSeqNonzeroStructure().
7107: Collective on Mat
7109: Input Parameters:
7110: . mat - the matrix (note that this is a pointer to the array of matrices, just to match the calling
7111: sequence of MatGetSequentialNonzeroStructure())
7113: Level: advanced
7115: Notes:
7116: Frees not only the matrices, but also the array that contains the matrices
7118: .seealso: MatGetSeqNonzeroStructure()
7119: @*/
7120: PetscErrorCode MatDestroySeqNonzeroStructure(Mat *mat)
7121: {
7126: MatDestroy(mat);
7127: return(0);
7128: }
7130: /*@
7131: MatIncreaseOverlap - Given a set of submatrices indicated by index sets,
7132: replaces the index sets by larger ones that represent submatrices with
7133: additional overlap.
7135: Collective on Mat
7137: Input Parameters:
7138: + mat - the matrix
7139: . n - the number of index sets
7140: . is - the array of index sets (these index sets will changed during the call)
7141: - ov - the additional overlap requested
7143: Options Database:
7144: . -mat_increase_overlap_scalable - use a scalable algorithm to compute the overlap (supported by MPIAIJ matrix)
7146: Level: developer
7148: Concepts: overlap
7149: Concepts: ASM^computing overlap
7151: .seealso: MatCreateSubMatrices()
7152: @*/
7153: PetscErrorCode MatIncreaseOverlap(Mat mat,PetscInt n,IS is[],PetscInt ov)
7154: {
7160: if (n < 0) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Must have one or more domains, you have %D",n);
7161: if (n) {
7164: }
7165: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
7166: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
7167: MatCheckPreallocated(mat,1);
7169: if (!ov) return(0);
7170: if (!mat->ops->increaseoverlap) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
7171: PetscLogEventBegin(MAT_IncreaseOverlap,mat,0,0,0);
7172: (*mat->ops->increaseoverlap)(mat,n,is,ov);
7173: PetscLogEventEnd(MAT_IncreaseOverlap,mat,0,0,0);
7174: return(0);
7175: }
7178: PetscErrorCode MatIncreaseOverlapSplit_Single(Mat,IS*,PetscInt);
7180: /*@
7181: MatIncreaseOverlapSplit - Given a set of submatrices indicated by index sets across
7182: a sub communicator, replaces the index sets by larger ones that represent submatrices with
7183: additional overlap.
7185: Collective on Mat
7187: Input Parameters:
7188: + mat - the matrix
7189: . n - the number of index sets
7190: . is - the array of index sets (these index sets will changed during the call)
7191: - ov - the additional overlap requested
7193: Options Database:
7194: . -mat_increase_overlap_scalable - use a scalable algorithm to compute the overlap (supported by MPIAIJ matrix)
7196: Level: developer
7198: Concepts: overlap
7199: Concepts: ASM^computing overlap
7201: .seealso: MatCreateSubMatrices()
7202: @*/
7203: PetscErrorCode MatIncreaseOverlapSplit(Mat mat,PetscInt n,IS is[],PetscInt ov)
7204: {
7205: PetscInt i;
7211: if (n < 0) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Must have one or more domains, you have %D",n);
7212: if (n) {
7215: }
7216: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
7217: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
7218: MatCheckPreallocated(mat,1);
7219: if (!ov) return(0);
7220: PetscLogEventBegin(MAT_IncreaseOverlap,mat,0,0,0);
7221: for(i=0; i<n; i++){
7222: MatIncreaseOverlapSplit_Single(mat,&is[i],ov);
7223: }
7224: PetscLogEventEnd(MAT_IncreaseOverlap,mat,0,0,0);
7225: return(0);
7226: }
7231: /*@
7232: MatGetBlockSize - Returns the matrix block size.
7234: Not Collective
7236: Input Parameter:
7237: . mat - the matrix
7239: Output Parameter:
7240: . bs - block size
7242: Notes:
7243: Block row formats are MATSEQBAIJ, MATMPIBAIJ, MATSEQSBAIJ, MATMPISBAIJ. These formats ALWAYS have square block storage in the matrix.
7245: If the block size has not been set yet this routine returns 1.
7247: Level: intermediate
7249: Concepts: matrices^block size
7251: .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSizes()
7252: @*/
7253: PetscErrorCode MatGetBlockSize(Mat mat,PetscInt *bs)
7254: {
7258: *bs = PetscAbs(mat->rmap->bs);
7259: return(0);
7260: }
7262: /*@
7263: MatGetBlockSizes - Returns the matrix block row and column sizes.
7265: Not Collective
7267: Input Parameter:
7268: . mat - the matrix
7270: Output Parameter:
7271: . rbs - row block size
7272: . cbs - column block size
7274: Notes:
7275: Block row formats are MATSEQBAIJ, MATMPIBAIJ, MATSEQSBAIJ, MATMPISBAIJ. These formats ALWAYS have square block storage in the matrix.
7276: If you pass a different block size for the columns than the rows, the row block size determines the square block storage.
7278: If a block size has not been set yet this routine returns 1.
7280: Level: intermediate
7282: Concepts: matrices^block size
7284: .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSize(), MatSetBlockSize(), MatSetBlockSizes()
7285: @*/
7286: PetscErrorCode MatGetBlockSizes(Mat mat,PetscInt *rbs, PetscInt *cbs)
7287: {
7292: if (rbs) *rbs = PetscAbs(mat->rmap->bs);
7293: if (cbs) *cbs = PetscAbs(mat->cmap->bs);
7294: return(0);
7295: }
7297: /*@
7298: MatSetBlockSize - Sets the matrix block size.
7300: Logically Collective on Mat
7302: Input Parameters:
7303: + mat - the matrix
7304: - bs - block size
7306: Notes:
7307: Block row formats are MATSEQBAIJ, MATMPIBAIJ, MATSEQSBAIJ, MATMPISBAIJ. These formats ALWAYS have square block storage in the matrix.
7308: This must be called before MatSetUp() or MatXXXSetPreallocation() (or will default to 1) and the block size cannot be changed later.
7310: For MATMPIAIJ and MATSEQAIJ matrix formats, this function can be called at a later stage, provided that the specified block size
7311: is compatible with the matrix local sizes.
7313: Level: intermediate
7315: Concepts: matrices^block size
7317: .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSize(), MatSetBlockSizes(), MatGetBlockSizes()
7318: @*/
7319: PetscErrorCode MatSetBlockSize(Mat mat,PetscInt bs)
7320: {
7326: MatSetBlockSizes(mat,bs,bs);
7327: return(0);
7328: }
7330: /*@
7331: MatSetVariableBlockSizes - Sets a diagonal blocks of the matrix that need not be of the same size
7333: Logically Collective on Mat
7335: Input Parameters:
7336: + mat - the matrix
7337: . nblocks - the number of blocks on this process
7338: - bsizes - the block sizes
7340: Notes:
7341: Currently used by PCVPBJACOBI for SeqAIJ matrices
7343: Level: intermediate
7345: Concepts: matrices^block size
7347: .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSize(), MatSetBlockSizes(), MatGetBlockSizes(), MatGetVariableBlockSizes()
7348: @*/
7349: PetscErrorCode MatSetVariableBlockSizes(Mat mat,PetscInt nblocks,PetscInt *bsizes)
7350: {
7352: PetscInt i,ncnt = 0, nlocal;
7356: if (nblocks < 0) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Number of local blocks must be great than or equal to zero");
7357: MatGetLocalSize(mat,&nlocal,NULL);
7358: for (i=0; i<nblocks; i++) ncnt += bsizes[i];
7359: 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);
7360: PetscFree(mat->bsizes);
7361: mat->nblocks = nblocks;
7362: PetscMalloc1(nblocks,&mat->bsizes);
7363: PetscMemcpy(mat->bsizes,bsizes,nblocks*sizeof(PetscInt));
7364: return(0);
7365: }
7367: /*@C
7368: MatGetVariableBlockSizes - Gets a diagonal blocks of the matrix that need not be of the same size
7370: Logically Collective on Mat
7372: Input Parameters:
7373: . mat - the matrix
7375: Output Parameters:
7376: + nblocks - the number of blocks on this process
7377: - bsizes - the block sizes
7379: Notes: Currently not supported from Fortran
7381: Level: intermediate
7383: Concepts: matrices^block size
7385: .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSize(), MatSetBlockSizes(), MatGetBlockSizes(), MatSetVariableBlockSizes()
7386: @*/
7387: PetscErrorCode MatGetVariableBlockSizes(Mat mat,PetscInt *nblocks,const PetscInt **bsizes)
7388: {
7391: *nblocks = mat->nblocks;
7392: *bsizes = mat->bsizes;
7393: return(0);
7394: }
7396: /*@
7397: MatSetBlockSizes - Sets the matrix block row and column sizes.
7399: Logically Collective on Mat
7401: Input Parameters:
7402: + mat - the matrix
7403: - rbs - row block size
7404: - cbs - column block size
7406: Notes:
7407: Block row formats are MATSEQBAIJ, MATMPIBAIJ, MATSEQSBAIJ, MATMPISBAIJ. These formats ALWAYS have square block storage in the matrix.
7408: If you pass a different block size for the columns than the rows, the row block size determines the square block storage.
7409: This must be called before MatSetUp() or MatXXXSetPreallocation() (or will default to 1) and the block size cannot be changed later
7411: For MATMPIAIJ and MATSEQAIJ matrix formats, this function can be called at a later stage, provided that the specified block sizes
7412: are compatible with the matrix local sizes.
7414: The row and column block size determine the blocksize of the "row" and "column" vectors returned by MatCreateVecs().
7416: Level: intermediate
7418: Concepts: matrices^block size
7420: .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSize(), MatSetBlockSize(), MatGetBlockSizes()
7421: @*/
7422: PetscErrorCode MatSetBlockSizes(Mat mat,PetscInt rbs,PetscInt cbs)
7423: {
7430: if (mat->ops->setblocksizes) {
7431: (*mat->ops->setblocksizes)(mat,rbs,cbs);
7432: }
7433: if (mat->rmap->refcnt) {
7434: ISLocalToGlobalMapping l2g = NULL;
7435: PetscLayout nmap = NULL;
7437: PetscLayoutDuplicate(mat->rmap,&nmap);
7438: if (mat->rmap->mapping) {
7439: ISLocalToGlobalMappingDuplicate(mat->rmap->mapping,&l2g);
7440: }
7441: PetscLayoutDestroy(&mat->rmap);
7442: mat->rmap = nmap;
7443: mat->rmap->mapping = l2g;
7444: }
7445: if (mat->cmap->refcnt) {
7446: ISLocalToGlobalMapping l2g = NULL;
7447: PetscLayout nmap = NULL;
7449: PetscLayoutDuplicate(mat->cmap,&nmap);
7450: if (mat->cmap->mapping) {
7451: ISLocalToGlobalMappingDuplicate(mat->cmap->mapping,&l2g);
7452: }
7453: PetscLayoutDestroy(&mat->cmap);
7454: mat->cmap = nmap;
7455: mat->cmap->mapping = l2g;
7456: }
7457: PetscLayoutSetBlockSize(mat->rmap,rbs);
7458: PetscLayoutSetBlockSize(mat->cmap,cbs);
7459: return(0);
7460: }
7462: /*@
7463: MatSetBlockSizesFromMats - Sets the matrix block row and column sizes to match a pair of matrices
7465: Logically Collective on Mat
7467: Input Parameters:
7468: + mat - the matrix
7469: . fromRow - matrix from which to copy row block size
7470: - fromCol - matrix from which to copy column block size (can be same as fromRow)
7472: Level: developer
7474: Concepts: matrices^block size
7476: .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSize(), MatSetBlockSizes()
7477: @*/
7478: PetscErrorCode MatSetBlockSizesFromMats(Mat mat,Mat fromRow,Mat fromCol)
7479: {
7486: if (fromRow->rmap->bs > 0) {PetscLayoutSetBlockSize(mat->rmap,fromRow->rmap->bs);}
7487: if (fromCol->cmap->bs > 0) {PetscLayoutSetBlockSize(mat->cmap,fromCol->cmap->bs);}
7488: return(0);
7489: }
7491: /*@
7492: MatResidual - Default routine to calculate the residual.
7494: Collective on Mat and Vec
7496: Input Parameters:
7497: + mat - the matrix
7498: . b - the right-hand-side
7499: - x - the approximate solution
7501: Output Parameter:
7502: . r - location to store the residual
7504: Level: developer
7506: .keywords: MG, default, multigrid, residual
7508: .seealso: PCMGSetResidual()
7509: @*/
7510: PetscErrorCode MatResidual(Mat mat,Vec b,Vec x,Vec r)
7511: {
7520: MatCheckPreallocated(mat,1);
7521: PetscLogEventBegin(MAT_Residual,mat,0,0,0);
7522: if (!mat->ops->residual) {
7523: MatMult(mat,x,r);
7524: VecAYPX(r,-1.0,b);
7525: } else {
7526: (*mat->ops->residual)(mat,b,x,r);
7527: }
7528: PetscLogEventEnd(MAT_Residual,mat,0,0,0);
7529: return(0);
7530: }
7532: /*@C
7533: MatGetRowIJ - Returns the compressed row storage i and j indices for sequential matrices.
7535: Collective on Mat
7537: Input Parameters:
7538: + mat - the matrix
7539: . shift - 0 or 1 indicating we want the indices starting at 0 or 1
7540: . symmetric - PETSC_TRUE or PETSC_FALSE indicating the matrix data structure should be symmetrized
7541: - inodecompressed - PETSC_TRUE or PETSC_FALSE indicating if the nonzero structure of the
7542: inodes or the nonzero elements is wanted. For BAIJ matrices the compressed version is
7543: always used.
7545: Output Parameters:
7546: + n - number of rows in the (possibly compressed) matrix
7547: . ia - the row pointers; that is ia[0] = 0, ia[row] = ia[row-1] + number of elements in that row of the matrix
7548: . ja - the column indices
7549: - done - indicates if the routine actually worked and returned appropriate ia[] and ja[] arrays; callers
7550: are responsible for handling the case when done == PETSC_FALSE and ia and ja are not set
7552: Level: developer
7554: Notes:
7555: You CANNOT change any of the ia[] or ja[] values.
7557: Use MatRestoreRowIJ() when you are finished accessing the ia[] and ja[] values.
7559: Fortran Notes:
7560: In Fortran use
7561: $
7562: $ PetscInt ia(1), ja(1)
7563: $ PetscOffset iia, jja
7564: $ call MatGetRowIJ(mat,shift,symmetric,inodecompressed,n,ia,iia,ja,jja,done,ierr)
7565: $ ! Access the ith and jth entries via ia(iia + i) and ja(jja + j)
7567: or
7568: $
7569: $ PetscInt, pointer :: ia(:),ja(:)
7570: $ call MatGetRowIJF90(mat,shift,symmetric,inodecompressed,n,ia,ja,done,ierr)
7571: $ ! Access the ith and jth entries via ia(i) and ja(j)
7573: .seealso: MatGetColumnIJ(), MatRestoreRowIJ(), MatSeqAIJGetArray()
7574: @*/
7575: PetscErrorCode MatGetRowIJ(Mat mat,PetscInt shift,PetscBool symmetric,PetscBool inodecompressed,PetscInt *n,const PetscInt *ia[],const PetscInt *ja[],PetscBool *done)
7576: {
7586: MatCheckPreallocated(mat,1);
7587: if (!mat->ops->getrowij) *done = PETSC_FALSE;
7588: else {
7589: *done = PETSC_TRUE;
7590: PetscLogEventBegin(MAT_GetRowIJ,mat,0,0,0);
7591: (*mat->ops->getrowij)(mat,shift,symmetric,inodecompressed,n,ia,ja,done);
7592: PetscLogEventEnd(MAT_GetRowIJ,mat,0,0,0);
7593: }
7594: return(0);
7595: }
7597: /*@C
7598: MatGetColumnIJ - Returns the compressed column storage i and j indices for sequential matrices.
7600: Collective on Mat
7602: Input Parameters:
7603: + mat - the matrix
7604: . shift - 1 or zero indicating we want the indices starting at 0 or 1
7605: . symmetric - PETSC_TRUE or PETSC_FALSE indicating the matrix data structure should be
7606: symmetrized
7607: . inodecompressed - PETSC_TRUE or PETSC_FALSE indicating if the nonzero structure of the
7608: inodes or the nonzero elements is wanted. For BAIJ matrices the compressed version is
7609: always used.
7610: . n - number of columns in the (possibly compressed) matrix
7611: . ia - the column pointers; that is ia[0] = 0, ia[col] = i[col-1] + number of elements in that col of the matrix
7612: - ja - the row indices
7614: Output Parameters:
7615: . done - PETSC_TRUE or PETSC_FALSE, indicating whether the values have been returned
7617: Level: developer
7619: .seealso: MatGetRowIJ(), MatRestoreColumnIJ()
7620: @*/
7621: PetscErrorCode MatGetColumnIJ(Mat mat,PetscInt shift,PetscBool symmetric,PetscBool inodecompressed,PetscInt *n,const PetscInt *ia[],const PetscInt *ja[],PetscBool *done)
7622: {
7632: MatCheckPreallocated(mat,1);
7633: if (!mat->ops->getcolumnij) *done = PETSC_FALSE;
7634: else {
7635: *done = PETSC_TRUE;
7636: (*mat->ops->getcolumnij)(mat,shift,symmetric,inodecompressed,n,ia,ja,done);
7637: }
7638: return(0);
7639: }
7641: /*@C
7642: MatRestoreRowIJ - Call after you are completed with the ia,ja indices obtained with
7643: MatGetRowIJ().
7645: Collective on Mat
7647: Input Parameters:
7648: + mat - the matrix
7649: . shift - 1 or zero indicating we want the indices starting at 0 or 1
7650: . symmetric - PETSC_TRUE or PETSC_FALSE indicating the matrix data structure should be
7651: symmetrized
7652: . inodecompressed - PETSC_TRUE or PETSC_FALSE indicating if the nonzero structure of the
7653: inodes or the nonzero elements is wanted. For BAIJ matrices the compressed version is
7654: always used.
7655: . n - size of (possibly compressed) matrix
7656: . ia - the row pointers
7657: - ja - the column indices
7659: Output Parameters:
7660: . done - PETSC_TRUE or PETSC_FALSE indicated that the values have been returned
7662: Note:
7663: This routine zeros out n, ia, and ja. This is to prevent accidental
7664: us of the array after it has been restored. If you pass NULL, it will
7665: not zero the pointers. Use of ia or ja after MatRestoreRowIJ() is invalid.
7667: Level: developer
7669: .seealso: MatGetRowIJ(), MatRestoreColumnIJ()
7670: @*/
7671: PetscErrorCode MatRestoreRowIJ(Mat mat,PetscInt shift,PetscBool symmetric,PetscBool inodecompressed,PetscInt *n,const PetscInt *ia[],const PetscInt *ja[],PetscBool *done)
7672: {
7681: MatCheckPreallocated(mat,1);
7683: if (!mat->ops->restorerowij) *done = PETSC_FALSE;
7684: else {
7685: *done = PETSC_TRUE;
7686: (*mat->ops->restorerowij)(mat,shift,symmetric,inodecompressed,n,ia,ja,done);
7687: if (n) *n = 0;
7688: if (ia) *ia = NULL;
7689: if (ja) *ja = NULL;
7690: }
7691: return(0);
7692: }
7694: /*@C
7695: MatRestoreColumnIJ - Call after you are completed with the ia,ja indices obtained with
7696: MatGetColumnIJ().
7698: Collective on Mat
7700: Input Parameters:
7701: + mat - the matrix
7702: . shift - 1 or zero indicating we want the indices starting at 0 or 1
7703: - symmetric - PETSC_TRUE or PETSC_FALSE indicating the matrix data structure should be
7704: symmetrized
7705: - inodecompressed - PETSC_TRUE or PETSC_FALSE indicating if the nonzero structure of the
7706: inodes or the nonzero elements is wanted. For BAIJ matrices the compressed version is
7707: always used.
7709: Output Parameters:
7710: + n - size of (possibly compressed) matrix
7711: . ia - the column pointers
7712: . ja - the row indices
7713: - done - PETSC_TRUE or PETSC_FALSE indicated that the values have been returned
7715: Level: developer
7717: .seealso: MatGetColumnIJ(), MatRestoreRowIJ()
7718: @*/
7719: PetscErrorCode MatRestoreColumnIJ(Mat mat,PetscInt shift,PetscBool symmetric,PetscBool inodecompressed,PetscInt *n,const PetscInt *ia[],const PetscInt *ja[],PetscBool *done)
7720: {
7729: MatCheckPreallocated(mat,1);
7731: if (!mat->ops->restorecolumnij) *done = PETSC_FALSE;
7732: else {
7733: *done = PETSC_TRUE;
7734: (*mat->ops->restorecolumnij)(mat,shift,symmetric,inodecompressed,n,ia,ja,done);
7735: if (n) *n = 0;
7736: if (ia) *ia = NULL;
7737: if (ja) *ja = NULL;
7738: }
7739: return(0);
7740: }
7742: /*@C
7743: MatColoringPatch -Used inside matrix coloring routines that
7744: use MatGetRowIJ() and/or MatGetColumnIJ().
7746: Collective on Mat
7748: Input Parameters:
7749: + mat - the matrix
7750: . ncolors - max color value
7751: . n - number of entries in colorarray
7752: - colorarray - array indicating color for each column
7754: Output Parameters:
7755: . iscoloring - coloring generated using colorarray information
7757: Level: developer
7759: .seealso: MatGetRowIJ(), MatGetColumnIJ()
7761: @*/
7762: PetscErrorCode MatColoringPatch(Mat mat,PetscInt ncolors,PetscInt n,ISColoringValue colorarray[],ISColoring *iscoloring)
7763: {
7771: MatCheckPreallocated(mat,1);
7773: if (!mat->ops->coloringpatch) {
7774: ISColoringCreate(PetscObjectComm((PetscObject)mat),ncolors,n,colorarray,PETSC_OWN_POINTER,iscoloring);
7775: } else {
7776: (*mat->ops->coloringpatch)(mat,ncolors,n,colorarray,iscoloring);
7777: }
7778: return(0);
7779: }
7782: /*@
7783: MatSetUnfactored - Resets a factored matrix to be treated as unfactored.
7785: Logically Collective on Mat
7787: Input Parameter:
7788: . mat - the factored matrix to be reset
7790: Notes:
7791: This routine should be used only with factored matrices formed by in-place
7792: factorization via ILU(0) (or by in-place LU factorization for the MATSEQDENSE
7793: format). This option can save memory, for example, when solving nonlinear
7794: systems with a matrix-free Newton-Krylov method and a matrix-based, in-place
7795: ILU(0) preconditioner.
7797: Note that one can specify in-place ILU(0) factorization by calling
7798: .vb
7799: PCType(pc,PCILU);
7800: PCFactorSeUseInPlace(pc);
7801: .ve
7802: or by using the options -pc_type ilu -pc_factor_in_place
7804: In-place factorization ILU(0) can also be used as a local
7805: solver for the blocks within the block Jacobi or additive Schwarz
7806: methods (runtime option: -sub_pc_factor_in_place). See Users-Manual: ch_pc
7807: for details on setting local solver options.
7809: Most users should employ the simplified KSP interface for linear solvers
7810: instead of working directly with matrix algebra routines such as this.
7811: See, e.g., KSPCreate().
7813: Level: developer
7815: .seealso: PCFactorSetUseInPlace(), PCFactorGetUseInPlace()
7817: Concepts: matrices^unfactored
7819: @*/
7820: PetscErrorCode MatSetUnfactored(Mat mat)
7821: {
7827: MatCheckPreallocated(mat,1);
7828: mat->factortype = MAT_FACTOR_NONE;
7829: if (!mat->ops->setunfactored) return(0);
7830: (*mat->ops->setunfactored)(mat);
7831: return(0);
7832: }
7834: /*MC
7835: MatDenseGetArrayF90 - Accesses a matrix array from Fortran90.
7837: Synopsis:
7838: MatDenseGetArrayF90(Mat x,{Scalar, pointer :: xx_v(:,:)},integer ierr)
7840: Not collective
7842: Input Parameter:
7843: . x - matrix
7845: Output Parameters:
7846: + xx_v - the Fortran90 pointer to the array
7847: - ierr - error code
7849: Example of Usage:
7850: .vb
7851: PetscScalar, pointer xx_v(:,:)
7852: ....
7853: call MatDenseGetArrayF90(x,xx_v,ierr)
7854: a = xx_v(3)
7855: call MatDenseRestoreArrayF90(x,xx_v,ierr)
7856: .ve
7858: Level: advanced
7860: .seealso: MatDenseRestoreArrayF90(), MatDenseGetArray(), MatDenseRestoreArray(), MatSeqAIJGetArrayF90()
7862: Concepts: matrices^accessing array
7864: M*/
7866: /*MC
7867: MatDenseRestoreArrayF90 - Restores a matrix array that has been
7868: accessed with MatDenseGetArrayF90().
7870: Synopsis:
7871: MatDenseRestoreArrayF90(Mat x,{Scalar, pointer :: xx_v(:,:)},integer ierr)
7873: Not collective
7875: Input Parameters:
7876: + x - matrix
7877: - xx_v - the Fortran90 pointer to the array
7879: Output Parameter:
7880: . ierr - error code
7882: Example of Usage:
7883: .vb
7884: PetscScalar, pointer xx_v(:,:)
7885: ....
7886: call MatDenseGetArrayF90(x,xx_v,ierr)
7887: a = xx_v(3)
7888: call MatDenseRestoreArrayF90(x,xx_v,ierr)
7889: .ve
7891: Level: advanced
7893: .seealso: MatDenseGetArrayF90(), MatDenseGetArray(), MatDenseRestoreArray(), MatSeqAIJRestoreArrayF90()
7895: M*/
7898: /*MC
7899: MatSeqAIJGetArrayF90 - Accesses a matrix array from Fortran90.
7901: Synopsis:
7902: MatSeqAIJGetArrayF90(Mat x,{Scalar, pointer :: xx_v(:)},integer ierr)
7904: Not collective
7906: Input Parameter:
7907: . x - matrix
7909: Output Parameters:
7910: + xx_v - the Fortran90 pointer to the array
7911: - ierr - error code
7913: Example of Usage:
7914: .vb
7915: PetscScalar, pointer xx_v(:)
7916: ....
7917: call MatSeqAIJGetArrayF90(x,xx_v,ierr)
7918: a = xx_v(3)
7919: call MatSeqAIJRestoreArrayF90(x,xx_v,ierr)
7920: .ve
7922: Level: advanced
7924: .seealso: MatSeqAIJRestoreArrayF90(), MatSeqAIJGetArray(), MatSeqAIJRestoreArray(), MatDenseGetArrayF90()
7926: Concepts: matrices^accessing array
7928: M*/
7930: /*MC
7931: MatSeqAIJRestoreArrayF90 - Restores a matrix array that has been
7932: accessed with MatSeqAIJGetArrayF90().
7934: Synopsis:
7935: MatSeqAIJRestoreArrayF90(Mat x,{Scalar, pointer :: xx_v(:)},integer ierr)
7937: Not collective
7939: Input Parameters:
7940: + x - matrix
7941: - xx_v - the Fortran90 pointer to the array
7943: Output Parameter:
7944: . ierr - error code
7946: Example of Usage:
7947: .vb
7948: PetscScalar, pointer xx_v(:)
7949: ....
7950: call MatSeqAIJGetArrayF90(x,xx_v,ierr)
7951: a = xx_v(3)
7952: call MatSeqAIJRestoreArrayF90(x,xx_v,ierr)
7953: .ve
7955: Level: advanced
7957: .seealso: MatSeqAIJGetArrayF90(), MatSeqAIJGetArray(), MatSeqAIJRestoreArray(), MatDenseRestoreArrayF90()
7959: M*/
7962: /*@
7963: MatCreateSubMatrix - Gets a single submatrix on the same number of processors
7964: as the original matrix.
7966: Collective on Mat
7968: Input Parameters:
7969: + mat - the original matrix
7970: . isrow - parallel IS containing the rows this processor should obtain
7971: . 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.
7972: - cll - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
7974: Output Parameter:
7975: . newmat - the new submatrix, of the same type as the old
7977: Level: advanced
7979: Notes:
7980: The submatrix will be able to be multiplied with vectors using the same layout as iscol.
7982: Some matrix types place restrictions on the row and column indices, such
7983: as that they be sorted or that they be equal to each other.
7985: The index sets may not have duplicate entries.
7987: The first time this is called you should use a cll of MAT_INITIAL_MATRIX,
7988: the MatCreateSubMatrix() routine will create the newmat for you. Any additional calls
7989: to this routine with a mat of the same nonzero structure and with a call of MAT_REUSE_MATRIX
7990: will reuse the matrix generated the first time. You should call MatDestroy() on newmat when
7991: you are finished using it.
7993: The communicator of the newly obtained matrix is ALWAYS the same as the communicator of
7994: the input matrix.
7996: If iscol is NULL then all columns are obtained (not supported in Fortran).
7998: Example usage:
7999: Consider the following 8x8 matrix with 34 non-zero values, that is
8000: assembled across 3 processors. Let's assume that proc0 owns 3 rows,
8001: proc1 owns 3 rows, proc2 owns 2 rows. This division can be shown
8002: as follows:
8004: .vb
8005: 1 2 0 | 0 3 0 | 0 4
8006: Proc0 0 5 6 | 7 0 0 | 8 0
8007: 9 0 10 | 11 0 0 | 12 0
8008: -------------------------------------
8009: 13 0 14 | 15 16 17 | 0 0
8010: Proc1 0 18 0 | 19 20 21 | 0 0
8011: 0 0 0 | 22 23 0 | 24 0
8012: -------------------------------------
8013: Proc2 25 26 27 | 0 0 28 | 29 0
8014: 30 0 0 | 31 32 33 | 0 34
8015: .ve
8017: Suppose isrow = [0 1 | 4 | 6 7] and iscol = [1 2 | 3 4 5 | 6]. The resulting submatrix is
8019: .vb
8020: 2 0 | 0 3 0 | 0
8021: Proc0 5 6 | 7 0 0 | 8
8022: -------------------------------
8023: Proc1 18 0 | 19 20 21 | 0
8024: -------------------------------
8025: Proc2 26 27 | 0 0 28 | 29
8026: 0 0 | 31 32 33 | 0
8027: .ve
8030: Concepts: matrices^submatrices
8032: .seealso: MatCreateSubMatrices()
8033: @*/
8034: PetscErrorCode MatCreateSubMatrix(Mat mat,IS isrow,IS iscol,MatReuse cll,Mat *newmat)
8035: {
8037: PetscMPIInt size;
8038: Mat *local;
8039: IS iscoltmp;
8048: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
8049: if (cll == MAT_IGNORE_MATRIX) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Cannot use MAT_IGNORE_MATRIX");
8051: MatCheckPreallocated(mat,1);
8052: MPI_Comm_size(PetscObjectComm((PetscObject)mat),&size);
8054: if (!iscol || isrow == iscol) {
8055: PetscBool stride;
8056: PetscMPIInt grabentirematrix = 0,grab;
8057: PetscObjectTypeCompare((PetscObject)isrow,ISSTRIDE,&stride);
8058: if (stride) {
8059: PetscInt first,step,n,rstart,rend;
8060: ISStrideGetInfo(isrow,&first,&step);
8061: if (step == 1) {
8062: MatGetOwnershipRange(mat,&rstart,&rend);
8063: if (rstart == first) {
8064: ISGetLocalSize(isrow,&n);
8065: if (n == rend-rstart) {
8066: grabentirematrix = 1;
8067: }
8068: }
8069: }
8070: }
8071: MPIU_Allreduce(&grabentirematrix,&grab,1,MPI_INT,MPI_MIN,PetscObjectComm((PetscObject)mat));
8072: if (grab) {
8073: PetscInfo(mat,"Getting entire matrix as submatrix\n");
8074: if (cll == MAT_INITIAL_MATRIX) {
8075: *newmat = mat;
8076: PetscObjectReference((PetscObject)mat);
8077: }
8078: return(0);
8079: }
8080: }
8082: if (!iscol) {
8083: ISCreateStride(PetscObjectComm((PetscObject)mat),mat->cmap->n,mat->cmap->rstart,1,&iscoltmp);
8084: } else {
8085: iscoltmp = iscol;
8086: }
8088: /* if original matrix is on just one processor then use submatrix generated */
8089: if (mat->ops->createsubmatrices && !mat->ops->createsubmatrix && size == 1 && cll == MAT_REUSE_MATRIX) {
8090: MatCreateSubMatrices(mat,1,&isrow,&iscoltmp,MAT_REUSE_MATRIX,&newmat);
8091: goto setproperties;
8092: } else if (mat->ops->createsubmatrices && !mat->ops->createsubmatrix && size == 1) {
8093: MatCreateSubMatrices(mat,1,&isrow,&iscoltmp,MAT_INITIAL_MATRIX,&local);
8094: *newmat = *local;
8095: PetscFree(local);
8096: goto setproperties;
8097: } else if (!mat->ops->createsubmatrix) {
8098: /* Create a new matrix type that implements the operation using the full matrix */
8099: PetscLogEventBegin(MAT_CreateSubMat,mat,0,0,0);
8100: switch (cll) {
8101: case MAT_INITIAL_MATRIX:
8102: MatCreateSubMatrixVirtual(mat,isrow,iscoltmp,newmat);
8103: break;
8104: case MAT_REUSE_MATRIX:
8105: MatSubMatrixVirtualUpdate(*newmat,mat,isrow,iscoltmp);
8106: break;
8107: default: SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_OUTOFRANGE,"Invalid MatReuse, must be either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX");
8108: }
8109: PetscLogEventEnd(MAT_CreateSubMat,mat,0,0,0);
8110: goto setproperties;
8111: }
8113: if (!mat->ops->createsubmatrix) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
8114: PetscLogEventBegin(MAT_CreateSubMat,mat,0,0,0);
8115: (*mat->ops->createsubmatrix)(mat,isrow,iscoltmp,cll,newmat);
8116: PetscLogEventEnd(MAT_CreateSubMat,mat,0,0,0);
8118: /* Propagate symmetry information for diagonal blocks */
8119: setproperties:
8120: if (isrow == iscoltmp) {
8121: if (mat->symmetric_set && mat->symmetric) {
8122: MatSetOption(*newmat,MAT_SYMMETRIC,PETSC_TRUE);
8123: }
8124: if (mat->structurally_symmetric_set && mat->structurally_symmetric) {
8125: MatSetOption(*newmat,MAT_STRUCTURALLY_SYMMETRIC,PETSC_TRUE);
8126: }
8127: if (mat->hermitian_set && mat->hermitian) {
8128: MatSetOption(*newmat,MAT_HERMITIAN,PETSC_TRUE);
8129: }
8130: if (mat->spd_set && mat->spd) {
8131: MatSetOption(*newmat,MAT_SPD,PETSC_TRUE);
8132: }
8133: }
8135: if (!iscol) {ISDestroy(&iscoltmp);}
8136: if (*newmat && cll == MAT_INITIAL_MATRIX) {PetscObjectStateIncrease((PetscObject)*newmat);}
8137: return(0);
8138: }
8140: /*@
8141: MatStashSetInitialSize - sets the sizes of the matrix stash, that is
8142: used during the assembly process to store values that belong to
8143: other processors.
8145: Not Collective
8147: Input Parameters:
8148: + mat - the matrix
8149: . size - the initial size of the stash.
8150: - bsize - the initial size of the block-stash(if used).
8152: Options Database Keys:
8153: + -matstash_initial_size <size> or <size0,size1,...sizep-1>
8154: - -matstash_block_initial_size <bsize> or <bsize0,bsize1,...bsizep-1>
8156: Level: intermediate
8158: Notes:
8159: The block-stash is used for values set with MatSetValuesBlocked() while
8160: the stash is used for values set with MatSetValues()
8162: Run with the option -info and look for output of the form
8163: MatAssemblyBegin_MPIXXX:Stash has MM entries, uses nn mallocs.
8164: to determine the appropriate value, MM, to use for size and
8165: MatAssemblyBegin_MPIXXX:Block-Stash has BMM entries, uses nn mallocs.
8166: to determine the value, BMM to use for bsize
8168: Concepts: stash^setting matrix size
8169: Concepts: matrices^stash
8171: .seealso: MatAssemblyBegin(), MatAssemblyEnd(), Mat, MatStashGetInfo()
8173: @*/
8174: PetscErrorCode MatStashSetInitialSize(Mat mat,PetscInt size, PetscInt bsize)
8175: {
8181: MatStashSetInitialSize_Private(&mat->stash,size);
8182: MatStashSetInitialSize_Private(&mat->bstash,bsize);
8183: return(0);
8184: }
8186: /*@
8187: MatInterpolateAdd - w = y + A*x or A'*x depending on the shape of
8188: the matrix
8190: Neighbor-wise Collective on Mat
8192: Input Parameters:
8193: + mat - the matrix
8194: . x,y - the vectors
8195: - w - where the result is stored
8197: Level: intermediate
8199: Notes:
8200: w may be the same vector as y.
8202: This allows one to use either the restriction or interpolation (its transpose)
8203: matrix to do the interpolation
8205: Concepts: interpolation
8207: .seealso: MatMultAdd(), MatMultTransposeAdd(), MatRestrict()
8209: @*/
8210: PetscErrorCode MatInterpolateAdd(Mat A,Vec x,Vec y,Vec w)
8211: {
8213: PetscInt M,N,Ny;
8221: MatCheckPreallocated(A,1);
8222: MatGetSize(A,&M,&N);
8223: VecGetSize(y,&Ny);
8224: if (M == Ny) {
8225: MatMultAdd(A,x,y,w);
8226: } else {
8227: MatMultTransposeAdd(A,x,y,w);
8228: }
8229: return(0);
8230: }
8232: /*@
8233: MatInterpolate - y = A*x or A'*x depending on the shape of
8234: the matrix
8236: Neighbor-wise Collective on Mat
8238: Input Parameters:
8239: + mat - the matrix
8240: - x,y - the vectors
8242: Level: intermediate
8244: Notes:
8245: This allows one to use either the restriction or interpolation (its transpose)
8246: matrix to do the interpolation
8248: Concepts: matrices^interpolation
8250: .seealso: MatMultAdd(), MatMultTransposeAdd(), MatRestrict()
8252: @*/
8253: PetscErrorCode MatInterpolate(Mat A,Vec x,Vec y)
8254: {
8256: PetscInt M,N,Ny;
8263: MatCheckPreallocated(A,1);
8264: MatGetSize(A,&M,&N);
8265: VecGetSize(y,&Ny);
8266: if (M == Ny) {
8267: MatMult(A,x,y);
8268: } else {
8269: MatMultTranspose(A,x,y);
8270: }
8271: return(0);
8272: }
8274: /*@
8275: MatRestrict - y = A*x or A'*x
8277: Neighbor-wise Collective on Mat
8279: Input Parameters:
8280: + mat - the matrix
8281: - x,y - the vectors
8283: Level: intermediate
8285: Notes:
8286: This allows one to use either the restriction or interpolation (its transpose)
8287: matrix to do the restriction
8289: Concepts: matrices^restriction
8291: .seealso: MatMultAdd(), MatMultTransposeAdd(), MatInterpolate()
8293: @*/
8294: PetscErrorCode MatRestrict(Mat A,Vec x,Vec y)
8295: {
8297: PetscInt M,N,Ny;
8304: MatCheckPreallocated(A,1);
8306: MatGetSize(A,&M,&N);
8307: VecGetSize(y,&Ny);
8308: if (M == Ny) {
8309: MatMult(A,x,y);
8310: } else {
8311: MatMultTranspose(A,x,y);
8312: }
8313: return(0);
8314: }
8316: /*@
8317: MatGetNullSpace - retrieves the null space of a matrix.
8319: Logically Collective on Mat and MatNullSpace
8321: Input Parameters:
8322: + mat - the matrix
8323: - nullsp - the null space object
8325: Level: developer
8327: Concepts: null space^attaching to matrix
8329: .seealso: MatCreate(), MatNullSpaceCreate(), MatSetNearNullSpace(), MatSetNullSpace()
8330: @*/
8331: PetscErrorCode MatGetNullSpace(Mat mat, MatNullSpace *nullsp)
8332: {
8336: *nullsp = (mat->symmetric_set && mat->symmetric && !mat->nullsp) ? mat->transnullsp : mat->nullsp;
8337: return(0);
8338: }
8340: /*@
8341: MatSetNullSpace - attaches a null space to a matrix.
8343: Logically Collective on Mat and MatNullSpace
8345: Input Parameters:
8346: + mat - the matrix
8347: - nullsp - the null space object
8349: Level: advanced
8351: Notes:
8352: This null space is used by the linear solvers. Overwrites any previous null space that may have been attached
8354: For inconsistent singular systems (linear systems where the right hand side is not in the range of the operator) you also likely should
8355: call MatSetTransposeNullSpace(). This allows the linear system to be solved in a least squares sense.
8357: You can remove the null space by calling this routine with an nullsp of NULL
8360: The fundamental theorem of linear algebra (Gilbert Strang, Introduction to Applied Mathematics, page 72) states that
8361: 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).
8362: 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
8363: 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
8364: 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).
8366: Krylov solvers can produce the minimal norm solution to the least squares problem by utilizing MatNullSpaceRemove().
8368: 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
8369: routine also automatically calls MatSetTransposeNullSpace().
8371: Concepts: null space^attaching to matrix
8373: .seealso: MatCreate(), MatNullSpaceCreate(), MatSetNearNullSpace(), MatGetNullSpace(), MatSetTransposeNullSpace(), MatGetTransposeNullSpace(), MatNullSpaceRemove()
8374: @*/
8375: PetscErrorCode MatSetNullSpace(Mat mat,MatNullSpace nullsp)
8376: {
8382: if (nullsp) {PetscObjectReference((PetscObject)nullsp);}
8383: MatNullSpaceDestroy(&mat->nullsp);
8384: mat->nullsp = nullsp;
8385: if (mat->symmetric_set && mat->symmetric) {
8386: MatSetTransposeNullSpace(mat,nullsp);
8387: }
8388: return(0);
8389: }
8391: /*@
8392: MatGetTransposeNullSpace - retrieves the null space of the transpose of a matrix.
8394: Logically Collective on Mat and MatNullSpace
8396: Input Parameters:
8397: + mat - the matrix
8398: - nullsp - the null space object
8400: Level: developer
8402: Concepts: null space^attaching to matrix
8404: .seealso: MatCreate(), MatNullSpaceCreate(), MatSetNearNullSpace(), MatSetTransposeNullSpace(), MatSetNullSpace(), MatGetNullSpace()
8405: @*/
8406: PetscErrorCode MatGetTransposeNullSpace(Mat mat, MatNullSpace *nullsp)
8407: {
8412: *nullsp = (mat->symmetric_set && mat->symmetric && !mat->transnullsp) ? mat->nullsp : mat->transnullsp;
8413: return(0);
8414: }
8416: /*@
8417: MatSetTransposeNullSpace - attaches a null space to a matrix.
8419: Logically Collective on Mat and MatNullSpace
8421: Input Parameters:
8422: + mat - the matrix
8423: - nullsp - the null space object
8425: Level: advanced
8427: Notes:
8428: 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.
8429: You must also call MatSetNullSpace()
8432: The fundamental theorem of linear algebra (Gilbert Strang, Introduction to Applied Mathematics, page 72) states that
8433: 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).
8434: 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
8435: 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
8436: 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).
8438: Krylov solvers can produce the minimal norm solution to the least squares problem by utilizing MatNullSpaceRemove().
8440: Concepts: null space^attaching to matrix
8442: .seealso: MatCreate(), MatNullSpaceCreate(), MatSetNearNullSpace(), MatGetNullSpace(), MatSetNullSpace(), MatGetTransposeNullSpace(), MatNullSpaceRemove()
8443: @*/
8444: PetscErrorCode MatSetTransposeNullSpace(Mat mat,MatNullSpace nullsp)
8445: {
8451: if (nullsp) {PetscObjectReference((PetscObject)nullsp);}
8452: MatNullSpaceDestroy(&mat->transnullsp);
8453: mat->transnullsp = nullsp;
8454: return(0);
8455: }
8457: /*@
8458: MatSetNearNullSpace - attaches a null space to a matrix, which is often the null space (rigid body modes) of the operator without boundary conditions
8459: This null space will be used to provide near null space vectors to a multigrid preconditioner built from this matrix.
8461: Logically Collective on Mat and MatNullSpace
8463: Input Parameters:
8464: + mat - the matrix
8465: - nullsp - the null space object
8467: Level: advanced
8469: Notes:
8470: Overwrites any previous near null space that may have been attached
8472: You can remove the null space by calling this routine with an nullsp of NULL
8474: Concepts: null space^attaching to matrix
8476: .seealso: MatCreate(), MatNullSpaceCreate(), MatSetNullSpace(), MatNullSpaceCreateRigidBody(), MatGetNearNullSpace()
8477: @*/
8478: PetscErrorCode MatSetNearNullSpace(Mat mat,MatNullSpace nullsp)
8479: {
8486: MatCheckPreallocated(mat,1);
8487: if (nullsp) {PetscObjectReference((PetscObject)nullsp);}
8488: MatNullSpaceDestroy(&mat->nearnullsp);
8489: mat->nearnullsp = nullsp;
8490: return(0);
8491: }
8493: /*@
8494: MatGetNearNullSpace -Get null space attached with MatSetNearNullSpace()
8496: Not Collective
8498: Input Parameters:
8499: . mat - the matrix
8501: Output Parameters:
8502: . nullsp - the null space object, NULL if not set
8504: Level: developer
8506: Concepts: null space^attaching to matrix
8508: .seealso: MatSetNearNullSpace(), MatGetNullSpace(), MatNullSpaceCreate()
8509: @*/
8510: PetscErrorCode MatGetNearNullSpace(Mat mat,MatNullSpace *nullsp)
8511: {
8516: MatCheckPreallocated(mat,1);
8517: *nullsp = mat->nearnullsp;
8518: return(0);
8519: }
8521: /*@C
8522: MatICCFactor - Performs in-place incomplete Cholesky factorization of matrix.
8524: Collective on Mat
8526: Input Parameters:
8527: + mat - the matrix
8528: . row - row/column permutation
8529: . fill - expected fill factor >= 1.0
8530: - level - level of fill, for ICC(k)
8532: Notes:
8533: Probably really in-place only when level of fill is zero, otherwise allocates
8534: new space to store factored matrix and deletes previous memory.
8536: Most users should employ the simplified KSP interface for linear solvers
8537: instead of working directly with matrix algebra routines such as this.
8538: See, e.g., KSPCreate().
8540: Level: developer
8542: Concepts: matrices^incomplete Cholesky factorization
8543: Concepts: Cholesky factorization
8545: .seealso: MatICCFactorSymbolic(), MatLUFactorNumeric(), MatCholeskyFactor()
8547: Developer Note: fortran interface is not autogenerated as the f90
8548: interface defintion cannot be generated correctly [due to MatFactorInfo]
8550: @*/
8551: PetscErrorCode MatICCFactor(Mat mat,IS row,const MatFactorInfo *info)
8552: {
8560: if (mat->rmap->N != mat->cmap->N) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONG,"matrix must be square");
8561: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
8562: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
8563: if (!mat->ops->iccfactor) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
8564: MatCheckPreallocated(mat,1);
8565: (*mat->ops->iccfactor)(mat,row,info);
8566: PetscObjectStateIncrease((PetscObject)mat);
8567: return(0);
8568: }
8570: /*@
8571: MatDiagonalScaleLocal - Scales columns of a matrix given the scaling values including the
8572: ghosted ones.
8574: Not Collective
8576: Input Parameters:
8577: + mat - the matrix
8578: - diag = the diagonal values, including ghost ones
8580: Level: developer
8582: Notes:
8583: Works only for MPIAIJ and MPIBAIJ matrices
8585: .seealso: MatDiagonalScale()
8586: @*/
8587: PetscErrorCode MatDiagonalScaleLocal(Mat mat,Vec diag)
8588: {
8590: PetscMPIInt size;
8597: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Matrix must be already assembled");
8598: PetscLogEventBegin(MAT_Scale,mat,0,0,0);
8599: MPI_Comm_size(PetscObjectComm((PetscObject)mat),&size);
8600: if (size == 1) {
8601: PetscInt n,m;
8602: VecGetSize(diag,&n);
8603: MatGetSize(mat,0,&m);
8604: if (m == n) {
8605: MatDiagonalScale(mat,0,diag);
8606: } else SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"Only supported for sequential matrices when no ghost points/periodic conditions");
8607: } else {
8608: PetscUseMethod(mat,"MatDiagonalScaleLocal_C",(Mat,Vec),(mat,diag));
8609: }
8610: PetscLogEventEnd(MAT_Scale,mat,0,0,0);
8611: PetscObjectStateIncrease((PetscObject)mat);
8612: return(0);
8613: }
8615: /*@
8616: MatGetInertia - Gets the inertia from a factored matrix
8618: Collective on Mat
8620: Input Parameter:
8621: . mat - the matrix
8623: Output Parameters:
8624: + nneg - number of negative eigenvalues
8625: . nzero - number of zero eigenvalues
8626: - npos - number of positive eigenvalues
8628: Level: advanced
8630: Notes:
8631: Matrix must have been factored by MatCholeskyFactor()
8634: @*/
8635: PetscErrorCode MatGetInertia(Mat mat,PetscInt *nneg,PetscInt *nzero,PetscInt *npos)
8636: {
8642: if (!mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
8643: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Numeric factor mat is not assembled");
8644: if (!mat->ops->getinertia) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
8645: (*mat->ops->getinertia)(mat,nneg,nzero,npos);
8646: return(0);
8647: }
8649: /* ----------------------------------------------------------------*/
8650: /*@C
8651: MatSolves - Solves A x = b, given a factored matrix, for a collection of vectors
8653: Neighbor-wise Collective on Mat and Vecs
8655: Input Parameters:
8656: + mat - the factored matrix
8657: - b - the right-hand-side vectors
8659: Output Parameter:
8660: . x - the result vectors
8662: Notes:
8663: The vectors b and x cannot be the same. I.e., one cannot
8664: call MatSolves(A,x,x).
8666: Notes:
8667: Most users should employ the simplified KSP interface for linear solvers
8668: instead of working directly with matrix algebra routines such as this.
8669: See, e.g., KSPCreate().
8671: Level: developer
8673: Concepts: matrices^triangular solves
8675: .seealso: MatSolveAdd(), MatSolveTranspose(), MatSolveTransposeAdd(), MatSolve()
8676: @*/
8677: PetscErrorCode MatSolves(Mat mat,Vecs b,Vecs x)
8678: {
8684: if (x == b) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"x and b must be different vectors");
8685: if (!mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
8686: if (!mat->rmap->N && !mat->cmap->N) return(0);
8688: if (!mat->ops->solves) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
8689: MatCheckPreallocated(mat,1);
8690: PetscLogEventBegin(MAT_Solves,mat,0,0,0);
8691: (*mat->ops->solves)(mat,b,x);
8692: PetscLogEventEnd(MAT_Solves,mat,0,0,0);
8693: return(0);
8694: }
8696: /*@
8697: MatIsSymmetric - Test whether a matrix is symmetric
8699: Collective on Mat
8701: Input Parameter:
8702: + A - the matrix to test
8703: - tol - difference between value and its transpose less than this amount counts as equal (use 0.0 for exact transpose)
8705: Output Parameters:
8706: . flg - the result
8708: Notes:
8709: For real numbers MatIsSymmetric() and MatIsHermitian() return identical results
8711: Level: intermediate
8713: Concepts: matrix^symmetry
8715: .seealso: MatTranspose(), MatIsTranspose(), MatIsHermitian(), MatIsStructurallySymmetric(), MatSetOption(), MatIsSymmetricKnown()
8716: @*/
8717: PetscErrorCode MatIsSymmetric(Mat A,PetscReal tol,PetscBool *flg)
8718: {
8725: if (!A->symmetric_set) {
8726: if (!A->ops->issymmetric) {
8727: MatType mattype;
8728: MatGetType(A,&mattype);
8729: SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Matrix of type <%s> does not support checking for symmetric",mattype);
8730: }
8731: (*A->ops->issymmetric)(A,tol,flg);
8732: if (!tol) {
8733: A->symmetric_set = PETSC_TRUE;
8734: A->symmetric = *flg;
8735: if (A->symmetric) {
8736: A->structurally_symmetric_set = PETSC_TRUE;
8737: A->structurally_symmetric = PETSC_TRUE;
8738: }
8739: }
8740: } else if (A->symmetric) {
8741: *flg = PETSC_TRUE;
8742: } else if (!tol) {
8743: *flg = PETSC_FALSE;
8744: } else {
8745: if (!A->ops->issymmetric) {
8746: MatType mattype;
8747: MatGetType(A,&mattype);
8748: SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Matrix of type <%s> does not support checking for symmetric",mattype);
8749: }
8750: (*A->ops->issymmetric)(A,tol,flg);
8751: }
8752: return(0);
8753: }
8755: /*@
8756: MatIsHermitian - Test whether a matrix is Hermitian
8758: Collective on Mat
8760: Input Parameter:
8761: + A - the matrix to test
8762: - tol - difference between value and its transpose less than this amount counts as equal (use 0.0 for exact Hermitian)
8764: Output Parameters:
8765: . flg - the result
8767: Level: intermediate
8769: Concepts: matrix^symmetry
8771: .seealso: MatTranspose(), MatIsTranspose(), MatIsHermitian(), MatIsStructurallySymmetric(), MatSetOption(),
8772: MatIsSymmetricKnown(), MatIsSymmetric()
8773: @*/
8774: PetscErrorCode MatIsHermitian(Mat A,PetscReal tol,PetscBool *flg)
8775: {
8782: if (!A->hermitian_set) {
8783: if (!A->ops->ishermitian) {
8784: MatType mattype;
8785: MatGetType(A,&mattype);
8786: SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Matrix of type <%s> does not support checking for hermitian",mattype);
8787: }
8788: (*A->ops->ishermitian)(A,tol,flg);
8789: if (!tol) {
8790: A->hermitian_set = PETSC_TRUE;
8791: A->hermitian = *flg;
8792: if (A->hermitian) {
8793: A->structurally_symmetric_set = PETSC_TRUE;
8794: A->structurally_symmetric = PETSC_TRUE;
8795: }
8796: }
8797: } else if (A->hermitian) {
8798: *flg = PETSC_TRUE;
8799: } else if (!tol) {
8800: *flg = PETSC_FALSE;
8801: } else {
8802: if (!A->ops->ishermitian) {
8803: MatType mattype;
8804: MatGetType(A,&mattype);
8805: SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Matrix of type <%s> does not support checking for hermitian",mattype);
8806: }
8807: (*A->ops->ishermitian)(A,tol,flg);
8808: }
8809: return(0);
8810: }
8812: /*@
8813: MatIsSymmetricKnown - Checks the flag on the matrix to see if it is symmetric.
8815: Not Collective
8817: Input Parameter:
8818: . A - the matrix to check
8820: Output Parameters:
8821: + set - if the symmetric flag is set (this tells you if the next flag is valid)
8822: - flg - the result
8824: Level: advanced
8826: Concepts: matrix^symmetry
8828: Note: Does not check the matrix values directly, so this may return unknown (set = PETSC_FALSE). Use MatIsSymmetric()
8829: if you want it explicitly checked
8831: .seealso: MatTranspose(), MatIsTranspose(), MatIsHermitian(), MatIsStructurallySymmetric(), MatSetOption(), MatIsSymmetric()
8832: @*/
8833: PetscErrorCode MatIsSymmetricKnown(Mat A,PetscBool *set,PetscBool *flg)
8834: {
8839: if (A->symmetric_set) {
8840: *set = PETSC_TRUE;
8841: *flg = A->symmetric;
8842: } else {
8843: *set = PETSC_FALSE;
8844: }
8845: return(0);
8846: }
8848: /*@
8849: MatIsHermitianKnown - Checks the flag on the matrix to see if it is hermitian.
8851: Not Collective
8853: Input Parameter:
8854: . A - the matrix to check
8856: Output Parameters:
8857: + set - if the hermitian flag is set (this tells you if the next flag is valid)
8858: - flg - the result
8860: Level: advanced
8862: Concepts: matrix^symmetry
8864: Note: Does not check the matrix values directly, so this may return unknown (set = PETSC_FALSE). Use MatIsHermitian()
8865: if you want it explicitly checked
8867: .seealso: MatTranspose(), MatIsTranspose(), MatIsHermitian(), MatIsStructurallySymmetric(), MatSetOption(), MatIsSymmetric()
8868: @*/
8869: PetscErrorCode MatIsHermitianKnown(Mat A,PetscBool *set,PetscBool *flg)
8870: {
8875: if (A->hermitian_set) {
8876: *set = PETSC_TRUE;
8877: *flg = A->hermitian;
8878: } else {
8879: *set = PETSC_FALSE;
8880: }
8881: return(0);
8882: }
8884: /*@
8885: MatIsStructurallySymmetric - Test whether a matrix is structurally symmetric
8887: Collective on Mat
8889: Input Parameter:
8890: . A - the matrix to test
8892: Output Parameters:
8893: . flg - the result
8895: Level: intermediate
8897: Concepts: matrix^symmetry
8899: .seealso: MatTranspose(), MatIsTranspose(), MatIsHermitian(), MatIsSymmetric(), MatSetOption()
8900: @*/
8901: PetscErrorCode MatIsStructurallySymmetric(Mat A,PetscBool *flg)
8902: {
8908: if (!A->structurally_symmetric_set) {
8909: if (!A->ops->isstructurallysymmetric) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Matrix does not support checking for structural symmetric");
8910: (*A->ops->isstructurallysymmetric)(A,&A->structurally_symmetric);
8912: A->structurally_symmetric_set = PETSC_TRUE;
8913: }
8914: *flg = A->structurally_symmetric;
8915: return(0);
8916: }
8918: /*@
8919: MatStashGetInfo - Gets how many values are currently in the matrix stash, i.e. need
8920: to be communicated to other processors during the MatAssemblyBegin/End() process
8922: Not collective
8924: Input Parameter:
8925: . vec - the vector
8927: Output Parameters:
8928: + nstash - the size of the stash
8929: . reallocs - the number of additional mallocs incurred.
8930: . bnstash - the size of the block stash
8931: - breallocs - the number of additional mallocs incurred.in the block stash
8933: Level: advanced
8935: .seealso: MatAssemblyBegin(), MatAssemblyEnd(), Mat, MatStashSetInitialSize()
8937: @*/
8938: PetscErrorCode MatStashGetInfo(Mat mat,PetscInt *nstash,PetscInt *reallocs,PetscInt *bnstash,PetscInt *breallocs)
8939: {
8943: MatStashGetInfo_Private(&mat->stash,nstash,reallocs);
8944: MatStashGetInfo_Private(&mat->bstash,bnstash,breallocs);
8945: return(0);
8946: }
8948: /*@C
8949: MatCreateVecs - Get vector(s) compatible with the matrix, i.e. with the same
8950: parallel layout
8952: Collective on Mat
8954: Input Parameter:
8955: . mat - the matrix
8957: Output Parameter:
8958: + right - (optional) vector that the matrix can be multiplied against
8959: - left - (optional) vector that the matrix vector product can be stored in
8961: Notes:
8962: 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().
8964: Notes:
8965: These are new vectors which are not owned by the Mat, they should be destroyed in VecDestroy() when no longer needed
8967: Level: advanced
8969: .seealso: MatCreate(), VecDestroy()
8970: @*/
8971: PetscErrorCode MatCreateVecs(Mat mat,Vec *right,Vec *left)
8972: {
8978: if (mat->ops->getvecs) {
8979: (*mat->ops->getvecs)(mat,right,left);
8980: } else {
8981: PetscInt rbs,cbs;
8982: MatGetBlockSizes(mat,&rbs,&cbs);
8983: if (right) {
8984: if (mat->cmap->n < 0) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"PetscLayout for columns not yet setup");
8985: VecCreate(PetscObjectComm((PetscObject)mat),right);
8986: VecSetSizes(*right,mat->cmap->n,PETSC_DETERMINE);
8987: VecSetBlockSize(*right,cbs);
8988: VecSetType(*right,mat->defaultvectype);
8989: PetscLayoutReference(mat->cmap,&(*right)->map);
8990: }
8991: if (left) {
8992: if (mat->rmap->n < 0) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"PetscLayout for rows not yet setup");
8993: VecCreate(PetscObjectComm((PetscObject)mat),left);
8994: VecSetSizes(*left,mat->rmap->n,PETSC_DETERMINE);
8995: VecSetBlockSize(*left,rbs);
8996: VecSetType(*left,mat->defaultvectype);
8997: PetscLayoutReference(mat->rmap,&(*left)->map);
8998: }
8999: }
9000: return(0);
9001: }
9003: /*@C
9004: MatFactorInfoInitialize - Initializes a MatFactorInfo data structure
9005: with default values.
9007: Not Collective
9009: Input Parameters:
9010: . info - the MatFactorInfo data structure
9013: Notes:
9014: The solvers are generally used through the KSP and PC objects, for example
9015: PCLU, PCILU, PCCHOLESKY, PCICC
9017: Level: developer
9019: .seealso: MatFactorInfo
9021: Developer Note: fortran interface is not autogenerated as the f90
9022: interface defintion cannot be generated correctly [due to MatFactorInfo]
9024: @*/
9026: PetscErrorCode MatFactorInfoInitialize(MatFactorInfo *info)
9027: {
9031: PetscMemzero(info,sizeof(MatFactorInfo));
9032: return(0);
9033: }
9035: /*@
9036: MatFactorSetSchurIS - Set indices corresponding to the Schur complement you wish to have computed
9038: Collective on Mat
9040: Input Parameters:
9041: + mat - the factored matrix
9042: - is - the index set defining the Schur indices (0-based)
9044: Notes:
9045: Call MatFactorSolveSchurComplement() or MatFactorSolveSchurComplementTranspose() after this call to solve a Schur complement system.
9047: You can call MatFactorGetSchurComplement() or MatFactorCreateSchurComplement() after this call.
9049: Level: developer
9051: Concepts:
9053: .seealso: MatGetFactor(), MatFactorGetSchurComplement(), MatFactorRestoreSchurComplement(), MatFactorCreateSchurComplement(), MatFactorSolveSchurComplement(),
9054: MatFactorSolveSchurComplementTranspose(), MatFactorSolveSchurComplement()
9056: @*/
9057: PetscErrorCode MatFactorSetSchurIS(Mat mat,IS is)
9058: {
9059: PetscErrorCode ierr,(*f)(Mat,IS);
9067: if (!mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Only for factored matrix");
9068: PetscObjectQueryFunction((PetscObject)mat,"MatFactorSetSchurIS_C",&f);
9069: 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");
9070: if (mat->schur) {
9071: MatDestroy(&mat->schur);
9072: }
9073: (*f)(mat,is);
9074: if (!mat->schur) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_PLIB,"Schur complement has not been created");
9075: MatFactorSetUpInPlaceSchur_Private(mat);
9076: return(0);
9077: }
9079: /*@
9080: MatFactorCreateSchurComplement - Create a Schur complement matrix object using Schur data computed during the factorization step
9082: Logically Collective on Mat
9084: Input Parameters:
9085: + F - the factored matrix obtained by calling MatGetFactor() from PETSc-MUMPS interface
9086: . S - location where to return the Schur complement, can be NULL
9087: - status - the status of the Schur complement matrix, can be NULL
9089: Notes:
9090: You must call MatFactorSetSchurIS() before calling this routine.
9092: The routine provides a copy of the Schur matrix stored within the solver data structures.
9093: The caller must destroy the object when it is no longer needed.
9094: If MatFactorInvertSchurComplement() has been called, the routine gets back the inverse.
9096: 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)
9098: Developer Notes:
9099: The reason this routine exists is because the representation of the Schur complement within the factor matrix may be different than a standard PETSc
9100: matrix representation and we normally do not want to use the time or memory to make a copy as a regular PETSc matrix.
9102: See MatCreateSchurComplement() or MatGetSchurComplement() for ways to create virtual or approximate Schur complements.
9104: Level: advanced
9106: References:
9108: .seealso: MatGetFactor(), MatFactorSetSchurIS(), MatFactorGetSchurComplement(), MatFactorSchurStatus
9109: @*/
9110: PetscErrorCode MatFactorCreateSchurComplement(Mat F,Mat* S,MatFactorSchurStatus* status)
9111: {
9118: if (S) {
9119: PetscErrorCode (*f)(Mat,Mat*);
9121: PetscObjectQueryFunction((PetscObject)F,"MatFactorCreateSchurComplement_C",&f);
9122: if (f) {
9123: (*f)(F,S);
9124: } else {
9125: MatDuplicate(F->schur,MAT_COPY_VALUES,S);
9126: }
9127: }
9128: if (status) *status = F->schur_status;
9129: return(0);
9130: }
9132: /*@
9133: MatFactorGetSchurComplement - Gets access to a Schur complement matrix using the current Schur data within a factored matrix
9135: Logically Collective on Mat
9137: Input Parameters:
9138: + F - the factored matrix obtained by calling MatGetFactor()
9139: . *S - location where to return the Schur complement, can be NULL
9140: - status - the status of the Schur complement matrix, can be NULL
9142: Notes:
9143: You must call MatFactorSetSchurIS() before calling this routine.
9145: Schur complement mode is currently implemented for sequential matrices.
9146: The routine returns a the Schur Complement stored within the data strutures of the solver.
9147: If MatFactorInvertSchurComplement() has previously been called, the returned matrix is actually the inverse of the Schur complement.
9148: The returned matrix should not be destroyed; the caller should call MatFactorRestoreSchurComplement() when the object is no longer needed.
9150: Use MatFactorCreateSchurComplement() to create a copy of the Schur complement matrix that is within a factored matrix
9152: See MatCreateSchurComplement() or MatGetSchurComplement() for ways to create virtual or approximate Schur complements.
9154: Level: advanced
9156: References:
9158: .seealso: MatGetFactor(), MatFactorSetSchurIS(), MatFactorRestoreSchurComplement(), MatFactorCreateSchurComplement(), MatFactorSchurStatus
9159: @*/
9160: PetscErrorCode MatFactorGetSchurComplement(Mat F,Mat* S,MatFactorSchurStatus* status)
9161: {
9166: if (S) *S = F->schur;
9167: if (status) *status = F->schur_status;
9168: return(0);
9169: }
9171: /*@
9172: MatFactorRestoreSchurComplement - Restore the Schur complement matrix object obtained from a call to MatFactorGetSchurComplement
9174: Logically Collective on Mat
9176: Input Parameters:
9177: + F - the factored matrix obtained by calling MatGetFactor()
9178: . *S - location where the Schur complement is stored
9179: - status - the status of the Schur complement matrix (see MatFactorSchurStatus)
9181: Notes:
9183: Level: advanced
9185: References:
9187: .seealso: MatGetFactor(), MatFactorSetSchurIS(), MatFactorRestoreSchurComplement(), MatFactorCreateSchurComplement(), MatFactorSchurStatus
9188: @*/
9189: PetscErrorCode MatFactorRestoreSchurComplement(Mat F,Mat* S,MatFactorSchurStatus status)
9190: {
9195: if (S) {
9197: *S = NULL;
9198: }
9199: F->schur_status = status;
9200: MatFactorUpdateSchurStatus_Private(F);
9201: return(0);
9202: }
9204: /*@
9205: MatFactorSolveSchurComplementTranspose - Solve the transpose of the Schur complement system computed during the factorization step
9207: Logically Collective on Mat
9209: Input Parameters:
9210: + F - the factored matrix obtained by calling MatGetFactor()
9211: . rhs - location where the right hand side of the Schur complement system is stored
9212: - sol - location where the solution of the Schur complement system has to be returned
9214: Notes:
9215: The sizes of the vectors should match the size of the Schur complement
9217: Must be called after MatFactorSetSchurIS()
9219: Level: advanced
9221: References:
9223: .seealso: MatGetFactor(), MatFactorSetSchurIS(), MatFactorSolveSchurComplement()
9224: @*/
9225: PetscErrorCode MatFactorSolveSchurComplementTranspose(Mat F, Vec rhs, Vec sol)
9226: {
9238: MatFactorFactorizeSchurComplement(F);
9239: switch (F->schur_status) {
9240: case MAT_FACTOR_SCHUR_FACTORED:
9241: MatSolveTranspose(F->schur,rhs,sol);
9242: break;
9243: case MAT_FACTOR_SCHUR_INVERTED:
9244: MatMultTranspose(F->schur,rhs,sol);
9245: break;
9246: default:
9247: SETERRQ1(PetscObjectComm((PetscObject)F),PETSC_ERR_SUP,"Unhandled MatFactorSchurStatus %D",F->schur_status);
9248: break;
9249: }
9250: return(0);
9251: }
9253: /*@
9254: MatFactorSolveSchurComplement - Solve the Schur complement system computed during the factorization step
9256: Logically Collective on Mat
9258: Input Parameters:
9259: + F - the factored matrix obtained by calling MatGetFactor()
9260: . rhs - location where the right hand side of the Schur complement system is stored
9261: - sol - location where the solution of the Schur complement system has to be returned
9263: Notes:
9264: The sizes of the vectors should match the size of the Schur complement
9266: Must be called after MatFactorSetSchurIS()
9268: Level: advanced
9270: References:
9272: .seealso: MatGetFactor(), MatFactorSetSchurIS(), MatFactorSolveSchurComplementTranspose()
9273: @*/
9274: PetscErrorCode MatFactorSolveSchurComplement(Mat F, Vec rhs, Vec sol)
9275: {
9287: MatFactorFactorizeSchurComplement(F);
9288: switch (F->schur_status) {
9289: case MAT_FACTOR_SCHUR_FACTORED:
9290: MatSolve(F->schur,rhs,sol);
9291: break;
9292: case MAT_FACTOR_SCHUR_INVERTED:
9293: MatMult(F->schur,rhs,sol);
9294: break;
9295: default:
9296: SETERRQ1(PetscObjectComm((PetscObject)F),PETSC_ERR_SUP,"Unhandled MatFactorSchurStatus %D",F->schur_status);
9297: break;
9298: }
9299: return(0);
9300: }
9302: /*@
9303: MatFactorInvertSchurComplement - Invert the Schur complement matrix computed during the factorization step
9305: Logically Collective on Mat
9307: Input Parameters:
9308: + F - the factored matrix obtained by calling MatGetFactor()
9310: Notes:
9311: Must be called after MatFactorSetSchurIS().
9313: Call MatFactorGetSchurComplement() or MatFactorCreateSchurComplement() AFTER this call to actually compute the inverse and get access to it.
9315: Level: advanced
9317: References:
9319: .seealso: MatGetFactor(), MatFactorSetSchurIS(), MatFactorGetSchurComplement(), MatFactorCreateSchurComplement()
9320: @*/
9321: PetscErrorCode MatFactorInvertSchurComplement(Mat F)
9322: {
9328: if (F->schur_status == MAT_FACTOR_SCHUR_INVERTED) return(0);
9329: MatFactorFactorizeSchurComplement(F);
9330: MatFactorInvertSchurComplement_Private(F);
9331: F->schur_status = MAT_FACTOR_SCHUR_INVERTED;
9332: return(0);
9333: }
9335: /*@
9336: MatFactorFactorizeSchurComplement - Factorize the Schur complement matrix computed during the factorization step
9338: Logically Collective on Mat
9340: Input Parameters:
9341: + F - the factored matrix obtained by calling MatGetFactor()
9343: Notes:
9344: Must be called after MatFactorSetSchurIS().
9346: Level: advanced
9348: References:
9350: .seealso: MatGetFactor(), MatFactorSetSchurIS(), MatFactorInvertSchurComplement()
9351: @*/
9352: PetscErrorCode MatFactorFactorizeSchurComplement(Mat F)
9353: {
9359: if (F->schur_status == MAT_FACTOR_SCHUR_INVERTED || F->schur_status == MAT_FACTOR_SCHUR_FACTORED) return(0);
9360: MatFactorFactorizeSchurComplement_Private(F);
9361: F->schur_status = MAT_FACTOR_SCHUR_FACTORED;
9362: return(0);
9363: }
9365: /*@
9366: MatPtAP - Creates the matrix product C = P^T * A * P
9368: Neighbor-wise Collective on Mat
9370: Input Parameters:
9371: + A - the matrix
9372: . P - the projection matrix
9373: . scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
9374: - fill - expected fill as ratio of nnz(C)/(nnz(A) + nnz(P)), use PETSC_DEFAULT if you do not have a good estimate
9375: if the result is a dense matrix this is irrelevent
9377: Output Parameters:
9378: . C - the product matrix
9380: Notes:
9381: C will be created and must be destroyed by the user with MatDestroy().
9383: This routine is currently only implemented for pairs of sequential dense matrices, AIJ matrices and classes
9384: which inherit from AIJ.
9386: Level: intermediate
9388: .seealso: MatPtAPSymbolic(), MatPtAPNumeric(), MatMatMult(), MatRARt()
9389: @*/
9390: PetscErrorCode MatPtAP(Mat A,Mat P,MatReuse scall,PetscReal fill,Mat *C)
9391: {
9393: PetscErrorCode (*fA)(Mat,Mat,MatReuse,PetscReal,Mat*);
9394: PetscErrorCode (*fP)(Mat,Mat,MatReuse,PetscReal,Mat*);
9395: PetscErrorCode (*ptap)(Mat,Mat,MatReuse,PetscReal,Mat*)=NULL;
9396: PetscBool sametype;
9401: MatCheckPreallocated(A,1);
9402: if (scall == MAT_INPLACE_MATRIX) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Inplace product not supported");
9403: if (!A->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
9404: if (A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
9407: MatCheckPreallocated(P,2);
9408: if (!P->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
9409: if (P->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
9411: if (A->rmap->N != A->cmap->N) SETERRQ2(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Matrix A must be square, %D != %D",A->rmap->N,A->cmap->N);
9412: if (P->rmap->N != A->cmap->N) SETERRQ2(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Matrix dimensions are incompatible, %D != %D",P->rmap->N,A->cmap->N);
9413: if (fill == PETSC_DEFAULT || fill == PETSC_DECIDE) fill = 2.0;
9414: if (fill < 1.0) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Expected fill=%g must be >= 1.0",(double)fill);
9416: if (scall == MAT_REUSE_MATRIX) {
9420: if (!(*C)->ops->ptapnumeric) SETERRQ(PetscObjectComm((PetscObject)C),PETSC_ERR_ARG_WRONGSTATE,"MatPtAPNumeric implementation is missing. You cannot use MAT_REUSE_MATRIX");
9421: PetscLogEventBegin(MAT_PtAP,A,P,0,0);
9422: PetscLogEventBegin(MAT_PtAPNumeric,A,P,0,0);
9423: (*(*C)->ops->ptapnumeric)(A,P,*C);
9424: PetscLogEventEnd(MAT_PtAPNumeric,A,P,0,0);
9425: PetscLogEventEnd(MAT_PtAP,A,P,0,0);
9426: return(0);
9427: }
9429: if (fill == PETSC_DEFAULT || fill == PETSC_DECIDE) fill = 2.0;
9430: if (fill < 1.0) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Expected fill=%g must be >= 1.0",(double)fill);
9432: fA = A->ops->ptap;
9433: fP = P->ops->ptap;
9434: PetscStrcmp(((PetscObject)A)->type_name,((PetscObject)P)->type_name,&sametype);
9435: if (fP == fA && sametype) {
9436: if (!fA) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"MatPtAP not supported for A of type %s",((PetscObject)A)->type_name);
9437: ptap = fA;
9438: } else {
9439: /* dispatch based on the type of A and P from their PetscObject's PetscFunctionLists. */
9440: char ptapname[256];
9441: PetscStrncpy(ptapname,"MatPtAP_",sizeof(ptapname));
9442: PetscStrlcat(ptapname,((PetscObject)A)->type_name,sizeof(ptapname));
9443: PetscStrlcat(ptapname,"_",sizeof(ptapname));
9444: PetscStrlcat(ptapname,((PetscObject)P)->type_name,sizeof(ptapname));
9445: PetscStrlcat(ptapname,"_C",sizeof(ptapname)); /* e.g., ptapname = "MatPtAP_seqdense_seqaij_C" */
9446: PetscObjectQueryFunction((PetscObject)P,ptapname,&ptap);
9447: if (!ptap) SETERRQ3(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_INCOMP,"MatPtAP requires A, %s, to be compatible with P, %s (Misses composed function %s)",((PetscObject)A)->type_name,((PetscObject)P)->type_name,ptapname);
9448: }
9450: PetscLogEventBegin(MAT_PtAP,A,P,0,0);
9451: (*ptap)(A,P,scall,fill,C);
9452: PetscLogEventEnd(MAT_PtAP,A,P,0,0);
9453: if (A->symmetric_set && A->symmetric) {
9454: MatSetOption(*C,MAT_SYMMETRIC,PETSC_TRUE);
9455: }
9456: return(0);
9457: }
9459: /*@
9460: MatPtAPNumeric - Computes the matrix product C = P^T * A * P
9462: Neighbor-wise Collective on Mat
9464: Input Parameters:
9465: + A - the matrix
9466: - P - the projection matrix
9468: Output Parameters:
9469: . C - the product matrix
9471: Notes:
9472: C must have been created by calling MatPtAPSymbolic and must be destroyed by
9473: the user using MatDeatroy().
9475: This routine is currently only implemented for pairs of AIJ matrices and classes
9476: which inherit from AIJ. C will be of type MATAIJ.
9478: Level: intermediate
9480: .seealso: MatPtAP(), MatPtAPSymbolic(), MatMatMultNumeric()
9481: @*/
9482: PetscErrorCode MatPtAPNumeric(Mat A,Mat P,Mat C)
9483: {
9489: if (!A->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
9490: if (A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
9493: MatCheckPreallocated(P,2);
9494: if (!P->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
9495: if (P->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
9498: MatCheckPreallocated(C,3);
9499: if (C->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
9500: if (P->cmap->N!=C->rmap->N) SETERRQ2(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Matrix dimensions are incompatible, %D != %D",P->cmap->N,C->rmap->N);
9501: if (P->rmap->N!=A->cmap->N) SETERRQ2(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Matrix dimensions are incompatible, %D != %D",P->rmap->N,A->cmap->N);
9502: if (A->rmap->N!=A->cmap->N) SETERRQ2(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Matrix 'A' must be square, %D != %D",A->rmap->N,A->cmap->N);
9503: if (P->cmap->N!=C->cmap->N) SETERRQ2(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Matrix dimensions are incompatible, %D != %D",P->cmap->N,C->cmap->N);
9504: MatCheckPreallocated(A,1);
9506: if (!C->ops->ptapnumeric) SETERRQ(PetscObjectComm((PetscObject)C),PETSC_ERR_ARG_WRONGSTATE,"MatPtAPNumeric implementation is missing. You should call MatPtAPSymbolic first");
9507: PetscLogEventBegin(MAT_PtAPNumeric,A,P,0,0);
9508: (*C->ops->ptapnumeric)(A,P,C);
9509: PetscLogEventEnd(MAT_PtAPNumeric,A,P,0,0);
9510: return(0);
9511: }
9513: /*@
9514: MatPtAPSymbolic - Creates the (i,j) structure of the matrix product C = P^T * A * P
9516: Neighbor-wise Collective on Mat
9518: Input Parameters:
9519: + A - the matrix
9520: - P - the projection matrix
9522: Output Parameters:
9523: . C - the (i,j) structure of the product matrix
9525: Notes:
9526: C will be created and must be destroyed by the user with MatDestroy().
9528: This routine is currently only implemented for pairs of SeqAIJ matrices and classes
9529: which inherit from SeqAIJ. C will be of type MATSEQAIJ. The product is computed using
9530: this (i,j) structure by calling MatPtAPNumeric().
9532: Level: intermediate
9534: .seealso: MatPtAP(), MatPtAPNumeric(), MatMatMultSymbolic()
9535: @*/
9536: PetscErrorCode MatPtAPSymbolic(Mat A,Mat P,PetscReal fill,Mat *C)
9537: {
9543: if (!A->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
9544: if (A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
9545: if (fill <1.0) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Expected fill=%g must be >= 1.0",(double)fill);
9548: MatCheckPreallocated(P,2);
9549: if (!P->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
9550: if (P->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
9553: if (P->rmap->N!=A->cmap->N) SETERRQ2(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Matrix dimensions are incompatible, %D != %D",P->rmap->N,A->cmap->N);
9554: if (A->rmap->N!=A->cmap->N) SETERRQ2(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Matrix 'A' must be square, %D != %D",A->rmap->N,A->cmap->N);
9555: MatCheckPreallocated(A,1);
9557: if (!A->ops->ptapsymbolic) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"MatType %s",((PetscObject)A)->type_name);
9558: PetscLogEventBegin(MAT_PtAPSymbolic,A,P,0,0);
9559: (*A->ops->ptapsymbolic)(A,P,fill,C);
9560: PetscLogEventEnd(MAT_PtAPSymbolic,A,P,0,0);
9562: /* MatSetBlockSize(*C,A->rmap->bs); NO! this is not always true -ma */
9563: return(0);
9564: }
9566: /*@
9567: MatRARt - Creates the matrix product C = R * A * R^T
9569: Neighbor-wise Collective on Mat
9571: Input Parameters:
9572: + A - the matrix
9573: . R - the projection matrix
9574: . scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
9575: - fill - expected fill as ratio of nnz(C)/nnz(A), use PETSC_DEFAULT if you do not have a good estimate
9576: if the result is a dense matrix this is irrelevent
9578: Output Parameters:
9579: . C - the product matrix
9581: Notes:
9582: C will be created and must be destroyed by the user with MatDestroy().
9584: This routine is currently only implemented for pairs of AIJ matrices and classes
9585: which inherit from AIJ. Due to PETSc sparse matrix block row distribution among processes,
9586: parallel MatRARt is implemented via explicit transpose of R, which could be very expensive.
9587: We recommend using MatPtAP().
9589: Level: intermediate
9591: .seealso: MatRARtSymbolic(), MatRARtNumeric(), MatMatMult(), MatPtAP()
9592: @*/
9593: PetscErrorCode MatRARt(Mat A,Mat R,MatReuse scall,PetscReal fill,Mat *C)
9594: {
9600: if (scall == MAT_INPLACE_MATRIX) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Inplace product not supported");
9601: if (!A->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
9602: if (A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
9605: MatCheckPreallocated(R,2);
9606: if (!R->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
9607: if (R->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
9609: if (R->cmap->N!=A->rmap->N) SETERRQ2(PetscObjectComm((PetscObject)R),PETSC_ERR_ARG_SIZ,"Matrix dimensions are incompatible, %D != %D",R->cmap->N,A->rmap->N);
9611: if (fill == PETSC_DEFAULT || fill == PETSC_DECIDE) fill = 2.0;
9612: if (fill < 1.0) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Expected fill=%g must be >= 1.0",(double)fill);
9613: MatCheckPreallocated(A,1);
9615: if (!A->ops->rart) {
9616: Mat Rt;
9617: MatTranspose(R,MAT_INITIAL_MATRIX,&Rt);
9618: MatMatMatMult(R,A,Rt,scall,fill,C);
9619: MatDestroy(&Rt);
9620: return(0);
9621: }
9622: PetscLogEventBegin(MAT_RARt,A,R,0,0);
9623: (*A->ops->rart)(A,R,scall,fill,C);
9624: PetscLogEventEnd(MAT_RARt,A,R,0,0);
9625: return(0);
9626: }
9628: /*@
9629: MatRARtNumeric - Computes the matrix product C = R * A * R^T
9631: Neighbor-wise Collective on Mat
9633: Input Parameters:
9634: + A - the matrix
9635: - R - the projection matrix
9637: Output Parameters:
9638: . C - the product matrix
9640: Notes:
9641: C must have been created by calling MatRARtSymbolic and must be destroyed by
9642: the user using MatDestroy().
9644: This routine is currently only implemented for pairs of AIJ matrices and classes
9645: which inherit from AIJ. C will be of type MATAIJ.
9647: Level: intermediate
9649: .seealso: MatRARt(), MatRARtSymbolic(), MatMatMultNumeric()
9650: @*/
9651: PetscErrorCode MatRARtNumeric(Mat A,Mat R,Mat C)
9652: {
9658: if (!A->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
9659: if (A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
9662: MatCheckPreallocated(R,2);
9663: if (!R->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
9664: if (R->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
9667: MatCheckPreallocated(C,3);
9668: if (C->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
9669: if (R->rmap->N!=C->rmap->N) SETERRQ2(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Matrix dimensions are incompatible, %D != %D",R->rmap->N,C->rmap->N);
9670: if (R->cmap->N!=A->rmap->N) SETERRQ2(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Matrix dimensions are incompatible, %D != %D",R->cmap->N,A->rmap->N);
9671: if (A->rmap->N!=A->cmap->N) SETERRQ2(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Matrix 'A' must be square, %D != %D",A->rmap->N,A->cmap->N);
9672: if (R->rmap->N!=C->cmap->N) SETERRQ2(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Matrix dimensions are incompatible, %D != %D",R->rmap->N,C->cmap->N);
9673: MatCheckPreallocated(A,1);
9675: PetscLogEventBegin(MAT_RARtNumeric,A,R,0,0);
9676: (*A->ops->rartnumeric)(A,R,C);
9677: PetscLogEventEnd(MAT_RARtNumeric,A,R,0,0);
9678: return(0);
9679: }
9681: /*@
9682: MatRARtSymbolic - Creates the (i,j) structure of the matrix product C = R * A * R^T
9684: Neighbor-wise Collective on Mat
9686: Input Parameters:
9687: + A - the matrix
9688: - R - the projection matrix
9690: Output Parameters:
9691: . C - the (i,j) structure of the product matrix
9693: Notes:
9694: C will be created and must be destroyed by the user with MatDestroy().
9696: This routine is currently only implemented for pairs of SeqAIJ matrices and classes
9697: which inherit from SeqAIJ. C will be of type MATSEQAIJ. The product is computed using
9698: this (i,j) structure by calling MatRARtNumeric().
9700: Level: intermediate
9702: .seealso: MatRARt(), MatRARtNumeric(), MatMatMultSymbolic()
9703: @*/
9704: PetscErrorCode MatRARtSymbolic(Mat A,Mat R,PetscReal fill,Mat *C)
9705: {
9711: if (!A->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
9712: if (A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
9713: if (fill <1.0) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Expected fill=%g must be >= 1.0",(double)fill);
9716: MatCheckPreallocated(R,2);
9717: if (!R->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
9718: if (R->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
9721: if (R->cmap->N!=A->rmap->N) SETERRQ2(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Matrix dimensions are incompatible, %D != %D",R->cmap->N,A->rmap->N);
9722: if (A->rmap->N!=A->cmap->N) SETERRQ2(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Matrix 'A' must be square, %D != %D",A->rmap->N,A->cmap->N);
9723: MatCheckPreallocated(A,1);
9724: PetscLogEventBegin(MAT_RARtSymbolic,A,R,0,0);
9725: (*A->ops->rartsymbolic)(A,R,fill,C);
9726: PetscLogEventEnd(MAT_RARtSymbolic,A,R,0,0);
9728: MatSetBlockSizes(*C,PetscAbs(R->rmap->bs),PetscAbs(R->rmap->bs));
9729: return(0);
9730: }
9732: /*@
9733: MatMatMult - Performs Matrix-Matrix Multiplication C=A*B.
9735: Neighbor-wise Collective on Mat
9737: Input Parameters:
9738: + A - the left matrix
9739: . B - the right matrix
9740: . scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
9741: - fill - expected fill as ratio of nnz(C)/(nnz(A) + nnz(B)), use PETSC_DEFAULT if you do not have a good estimate
9742: if the result is a dense matrix this is irrelevent
9744: Output Parameters:
9745: . C - the product matrix
9747: Notes:
9748: Unless scall is MAT_REUSE_MATRIX C will be created.
9750: 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
9751: call to this function with either MAT_INITIAL_MATRIX or MatMatMultSymbolic()
9753: To determine the correct fill value, run with -info and search for the string "Fill ratio" to see the value
9754: actually needed.
9756: If you have many matrices with the same non-zero structure to multiply, you
9757: should either
9758: $ 1) use MAT_REUSE_MATRIX in all calls but the first or
9759: $ 2) call MatMatMultSymbolic() once and then MatMatMultNumeric() for each product needed
9760: 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
9761: with MAT_REUSE_MATRIX, rather than first having MatMatMult() create it for you. You can NEVER do this if the matrix C is sparse.
9763: Level: intermediate
9765: .seealso: MatMatMultSymbolic(), MatMatMultNumeric(), MatTransposeMatMult(), MatMatTransposeMult(), MatPtAP()
9766: @*/
9767: PetscErrorCode MatMatMult(Mat A,Mat B,MatReuse scall,PetscReal fill,Mat *C)
9768: {
9770: PetscErrorCode (*fA)(Mat,Mat,MatReuse,PetscReal,Mat*);
9771: PetscErrorCode (*fB)(Mat,Mat,MatReuse,PetscReal,Mat*);
9772: PetscErrorCode (*mult)(Mat,Mat,MatReuse,PetscReal,Mat*)=NULL;
9777: MatCheckPreallocated(A,1);
9778: if (!A->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
9779: if (A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
9782: MatCheckPreallocated(B,2);
9783: if (!B->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
9784: if (B->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
9786: if (scall == MAT_INPLACE_MATRIX) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Inplace product not supported");
9787: if (B->rmap->N!=A->cmap->N) SETERRQ2(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Matrix dimensions are incompatible, %D != %D",B->rmap->N,A->cmap->N);
9788: if (scall == MAT_REUSE_MATRIX) {
9791: PetscLogEventBegin(MAT_MatMult,A,B,0,0);
9792: PetscLogEventBegin(MAT_MatMultNumeric,A,B,0,0);
9793: (*(*C)->ops->matmultnumeric)(A,B,*C);
9794: PetscLogEventEnd(MAT_MatMultNumeric,A,B,0,0);
9795: PetscLogEventEnd(MAT_MatMult,A,B,0,0);
9796: return(0);
9797: }
9798: if (fill == PETSC_DEFAULT || fill == PETSC_DECIDE) fill = 2.0;
9799: if (fill < 1.0) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Expected fill=%g must be >= 1.0",(double)fill);
9801: fA = A->ops->matmult;
9802: fB = B->ops->matmult;
9803: if (fB == fA) {
9804: if (!fB) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"MatMatMult not supported for B of type %s",((PetscObject)B)->type_name);
9805: mult = fB;
9806: } else {
9807: /* dispatch based on the type of A and B from their PetscObject's PetscFunctionLists. */
9808: char multname[256];
9809: PetscStrncpy(multname,"MatMatMult_",sizeof(multname));
9810: PetscStrlcat(multname,((PetscObject)A)->type_name,sizeof(multname));
9811: PetscStrlcat(multname,"_",sizeof(multname));
9812: PetscStrlcat(multname,((PetscObject)B)->type_name,sizeof(multname));
9813: PetscStrlcat(multname,"_C",sizeof(multname)); /* e.g., multname = "MatMatMult_seqdense_seqaij_C" */
9814: PetscObjectQueryFunction((PetscObject)B,multname,&mult);
9815: if (!mult) SETERRQ2(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_INCOMP,"MatMatMult requires A, %s, to be compatible with B, %s",((PetscObject)A)->type_name,((PetscObject)B)->type_name);
9816: }
9817: PetscLogEventBegin(MAT_MatMult,A,B,0,0);
9818: (*mult)(A,B,scall,fill,C);
9819: PetscLogEventEnd(MAT_MatMult,A,B,0,0);
9820: return(0);
9821: }
9823: /*@
9824: MatMatMultSymbolic - Performs construction, preallocation, and computes the ij structure
9825: of the matrix-matrix product C=A*B. Call this routine before calling MatMatMultNumeric().
9827: Neighbor-wise Collective on Mat
9829: Input Parameters:
9830: + A - the left matrix
9831: . B - the right matrix
9832: - fill - expected fill as ratio of nnz(C)/(nnz(A) + nnz(B)), use PETSC_DEFAULT if you do not have a good estimate,
9833: if C is a dense matrix this is irrelevent
9835: Output Parameters:
9836: . C - the product matrix
9838: Notes:
9839: Unless scall is MAT_REUSE_MATRIX C will be created.
9841: To determine the correct fill value, run with -info and search for the string "Fill ratio" to see the value
9842: actually needed.
9844: This routine is currently implemented for
9845: - pairs of AIJ matrices and classes which inherit from AIJ, C will be of type AIJ
9846: - pairs of AIJ (A) and Dense (B) matrix, C will be of type Dense.
9847: - pairs of Dense (A) and AIJ (B) matrix, C will be of type Dense.
9849: Level: intermediate
9851: Developers Note: There are ways to estimate the number of nonzeros in the resulting product, see for example, http://arxiv.org/abs/1006.4173
9852: We should incorporate them into PETSc.
9854: .seealso: MatMatMult(), MatMatMultNumeric()
9855: @*/
9856: PetscErrorCode MatMatMultSymbolic(Mat A,Mat B,PetscReal fill,Mat *C)
9857: {
9859: PetscErrorCode (*Asymbolic)(Mat,Mat,PetscReal,Mat*);
9860: PetscErrorCode (*Bsymbolic)(Mat,Mat,PetscReal,Mat*);
9861: PetscErrorCode (*symbolic)(Mat,Mat,PetscReal,Mat*)=NULL;
9866: if (!A->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
9867: if (A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
9871: MatCheckPreallocated(B,2);
9872: if (!B->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
9873: if (B->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
9876: if (B->rmap->N!=A->cmap->N) SETERRQ2(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Matrix dimensions are incompatible, %D != %D",B->rmap->N,A->cmap->N);
9877: if (fill == PETSC_DEFAULT) fill = 2.0;
9878: if (fill < 1.0) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Expected fill=%g must be > 1.0",(double)fill);
9879: MatCheckPreallocated(A,1);
9881: Asymbolic = A->ops->matmultsymbolic;
9882: Bsymbolic = B->ops->matmultsymbolic;
9883: if (Asymbolic == Bsymbolic) {
9884: if (!Bsymbolic) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"C=A*B not implemented for B of type %s",((PetscObject)B)->type_name);
9885: symbolic = Bsymbolic;
9886: } else { /* dispatch based on the type of A and B */
9887: char symbolicname[256];
9888: PetscStrncpy(symbolicname,"MatMatMultSymbolic_",sizeof(symbolicname));
9889: PetscStrlcat(symbolicname,((PetscObject)A)->type_name,sizeof(symbolicname));
9890: PetscStrlcat(symbolicname,"_",sizeof(symbolicname));
9891: PetscStrlcat(symbolicname,((PetscObject)B)->type_name,sizeof(symbolicname));
9892: PetscStrlcat(symbolicname,"_C",sizeof(symbolicname));
9893: PetscObjectQueryFunction((PetscObject)B,symbolicname,&symbolic);
9894: if (!symbolic) SETERRQ2(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_INCOMP,"MatMatMultSymbolic requires A, %s, to be compatible with B, %s",((PetscObject)A)->type_name,((PetscObject)B)->type_name);
9895: }
9896: PetscLogEventBegin(MAT_MatMultSymbolic,A,B,0,0);
9897: (*symbolic)(A,B,fill,C);
9898: PetscLogEventEnd(MAT_MatMultSymbolic,A,B,0,0);
9899: return(0);
9900: }
9902: /*@
9903: MatMatMultNumeric - Performs the numeric matrix-matrix product.
9904: Call this routine after first calling MatMatMultSymbolic().
9906: Neighbor-wise Collective on Mat
9908: Input Parameters:
9909: + A - the left matrix
9910: - B - the right matrix
9912: Output Parameters:
9913: . C - the product matrix, which was created by from MatMatMultSymbolic() or a call to MatMatMult().
9915: Notes:
9916: C must have been created with MatMatMultSymbolic().
9918: This routine is currently implemented for
9919: - pairs of AIJ matrices and classes which inherit from AIJ, C will be of type MATAIJ.
9920: - pairs of AIJ (A) and Dense (B) matrix, C will be of type Dense.
9921: - pairs of Dense (A) and AIJ (B) matrix, C will be of type Dense.
9923: Level: intermediate
9925: .seealso: MatMatMult(), MatMatMultSymbolic()
9926: @*/
9927: PetscErrorCode MatMatMultNumeric(Mat A,Mat B,Mat C)
9928: {
9932: MatMatMult(A,B,MAT_REUSE_MATRIX,0.0,&C);
9933: return(0);
9934: }
9936: /*@
9937: MatMatTransposeMult - Performs Matrix-Matrix Multiplication C=A*B^T.
9939: Neighbor-wise Collective on Mat
9941: Input Parameters:
9942: + A - the left matrix
9943: . B - the right matrix
9944: . scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
9945: - fill - expected fill as ratio of nnz(C)/(nnz(A) + nnz(B)), use PETSC_DEFAULT if not known
9947: Output Parameters:
9948: . C - the product matrix
9950: Notes:
9951: C will be created if MAT_INITIAL_MATRIX and must be destroyed by the user with MatDestroy().
9953: MAT_REUSE_MATRIX can only be used if the matrices A and B have the same nonzero pattern as in the previous call
9955: To determine the correct fill value, run with -info and search for the string "Fill ratio" to see the value
9956: actually needed.
9958: This routine is currently only implemented for pairs of SeqAIJ matrices, for the SeqDense class,
9959: and for pairs of MPIDense matrices.
9961: Options Database Keys:
9962: + -matmattransmult_mpidense_mpidense_via {allgatherv,cyclic} - Choose between algorthims for MPIDense matrices: the
9963: first redundantly copies the transposed B matrix on each process and requiers O(log P) communication complexity;
9964: the second never stores more than one portion of the B matrix at a time by requires O(P) communication complexity.
9966: Level: intermediate
9968: .seealso: MatMatTransposeMultSymbolic(), MatMatTransposeMultNumeric(), MatMatMult(), MatTransposeMatMult() MatPtAP()
9969: @*/
9970: PetscErrorCode MatMatTransposeMult(Mat A,Mat B,MatReuse scall,PetscReal fill,Mat *C)
9971: {
9973: PetscErrorCode (*fA)(Mat,Mat,MatReuse,PetscReal,Mat*);
9974: PetscErrorCode (*fB)(Mat,Mat,MatReuse,PetscReal,Mat*);
9979: if (scall == MAT_INPLACE_MATRIX) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Inplace product not supported");
9980: if (!A->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
9981: if (A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
9984: MatCheckPreallocated(B,2);
9985: if (!B->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
9986: if (B->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
9988: if (B->cmap->N!=A->cmap->N) SETERRQ2(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Matrix dimensions are incompatible, AN %D != BN %D",A->cmap->N,B->cmap->N);
9989: if (fill == PETSC_DEFAULT || fill == PETSC_DECIDE) fill = 2.0;
9990: if (fill < 1.0) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Expected fill=%g must be > 1.0",(double)fill);
9991: MatCheckPreallocated(A,1);
9993: fA = A->ops->mattransposemult;
9994: if (!fA) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"MatMatTransposeMult not supported for A of type %s",((PetscObject)A)->type_name);
9995: fB = B->ops->mattransposemult;
9996: if (!fB) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"MatMatTransposeMult not supported for B of type %s",((PetscObject)B)->type_name);
9997: if (fB!=fA) SETERRQ2(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_INCOMP,"MatMatTransposeMult requires A, %s, to be compatible with B, %s",((PetscObject)A)->type_name,((PetscObject)B)->type_name);
9999: PetscLogEventBegin(MAT_MatTransposeMult,A,B,0,0);
10000: if (scall == MAT_INITIAL_MATRIX) {
10001: PetscLogEventBegin(MAT_MatTransposeMultSymbolic,A,B,0,0);
10002: (*A->ops->mattransposemultsymbolic)(A,B,fill,C);
10003: PetscLogEventEnd(MAT_MatTransposeMultSymbolic,A,B,0,0);
10004: }
10005: PetscLogEventBegin(MAT_MatTransposeMultNumeric,A,B,0,0);
10006: (*A->ops->mattransposemultnumeric)(A,B,*C);
10007: PetscLogEventEnd(MAT_MatTransposeMultNumeric,A,B,0,0);
10008: PetscLogEventEnd(MAT_MatTransposeMult,A,B,0,0);
10009: return(0);
10010: }
10012: /*@
10013: MatTransposeMatMult - Performs Matrix-Matrix Multiplication C=A^T*B.
10015: Neighbor-wise Collective on Mat
10017: Input Parameters:
10018: + A - the left matrix
10019: . B - the right matrix
10020: . scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
10021: - fill - expected fill as ratio of nnz(C)/(nnz(A) + nnz(B)), use PETSC_DEFAULT if not known
10023: Output Parameters:
10024: . C - the product matrix
10026: Notes:
10027: C will be created if MAT_INITIAL_MATRIX and must be destroyed by the user with MatDestroy().
10029: MAT_REUSE_MATRIX can only be used if the matrices A and B have the same nonzero pattern as in the previous call
10031: To determine the correct fill value, run with -info and search for the string "Fill ratio" to see the value
10032: actually needed.
10034: This routine is currently implemented for pairs of AIJ matrices and pairs of SeqDense matrices and classes
10035: which inherit from SeqAIJ. C will be of same type as the input matrices.
10037: Level: intermediate
10039: .seealso: MatTransposeMatMultSymbolic(), MatTransposeMatMultNumeric(), MatMatMult(), MatMatTransposeMult(), MatPtAP()
10040: @*/
10041: PetscErrorCode MatTransposeMatMult(Mat A,Mat B,MatReuse scall,PetscReal fill,Mat *C)
10042: {
10044: PetscErrorCode (*fA)(Mat,Mat,MatReuse,PetscReal,Mat*);
10045: PetscErrorCode (*fB)(Mat,Mat,MatReuse,PetscReal,Mat*);
10046: PetscErrorCode (*transposematmult)(Mat,Mat,MatReuse,PetscReal,Mat*) = NULL;
10051: if (scall == MAT_INPLACE_MATRIX) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Inplace product not supported");
10052: if (!A->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
10053: if (A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
10056: MatCheckPreallocated(B,2);
10057: if (!B->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
10058: if (B->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
10060: if (B->rmap->N!=A->rmap->N) SETERRQ2(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Matrix dimensions are incompatible, %D != %D",B->rmap->N,A->rmap->N);
10061: if (fill == PETSC_DEFAULT || fill == PETSC_DECIDE) fill = 2.0;
10062: if (fill < 1.0) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Expected fill=%g must be > 1.0",(double)fill);
10063: MatCheckPreallocated(A,1);
10065: fA = A->ops->transposematmult;
10066: fB = B->ops->transposematmult;
10067: if (fB==fA) {
10068: if (!fA) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"MatTransposeMatMult not supported for A of type %s",((PetscObject)A)->type_name);
10069: transposematmult = fA;
10070: } else {
10071: /* dispatch based on the type of A and B from their PetscObject's PetscFunctionLists. */
10072: char multname[256];
10073: PetscStrncpy(multname,"MatTransposeMatMult_",sizeof(multname));
10074: PetscStrlcat(multname,((PetscObject)A)->type_name,sizeof(multname));
10075: PetscStrlcat(multname,"_",sizeof(multname));
10076: PetscStrlcat(multname,((PetscObject)B)->type_name,sizeof(multname));
10077: PetscStrlcat(multname,"_C",sizeof(multname)); /* e.g., multname = "MatMatMult_seqdense_seqaij_C" */
10078: PetscObjectQueryFunction((PetscObject)B,multname,&transposematmult);
10079: if (!transposematmult) SETERRQ2(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_INCOMP,"MatTransposeMatMult requires A, %s, to be compatible with B, %s",((PetscObject)A)->type_name,((PetscObject)B)->type_name);
10080: }
10081: PetscLogEventBegin(MAT_TransposeMatMult,A,B,0,0);
10082: (*transposematmult)(A,B,scall,fill,C);
10083: PetscLogEventEnd(MAT_TransposeMatMult,A,B,0,0);
10084: return(0);
10085: }
10087: /*@
10088: MatMatMatMult - Performs Matrix-Matrix-Matrix Multiplication D=A*B*C.
10090: Neighbor-wise Collective on Mat
10092: Input Parameters:
10093: + A - the left matrix
10094: . B - the middle matrix
10095: . C - the right matrix
10096: . scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
10097: - 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
10098: if the result is a dense matrix this is irrelevent
10100: Output Parameters:
10101: . D - the product matrix
10103: Notes:
10104: Unless scall is MAT_REUSE_MATRIX D will be created.
10106: MAT_REUSE_MATRIX can only be used if the matrices A, B and C have the same nonzero pattern as in the previous call
10108: To determine the correct fill value, run with -info and search for the string "Fill ratio" to see the value
10109: actually needed.
10111: If you have many matrices with the same non-zero structure to multiply, you
10112: should use MAT_REUSE_MATRIX in all calls but the first or
10114: Level: intermediate
10116: .seealso: MatMatMult, MatPtAP()
10117: @*/
10118: PetscErrorCode MatMatMatMult(Mat A,Mat B,Mat C,MatReuse scall,PetscReal fill,Mat *D)
10119: {
10121: PetscErrorCode (*fA)(Mat,Mat,Mat,MatReuse,PetscReal,Mat*);
10122: PetscErrorCode (*fB)(Mat,Mat,Mat,MatReuse,PetscReal,Mat*);
10123: PetscErrorCode (*fC)(Mat,Mat,Mat,MatReuse,PetscReal,Mat*);
10124: PetscErrorCode (*mult)(Mat,Mat,Mat,MatReuse,PetscReal,Mat*)=NULL;
10129: MatCheckPreallocated(A,1);
10130: if (scall == MAT_INPLACE_MATRIX) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Inplace product not supported");
10131: if (!A->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
10132: if (A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
10135: MatCheckPreallocated(B,2);
10136: if (!B->assembled) SETERRQ(PetscObjectComm((PetscObject)B),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
10137: if (B->factortype) SETERRQ(PetscObjectComm((PetscObject)B),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
10140: MatCheckPreallocated(C,3);
10141: if (!C->assembled) SETERRQ(PetscObjectComm((PetscObject)C),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
10142: if (C->factortype) SETERRQ(PetscObjectComm((PetscObject)C),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
10143: if (B->rmap->N!=A->cmap->N) SETERRQ2(PetscObjectComm((PetscObject)B),PETSC_ERR_ARG_SIZ,"Matrix dimensions are incompatible, %D != %D",B->rmap->N,A->cmap->N);
10144: if (C->rmap->N!=B->cmap->N) SETERRQ2(PetscObjectComm((PetscObject)C),PETSC_ERR_ARG_SIZ,"Matrix dimensions are incompatible, %D != %D",C->rmap->N,B->cmap->N);
10145: if (scall == MAT_REUSE_MATRIX) {
10148: PetscLogEventBegin(MAT_MatMatMult,A,B,0,0);
10149: (*(*D)->ops->matmatmult)(A,B,C,scall,fill,D);
10150: PetscLogEventEnd(MAT_MatMatMult,A,B,0,0);
10151: return(0);
10152: }
10153: if (fill == PETSC_DEFAULT || fill == PETSC_DECIDE) fill = 2.0;
10154: if (fill < 1.0) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Expected fill=%g must be >= 1.0",(double)fill);
10156: fA = A->ops->matmatmult;
10157: fB = B->ops->matmatmult;
10158: fC = C->ops->matmatmult;
10159: if (fA == fB && fA == fC) {
10160: if (!fA) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"MatMatMatMult not supported for A of type %s",((PetscObject)A)->type_name);
10161: mult = fA;
10162: } else {
10163: /* dispatch based on the type of A, B and C from their PetscObject's PetscFunctionLists. */
10164: char multname[256];
10165: PetscStrncpy(multname,"MatMatMatMult_",sizeof(multname));
10166: PetscStrlcat(multname,((PetscObject)A)->type_name,sizeof(multname));
10167: PetscStrlcat(multname,"_",sizeof(multname));
10168: PetscStrlcat(multname,((PetscObject)B)->type_name,sizeof(multname));
10169: PetscStrlcat(multname,"_",sizeof(multname));
10170: PetscStrlcat(multname,((PetscObject)C)->type_name,sizeof(multname));
10171: PetscStrlcat(multname,"_C",sizeof(multname));
10172: PetscObjectQueryFunction((PetscObject)B,multname,&mult);
10173: if (!mult) SETERRQ3(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_INCOMP,"MatMatMatMult requires A, %s, to be compatible with B, %s, C, %s",((PetscObject)A)->type_name,((PetscObject)B)->type_name,((PetscObject)C)->type_name);
10174: }
10175: PetscLogEventBegin(MAT_MatMatMult,A,B,0,0);
10176: (*mult)(A,B,C,scall,fill,D);
10177: PetscLogEventEnd(MAT_MatMatMult,A,B,0,0);
10178: return(0);
10179: }
10181: /*@
10182: MatCreateRedundantMatrix - Create redundant matrices and put them into processors of subcommunicators.
10184: Collective on Mat
10186: Input Parameters:
10187: + mat - the matrix
10188: . nsubcomm - the number of subcommunicators (= number of redundant parallel or sequential matrices)
10189: . subcomm - MPI communicator split from the communicator where mat resides in (or MPI_COMM_NULL if nsubcomm is used)
10190: - reuse - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
10192: Output Parameter:
10193: . matredundant - redundant matrix
10195: Notes:
10196: MAT_REUSE_MATRIX can only be used when the nonzero structure of the
10197: original matrix has not changed from that last call to MatCreateRedundantMatrix().
10199: This routine creates the duplicated matrices in subcommunicators; you should NOT create them before
10200: calling it.
10202: Level: advanced
10204: Concepts: subcommunicator
10205: Concepts: duplicate matrix
10207: .seealso: MatDestroy()
10208: @*/
10209: PetscErrorCode MatCreateRedundantMatrix(Mat mat,PetscInt nsubcomm,MPI_Comm subcomm,MatReuse reuse,Mat *matredundant)
10210: {
10212: MPI_Comm comm;
10213: PetscMPIInt size;
10214: PetscInt mloc_sub,nloc_sub,rstart,rend,M=mat->rmap->N,N=mat->cmap->N,bs=mat->rmap->bs;
10215: Mat_Redundant *redund=NULL;
10216: PetscSubcomm psubcomm=NULL;
10217: MPI_Comm subcomm_in=subcomm;
10218: Mat *matseq;
10219: IS isrow,iscol;
10220: PetscBool newsubcomm=PETSC_FALSE;
10224: if (nsubcomm && reuse == MAT_REUSE_MATRIX) {
10227: }
10229: MPI_Comm_size(PetscObjectComm((PetscObject)mat),&size);
10230: if (size == 1 || nsubcomm == 1) {
10231: if (reuse == MAT_INITIAL_MATRIX) {
10232: MatDuplicate(mat,MAT_COPY_VALUES,matredundant);
10233: } else {
10234: 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");
10235: MatCopy(mat,*matredundant,SAME_NONZERO_PATTERN);
10236: }
10237: return(0);
10238: }
10240: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
10241: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
10242: MatCheckPreallocated(mat,1);
10244: PetscLogEventBegin(MAT_RedundantMat,mat,0,0,0);
10245: if (subcomm_in == MPI_COMM_NULL && reuse == MAT_INITIAL_MATRIX) { /* get subcomm if user does not provide subcomm */
10246: /* create psubcomm, then get subcomm */
10247: PetscObjectGetComm((PetscObject)mat,&comm);
10248: MPI_Comm_size(comm,&size);
10249: if (nsubcomm < 1 || nsubcomm > size) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"nsubcomm must between 1 and %D",size);
10251: PetscSubcommCreate(comm,&psubcomm);
10252: PetscSubcommSetNumber(psubcomm,nsubcomm);
10253: PetscSubcommSetType(psubcomm,PETSC_SUBCOMM_CONTIGUOUS);
10254: PetscSubcommSetFromOptions(psubcomm);
10255: PetscCommDuplicate(PetscSubcommChild(psubcomm),&subcomm,NULL);
10256: newsubcomm = PETSC_TRUE;
10257: PetscSubcommDestroy(&psubcomm);
10258: }
10260: /* get isrow, iscol and a local sequential matrix matseq[0] */
10261: if (reuse == MAT_INITIAL_MATRIX) {
10262: mloc_sub = PETSC_DECIDE;
10263: nloc_sub = PETSC_DECIDE;
10264: if (bs < 1) {
10265: PetscSplitOwnership(subcomm,&mloc_sub,&M);
10266: PetscSplitOwnership(subcomm,&nloc_sub,&N);
10267: } else {
10268: PetscSplitOwnershipBlock(subcomm,bs,&mloc_sub,&M);
10269: PetscSplitOwnershipBlock(subcomm,bs,&nloc_sub,&N);
10270: }
10271: MPI_Scan(&mloc_sub,&rend,1,MPIU_INT,MPI_SUM,subcomm);
10272: rstart = rend - mloc_sub;
10273: ISCreateStride(PETSC_COMM_SELF,mloc_sub,rstart,1,&isrow);
10274: ISCreateStride(PETSC_COMM_SELF,N,0,1,&iscol);
10275: } else { /* reuse == MAT_REUSE_MATRIX */
10276: 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");
10277: /* retrieve subcomm */
10278: PetscObjectGetComm((PetscObject)(*matredundant),&subcomm);
10279: redund = (*matredundant)->redundant;
10280: isrow = redund->isrow;
10281: iscol = redund->iscol;
10282: matseq = redund->matseq;
10283: }
10284: MatCreateSubMatrices(mat,1,&isrow,&iscol,reuse,&matseq);
10286: /* get matredundant over subcomm */
10287: if (reuse == MAT_INITIAL_MATRIX) {
10288: MatCreateMPIMatConcatenateSeqMat(subcomm,matseq[0],nloc_sub,reuse,matredundant);
10290: /* create a supporting struct and attach it to C for reuse */
10291: PetscNewLog(*matredundant,&redund);
10292: (*matredundant)->redundant = redund;
10293: redund->isrow = isrow;
10294: redund->iscol = iscol;
10295: redund->matseq = matseq;
10296: if (newsubcomm) {
10297: redund->subcomm = subcomm;
10298: } else {
10299: redund->subcomm = MPI_COMM_NULL;
10300: }
10301: } else {
10302: MatCreateMPIMatConcatenateSeqMat(subcomm,matseq[0],PETSC_DECIDE,reuse,matredundant);
10303: }
10304: PetscLogEventEnd(MAT_RedundantMat,mat,0,0,0);
10305: return(0);
10306: }
10308: /*@C
10309: MatGetMultiProcBlock - Create multiple [bjacobi] 'parallel submatrices' from
10310: a given 'mat' object. Each submatrix can span multiple procs.
10312: Collective on Mat
10314: Input Parameters:
10315: + mat - the matrix
10316: . subcomm - the subcommunicator obtained by com_split(comm)
10317: - scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
10319: Output Parameter:
10320: . subMat - 'parallel submatrices each spans a given subcomm
10322: Notes:
10323: The submatrix partition across processors is dictated by 'subComm' a
10324: communicator obtained by com_split(comm). The comm_split
10325: is not restriced to be grouped with consecutive original ranks.
10327: Due the comm_split() usage, the parallel layout of the submatrices
10328: map directly to the layout of the original matrix [wrt the local
10329: row,col partitioning]. So the original 'DiagonalMat' naturally maps
10330: into the 'DiagonalMat' of the subMat, hence it is used directly from
10331: the subMat. However the offDiagMat looses some columns - and this is
10332: reconstructed with MatSetValues()
10334: Level: advanced
10336: Concepts: subcommunicator
10337: Concepts: submatrices
10339: .seealso: MatCreateSubMatrices()
10340: @*/
10341: PetscErrorCode MatGetMultiProcBlock(Mat mat, MPI_Comm subComm, MatReuse scall,Mat *subMat)
10342: {
10344: PetscMPIInt commsize,subCommSize;
10347: MPI_Comm_size(PetscObjectComm((PetscObject)mat),&commsize);
10348: MPI_Comm_size(subComm,&subCommSize);
10349: if (subCommSize > commsize) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_OUTOFRANGE,"CommSize %D < SubCommZize %D",commsize,subCommSize);
10351: 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");
10352: PetscLogEventBegin(MAT_GetMultiProcBlock,mat,0,0,0);
10353: (*mat->ops->getmultiprocblock)(mat,subComm,scall,subMat);
10354: PetscLogEventEnd(MAT_GetMultiProcBlock,mat,0,0,0);
10355: return(0);
10356: }
10358: /*@
10359: MatGetLocalSubMatrix - Gets a reference to a submatrix specified in local numbering
10361: Not Collective
10363: Input Arguments:
10364: mat - matrix to extract local submatrix from
10365: isrow - local row indices for submatrix
10366: iscol - local column indices for submatrix
10368: Output Arguments:
10369: submat - the submatrix
10371: Level: intermediate
10373: Notes:
10374: The submat should be returned with MatRestoreLocalSubMatrix().
10376: Depending on the format of mat, the returned submat may not implement MatMult(). Its communicator may be
10377: the same as mat, it may be PETSC_COMM_SELF, or some other subcomm of mat's.
10379: The submat always implements MatSetValuesLocal(). If isrow and iscol have the same block size, then
10380: MatSetValuesBlockedLocal() will also be implemented.
10382: The mat must have had a ISLocalToGlobalMapping provided to it with MatSetLocalToGlobalMapping(). Note that
10383: matrices obtained with DMCreateMatrix() generally already have the local to global mapping provided.
10385: .seealso: MatRestoreLocalSubMatrix(), MatCreateLocalRef(), MatSetLocalToGlobalMapping()
10386: @*/
10387: PetscErrorCode MatGetLocalSubMatrix(Mat mat,IS isrow,IS iscol,Mat *submat)
10388: {
10397: if (!mat->rmap->mapping) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Matrix must have local to global mapping provided before this call");
10399: if (mat->ops->getlocalsubmatrix) {
10400: (*mat->ops->getlocalsubmatrix)(mat,isrow,iscol,submat);
10401: } else {
10402: MatCreateLocalRef(mat,isrow,iscol,submat);
10403: }
10404: return(0);
10405: }
10407: /*@
10408: MatRestoreLocalSubMatrix - Restores a reference to a submatrix specified in local numbering
10410: Not Collective
10412: Input Arguments:
10413: mat - matrix to extract local submatrix from
10414: isrow - local row indices for submatrix
10415: iscol - local column indices for submatrix
10416: submat - the submatrix
10418: Level: intermediate
10420: .seealso: MatGetLocalSubMatrix()
10421: @*/
10422: PetscErrorCode MatRestoreLocalSubMatrix(Mat mat,IS isrow,IS iscol,Mat *submat)
10423: {
10432: if (*submat) {
10434: }
10436: if (mat->ops->restorelocalsubmatrix) {
10437: (*mat->ops->restorelocalsubmatrix)(mat,isrow,iscol,submat);
10438: } else {
10439: MatDestroy(submat);
10440: }
10441: *submat = NULL;
10442: return(0);
10443: }
10445: /* --------------------------------------------------------*/
10446: /*@
10447: MatFindZeroDiagonals - Finds all the rows of a matrix that have zero or no diagonal entry in the matrix
10449: Collective on Mat
10451: Input Parameter:
10452: . mat - the matrix
10454: Output Parameter:
10455: . is - if any rows have zero diagonals this contains the list of them
10457: Level: developer
10459: Concepts: matrix-vector product
10461: .seealso: MatMultTranspose(), MatMultAdd(), MatMultTransposeAdd()
10462: @*/
10463: PetscErrorCode MatFindZeroDiagonals(Mat mat,IS *is)
10464: {
10470: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
10471: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
10473: if (!mat->ops->findzerodiagonals) {
10474: Vec diag;
10475: const PetscScalar *a;
10476: PetscInt *rows;
10477: PetscInt rStart, rEnd, r, nrow = 0;
10479: MatCreateVecs(mat, &diag, NULL);
10480: MatGetDiagonal(mat, diag);
10481: MatGetOwnershipRange(mat, &rStart, &rEnd);
10482: VecGetArrayRead(diag, &a);
10483: for (r = 0; r < rEnd-rStart; ++r) if (a[r] == 0.0) ++nrow;
10484: PetscMalloc1(nrow, &rows);
10485: nrow = 0;
10486: for (r = 0; r < rEnd-rStart; ++r) if (a[r] == 0.0) rows[nrow++] = r+rStart;
10487: VecRestoreArrayRead(diag, &a);
10488: VecDestroy(&diag);
10489: ISCreateGeneral(PetscObjectComm((PetscObject) mat), nrow, rows, PETSC_OWN_POINTER, is);
10490: } else {
10491: (*mat->ops->findzerodiagonals)(mat, is);
10492: }
10493: return(0);
10494: }
10496: /*@
10497: MatFindOffBlockDiagonalEntries - Finds all the rows of a matrix that have entries outside of the main diagonal block (defined by the matrix block size)
10499: Collective on Mat
10501: Input Parameter:
10502: . mat - the matrix
10504: Output Parameter:
10505: . is - contains the list of rows with off block diagonal entries
10507: Level: developer
10509: Concepts: matrix-vector product
10511: .seealso: MatMultTranspose(), MatMultAdd(), MatMultTransposeAdd()
10512: @*/
10513: PetscErrorCode MatFindOffBlockDiagonalEntries(Mat mat,IS *is)
10514: {
10520: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
10521: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
10523: if (!mat->ops->findoffblockdiagonalentries) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"This matrix type does not have a find off block diagonal entries defined");
10524: (*mat->ops->findoffblockdiagonalentries)(mat,is);
10525: return(0);
10526: }
10528: /*@C
10529: MatInvertBlockDiagonal - Inverts the block diagonal entries.
10531: Collective on Mat
10533: Input Parameters:
10534: . mat - the matrix
10536: Output Parameters:
10537: . values - the block inverses in column major order (FORTRAN-like)
10539: Note:
10540: This routine is not available from Fortran.
10542: Level: advanced
10544: .seealso: MatInvertBockDiagonalMat
10545: @*/
10546: PetscErrorCode MatInvertBlockDiagonal(Mat mat,const PetscScalar **values)
10547: {
10552: if (!mat->assembled) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
10553: if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
10554: if (!mat->ops->invertblockdiagonal) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"Not supported");
10555: (*mat->ops->invertblockdiagonal)(mat,values);
10556: return(0);
10557: }
10559: /*@C
10560: MatInvertVariableBlockDiagonal - Inverts the block diagonal entries.
10562: Collective on Mat
10564: Input Parameters:
10565: + mat - the matrix
10566: . nblocks - the number of blocks
10567: - bsizes - the size of each block
10569: Output Parameters:
10570: . values - the block inverses in column major order (FORTRAN-like)
10572: Note:
10573: This routine is not available from Fortran.
10575: Level: advanced
10577: .seealso: MatInvertBockDiagonal()
10578: @*/
10579: PetscErrorCode MatInvertVariableBlockDiagonal(Mat mat,PetscInt nblocks,const PetscInt *bsizes,PetscScalar *values)
10580: {
10585: if (!mat->assembled) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
10586: if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
10587: if (!mat->ops->invertvariableblockdiagonal) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"Not supported");
10588: (*mat->ops->invertvariableblockdiagonal)(mat,nblocks,bsizes,values);
10589: return(0);
10590: }
10592: /*@
10593: MatInvertBlockDiagonalMat - set matrix C to be the inverted block diagonal of matrix A
10595: Collective on Mat
10597: Input Parameters:
10598: . A - the matrix
10600: Output Parameters:
10601: . C - matrix with inverted block diagonal of A. This matrix should be created and may have its type set.
10603: Notes: the blocksize of the matrix is used to determine the blocks on the diagonal of C
10605: Level: advanced
10607: .seealso: MatInvertBockDiagonal()
10608: @*/
10609: PetscErrorCode MatInvertBlockDiagonalMat(Mat A,Mat C)
10610: {
10611: PetscErrorCode ierr;
10612: const PetscScalar *vals;
10613: PetscInt *dnnz;
10614: PetscInt M,N,m,n,rstart,rend,bs,i,j;
10617: MatInvertBlockDiagonal(A,&vals);
10618: MatGetBlockSize(A,&bs);
10619: MatGetSize(A,&M,&N);
10620: MatGetLocalSize(A,&m,&n);
10621: MatSetSizes(C,m,n,M,N);
10622: MatSetBlockSize(C,bs);
10623: PetscMalloc1(m/bs,&dnnz);
10624: for (j = 0; j < m/bs; j++) dnnz[j] = 1;
10625: MatXAIJSetPreallocation(C,bs,dnnz,NULL,NULL,NULL);
10626: PetscFree(dnnz);
10627: MatGetOwnershipRange(C,&rstart,&rend);
10628: MatSetOption(C,MAT_ROW_ORIENTED,PETSC_FALSE);
10629: for (i = rstart/bs; i < rend/bs; i++) {
10630: MatSetValuesBlocked(C,1,&i,1,&i,&vals[(i-rstart/bs)*bs*bs],INSERT_VALUES);
10631: }
10632: MatAssemblyBegin(C,MAT_FINAL_ASSEMBLY);
10633: MatAssemblyEnd(C,MAT_FINAL_ASSEMBLY);
10634: MatSetOption(C,MAT_ROW_ORIENTED,PETSC_TRUE);
10635: return(0);
10636: }
10638: /*@C
10639: MatTransposeColoringDestroy - Destroys a coloring context for matrix product C=A*B^T that was created
10640: via MatTransposeColoringCreate().
10642: Collective on MatTransposeColoring
10644: Input Parameter:
10645: . c - coloring context
10647: Level: intermediate
10649: .seealso: MatTransposeColoringCreate()
10650: @*/
10651: PetscErrorCode MatTransposeColoringDestroy(MatTransposeColoring *c)
10652: {
10653: PetscErrorCode ierr;
10654: MatTransposeColoring matcolor=*c;
10657: if (!matcolor) return(0);
10658: if (--((PetscObject)matcolor)->refct > 0) {matcolor = 0; return(0);}
10660: PetscFree3(matcolor->ncolumns,matcolor->nrows,matcolor->colorforrow);
10661: PetscFree(matcolor->rows);
10662: PetscFree(matcolor->den2sp);
10663: PetscFree(matcolor->colorforcol);
10664: PetscFree(matcolor->columns);
10665: if (matcolor->brows>0) {
10666: PetscFree(matcolor->lstart);
10667: }
10668: PetscHeaderDestroy(c);
10669: return(0);
10670: }
10672: /*@C
10673: MatTransColoringApplySpToDen - Given a symbolic matrix product C=A*B^T for which
10674: a MatTransposeColoring context has been created, computes a dense B^T by Apply
10675: MatTransposeColoring to sparse B.
10677: Collective on MatTransposeColoring
10679: Input Parameters:
10680: + B - sparse matrix B
10681: . Btdense - symbolic dense matrix B^T
10682: - coloring - coloring context created with MatTransposeColoringCreate()
10684: Output Parameter:
10685: . Btdense - dense matrix B^T
10687: Level: advanced
10689: Notes:
10690: These are used internally for some implementations of MatRARt()
10692: .seealso: MatTransposeColoringCreate(), MatTransposeColoringDestroy(), MatTransColoringApplyDenToSp()
10694: .keywords: coloring
10695: @*/
10696: PetscErrorCode MatTransColoringApplySpToDen(MatTransposeColoring coloring,Mat B,Mat Btdense)
10697: {
10705: if (!B->ops->transcoloringapplysptoden) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Not supported for this matrix type %s",((PetscObject)B)->type_name);
10706: (B->ops->transcoloringapplysptoden)(coloring,B,Btdense);
10707: return(0);
10708: }
10710: /*@C
10711: MatTransColoringApplyDenToSp - Given a symbolic matrix product Csp=A*B^T for which
10712: a MatTransposeColoring context has been created and a dense matrix Cden=A*Btdense
10713: in which Btdens is obtained from MatTransColoringApplySpToDen(), recover sparse matrix
10714: Csp from Cden.
10716: Collective on MatTransposeColoring
10718: Input Parameters:
10719: + coloring - coloring context created with MatTransposeColoringCreate()
10720: - Cden - matrix product of a sparse matrix and a dense matrix Btdense
10722: Output Parameter:
10723: . Csp - sparse matrix
10725: Level: advanced
10727: Notes:
10728: These are used internally for some implementations of MatRARt()
10730: .seealso: MatTransposeColoringCreate(), MatTransposeColoringDestroy(), MatTransColoringApplySpToDen()
10732: .keywords: coloring
10733: @*/
10734: PetscErrorCode MatTransColoringApplyDenToSp(MatTransposeColoring matcoloring,Mat Cden,Mat Csp)
10735: {
10743: if (!Csp->ops->transcoloringapplydentosp) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Not supported for this matrix type %s",((PetscObject)Csp)->type_name);
10744: (Csp->ops->transcoloringapplydentosp)(matcoloring,Cden,Csp);
10745: return(0);
10746: }
10748: /*@C
10749: MatTransposeColoringCreate - Creates a matrix coloring context for matrix product C=A*B^T.
10751: Collective on Mat
10753: Input Parameters:
10754: + mat - the matrix product C
10755: - iscoloring - the coloring of the matrix; usually obtained with MatColoringCreate() or DMCreateColoring()
10757: Output Parameter:
10758: . color - the new coloring context
10760: Level: intermediate
10762: .seealso: MatTransposeColoringDestroy(), MatTransColoringApplySpToDen(),
10763: MatTransColoringApplyDenToSp()
10764: @*/
10765: PetscErrorCode MatTransposeColoringCreate(Mat mat,ISColoring iscoloring,MatTransposeColoring *color)
10766: {
10767: MatTransposeColoring c;
10768: MPI_Comm comm;
10769: PetscErrorCode ierr;
10772: PetscLogEventBegin(MAT_TransposeColoringCreate,mat,0,0,0);
10773: PetscObjectGetComm((PetscObject)mat,&comm);
10774: PetscHeaderCreate(c,MAT_TRANSPOSECOLORING_CLASSID,"MatTransposeColoring","Matrix product C=A*B^T via coloring","Mat",comm,MatTransposeColoringDestroy,NULL);
10776: c->ctype = iscoloring->ctype;
10777: if (mat->ops->transposecoloringcreate) {
10778: (*mat->ops->transposecoloringcreate)(mat,iscoloring,c);
10779: } else SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Code not yet written for this matrix type");
10781: *color = c;
10782: PetscLogEventEnd(MAT_TransposeColoringCreate,mat,0,0,0);
10783: return(0);
10784: }
10786: /*@
10787: MatGetNonzeroState - Returns a 64 bit integer representing the current state of nonzeros in the matrix. If the
10788: matrix has had no new nonzero locations added to the matrix since the previous call then the value will be the
10789: same, otherwise it will be larger
10791: Not Collective
10793: Input Parameter:
10794: . A - the matrix
10796: Output Parameter:
10797: . state - the current state
10799: Notes:
10800: You can only compare states from two different calls to the SAME matrix, you cannot compare calls between
10801: different matrices
10803: Level: intermediate
10805: @*/
10806: PetscErrorCode MatGetNonzeroState(Mat mat,PetscObjectState *state)
10807: {
10810: *state = mat->nonzerostate;
10811: return(0);
10812: }
10814: /*@
10815: MatCreateMPIMatConcatenateSeqMat - Creates a single large PETSc matrix by concatenating sequential
10816: matrices from each processor
10818: Collective on MPI_Comm
10820: Input Parameters:
10821: + comm - the communicators the parallel matrix will live on
10822: . seqmat - the input sequential matrices
10823: . n - number of local columns (or PETSC_DECIDE)
10824: - reuse - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
10826: Output Parameter:
10827: . mpimat - the parallel matrix generated
10829: Level: advanced
10831: Notes:
10832: The number of columns of the matrix in EACH processor MUST be the same.
10834: @*/
10835: PetscErrorCode MatCreateMPIMatConcatenateSeqMat(MPI_Comm comm,Mat seqmat,PetscInt n,MatReuse reuse,Mat *mpimat)
10836: {
10840: if (!seqmat->ops->creatempimatconcatenateseqmat) SETERRQ1(PetscObjectComm((PetscObject)seqmat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)seqmat)->type_name);
10841: 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");
10843: PetscLogEventBegin(MAT_Merge,seqmat,0,0,0);
10844: (*seqmat->ops->creatempimatconcatenateseqmat)(comm,seqmat,n,reuse,mpimat);
10845: PetscLogEventEnd(MAT_Merge,seqmat,0,0,0);
10846: return(0);
10847: }
10849: /*@
10850: MatSubdomainsCreateCoalesce - Creates index subdomains by coalescing adjacent
10851: ranks' ownership ranges.
10853: Collective on A
10855: Input Parameters:
10856: + A - the matrix to create subdomains from
10857: - N - requested number of subdomains
10860: Output Parameters:
10861: + n - number of subdomains resulting on this rank
10862: - iss - IS list with indices of subdomains on this rank
10864: Level: advanced
10866: Notes:
10867: number of subdomains must be smaller than the communicator size
10868: @*/
10869: PetscErrorCode MatSubdomainsCreateCoalesce(Mat A,PetscInt N,PetscInt *n,IS *iss[])
10870: {
10871: MPI_Comm comm,subcomm;
10872: PetscMPIInt size,rank,color;
10873: PetscInt rstart,rend,k;
10874: PetscErrorCode ierr;
10877: PetscObjectGetComm((PetscObject)A,&comm);
10878: MPI_Comm_size(comm,&size);
10879: MPI_Comm_rank(comm,&rank);
10880: 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);
10881: *n = 1;
10882: k = ((PetscInt)size)/N + ((PetscInt)size%N>0); /* There are up to k ranks to a color */
10883: color = rank/k;
10884: MPI_Comm_split(comm,color,rank,&subcomm);
10885: PetscMalloc1(1,iss);
10886: MatGetOwnershipRange(A,&rstart,&rend);
10887: ISCreateStride(subcomm,rend-rstart,rstart,1,iss[0]);
10888: MPI_Comm_free(&subcomm);
10889: return(0);
10890: }
10892: /*@
10893: MatGalerkin - Constructs the coarse grid problem via Galerkin projection.
10895: If the interpolation and restriction operators are the same, uses MatPtAP.
10896: If they are not the same, use MatMatMatMult.
10898: Once the coarse grid problem is constructed, correct for interpolation operators
10899: that are not of full rank, which can legitimately happen in the case of non-nested
10900: geometric multigrid.
10902: Input Parameters:
10903: + restrct - restriction operator
10904: . dA - fine grid matrix
10905: . interpolate - interpolation operator
10906: . reuse - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
10907: - fill - expected fill, use PETSC_DEFAULT if you do not have a good estimate
10909: Output Parameters:
10910: . A - the Galerkin coarse matrix
10912: Options Database Key:
10913: . -pc_mg_galerkin <both,pmat,mat,none>
10915: Level: developer
10917: .keywords: MG, multigrid, Galerkin
10919: .seealso: MatPtAP(), MatMatMatMult()
10920: @*/
10921: PetscErrorCode MatGalerkin(Mat restrct, Mat dA, Mat interpolate, MatReuse reuse, PetscReal fill, Mat *A)
10922: {
10924: IS zerorows;
10925: Vec diag;
10928: if (reuse == MAT_INPLACE_MATRIX) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Inplace product not supported");
10929: /* Construct the coarse grid matrix */
10930: if (interpolate == restrct) {
10931: MatPtAP(dA,interpolate,reuse,fill,A);
10932: } else {
10933: MatMatMatMult(restrct,dA,interpolate,reuse,fill,A);
10934: }
10936: /* If the interpolation matrix is not of full rank, A will have zero rows.
10937: This can legitimately happen in the case of non-nested geometric multigrid.
10938: In that event, we set the rows of the matrix to the rows of the identity,
10939: ignoring the equations (as the RHS will also be zero). */
10941: MatFindZeroRows(*A, &zerorows);
10943: if (zerorows != NULL) { /* if there are any zero rows */
10944: MatCreateVecs(*A, &diag, NULL);
10945: MatGetDiagonal(*A, diag);
10946: VecISSet(diag, zerorows, 1.0);
10947: MatDiagonalSet(*A, diag, INSERT_VALUES);
10948: VecDestroy(&diag);
10949: ISDestroy(&zerorows);
10950: }
10951: return(0);
10952: }
10954: /*@C
10955: MatSetOperation - Allows user to set a matrix operation for any matrix type
10957: Logically Collective on Mat
10959: Input Parameters:
10960: + mat - the matrix
10961: . op - the name of the operation
10962: - f - the function that provides the operation
10964: Level: developer
10966: Usage:
10967: $ extern PetscErrorCode usermult(Mat,Vec,Vec);
10968: $ MatCreateXXX(comm,...&A);
10969: $ MatSetOperation(A,MATOP_MULT,(void(*)(void))usermult);
10971: Notes:
10972: See the file include/petscmat.h for a complete list of matrix
10973: operations, which all have the form MATOP_<OPERATION>, where
10974: <OPERATION> is the name (in all capital letters) of the
10975: user interface routine (e.g., MatMult() -> MATOP_MULT).
10977: All user-provided functions (except for MATOP_DESTROY) should have the same calling
10978: sequence as the usual matrix interface routines, since they
10979: are intended to be accessed via the usual matrix interface
10980: routines, e.g.,
10981: $ MatMult(Mat,Vec,Vec) -> usermult(Mat,Vec,Vec)
10983: In particular each function MUST return an error code of 0 on success and
10984: nonzero on failure.
10986: This routine is distinct from MatShellSetOperation() in that it can be called on any matrix type.
10988: .keywords: matrix, set, operation
10990: .seealso: MatGetOperation(), MatCreateShell(), MatShellSetContext(), MatShellSetOperation()
10991: @*/
10992: PetscErrorCode MatSetOperation(Mat mat,MatOperation op,void (*f)(void))
10993: {
10996: if (op == MATOP_VIEW && !mat->ops->viewnative && f != (void (*)(void))(mat->ops->view)) {
10997: mat->ops->viewnative = mat->ops->view;
10998: }
10999: (((void(**)(void))mat->ops)[op]) = f;
11000: return(0);
11001: }
11003: /*@C
11004: MatGetOperation - Gets a matrix operation for any matrix type.
11006: Not Collective
11008: Input Parameters:
11009: + mat - the matrix
11010: - op - the name of the operation
11012: Output Parameter:
11013: . f - the function that provides the operation
11015: Level: developer
11017: Usage:
11018: $ PetscErrorCode (*usermult)(Mat,Vec,Vec);
11019: $ MatGetOperation(A,MATOP_MULT,(void(**)(void))&usermult);
11021: Notes:
11022: See the file include/petscmat.h for a complete list of matrix
11023: operations, which all have the form MATOP_<OPERATION>, where
11024: <OPERATION> is the name (in all capital letters) of the
11025: user interface routine (e.g., MatMult() -> MATOP_MULT).
11027: This routine is distinct from MatShellGetOperation() in that it can be called on any matrix type.
11029: .keywords: matrix, get, operation
11031: .seealso: MatSetOperation(), MatCreateShell(), MatShellGetContext(), MatShellGetOperation()
11032: @*/
11033: PetscErrorCode MatGetOperation(Mat mat,MatOperation op,void(**f)(void))
11034: {
11037: *f = (((void (**)(void))mat->ops)[op]);
11038: return(0);
11039: }
11041: /*@
11042: MatHasOperation - Determines whether the given matrix supports the particular
11043: operation.
11045: Not Collective
11047: Input Parameters:
11048: + mat - the matrix
11049: - op - the operation, for example, MATOP_GET_DIAGONAL
11051: Output Parameter:
11052: . has - either PETSC_TRUE or PETSC_FALSE
11054: Level: advanced
11056: Notes:
11057: See the file include/petscmat.h for a complete list of matrix
11058: operations, which all have the form MATOP_<OPERATION>, where
11059: <OPERATION> is the name (in all capital letters) of the
11060: user-level routine. E.g., MatNorm() -> MATOP_NORM.
11062: .keywords: matrix, has, operation
11064: .seealso: MatCreateShell()
11065: @*/
11066: PetscErrorCode MatHasOperation(Mat mat,MatOperation op,PetscBool *has)
11067: {
11074: if (mat->ops->hasoperation) {
11075: (*mat->ops->hasoperation)(mat,op,has);
11076: } else {
11077: if (((void**)mat->ops)[op]) *has = PETSC_TRUE;
11078: else {
11079: *has = PETSC_FALSE;
11080: if (op == MATOP_CREATE_SUBMATRIX) {
11081: PetscMPIInt size;
11083: MPI_Comm_size(PetscObjectComm((PetscObject)mat),&size);
11084: if (size == 1) {
11085: MatHasOperation(mat,MATOP_CREATE_SUBMATRICES,has);
11086: }
11087: }
11088: }
11089: }
11090: return(0);
11091: }
11093: /*@
11094: MatHasCongruentLayouts - Determines whether the rows and columns layouts
11095: of the matrix are congruent
11097: Collective on mat
11099: Input Parameters:
11100: . mat - the matrix
11102: Output Parameter:
11103: . cong - either PETSC_TRUE or PETSC_FALSE
11105: Level: beginner
11107: Notes:
11109: .keywords: matrix, has
11111: .seealso: MatCreate(), MatSetSizes()
11112: @*/
11113: PetscErrorCode MatHasCongruentLayouts(Mat mat,PetscBool *cong)
11114: {
11121: if (!mat->rmap || !mat->cmap) {
11122: *cong = mat->rmap == mat->cmap ? PETSC_TRUE : PETSC_FALSE;
11123: return(0);
11124: }
11125: if (mat->congruentlayouts == PETSC_DECIDE) { /* first time we compare rows and cols layouts */
11126: PetscLayoutCompare(mat->rmap,mat->cmap,cong);
11127: if (*cong) mat->congruentlayouts = 1;
11128: else mat->congruentlayouts = 0;
11129: } else *cong = mat->congruentlayouts ? PETSC_TRUE : PETSC_FALSE;
11130: return(0);
11131: }
11133: /*@
11134: MatFreeIntermediateDataStructures - Free intermediate data structures created for reuse,
11135: e.g., matrx product of MatPtAP.
11137: Collective on mat
11139: Input Parameters:
11140: . mat - the matrix
11142: Output Parameter:
11143: . mat - the matrix with intermediate data structures released
11145: Level: advanced
11147: Notes:
11149: .keywords: matrix
11151: .seealso: MatPtAP(), MatMatMult()
11152: @*/
11153: PetscErrorCode MatFreeIntermediateDataStructures(Mat mat)
11154: {
11160: if (mat->ops->freeintermediatedatastructures) {
11161: (*mat->ops->freeintermediatedatastructures)(mat);
11162: }
11163: return(0);
11164: }