Actual source code: matrix.c
petsc-3.12.2 2019-11-22
1: /*
2: This is where the abstract matrix operations are defined
3: */
5: #include <petsc/private/matimpl.h>
6: #include <petsc/private/isimpl.h>
7: #include <petsc/private/vecimpl.h>
9: /* Logging support */
10: PetscClassId MAT_CLASSID;
11: PetscClassId MAT_COLORING_CLASSID;
12: PetscClassId MAT_FDCOLORING_CLASSID;
13: PetscClassId MAT_TRANSPOSECOLORING_CLASSID;
15: PetscLogEvent MAT_Mult, MAT_Mults, MAT_MultConstrained, MAT_MultAdd, MAT_MultTranspose;
16: PetscLogEvent MAT_MultTransposeConstrained, MAT_MultTransposeAdd, MAT_Solve, MAT_Solves, MAT_SolveAdd, MAT_SolveTranspose, MAT_MatSolve,MAT_MatTrSolve;
17: PetscLogEvent MAT_SolveTransposeAdd, MAT_SOR, MAT_ForwardSolve, MAT_BackwardSolve, MAT_LUFactor, MAT_LUFactorSymbolic;
18: PetscLogEvent MAT_LUFactorNumeric, MAT_CholeskyFactor, MAT_CholeskyFactorSymbolic, MAT_CholeskyFactorNumeric, MAT_ILUFactor;
19: PetscLogEvent MAT_ILUFactorSymbolic, MAT_ICCFactorSymbolic, MAT_Copy, MAT_Convert, MAT_Scale, MAT_AssemblyBegin;
20: PetscLogEvent MAT_AssemblyEnd, MAT_SetValues, MAT_GetValues, MAT_GetRow, MAT_GetRowIJ, MAT_CreateSubMats, MAT_GetOrdering, MAT_RedundantMat, MAT_GetSeqNonzeroStructure;
21: PetscLogEvent MAT_IncreaseOverlap, MAT_Partitioning, MAT_PartitioningND, MAT_Coarsen, MAT_ZeroEntries, MAT_Load, MAT_View, MAT_AXPY, MAT_FDColoringCreate;
22: PetscLogEvent MAT_FDColoringSetUp, MAT_FDColoringApply,MAT_Transpose,MAT_FDColoringFunction, MAT_CreateSubMat;
23: PetscLogEvent MAT_TransposeColoringCreate;
24: PetscLogEvent MAT_MatMult, MAT_MatMultSymbolic, MAT_MatMultNumeric;
25: PetscLogEvent MAT_PtAP, MAT_PtAPSymbolic, MAT_PtAPNumeric,MAT_RARt, MAT_RARtSymbolic, MAT_RARtNumeric;
26: PetscLogEvent MAT_MatTransposeMult, MAT_MatTransposeMultSymbolic, MAT_MatTransposeMultNumeric;
27: PetscLogEvent MAT_TransposeMatMult, MAT_TransposeMatMultSymbolic, MAT_TransposeMatMultNumeric;
28: PetscLogEvent MAT_MatMatMult, MAT_MatMatMultSymbolic, MAT_MatMatMultNumeric;
29: PetscLogEvent MAT_MultHermitianTranspose,MAT_MultHermitianTransposeAdd;
30: PetscLogEvent MAT_Getsymtranspose, MAT_Getsymtransreduced, MAT_GetBrowsOfAcols;
31: PetscLogEvent MAT_GetBrowsOfAocols, MAT_Getlocalmat, MAT_Getlocalmatcondensed, MAT_Seqstompi, MAT_Seqstompinum, MAT_Seqstompisym;
32: PetscLogEvent MAT_Applypapt, MAT_Applypapt_numeric, MAT_Applypapt_symbolic, MAT_GetSequentialNonzeroStructure;
33: PetscLogEvent MAT_GetMultiProcBlock;
34: PetscLogEvent MAT_CUSPARSECopyToGPU, MAT_SetValuesBatch;
35: PetscLogEvent MAT_ViennaCLCopyToGPU;
36: PetscLogEvent MAT_DenseCopyToGPU, MAT_DenseCopyFromGPU;
37: PetscLogEvent MAT_Merge,MAT_Residual,MAT_SetRandom;
38: PetscLogEvent MAT_FactorFactS,MAT_FactorInvS;
39: PetscLogEvent MATCOLORING_Apply,MATCOLORING_Comm,MATCOLORING_Local,MATCOLORING_ISCreate,MATCOLORING_SetUp,MATCOLORING_Weights;
41: const char *const MatFactorTypes[] = {"NONE","LU","CHOLESKY","ILU","ICC","ILUDT","MatFactorType","MAT_FACTOR_",0};
43: /*@
44: MatSetRandom - Sets all components of a matrix to random numbers. For sparse matrices that have been preallocated but not been assembled it randomly selects appropriate locations,
45: for sparse matrices that already have locations it fills the locations with random numbers
47: Logically Collective on Mat
49: Input Parameters:
50: + x - the matrix
51: - rctx - the random number context, formed by PetscRandomCreate(), or NULL and
52: it will create one internally.
54: Output Parameter:
55: . x - the matrix
57: Example of Usage:
58: .vb
59: PetscRandomCreate(PETSC_COMM_WORLD,&rctx);
60: MatSetRandom(x,rctx);
61: PetscRandomDestroy(rctx);
62: .ve
64: Level: intermediate
67: .seealso: MatZeroEntries(), MatSetValues(), PetscRandomCreate(), PetscRandomDestroy()
68: @*/
69: PetscErrorCode MatSetRandom(Mat x,PetscRandom rctx)
70: {
72: PetscRandom randObj = NULL;
79: if (!x->ops->setrandom) SETERRQ1(PetscObjectComm((PetscObject)x),PETSC_ERR_SUP,"Mat type %s",((PetscObject)x)->type_name);
81: if (!rctx) {
82: MPI_Comm comm;
83: PetscObjectGetComm((PetscObject)x,&comm);
84: PetscRandomCreate(comm,&randObj);
85: PetscRandomSetFromOptions(randObj);
86: rctx = randObj;
87: }
89: PetscLogEventBegin(MAT_SetRandom,x,rctx,0,0);
90: (*x->ops->setrandom)(x,rctx);
91: PetscLogEventEnd(MAT_SetRandom,x,rctx,0,0);
93: MatAssemblyBegin(x, MAT_FINAL_ASSEMBLY);
94: MatAssemblyEnd(x, MAT_FINAL_ASSEMBLY);
95: PetscRandomDestroy(&randObj);
96: return(0);
97: }
99: /*@
100: MatFactorGetErrorZeroPivot - returns the pivot value that was determined to be zero and the row it occurred in
102: Logically Collective on Mat
104: Input Parameters:
105: . mat - the factored matrix
107: Output Parameter:
108: + pivot - the pivot value computed
109: - row - the row that the zero pivot occurred. Note that this row must be interpreted carefully due to row reorderings and which processes
110: the share the matrix
112: Level: advanced
114: Notes:
115: This routine does not work for factorizations done with external packages.
116: This routine should only be called if MatGetFactorError() returns a value of MAT_FACTOR_NUMERIC_ZEROPIVOT
118: This can be called on non-factored matrices that come from, for example, matrices used in SOR.
120: .seealso: MatZeroEntries(), MatFactor(), MatGetFactor(), MatFactorSymbolic(), MatFactorClearError(), MatFactorGetErrorZeroPivot()
121: @*/
122: PetscErrorCode MatFactorGetErrorZeroPivot(Mat mat,PetscReal *pivot,PetscInt *row)
123: {
126: *pivot = mat->factorerror_zeropivot_value;
127: *row = mat->factorerror_zeropivot_row;
128: return(0);
129: }
131: /*@
132: MatFactorGetError - gets the error code from a factorization
134: Logically Collective on Mat
136: Input Parameters:
137: . mat - the factored matrix
139: Output Parameter:
140: . err - the error code
142: Level: advanced
144: Notes:
145: This can be called on non-factored matrices that come from, for example, matrices used in SOR.
147: .seealso: MatZeroEntries(), MatFactor(), MatGetFactor(), MatFactorSymbolic(), MatFactorClearError(), MatFactorGetErrorZeroPivot()
148: @*/
149: PetscErrorCode MatFactorGetError(Mat mat,MatFactorError *err)
150: {
153: *err = mat->factorerrortype;
154: return(0);
155: }
157: /*@
158: MatFactorClearError - clears the error code in a factorization
160: Logically Collective on Mat
162: Input Parameter:
163: . mat - the factored matrix
165: Level: developer
167: Notes:
168: This can be called on non-factored matrices that come from, for example, matrices used in SOR.
170: .seealso: MatZeroEntries(), MatFactor(), MatGetFactor(), MatFactorSymbolic(), MatFactorGetError(), MatFactorGetErrorZeroPivot()
171: @*/
172: PetscErrorCode MatFactorClearError(Mat mat)
173: {
176: mat->factorerrortype = MAT_FACTOR_NOERROR;
177: mat->factorerror_zeropivot_value = 0.0;
178: mat->factorerror_zeropivot_row = 0;
179: return(0);
180: }
182: PETSC_INTERN PetscErrorCode MatFindNonzeroRowsOrCols_Basic(Mat mat,PetscBool cols,PetscReal tol,IS *nonzero)
183: {
184: PetscErrorCode ierr;
185: Vec r,l;
186: const PetscScalar *al;
187: PetscInt i,nz,gnz,N,n;
190: MatCreateVecs(mat,&r,&l);
191: if (!cols) { /* nonzero rows */
192: MatGetSize(mat,&N,NULL);
193: MatGetLocalSize(mat,&n,NULL);
194: VecSet(l,0.0);
195: VecSetRandom(r,NULL);
196: MatMult(mat,r,l);
197: VecGetArrayRead(l,&al);
198: } else { /* nonzero columns */
199: MatGetSize(mat,NULL,&N);
200: MatGetLocalSize(mat,NULL,&n);
201: VecSet(r,0.0);
202: VecSetRandom(l,NULL);
203: MatMultTranspose(mat,l,r);
204: VecGetArrayRead(r,&al);
205: }
206: if (tol <= 0.0) { for (i=0,nz=0;i<n;i++) if (al[i] != 0.0) nz++; }
207: else { for (i=0,nz=0;i<n;i++) if (PetscAbsScalar(al[i]) > tol) nz++; }
208: MPIU_Allreduce(&nz,&gnz,1,MPIU_INT,MPI_SUM,PetscObjectComm((PetscObject)mat));
209: if (gnz != N) {
210: PetscInt *nzr;
211: PetscMalloc1(nz,&nzr);
212: if (nz) {
213: if (tol < 0) { for (i=0,nz=0;i<n;i++) if (al[i] != 0.0) nzr[nz++] = i; }
214: else { for (i=0,nz=0;i<n;i++) if (PetscAbsScalar(al[i]) > tol) nzr[nz++] = i; }
215: }
216: ISCreateGeneral(PetscObjectComm((PetscObject)mat),nz,nzr,PETSC_OWN_POINTER,nonzero);
217: } else *nonzero = NULL;
218: if (!cols) { /* nonzero rows */
219: VecRestoreArrayRead(l,&al);
220: } else {
221: VecRestoreArrayRead(r,&al);
222: }
223: VecDestroy(&l);
224: VecDestroy(&r);
225: return(0);
226: }
228: /*@
229: MatFindNonzeroRows - Locate all rows that are not completely zero in the matrix
231: Input Parameter:
232: . A - the matrix
234: Output Parameter:
235: . keptrows - the rows that are not completely zero
237: Notes:
238: keptrows is set to NULL if all rows are nonzero.
240: Level: intermediate
242: @*/
243: PetscErrorCode MatFindNonzeroRows(Mat mat,IS *keptrows)
244: {
251: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
252: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
253: if (!mat->ops->findnonzerorows) {
254: MatFindNonzeroRowsOrCols_Basic(mat,PETSC_FALSE,0.0,keptrows);
255: } else {
256: (*mat->ops->findnonzerorows)(mat,keptrows);
257: }
258: return(0);
259: }
261: /*@
262: MatFindZeroRows - Locate all rows that are completely zero in the matrix
264: Input Parameter:
265: . A - the matrix
267: Output Parameter:
268: . zerorows - the rows that are completely zero
270: Notes:
271: zerorows is set to NULL if no rows are zero.
273: Level: intermediate
275: @*/
276: PetscErrorCode MatFindZeroRows(Mat mat,IS *zerorows)
277: {
279: IS keptrows;
280: PetscInt m, n;
285: MatFindNonzeroRows(mat, &keptrows);
286: /* MatFindNonzeroRows sets keptrows to NULL if there are no zero rows.
287: In keeping with this convention, we set zerorows to NULL if there are no zero
288: rows. */
289: if (keptrows == NULL) {
290: *zerorows = NULL;
291: } else {
292: MatGetOwnershipRange(mat,&m,&n);
293: ISComplement(keptrows,m,n,zerorows);
294: ISDestroy(&keptrows);
295: }
296: return(0);
297: }
299: /*@
300: MatGetDiagonalBlock - Returns the part of the matrix associated with the on-process coupling
302: Not Collective
304: Input Parameters:
305: . A - the matrix
307: Output Parameters:
308: . a - the diagonal part (which is a SEQUENTIAL matrix)
310: Notes:
311: see the manual page for MatCreateAIJ() for more information on the "diagonal part" of the matrix.
312: Use caution, as the reference count on the returned matrix is not incremented and it is used as
313: part of the containing MPI Mat's normal operation.
315: Level: advanced
317: @*/
318: PetscErrorCode MatGetDiagonalBlock(Mat A,Mat *a)
319: {
326: if (A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
327: if (!A->ops->getdiagonalblock) {
328: PetscMPIInt size;
329: MPI_Comm_size(PetscObjectComm((PetscObject)A),&size);
330: if (size == 1) {
331: *a = A;
332: return(0);
333: } else 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: return(0);
392: }
394: /*@C
395: MatGetGhosts - Get the global index of all ghost nodes defined by the sparse matrix
397: Collective on Mat
399: Input Parameter:
400: . mat - the matrix
402: Output Parameters:
403: + nghosts - number of ghosts (note for BAIJ matrices there is one ghost for each block)
404: - ghosts - the global indices of the ghost points
406: Notes:
407: the nghosts and ghosts are suitable to pass into VecCreateGhost()
409: Level: advanced
411: @*/
412: PetscErrorCode MatGetGhosts(Mat mat,PetscInt *nghosts,const PetscInt *ghosts[])
413: {
419: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
420: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
421: if (!mat->ops->getghosts) {
422: if (nghosts) *nghosts = 0;
423: if (ghosts) *ghosts = 0;
424: } else {
425: (*mat->ops->getghosts)(mat,nghosts,ghosts);
426: }
427: return(0);
428: }
431: /*@
432: MatImaginaryPart - Moves the imaginary part of the matrix to the real part and zeros the imaginary part
434: Logically Collective on Mat
436: Input Parameters:
437: . mat - the matrix
439: Level: advanced
442: .seealso: MatRealPart()
443: @*/
444: PetscErrorCode MatImaginaryPart(Mat mat)
445: {
451: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
452: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
453: if (!mat->ops->imaginarypart) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
454: MatCheckPreallocated(mat,1);
455: (*mat->ops->imaginarypart)(mat);
456: return(0);
457: }
459: /*@
460: MatMissingDiagonal - Determine if sparse matrix is missing a diagonal entry (or block entry for BAIJ matrices)
462: Not Collective
464: Input Parameter:
465: . mat - the matrix
467: Output Parameters:
468: + missing - is any diagonal missing
469: - dd - first diagonal entry that is missing (optional) on this process
471: Level: advanced
474: .seealso: MatRealPart()
475: @*/
476: PetscErrorCode MatMissingDiagonal(Mat mat,PetscBool *missing,PetscInt *dd)
477: {
483: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
484: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
485: if (!mat->ops->missingdiagonal) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
486: (*mat->ops->missingdiagonal)(mat,missing,dd);
487: return(0);
488: }
490: /*@C
491: MatGetRow - Gets a row of a matrix. You MUST call MatRestoreRow()
492: for each row that you get to ensure that your application does
493: not bleed memory.
495: Not Collective
497: Input Parameters:
498: + mat - the matrix
499: - row - the row to get
501: Output Parameters:
502: + ncols - if not NULL, the number of nonzeros in the row
503: . cols - if not NULL, the column numbers
504: - vals - if not NULL, the values
506: Notes:
507: This routine is provided for people who need to have direct access
508: to the structure of a matrix. We hope that we provide enough
509: high-level matrix routines that few users will need it.
511: MatGetRow() always returns 0-based column indices, regardless of
512: whether the internal representation is 0-based (default) or 1-based.
514: For better efficiency, set cols and/or vals to NULL if you do
515: not wish to extract these quantities.
517: The user can only examine the values extracted with MatGetRow();
518: the values cannot be altered. To change the matrix entries, one
519: must use MatSetValues().
521: You can only have one call to MatGetRow() outstanding for a particular
522: matrix at a time, per processor. MatGetRow() can only obtain rows
523: associated with the given processor, it cannot get rows from the
524: other processors; for that we suggest using MatCreateSubMatrices(), then
525: MatGetRow() on the submatrix. The row index passed to MatGetRow()
526: is in the global number of rows.
528: Fortran Notes:
529: The calling sequence from Fortran is
530: .vb
531: MatGetRow(matrix,row,ncols,cols,values,ierr)
532: Mat matrix (input)
533: integer row (input)
534: integer ncols (output)
535: integer cols(maxcols) (output)
536: double precision (or double complex) values(maxcols) output
537: .ve
538: where maxcols >= maximum nonzeros in any row of the matrix.
541: Caution:
542: Do not try to change the contents of the output arrays (cols and vals).
543: In some cases, this may corrupt the matrix.
545: Level: advanced
547: .seealso: MatRestoreRow(), MatSetValues(), MatGetValues(), MatCreateSubMatrices(), MatGetDiagonal()
548: @*/
549: PetscErrorCode MatGetRow(Mat mat,PetscInt row,PetscInt *ncols,const PetscInt *cols[],const PetscScalar *vals[])
550: {
552: PetscInt incols;
557: if (!mat->assembled) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
558: if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
559: if (!mat->ops->getrow) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
560: MatCheckPreallocated(mat,1);
561: PetscLogEventBegin(MAT_GetRow,mat,0,0,0);
562: (*mat->ops->getrow)(mat,row,&incols,(PetscInt**)cols,(PetscScalar**)vals);
563: if (ncols) *ncols = incols;
564: PetscLogEventEnd(MAT_GetRow,mat,0,0,0);
565: return(0);
566: }
568: /*@
569: MatConjugate - replaces the matrix values with their complex conjugates
571: Logically Collective on Mat
573: Input Parameters:
574: . mat - the matrix
576: Level: advanced
578: .seealso: VecConjugate()
579: @*/
580: PetscErrorCode MatConjugate(Mat mat)
581: {
582: #if defined(PETSC_USE_COMPLEX)
587: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
588: 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");
589: (*mat->ops->conjugate)(mat);
590: #else
592: #endif
593: return(0);
594: }
596: /*@C
597: MatRestoreRow - Frees any temporary space allocated by MatGetRow().
599: Not Collective
601: Input Parameters:
602: + mat - the matrix
603: . row - the row to get
604: . ncols, cols - the number of nonzeros and their columns
605: - vals - if nonzero the column values
607: Notes:
608: This routine should be called after you have finished examining the entries.
610: This routine zeros out ncols, cols, and vals. This is to prevent accidental
611: us of the array after it has been restored. If you pass NULL, it will
612: not zero the pointers. Use of cols or vals after MatRestoreRow is invalid.
614: Fortran Notes:
615: The calling sequence from Fortran is
616: .vb
617: MatRestoreRow(matrix,row,ncols,cols,values,ierr)
618: Mat matrix (input)
619: integer row (input)
620: integer ncols (output)
621: integer cols(maxcols) (output)
622: double precision (or double complex) values(maxcols) output
623: .ve
624: Where maxcols >= maximum nonzeros in any row of the matrix.
626: In Fortran MatRestoreRow() MUST be called after MatGetRow()
627: before another call to MatGetRow() can be made.
629: Level: advanced
631: .seealso: MatGetRow()
632: @*/
633: PetscErrorCode MatRestoreRow(Mat mat,PetscInt row,PetscInt *ncols,const PetscInt *cols[],const PetscScalar *vals[])
634: {
640: if (!mat->assembled) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
641: if (!mat->ops->restorerow) return(0);
642: (*mat->ops->restorerow)(mat,row,ncols,(PetscInt **)cols,(PetscScalar **)vals);
643: if (ncols) *ncols = 0;
644: if (cols) *cols = NULL;
645: if (vals) *vals = NULL;
646: return(0);
647: }
649: /*@
650: MatGetRowUpperTriangular - Sets a flag to enable calls to MatGetRow() for matrix in MATSBAIJ format.
651: You should call MatRestoreRowUpperTriangular() after calling MatGetRow/MatRestoreRow() to disable the flag.
653: Not Collective
655: Input Parameters:
656: . mat - the matrix
658: Notes:
659: The flag is to ensure that users are aware of MatGetRow() only provides the upper triangular part of the row for the matrices in MATSBAIJ format.
661: Level: advanced
663: .seealso: MatRestoreRowUpperTriangular()
664: @*/
665: PetscErrorCode MatGetRowUpperTriangular(Mat mat)
666: {
672: if (!mat->assembled) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
673: if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
674: MatCheckPreallocated(mat,1);
675: if (!mat->ops->getrowuppertriangular) return(0);
676: (*mat->ops->getrowuppertriangular)(mat);
677: return(0);
678: }
680: /*@
681: MatRestoreRowUpperTriangular - Disable calls to MatGetRow() for matrix in MATSBAIJ format.
683: Not Collective
685: Input Parameters:
686: . mat - the matrix
688: Notes:
689: This routine should be called after you have finished MatGetRow/MatRestoreRow().
692: Level: advanced
694: .seealso: MatGetRowUpperTriangular()
695: @*/
696: PetscErrorCode MatRestoreRowUpperTriangular(Mat mat)
697: {
703: if (!mat->assembled) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
704: if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
705: MatCheckPreallocated(mat,1);
706: if (!mat->ops->restorerowuppertriangular) return(0);
707: (*mat->ops->restorerowuppertriangular)(mat);
708: return(0);
709: }
711: /*@C
712: MatSetOptionsPrefix - Sets the prefix used for searching for all
713: Mat options in the database.
715: Logically Collective on Mat
717: Input Parameter:
718: + A - the Mat context
719: - prefix - the prefix to prepend to all option names
721: Notes:
722: A hyphen (-) must NOT be given at the beginning of the prefix name.
723: The first character of all runtime options is AUTOMATICALLY the hyphen.
725: Level: advanced
727: .seealso: MatSetFromOptions()
728: @*/
729: PetscErrorCode MatSetOptionsPrefix(Mat A,const char prefix[])
730: {
735: PetscObjectSetOptionsPrefix((PetscObject)A,prefix);
736: return(0);
737: }
739: /*@C
740: MatAppendOptionsPrefix - Appends to the prefix used for searching for all
741: Mat options in the database.
743: Logically Collective on Mat
745: Input Parameters:
746: + A - the Mat context
747: - prefix - the prefix to prepend to all option names
749: Notes:
750: A hyphen (-) must NOT be given at the beginning of the prefix name.
751: The first character of all runtime options is AUTOMATICALLY the hyphen.
753: Level: advanced
755: .seealso: MatGetOptionsPrefix()
756: @*/
757: PetscErrorCode MatAppendOptionsPrefix(Mat A,const char prefix[])
758: {
763: PetscObjectAppendOptionsPrefix((PetscObject)A,prefix);
764: return(0);
765: }
767: /*@C
768: MatGetOptionsPrefix - Sets the prefix used for searching for all
769: Mat options in the database.
771: Not Collective
773: Input Parameter:
774: . A - the Mat context
776: Output Parameter:
777: . prefix - pointer to the prefix string used
779: Notes:
780: On the fortran side, the user should pass in a string 'prefix' of
781: sufficient length to hold the prefix.
783: Level: advanced
785: .seealso: MatAppendOptionsPrefix()
786: @*/
787: PetscErrorCode MatGetOptionsPrefix(Mat A,const char *prefix[])
788: {
793: PetscObjectGetOptionsPrefix((PetscObject)A,prefix);
794: return(0);
795: }
797: /*@
798: MatResetPreallocation - Reset mat to use the original nonzero pattern provided by users.
800: Collective on Mat
802: Input Parameters:
803: . A - the Mat context
805: Notes:
806: The allocated memory will be shrunk after calling MatAssembly with MAT_FINAL_ASSEMBLY. Users can reset the preallocation to access the original memory.
807: Currently support MPIAIJ and SEQAIJ.
809: Level: beginner
811: .seealso: MatSeqAIJSetPreallocation(), MatMPIAIJSetPreallocation(), MatXAIJSetPreallocation()
812: @*/
813: PetscErrorCode MatResetPreallocation(Mat A)
814: {
820: PetscUseMethod(A,"MatResetPreallocation_C",(Mat),(A));
821: return(0);
822: }
825: /*@
826: MatSetUp - Sets up the internal matrix data structures for the later use.
828: Collective on Mat
830: Input Parameters:
831: . A - the Mat context
833: Notes:
834: If the user has not set preallocation for this matrix then a default preallocation that is likely to be inefficient is used.
836: If a suitable preallocation routine is used, this function does not need to be called.
838: See the Performance chapter of the PETSc users manual for how to preallocate matrices
840: Level: beginner
842: .seealso: MatCreate(), MatDestroy()
843: @*/
844: PetscErrorCode MatSetUp(Mat A)
845: {
846: PetscMPIInt size;
851: if (!((PetscObject)A)->type_name) {
852: MPI_Comm_size(PetscObjectComm((PetscObject)A), &size);
853: if (size == 1) {
854: MatSetType(A, MATSEQAIJ);
855: } else {
856: MatSetType(A, MATMPIAIJ);
857: }
858: }
859: if (!A->preallocated && A->ops->setup) {
860: PetscInfo(A,"Warning not preallocating matrix storage\n");
861: (*A->ops->setup)(A);
862: }
863: PetscLayoutSetUp(A->rmap);
864: PetscLayoutSetUp(A->cmap);
865: A->preallocated = PETSC_TRUE;
866: return(0);
867: }
869: #if defined(PETSC_HAVE_SAWS)
870: #include <petscviewersaws.h>
871: #endif
872: /*@C
873: MatView - Visualizes a matrix object.
875: Collective on Mat
877: Input Parameters:
878: + mat - the matrix
879: - viewer - visualization context
881: Notes:
882: The available visualization contexts include
883: + PETSC_VIEWER_STDOUT_SELF - for sequential matrices
884: . PETSC_VIEWER_STDOUT_WORLD - for parallel matrices created on PETSC_COMM_WORLD
885: . PETSC_VIEWER_STDOUT_(comm) - for matrices created on MPI communicator comm
886: - PETSC_VIEWER_DRAW_WORLD - graphical display of nonzero structure
888: The user can open alternative visualization contexts with
889: + PetscViewerASCIIOpen() - Outputs matrix to a specified file
890: . PetscViewerBinaryOpen() - Outputs matrix in binary to a
891: specified file; corresponding input uses MatLoad()
892: . PetscViewerDrawOpen() - Outputs nonzero matrix structure to
893: an X window display
894: - PetscViewerSocketOpen() - Outputs matrix to Socket viewer.
895: Currently only the sequential dense and AIJ
896: matrix types support the Socket viewer.
898: The user can call PetscViewerPushFormat() to specify the output
899: format of ASCII printed objects (when using PETSC_VIEWER_STDOUT_SELF,
900: PETSC_VIEWER_STDOUT_WORLD and PetscViewerASCIIOpen). Available formats include
901: + PETSC_VIEWER_DEFAULT - default, prints matrix contents
902: . PETSC_VIEWER_ASCII_MATLAB - prints matrix contents in Matlab format
903: . PETSC_VIEWER_ASCII_DENSE - prints entire matrix including zeros
904: . PETSC_VIEWER_ASCII_COMMON - prints matrix contents, using a sparse
905: format common among all matrix types
906: . PETSC_VIEWER_ASCII_IMPL - prints matrix contents, using an implementation-specific
907: format (which is in many cases the same as the default)
908: . PETSC_VIEWER_ASCII_INFO - prints basic information about the matrix
909: size and structure (not the matrix entries)
910: - PETSC_VIEWER_ASCII_INFO_DETAIL - prints more detailed information about
911: the matrix structure
913: Options Database Keys:
914: + -mat_view ::ascii_info - Prints info on matrix at conclusion of MatAssemblyEnd()
915: . -mat_view ::ascii_info_detail - Prints more detailed info
916: . -mat_view - Prints matrix in ASCII format
917: . -mat_view ::ascii_matlab - Prints matrix in Matlab format
918: . -mat_view draw - PetscDraws nonzero structure of matrix, using MatView() and PetscDrawOpenX().
919: . -display <name> - Sets display name (default is host)
920: . -draw_pause <sec> - Sets number of seconds to pause after display
921: . -mat_view socket - Sends matrix to socket, can be accessed from Matlab (see Users-Manual: Chapter 12 Using MATLAB with PETSc for details)
922: . -viewer_socket_machine <machine> -
923: . -viewer_socket_port <port> -
924: . -mat_view binary - save matrix to file in binary format
925: - -viewer_binary_filename <name> -
926: Level: beginner
928: Notes:
929: The ASCII viewers are only recommended for small matrices on at most a moderate number of processes,
930: the program will seemingly hang and take hours for larger matrices, for larger matrices one should use the binary format.
932: See the manual page for MatLoad() for the exact format of the binary file when the binary
933: viewer is used.
935: See share/petsc/matlab/PetscBinaryRead.m for a Matlab code that can read in the binary file when the binary
936: viewer is used.
938: One can use '-mat_view draw -draw_pause -1' to pause the graphical display of matrix nonzero structure,
939: and then use the following mouse functions.
940: + left mouse: zoom in
941: . middle mouse: zoom out
942: - right mouse: continue with the simulation
944: .seealso: PetscViewerPushFormat(), PetscViewerASCIIOpen(), PetscViewerDrawOpen(),
945: PetscViewerSocketOpen(), PetscViewerBinaryOpen(), MatLoad()
946: @*/
947: PetscErrorCode MatView(Mat mat,PetscViewer viewer)
948: {
949: PetscErrorCode ierr;
950: PetscInt rows,cols,rbs,cbs;
951: PetscBool iascii,ibinary,isstring;
952: PetscViewerFormat format;
953: PetscMPIInt size;
954: #if defined(PETSC_HAVE_SAWS)
955: PetscBool issaws;
956: #endif
961: if (!viewer) {
962: PetscViewerASCIIGetStdout(PetscObjectComm((PetscObject)mat),&viewer);
963: }
966: MatCheckPreallocated(mat,1);
967: PetscViewerGetFormat(viewer,&format);
968: MPI_Comm_size(PetscObjectComm((PetscObject)mat),&size);
969: if (size == 1 && format == PETSC_VIEWER_LOAD_BALANCE) return(0);
970: PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERBINARY,&ibinary);
971: PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERSTRING,&isstring);
972: if (ibinary) {
973: PetscBool mpiio;
974: PetscViewerBinaryGetUseMPIIO(viewer,&mpiio);
975: if (mpiio) SETERRQ(PetscObjectComm((PetscObject)viewer),PETSC_ERR_SUP,"PETSc matrix viewers do not support using MPI-IO, turn off that flag");
976: }
978: PetscLogEventBegin(MAT_View,mat,viewer,0,0);
979: PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERASCII,&iascii);
980: if ((!iascii || (format != PETSC_VIEWER_ASCII_INFO || format == PETSC_VIEWER_ASCII_INFO_DETAIL)) && mat->factortype) {
981: SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"No viewers for factored matrix except ASCII info or info_detailed");
982: }
984: #if defined(PETSC_HAVE_SAWS)
985: PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERSAWS,&issaws);
986: #endif
987: if (iascii) {
988: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ORDER,"Must call MatAssemblyBegin/End() before viewing matrix");
989: PetscObjectPrintClassNamePrefixType((PetscObject)mat,viewer);
990: if (format == PETSC_VIEWER_ASCII_INFO || format == PETSC_VIEWER_ASCII_INFO_DETAIL) {
991: MatNullSpace nullsp,transnullsp;
993: PetscViewerASCIIPushTab(viewer);
994: MatGetSize(mat,&rows,&cols);
995: MatGetBlockSizes(mat,&rbs,&cbs);
996: if (rbs != 1 || cbs != 1) {
997: if (rbs != cbs) {PetscViewerASCIIPrintf(viewer,"rows=%D, cols=%D, rbs=%D, cbs=%D\n",rows,cols,rbs,cbs);}
998: else {PetscViewerASCIIPrintf(viewer,"rows=%D, cols=%D, bs=%D\n",rows,cols,rbs);}
999: } else {
1000: PetscViewerASCIIPrintf(viewer,"rows=%D, cols=%D\n",rows,cols);
1001: }
1002: if (mat->factortype) {
1003: MatSolverType solver;
1004: MatFactorGetSolverType(mat,&solver);
1005: PetscViewerASCIIPrintf(viewer,"package used to perform factorization: %s\n",solver);
1006: }
1007: if (mat->ops->getinfo) {
1008: MatInfo info;
1009: MatGetInfo(mat,MAT_GLOBAL_SUM,&info);
1010: PetscViewerASCIIPrintf(viewer,"total: nonzeros=%.f, allocated nonzeros=%.f\n",info.nz_used,info.nz_allocated);
1011: PetscViewerASCIIPrintf(viewer,"total number of mallocs used during MatSetValues calls=%D\n",(PetscInt)info.mallocs);
1012: }
1013: MatGetNullSpace(mat,&nullsp);
1014: MatGetTransposeNullSpace(mat,&transnullsp);
1015: if (nullsp) {PetscViewerASCIIPrintf(viewer," has attached null space\n");}
1016: if (transnullsp && transnullsp != nullsp) {PetscViewerASCIIPrintf(viewer," has attached transposed null space\n");}
1017: MatGetNearNullSpace(mat,&nullsp);
1018: if (nullsp) {PetscViewerASCIIPrintf(viewer," has attached near null space\n");}
1019: }
1020: #if defined(PETSC_HAVE_SAWS)
1021: } else if (issaws) {
1022: PetscMPIInt rank;
1024: PetscObjectName((PetscObject)mat);
1025: MPI_Comm_rank(PETSC_COMM_WORLD,&rank);
1026: if (!((PetscObject)mat)->amsmem && !rank) {
1027: PetscObjectViewSAWs((PetscObject)mat,viewer);
1028: }
1029: #endif
1030: } else if (isstring) {
1031: const char *type;
1032: MatGetType(mat,&type);
1033: PetscViewerStringSPrintf(viewer," MatType: %-7.7s",type);
1034: if (mat->ops->view) {(*mat->ops->view)(mat,viewer);}
1035: }
1036: if ((format == PETSC_VIEWER_NATIVE || format == PETSC_VIEWER_LOAD_BALANCE) && mat->ops->viewnative) {
1037: PetscViewerASCIIPushTab(viewer);
1038: (*mat->ops->viewnative)(mat,viewer);
1039: PetscViewerASCIIPopTab(viewer);
1040: } else if (mat->ops->view) {
1041: PetscViewerASCIIPushTab(viewer);
1042: (*mat->ops->view)(mat,viewer);
1043: PetscViewerASCIIPopTab(viewer);
1044: }
1045: if (iascii) {
1046: PetscViewerGetFormat(viewer,&format);
1047: if (format == PETSC_VIEWER_ASCII_INFO || format == PETSC_VIEWER_ASCII_INFO_DETAIL) {
1048: PetscViewerASCIIPopTab(viewer);
1049: }
1050: }
1051: PetscLogEventEnd(MAT_View,mat,viewer,0,0);
1052: return(0);
1053: }
1055: #if defined(PETSC_USE_DEBUG)
1056: #include <../src/sys/totalview/tv_data_display.h>
1057: PETSC_UNUSED static int TV_display_type(const struct _p_Mat *mat)
1058: {
1059: TV_add_row("Local rows", "int", &mat->rmap->n);
1060: TV_add_row("Local columns", "int", &mat->cmap->n);
1061: TV_add_row("Global rows", "int", &mat->rmap->N);
1062: TV_add_row("Global columns", "int", &mat->cmap->N);
1063: TV_add_row("Typename", TV_ascii_string_type, ((PetscObject)mat)->type_name);
1064: return TV_format_OK;
1065: }
1066: #endif
1068: /*@C
1069: MatLoad - Loads a matrix that has been stored in binary/HDF5 format
1070: with MatView(). The matrix format is determined from the options database.
1071: Generates a parallel MPI matrix if the communicator has more than one
1072: processor. The default matrix type is AIJ.
1074: Collective on PetscViewer
1076: Input Parameters:
1077: + newmat - the newly loaded matrix, this needs to have been created with MatCreate()
1078: or some related function before a call to MatLoad()
1079: - viewer - binary/HDF5 file viewer
1081: Options Database Keys:
1082: Used with block matrix formats (MATSEQBAIJ, ...) to specify
1083: block size
1084: . -matload_block_size <bs>
1086: Level: beginner
1088: Notes:
1089: If the Mat type has not yet been given then MATAIJ is used, call MatSetFromOptions() on the
1090: Mat before calling this routine if you wish to set it from the options database.
1092: MatLoad() automatically loads into the options database any options
1093: given in the file filename.info where filename is the name of the file
1094: that was passed to the PetscViewerBinaryOpen(). The options in the info
1095: file will be ignored if you use the -viewer_binary_skip_info option.
1097: If the type or size of newmat is not set before a call to MatLoad, PETSc
1098: sets the default matrix type AIJ and sets the local and global sizes.
1099: If type and/or size is already set, then the same are used.
1101: In parallel, each processor can load a subset of rows (or the
1102: entire matrix). This routine is especially useful when a large
1103: matrix is stored on disk and only part of it is desired on each
1104: processor. For example, a parallel solver may access only some of
1105: the rows from each processor. The algorithm used here reads
1106: relatively small blocks of data rather than reading the entire
1107: matrix and then subsetting it.
1109: Viewer's PetscViewerType must be either PETSCVIEWERBINARY or PETSCVIEWERHDF5.
1110: Such viewer can be created using PetscViewerBinaryOpen()/PetscViewerHDF5Open(),
1111: or the sequence like
1112: $ PetscViewer v;
1113: $ PetscViewerCreate(PETSC_COMM_WORLD,&v);
1114: $ PetscViewerSetType(v,PETSCVIEWERBINARY);
1115: $ PetscViewerSetFromOptions(v);
1116: $ PetscViewerFileSetMode(v,FILE_MODE_READ);
1117: $ PetscViewerFileSetName(v,"datafile");
1118: The optional PetscViewerSetFromOptions() call allows to override PetscViewerSetType() using option
1119: $ -viewer_type {binary,hdf5}
1121: See the example src/ksp/ksp/examples/tutorials/ex27.c with the first approach,
1122: and src/mat/examples/tutorials/ex10.c with the second approach.
1124: Notes about the PETSc binary format:
1125: In case of PETSCVIEWERBINARY, a native PETSc binary format is used. Each of the blocks
1126: is read onto rank 0 and then shipped to its destination rank, one after another.
1127: Multiple objects, both matrices and vectors, can be stored within the same file.
1128: Their PetscObject name is ignored; they are loaded in the order of their storage.
1130: Most users should not need to know the details of the binary storage
1131: format, since MatLoad() and MatView() completely hide these details.
1132: But for anyone who's interested, the standard binary matrix storage
1133: format is
1135: $ PetscInt MAT_FILE_CLASSID
1136: $ PetscInt number of rows
1137: $ PetscInt number of columns
1138: $ PetscInt total number of nonzeros
1139: $ PetscInt *number nonzeros in each row
1140: $ PetscInt *column indices of all nonzeros (starting index is zero)
1141: $ PetscScalar *values of all nonzeros
1143: PETSc automatically does the byte swapping for
1144: machines that store the bytes reversed, e.g. DEC alpha, freebsd,
1145: linux, Windows and the paragon; thus if you write your own binary
1146: read/write routines you have to swap the bytes; see PetscBinaryRead()
1147: and PetscBinaryWrite() to see how this may be done.
1149: Notes about the HDF5 (MATLAB MAT-File Version 7.3) format:
1150: In case of PETSCVIEWERHDF5, a parallel HDF5 reader is used.
1151: Each processor's chunk is loaded independently by its owning rank.
1152: Multiple objects, both matrices and vectors, can be stored within the same file.
1153: They are looked up by their PetscObject name.
1155: As the MATLAB MAT-File Version 7.3 format is also a HDF5 flavor, we decided to use
1156: by default the same structure and naming of the AIJ arrays and column count
1157: within the HDF5 file. This means that a MAT file saved with -v7.3 flag, e.g.
1158: $ save example.mat A b -v7.3
1159: can be directly read by this routine (see Reference 1 for details).
1160: Note that depending on your MATLAB version, this format might be a default,
1161: otherwise you can set it as default in Preferences.
1163: Unless -nocompression flag is used to save the file in MATLAB,
1164: PETSc must be configured with ZLIB package.
1166: See also examples src/mat/examples/tutorials/ex10.c and src/ksp/ksp/examples/tutorials/ex27.c
1168: Current HDF5 (MAT-File) limitations:
1169: This reader currently supports only real MATSEQAIJ, MATMPIAIJ, MATSEQDENSE and MATMPIDENSE matrices.
1171: Corresponding MatView() is not yet implemented.
1173: The loaded matrix is actually a transpose of the original one in MATLAB,
1174: unless you push PETSC_VIEWER_HDF5_MAT format (see examples above).
1175: With this format, matrix is automatically transposed by PETSc,
1176: unless the matrix is marked as SPD or symmetric
1177: (see MatSetOption(), MAT_SPD, MAT_SYMMETRIC).
1179: References:
1180: 1. MATLAB(R) Documentation, manual page of save(), https://www.mathworks.com/help/matlab/ref/save.html#btox10b-1-version
1182: .seealso: PetscViewerBinaryOpen(), PetscViewerSetType(), MatView(), VecLoad()
1184: @*/
1185: PetscErrorCode MatLoad(Mat newmat,PetscViewer viewer)
1186: {
1188: PetscBool flg;
1194: if (!((PetscObject)newmat)->type_name) {
1195: MatSetType(newmat,MATAIJ);
1196: }
1198: flg = PETSC_FALSE;
1199: PetscOptionsGetBool(((PetscObject)newmat)->options,((PetscObject)newmat)->prefix,"-matload_symmetric",&flg,NULL);
1200: if (flg) {
1201: MatSetOption(newmat,MAT_SYMMETRIC,PETSC_TRUE);
1202: MatSetOption(newmat,MAT_SYMMETRY_ETERNAL,PETSC_TRUE);
1203: }
1204: flg = PETSC_FALSE;
1205: PetscOptionsGetBool(((PetscObject)newmat)->options,((PetscObject)newmat)->prefix,"-matload_spd",&flg,NULL);
1206: if (flg) {
1207: MatSetOption(newmat,MAT_SPD,PETSC_TRUE);
1208: }
1210: if (!newmat->ops->load) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"MatLoad is not supported for type");
1211: PetscLogEventBegin(MAT_Load,viewer,0,0,0);
1212: (*newmat->ops->load)(newmat,viewer);
1213: PetscLogEventEnd(MAT_Load,viewer,0,0,0);
1214: return(0);
1215: }
1217: PetscErrorCode MatDestroy_Redundant(Mat_Redundant **redundant)
1218: {
1220: Mat_Redundant *redund = *redundant;
1221: PetscInt i;
1224: if (redund){
1225: if (redund->matseq) { /* via MatCreateSubMatrices() */
1226: ISDestroy(&redund->isrow);
1227: ISDestroy(&redund->iscol);
1228: MatDestroySubMatrices(1,&redund->matseq);
1229: } else {
1230: PetscFree2(redund->send_rank,redund->recv_rank);
1231: PetscFree(redund->sbuf_j);
1232: PetscFree(redund->sbuf_a);
1233: for (i=0; i<redund->nrecvs; i++) {
1234: PetscFree(redund->rbuf_j[i]);
1235: PetscFree(redund->rbuf_a[i]);
1236: }
1237: PetscFree4(redund->sbuf_nz,redund->rbuf_nz,redund->rbuf_j,redund->rbuf_a);
1238: }
1240: if (redund->subcomm) {
1241: PetscCommDestroy(&redund->subcomm);
1242: }
1243: PetscFree(redund);
1244: }
1245: return(0);
1246: }
1248: /*@
1249: MatDestroy - Frees space taken by a matrix.
1251: Collective on Mat
1253: Input Parameter:
1254: . A - the matrix
1256: Level: beginner
1258: @*/
1259: PetscErrorCode MatDestroy(Mat *A)
1260: {
1264: if (!*A) return(0);
1266: if (--((PetscObject)(*A))->refct > 0) {*A = NULL; return(0);}
1268: /* if memory was published with SAWs then destroy it */
1269: PetscObjectSAWsViewOff((PetscObject)*A);
1270: if ((*A)->ops->destroy) {
1271: (*(*A)->ops->destroy)(*A);
1272: }
1274: PetscFree((*A)->defaultvectype);
1275: PetscFree((*A)->bsizes);
1276: PetscFree((*A)->solvertype);
1277: MatDestroy_Redundant(&(*A)->redundant);
1278: MatNullSpaceDestroy(&(*A)->nullsp);
1279: MatNullSpaceDestroy(&(*A)->transnullsp);
1280: MatNullSpaceDestroy(&(*A)->nearnullsp);
1281: MatDestroy(&(*A)->schur);
1282: PetscLayoutDestroy(&(*A)->rmap);
1283: PetscLayoutDestroy(&(*A)->cmap);
1284: PetscHeaderDestroy(A);
1285: return(0);
1286: }
1288: /*@C
1289: MatSetValues - Inserts or adds a block of values into a matrix.
1290: These values may be cached, so MatAssemblyBegin() and MatAssemblyEnd()
1291: MUST be called after all calls to MatSetValues() have been completed.
1293: Not Collective
1295: Input Parameters:
1296: + mat - the matrix
1297: . v - a logically two-dimensional array of values
1298: . m, idxm - the number of rows and their global indices
1299: . n, idxn - the number of columns and their global indices
1300: - addv - either ADD_VALUES or INSERT_VALUES, where
1301: ADD_VALUES adds values to any existing entries, and
1302: INSERT_VALUES replaces existing entries with new values
1304: Notes:
1305: If you create the matrix yourself (that is not with a call to DMCreateMatrix()) then you MUST call MatXXXXSetPreallocation() or
1306: MatSetUp() before using this routine
1308: By default the values, v, are row-oriented. See MatSetOption() for other options.
1310: Calls to MatSetValues() with the INSERT_VALUES and ADD_VALUES
1311: options cannot be mixed without intervening calls to the assembly
1312: routines.
1314: MatSetValues() uses 0-based row and column numbers in Fortran
1315: as well as in C.
1317: Negative indices may be passed in idxm and idxn, these rows and columns are
1318: simply ignored. This allows easily inserting element stiffness matrices
1319: with homogeneous Dirchlet boundary conditions that you don't want represented
1320: in the matrix.
1322: Efficiency Alert:
1323: The routine MatSetValuesBlocked() may offer much better efficiency
1324: for users of block sparse formats (MATSEQBAIJ and MATMPIBAIJ).
1326: Level: beginner
1328: Developer Notes:
1329: This is labeled with C so does not automatically generate Fortran stubs and interfaces
1330: because it requires multiple Fortran interfaces depending on which arguments are scalar or arrays.
1332: .seealso: MatSetOption(), MatAssemblyBegin(), MatAssemblyEnd(), MatSetValuesBlocked(), MatSetValuesLocal(),
1333: InsertMode, INSERT_VALUES, ADD_VALUES
1334: @*/
1335: PetscErrorCode MatSetValues(Mat mat,PetscInt m,const PetscInt idxm[],PetscInt n,const PetscInt idxn[],const PetscScalar v[],InsertMode addv)
1336: {
1338: #if defined(PETSC_USE_DEBUG)
1339: PetscInt i,j;
1340: #endif
1345: if (!m || !n) return(0); /* no values to insert */
1348: MatCheckPreallocated(mat,1);
1350: if (mat->insertmode == NOT_SET_VALUES) {
1351: mat->insertmode = addv;
1352: }
1353: #if defined(PETSC_USE_DEBUG)
1354: else if (mat->insertmode != addv) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Cannot mix add values and insert values");
1355: if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
1356: if (!mat->ops->setvalues) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
1358: for (i=0; i<m; i++) {
1359: for (j=0; j<n; j++) {
1360: if (mat->erroriffailure && PetscIsInfOrNanScalar(v[i*n+j]))
1361: #if defined(PETSC_USE_COMPLEX)
1362: 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]);
1363: #else
1364: SETERRQ3(PETSC_COMM_SELF,PETSC_ERR_FP,"Inserting %g at matrix entry (%D,%D)",(double)v[i*n+j],idxm[i],idxn[j]);
1365: #endif
1366: }
1367: }
1368: #endif
1370: if (mat->assembled) {
1371: mat->was_assembled = PETSC_TRUE;
1372: mat->assembled = PETSC_FALSE;
1373: }
1374: PetscLogEventBegin(MAT_SetValues,mat,0,0,0);
1375: (*mat->ops->setvalues)(mat,m,idxm,n,idxn,v,addv);
1376: PetscLogEventEnd(MAT_SetValues,mat,0,0,0);
1377: return(0);
1378: }
1381: /*@
1382: MatSetValuesRowLocal - Inserts a row (block row for BAIJ matrices) of nonzero
1383: values into a matrix
1385: Not Collective
1387: Input Parameters:
1388: + mat - the matrix
1389: . row - the (block) row to set
1390: - v - a logically two-dimensional array of values
1392: Notes:
1393: By the values, v, are column-oriented (for the block version) and sorted
1395: All the nonzeros in the row must be provided
1397: The matrix must have previously had its column indices set
1399: The row must belong to this process
1401: Level: intermediate
1403: .seealso: MatSetOption(), MatAssemblyBegin(), MatAssemblyEnd(), MatSetValuesBlocked(), MatSetValuesLocal(),
1404: InsertMode, INSERT_VALUES, ADD_VALUES, MatSetValues(), MatSetValuesRow(), MatSetLocalToGlobalMapping()
1405: @*/
1406: PetscErrorCode MatSetValuesRowLocal(Mat mat,PetscInt row,const PetscScalar v[])
1407: {
1409: PetscInt globalrow;
1415: ISLocalToGlobalMappingApply(mat->rmap->mapping,1,&row,&globalrow);
1416: MatSetValuesRow(mat,globalrow,v);
1417: return(0);
1418: }
1420: /*@
1421: MatSetValuesRow - Inserts a row (block row for BAIJ matrices) of nonzero
1422: values into a matrix
1424: Not Collective
1426: Input Parameters:
1427: + mat - the matrix
1428: . row - the (block) row to set
1429: - 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
1431: Notes:
1432: The values, v, are column-oriented for the block version.
1434: All the nonzeros in the row must be provided
1436: THE MATRIX MUST HAVE PREVIOUSLY HAD ITS COLUMN INDICES SET. IT IS RARE THAT THIS ROUTINE IS USED, usually MatSetValues() is used.
1438: The row must belong to this process
1440: Level: advanced
1442: .seealso: MatSetOption(), MatAssemblyBegin(), MatAssemblyEnd(), MatSetValuesBlocked(), MatSetValuesLocal(),
1443: InsertMode, INSERT_VALUES, ADD_VALUES, MatSetValues()
1444: @*/
1445: PetscErrorCode MatSetValuesRow(Mat mat,PetscInt row,const PetscScalar v[])
1446: {
1452: MatCheckPreallocated(mat,1);
1454: #if defined(PETSC_USE_DEBUG)
1455: if (mat->insertmode == ADD_VALUES) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Cannot mix add and insert values");
1456: if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
1457: #endif
1458: mat->insertmode = INSERT_VALUES;
1460: if (mat->assembled) {
1461: mat->was_assembled = PETSC_TRUE;
1462: mat->assembled = PETSC_FALSE;
1463: }
1464: PetscLogEventBegin(MAT_SetValues,mat,0,0,0);
1465: if (!mat->ops->setvaluesrow) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
1466: (*mat->ops->setvaluesrow)(mat,row,v);
1467: PetscLogEventEnd(MAT_SetValues,mat,0,0,0);
1468: return(0);
1469: }
1471: /*@
1472: MatSetValuesStencil - Inserts or adds a block of values into a matrix.
1473: Using structured grid indexing
1475: Not Collective
1477: Input Parameters:
1478: + mat - the matrix
1479: . m - number of rows being entered
1480: . idxm - grid coordinates (and component number when dof > 1) for matrix rows being entered
1481: . n - number of columns being entered
1482: . idxn - grid coordinates (and component number when dof > 1) for matrix columns being entered
1483: . v - a logically two-dimensional array of values
1484: - addv - either ADD_VALUES or INSERT_VALUES, where
1485: ADD_VALUES adds values to any existing entries, and
1486: INSERT_VALUES replaces existing entries with new values
1488: Notes:
1489: By default the values, v, are row-oriented. See MatSetOption() for other options.
1491: Calls to MatSetValuesStencil() with the INSERT_VALUES and ADD_VALUES
1492: options cannot be mixed without intervening calls to the assembly
1493: routines.
1495: The grid coordinates are across the entire grid, not just the local portion
1497: MatSetValuesStencil() uses 0-based row and column numbers in Fortran
1498: as well as in C.
1500: For setting/accessing vector values via array coordinates you can use the DMDAVecGetArray() routine
1502: In order to use this routine you must either obtain the matrix with DMCreateMatrix()
1503: or call MatSetLocalToGlobalMapping() and MatSetStencil() first.
1505: The columns and rows in the stencil passed in MUST be contained within the
1506: ghost region of the given process as set with DMDACreateXXX() or MatSetStencil(). For example,
1507: if you create a DMDA with an overlap of one grid level and on a particular process its first
1508: local nonghost x logical coordinate is 6 (so its first ghost x logical coordinate is 5) the
1509: first i index you can use in your column and row indices in MatSetStencil() is 5.
1511: In Fortran idxm and idxn should be declared as
1512: $ MatStencil idxm(4,m),idxn(4,n)
1513: and the values inserted using
1514: $ idxm(MatStencil_i,1) = i
1515: $ idxm(MatStencil_j,1) = j
1516: $ idxm(MatStencil_k,1) = k
1517: $ idxm(MatStencil_c,1) = c
1518: etc
1520: For periodic boundary conditions use negative indices for values to the left (below 0; that are to be
1521: obtained by wrapping values from right edge). For values to the right of the last entry using that index plus one
1522: etc to obtain values that obtained by wrapping the values from the left edge. This does not work for anything but the
1523: DM_BOUNDARY_PERIODIC boundary type.
1525: 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
1526: a single value per point) you can skip filling those indices.
1528: Inspired by the structured grid interface to the HYPRE package
1529: (https://computation.llnl.gov/projects/hypre-scalable-linear-solvers-multigrid-methods)
1531: Efficiency Alert:
1532: The routine MatSetValuesBlockedStencil() may offer much better efficiency
1533: for users of block sparse formats (MATSEQBAIJ and MATMPIBAIJ).
1535: Level: beginner
1537: .seealso: MatSetOption(), MatAssemblyBegin(), MatAssemblyEnd(), MatSetValuesBlocked(), MatSetValuesLocal()
1538: MatSetValues(), MatSetValuesBlockedStencil(), MatSetStencil(), DMCreateMatrix(), DMDAVecGetArray(), MatStencil
1539: @*/
1540: PetscErrorCode MatSetValuesStencil(Mat mat,PetscInt m,const MatStencil idxm[],PetscInt n,const MatStencil idxn[],const PetscScalar v[],InsertMode addv)
1541: {
1543: PetscInt buf[8192],*bufm=0,*bufn=0,*jdxm,*jdxn;
1544: PetscInt j,i,dim = mat->stencil.dim,*dims = mat->stencil.dims+1,tmp;
1545: PetscInt *starts = mat->stencil.starts,*dxm = (PetscInt*)idxm,*dxn = (PetscInt*)idxn,sdim = dim - (1 - (PetscInt)mat->stencil.noc);
1548: if (!m || !n) return(0); /* no values to insert */
1554: if ((m+n) <= (PetscInt)(sizeof(buf)/sizeof(PetscInt))) {
1555: jdxm = buf; jdxn = buf+m;
1556: } else {
1557: PetscMalloc2(m,&bufm,n,&bufn);
1558: jdxm = bufm; jdxn = bufn;
1559: }
1560: for (i=0; i<m; i++) {
1561: for (j=0; j<3-sdim; j++) dxm++;
1562: tmp = *dxm++ - starts[0];
1563: for (j=0; j<dim-1; j++) {
1564: if ((*dxm++ - starts[j+1]) < 0 || tmp < 0) tmp = -1;
1565: else tmp = tmp*dims[j] + *(dxm-1) - starts[j+1];
1566: }
1567: if (mat->stencil.noc) dxm++;
1568: jdxm[i] = tmp;
1569: }
1570: for (i=0; i<n; i++) {
1571: for (j=0; j<3-sdim; j++) dxn++;
1572: tmp = *dxn++ - starts[0];
1573: for (j=0; j<dim-1; j++) {
1574: if ((*dxn++ - starts[j+1]) < 0 || tmp < 0) tmp = -1;
1575: else tmp = tmp*dims[j] + *(dxn-1) - starts[j+1];
1576: }
1577: if (mat->stencil.noc) dxn++;
1578: jdxn[i] = tmp;
1579: }
1580: MatSetValuesLocal(mat,m,jdxm,n,jdxn,v,addv);
1581: PetscFree2(bufm,bufn);
1582: return(0);
1583: }
1585: /*@
1586: MatSetValuesBlockedStencil - Inserts or adds a block of values into a matrix.
1587: Using structured grid indexing
1589: Not Collective
1591: Input Parameters:
1592: + mat - the matrix
1593: . m - number of rows being entered
1594: . idxm - grid coordinates for matrix rows being entered
1595: . n - number of columns being entered
1596: . idxn - grid coordinates for matrix columns being entered
1597: . v - a logically two-dimensional array of values
1598: - addv - either ADD_VALUES or INSERT_VALUES, where
1599: ADD_VALUES adds values to any existing entries, and
1600: INSERT_VALUES replaces existing entries with new values
1602: Notes:
1603: By default the values, v, are row-oriented and unsorted.
1604: See MatSetOption() for other options.
1606: Calls to MatSetValuesBlockedStencil() with the INSERT_VALUES and ADD_VALUES
1607: options cannot be mixed without intervening calls to the assembly
1608: routines.
1610: The grid coordinates are across the entire grid, not just the local portion
1612: MatSetValuesBlockedStencil() uses 0-based row and column numbers in Fortran
1613: as well as in C.
1615: For setting/accessing vector values via array coordinates you can use the DMDAVecGetArray() routine
1617: In order to use this routine you must either obtain the matrix with DMCreateMatrix()
1618: or call MatSetBlockSize(), MatSetLocalToGlobalMapping() and MatSetStencil() first.
1620: The columns and rows in the stencil passed in MUST be contained within the
1621: ghost region of the given process as set with DMDACreateXXX() or MatSetStencil(). For example,
1622: if you create a DMDA with an overlap of one grid level and on a particular process its first
1623: local nonghost x logical coordinate is 6 (so its first ghost x logical coordinate is 5) the
1624: first i index you can use in your column and row indices in MatSetStencil() is 5.
1626: In Fortran idxm and idxn should be declared as
1627: $ MatStencil idxm(4,m),idxn(4,n)
1628: and the values inserted using
1629: $ idxm(MatStencil_i,1) = i
1630: $ idxm(MatStencil_j,1) = j
1631: $ idxm(MatStencil_k,1) = k
1632: etc
1634: Negative indices may be passed in idxm and idxn, these rows and columns are
1635: simply ignored. This allows easily inserting element stiffness matrices
1636: with homogeneous Dirchlet boundary conditions that you don't want represented
1637: in the matrix.
1639: Inspired by the structured grid interface to the HYPRE package
1640: (https://computation.llnl.gov/projects/hypre-scalable-linear-solvers-multigrid-methods)
1642: Level: beginner
1644: .seealso: MatSetOption(), MatAssemblyBegin(), MatAssemblyEnd(), MatSetValuesBlocked(), MatSetValuesLocal()
1645: MatSetValues(), MatSetValuesStencil(), MatSetStencil(), DMCreateMatrix(), DMDAVecGetArray(), MatStencil,
1646: MatSetBlockSize(), MatSetLocalToGlobalMapping()
1647: @*/
1648: PetscErrorCode MatSetValuesBlockedStencil(Mat mat,PetscInt m,const MatStencil idxm[],PetscInt n,const MatStencil idxn[],const PetscScalar v[],InsertMode addv)
1649: {
1651: PetscInt buf[8192],*bufm=0,*bufn=0,*jdxm,*jdxn;
1652: PetscInt j,i,dim = mat->stencil.dim,*dims = mat->stencil.dims+1,tmp;
1653: PetscInt *starts = mat->stencil.starts,*dxm = (PetscInt*)idxm,*dxn = (PetscInt*)idxn,sdim = dim - (1 - (PetscInt)mat->stencil.noc);
1656: if (!m || !n) return(0); /* no values to insert */
1663: if ((m+n) <= (PetscInt)(sizeof(buf)/sizeof(PetscInt))) {
1664: jdxm = buf; jdxn = buf+m;
1665: } else {
1666: PetscMalloc2(m,&bufm,n,&bufn);
1667: jdxm = bufm; jdxn = bufn;
1668: }
1669: for (i=0; i<m; i++) {
1670: for (j=0; j<3-sdim; j++) dxm++;
1671: tmp = *dxm++ - starts[0];
1672: for (j=0; j<sdim-1; j++) {
1673: if ((*dxm++ - starts[j+1]) < 0 || tmp < 0) tmp = -1;
1674: else tmp = tmp*dims[j] + *(dxm-1) - starts[j+1];
1675: }
1676: dxm++;
1677: jdxm[i] = tmp;
1678: }
1679: for (i=0; i<n; i++) {
1680: for (j=0; j<3-sdim; j++) dxn++;
1681: tmp = *dxn++ - starts[0];
1682: for (j=0; j<sdim-1; j++) {
1683: if ((*dxn++ - starts[j+1]) < 0 || tmp < 0) tmp = -1;
1684: else tmp = tmp*dims[j] + *(dxn-1) - starts[j+1];
1685: }
1686: dxn++;
1687: jdxn[i] = tmp;
1688: }
1689: MatSetValuesBlockedLocal(mat,m,jdxm,n,jdxn,v,addv);
1690: PetscFree2(bufm,bufn);
1691: return(0);
1692: }
1694: /*@
1695: MatSetStencil - Sets the grid information for setting values into a matrix via
1696: MatSetValuesStencil()
1698: Not Collective
1700: Input Parameters:
1701: + mat - the matrix
1702: . dim - dimension of the grid 1, 2, or 3
1703: . dims - number of grid points in x, y, and z direction, including ghost points on your processor
1704: . starts - starting point of ghost nodes on your processor in x, y, and z direction
1705: - dof - number of degrees of freedom per node
1708: Inspired by the structured grid interface to the HYPRE package
1709: (www.llnl.gov/CASC/hyper)
1711: For matrices generated with DMCreateMatrix() this routine is automatically called and so not needed by the
1712: user.
1714: Level: beginner
1716: .seealso: MatSetOption(), MatAssemblyBegin(), MatAssemblyEnd(), MatSetValuesBlocked(), MatSetValuesLocal()
1717: MatSetValues(), MatSetValuesBlockedStencil(), MatSetValuesStencil()
1718: @*/
1719: PetscErrorCode MatSetStencil(Mat mat,PetscInt dim,const PetscInt dims[],const PetscInt starts[],PetscInt dof)
1720: {
1721: PetscInt i;
1728: mat->stencil.dim = dim + (dof > 1);
1729: for (i=0; i<dim; i++) {
1730: mat->stencil.dims[i] = dims[dim-i-1]; /* copy the values in backwards */
1731: mat->stencil.starts[i] = starts[dim-i-1];
1732: }
1733: mat->stencil.dims[dim] = dof;
1734: mat->stencil.starts[dim] = 0;
1735: mat->stencil.noc = (PetscBool)(dof == 1);
1736: return(0);
1737: }
1739: /*@C
1740: MatSetValuesBlocked - Inserts or adds a block of values into a matrix.
1742: Not Collective
1744: Input Parameters:
1745: + mat - the matrix
1746: . v - a logically two-dimensional array of values
1747: . m, idxm - the number of block rows and their global block indices
1748: . n, idxn - the number of block columns and their global block indices
1749: - addv - either ADD_VALUES or INSERT_VALUES, where
1750: ADD_VALUES adds values to any existing entries, and
1751: INSERT_VALUES replaces existing entries with new values
1753: Notes:
1754: If you create the matrix yourself (that is not with a call to DMCreateMatrix()) then you MUST call
1755: MatXXXXSetPreallocation() or MatSetUp() before using this routine.
1757: The m and n count the NUMBER of blocks in the row direction and column direction,
1758: NOT the total number of rows/columns; for example, if the block size is 2 and
1759: you are passing in values for rows 2,3,4,5 then m would be 2 (not 4).
1760: The values in idxm would be 1 2; that is the first index for each block divided by
1761: the block size.
1763: Note that you must call MatSetBlockSize() when constructing this matrix (before
1764: preallocating it).
1766: By default the values, v, are row-oriented, so the layout of
1767: v is the same as for MatSetValues(). See MatSetOption() for other options.
1769: Calls to MatSetValuesBlocked() with the INSERT_VALUES and ADD_VALUES
1770: options cannot be mixed without intervening calls to the assembly
1771: routines.
1773: MatSetValuesBlocked() uses 0-based row and column numbers in Fortran
1774: as well as in C.
1776: Negative indices may be passed in idxm and idxn, these rows and columns are
1777: simply ignored. This allows easily inserting element stiffness matrices
1778: with homogeneous Dirchlet boundary conditions that you don't want represented
1779: in the matrix.
1781: Each time an entry is set within a sparse matrix via MatSetValues(),
1782: internal searching must be done to determine where to place the
1783: data in the matrix storage space. By instead inserting blocks of
1784: entries via MatSetValuesBlocked(), the overhead of matrix assembly is
1785: reduced.
1787: Example:
1788: $ Suppose m=n=2 and block size(bs) = 2 The array is
1789: $
1790: $ 1 2 | 3 4
1791: $ 5 6 | 7 8
1792: $ - - - | - - -
1793: $ 9 10 | 11 12
1794: $ 13 14 | 15 16
1795: $
1796: $ v[] should be passed in like
1797: $ v[] = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]
1798: $
1799: $ If you are not using row oriented storage of v (that is you called MatSetOption(mat,MAT_ROW_ORIENTED,PETSC_FALSE)) then
1800: $ v[] = [1,5,9,13,2,6,10,14,3,7,11,15,4,8,12,16]
1802: Level: intermediate
1804: .seealso: MatSetBlockSize(), MatSetOption(), MatAssemblyBegin(), MatAssemblyEnd(), MatSetValues(), MatSetValuesBlockedLocal()
1805: @*/
1806: PetscErrorCode MatSetValuesBlocked(Mat mat,PetscInt m,const PetscInt idxm[],PetscInt n,const PetscInt idxn[],const PetscScalar v[],InsertMode addv)
1807: {
1813: if (!m || !n) return(0); /* no values to insert */
1817: MatCheckPreallocated(mat,1);
1818: if (mat->insertmode == NOT_SET_VALUES) {
1819: mat->insertmode = addv;
1820: }
1821: #if defined(PETSC_USE_DEBUG)
1822: else if (mat->insertmode != addv) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Cannot mix add values and insert values");
1823: if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
1824: if (!mat->ops->setvaluesblocked && !mat->ops->setvalues) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
1825: #endif
1827: if (mat->assembled) {
1828: mat->was_assembled = PETSC_TRUE;
1829: mat->assembled = PETSC_FALSE;
1830: }
1831: PetscLogEventBegin(MAT_SetValues,mat,0,0,0);
1832: if (mat->ops->setvaluesblocked) {
1833: (*mat->ops->setvaluesblocked)(mat,m,idxm,n,idxn,v,addv);
1834: } else {
1835: PetscInt buf[8192],*bufr=0,*bufc=0,*iidxm,*iidxn;
1836: PetscInt i,j,bs,cbs;
1837: MatGetBlockSizes(mat,&bs,&cbs);
1838: if (m*bs+n*cbs <= (PetscInt)(sizeof(buf)/sizeof(PetscInt))) {
1839: iidxm = buf; iidxn = buf + m*bs;
1840: } else {
1841: PetscMalloc2(m*bs,&bufr,n*cbs,&bufc);
1842: iidxm = bufr; iidxn = bufc;
1843: }
1844: for (i=0; i<m; i++) {
1845: for (j=0; j<bs; j++) {
1846: iidxm[i*bs+j] = bs*idxm[i] + j;
1847: }
1848: }
1849: for (i=0; i<n; i++) {
1850: for (j=0; j<cbs; j++) {
1851: iidxn[i*cbs+j] = cbs*idxn[i] + j;
1852: }
1853: }
1854: MatSetValues(mat,m*bs,iidxm,n*cbs,iidxn,v,addv);
1855: PetscFree2(bufr,bufc);
1856: }
1857: PetscLogEventEnd(MAT_SetValues,mat,0,0,0);
1858: return(0);
1859: }
1861: /*@
1862: MatGetValues - Gets a block of values from a matrix.
1864: Not Collective; currently only returns a local block
1866: Input Parameters:
1867: + mat - the matrix
1868: . v - a logically two-dimensional array for storing the values
1869: . m, idxm - the number of rows and their global indices
1870: - n, idxn - the number of columns and their global indices
1872: Notes:
1873: The user must allocate space (m*n PetscScalars) for the values, v.
1874: The values, v, are then returned in a row-oriented format,
1875: analogous to that used by default in MatSetValues().
1877: MatGetValues() uses 0-based row and column numbers in
1878: Fortran as well as in C.
1880: MatGetValues() requires that the matrix has been assembled
1881: with MatAssemblyBegin()/MatAssemblyEnd(). Thus, calls to
1882: MatSetValues() and MatGetValues() CANNOT be made in succession
1883: without intermediate matrix assembly.
1885: Negative row or column indices will be ignored and those locations in v[] will be
1886: left unchanged.
1888: Level: advanced
1890: .seealso: MatGetRow(), MatCreateSubMatrices(), MatSetValues()
1891: @*/
1892: PetscErrorCode MatGetValues(Mat mat,PetscInt m,const PetscInt idxm[],PetscInt n,const PetscInt idxn[],PetscScalar v[])
1893: {
1899: if (!m || !n) return(0);
1903: if (!mat->assembled) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
1904: if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
1905: if (!mat->ops->getvalues) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
1906: MatCheckPreallocated(mat,1);
1908: PetscLogEventBegin(MAT_GetValues,mat,0,0,0);
1909: (*mat->ops->getvalues)(mat,m,idxm,n,idxn,v);
1910: PetscLogEventEnd(MAT_GetValues,mat,0,0,0);
1911: return(0);
1912: }
1914: /*@
1915: MatSetValuesBatch - Adds (ADD_VALUES) many blocks of values into a matrix at once. The blocks must all be square and
1916: the same size. Currently, this can only be called once and creates the given matrix.
1918: Not Collective
1920: Input Parameters:
1921: + mat - the matrix
1922: . nb - the number of blocks
1923: . bs - the number of rows (and columns) in each block
1924: . rows - a concatenation of the rows for each block
1925: - v - a concatenation of logically two-dimensional arrays of values
1927: Notes:
1928: In the future, we will extend this routine to handle rectangular blocks, and to allow multiple calls for a given matrix.
1930: Level: advanced
1932: .seealso: MatSetOption(), MatAssemblyBegin(), MatAssemblyEnd(), MatSetValuesBlocked(), MatSetValuesLocal(),
1933: InsertMode, INSERT_VALUES, ADD_VALUES, MatSetValues()
1934: @*/
1935: PetscErrorCode MatSetValuesBatch(Mat mat, PetscInt nb, PetscInt bs, PetscInt rows[], const PetscScalar v[])
1936: {
1944: #if defined(PETSC_USE_DEBUG)
1945: if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
1946: #endif
1948: PetscLogEventBegin(MAT_SetValuesBatch,mat,0,0,0);
1949: if (mat->ops->setvaluesbatch) {
1950: (*mat->ops->setvaluesbatch)(mat,nb,bs,rows,v);
1951: } else {
1952: PetscInt b;
1953: for (b = 0; b < nb; ++b) {
1954: MatSetValues(mat, bs, &rows[b*bs], bs, &rows[b*bs], &v[b*bs*bs], ADD_VALUES);
1955: }
1956: }
1957: PetscLogEventEnd(MAT_SetValuesBatch,mat,0,0,0);
1958: return(0);
1959: }
1961: /*@
1962: MatSetLocalToGlobalMapping - Sets a local-to-global numbering for use by
1963: the routine MatSetValuesLocal() to allow users to insert matrix entries
1964: using a local (per-processor) numbering.
1966: Not Collective
1968: Input Parameters:
1969: + x - the matrix
1970: . rmapping - row mapping created with ISLocalToGlobalMappingCreate() or ISLocalToGlobalMappingCreateIS()
1971: - cmapping - column mapping
1973: Level: intermediate
1976: .seealso: MatAssemblyBegin(), MatAssemblyEnd(), MatSetValues(), MatSetValuesLocal()
1977: @*/
1978: PetscErrorCode MatSetLocalToGlobalMapping(Mat x,ISLocalToGlobalMapping rmapping,ISLocalToGlobalMapping cmapping)
1979: {
1988: if (x->ops->setlocaltoglobalmapping) {
1989: (*x->ops->setlocaltoglobalmapping)(x,rmapping,cmapping);
1990: } else {
1991: PetscLayoutSetISLocalToGlobalMapping(x->rmap,rmapping);
1992: PetscLayoutSetISLocalToGlobalMapping(x->cmap,cmapping);
1993: }
1994: return(0);
1995: }
1998: /*@
1999: MatGetLocalToGlobalMapping - Gets the local-to-global numbering set by MatSetLocalToGlobalMapping()
2001: Not Collective
2003: Input Parameters:
2004: . A - the matrix
2006: Output Parameters:
2007: + rmapping - row mapping
2008: - cmapping - column mapping
2010: Level: advanced
2013: .seealso: MatSetValuesLocal()
2014: @*/
2015: PetscErrorCode MatGetLocalToGlobalMapping(Mat A,ISLocalToGlobalMapping *rmapping,ISLocalToGlobalMapping *cmapping)
2016: {
2022: if (rmapping) *rmapping = A->rmap->mapping;
2023: if (cmapping) *cmapping = A->cmap->mapping;
2024: return(0);
2025: }
2027: /*@
2028: MatGetLayouts - Gets the PetscLayout objects for rows and columns
2030: Not Collective
2032: Input Parameters:
2033: . A - the matrix
2035: Output Parameters:
2036: + rmap - row layout
2037: - cmap - column layout
2039: Level: advanced
2041: .seealso: MatCreateVecs(), MatGetLocalToGlobalMapping()
2042: @*/
2043: PetscErrorCode MatGetLayouts(Mat A,PetscLayout *rmap,PetscLayout *cmap)
2044: {
2050: if (rmap) *rmap = A->rmap;
2051: if (cmap) *cmap = A->cmap;
2052: return(0);
2053: }
2055: /*@C
2056: MatSetValuesLocal - Inserts or adds values into certain locations of a matrix,
2057: using a local ordering of the nodes.
2059: Not Collective
2061: Input Parameters:
2062: + mat - the matrix
2063: . nrow, irow - number of rows and their local indices
2064: . ncol, icol - number of columns and their local indices
2065: . y - a logically two-dimensional array of values
2066: - addv - either INSERT_VALUES or ADD_VALUES, where
2067: ADD_VALUES adds values to any existing entries, and
2068: INSERT_VALUES replaces existing entries with new values
2070: Notes:
2071: If you create the matrix yourself (that is not with a call to DMCreateMatrix()) then you MUST call MatXXXXSetPreallocation() or
2072: MatSetUp() before using this routine
2074: If you create the matrix yourself (that is not with a call to DMCreateMatrix()) then you MUST call MatSetLocalToGlobalMapping() before using this routine
2076: Calls to MatSetValuesLocal() with the INSERT_VALUES and ADD_VALUES
2077: options cannot be mixed without intervening calls to the assembly
2078: routines.
2080: These values may be cached, so MatAssemblyBegin() and MatAssemblyEnd()
2081: MUST be called after all calls to MatSetValuesLocal() have been completed.
2083: Level: intermediate
2085: Developer Notes:
2086: This is labeled with C so does not automatically generate Fortran stubs and interfaces
2087: because it requires multiple Fortran interfaces depending on which arguments are scalar or arrays.
2089: .seealso: MatAssemblyBegin(), MatAssemblyEnd(), MatSetValues(), MatSetLocalToGlobalMapping(),
2090: MatSetValueLocal()
2091: @*/
2092: PetscErrorCode MatSetValuesLocal(Mat mat,PetscInt nrow,const PetscInt irow[],PetscInt ncol,const PetscInt icol[],const PetscScalar y[],InsertMode addv)
2093: {
2099: MatCheckPreallocated(mat,1);
2100: if (!nrow || !ncol) return(0); /* no values to insert */
2103: if (mat->insertmode == NOT_SET_VALUES) {
2104: mat->insertmode = addv;
2105: }
2106: #if defined(PETSC_USE_DEBUG)
2107: else if (mat->insertmode != addv) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Cannot mix add values and insert values");
2108: if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2109: if (!mat->ops->setvalueslocal && !mat->ops->setvalues) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
2110: #endif
2112: if (mat->assembled) {
2113: mat->was_assembled = PETSC_TRUE;
2114: mat->assembled = PETSC_FALSE;
2115: }
2116: PetscLogEventBegin(MAT_SetValues,mat,0,0,0);
2117: if (mat->ops->setvalueslocal) {
2118: (*mat->ops->setvalueslocal)(mat,nrow,irow,ncol,icol,y,addv);
2119: } else {
2120: PetscInt buf[8192],*bufr=0,*bufc=0,*irowm,*icolm;
2121: if ((nrow+ncol) <= (PetscInt)(sizeof(buf)/sizeof(PetscInt))) {
2122: irowm = buf; icolm = buf+nrow;
2123: } else {
2124: PetscMalloc2(nrow,&bufr,ncol,&bufc);
2125: irowm = bufr; icolm = bufc;
2126: }
2127: ISLocalToGlobalMappingApply(mat->rmap->mapping,nrow,irow,irowm);
2128: ISLocalToGlobalMappingApply(mat->cmap->mapping,ncol,icol,icolm);
2129: MatSetValues(mat,nrow,irowm,ncol,icolm,y,addv);
2130: PetscFree2(bufr,bufc);
2131: }
2132: PetscLogEventEnd(MAT_SetValues,mat,0,0,0);
2133: return(0);
2134: }
2136: /*@C
2137: MatSetValuesBlockedLocal - Inserts or adds values into certain locations of a matrix,
2138: using a local ordering of the nodes a block at a time.
2140: Not Collective
2142: Input Parameters:
2143: + x - the matrix
2144: . nrow, irow - number of rows and their local indices
2145: . ncol, icol - number of columns and their local indices
2146: . y - a logically two-dimensional array of values
2147: - addv - either INSERT_VALUES or ADD_VALUES, where
2148: ADD_VALUES adds values to any existing entries, and
2149: INSERT_VALUES replaces existing entries with new values
2151: Notes:
2152: If you create the matrix yourself (that is not with a call to DMCreateMatrix()) then you MUST call MatXXXXSetPreallocation() or
2153: MatSetUp() before using this routine
2155: If you create the matrix yourself (that is not with a call to DMCreateMatrix()) then you MUST call MatSetBlockSize() and MatSetLocalToGlobalMapping()
2156: before using this routineBefore calling MatSetValuesLocal(), the user must first set the
2158: Calls to MatSetValuesBlockedLocal() with the INSERT_VALUES and ADD_VALUES
2159: options cannot be mixed without intervening calls to the assembly
2160: routines.
2162: These values may be cached, so MatAssemblyBegin() and MatAssemblyEnd()
2163: MUST be called after all calls to MatSetValuesBlockedLocal() have been completed.
2165: Level: intermediate
2167: Developer Notes:
2168: This is labeled with C so does not automatically generate Fortran stubs and interfaces
2169: because it requires multiple Fortran interfaces depending on which arguments are scalar or arrays.
2171: .seealso: MatSetBlockSize(), MatSetLocalToGlobalMapping(), MatAssemblyBegin(), MatAssemblyEnd(),
2172: MatSetValuesLocal(), MatSetValuesBlocked()
2173: @*/
2174: PetscErrorCode MatSetValuesBlockedLocal(Mat mat,PetscInt nrow,const PetscInt irow[],PetscInt ncol,const PetscInt icol[],const PetscScalar y[],InsertMode addv)
2175: {
2181: MatCheckPreallocated(mat,1);
2182: if (!nrow || !ncol) return(0); /* no values to insert */
2186: if (mat->insertmode == NOT_SET_VALUES) {
2187: mat->insertmode = addv;
2188: }
2189: #if defined(PETSC_USE_DEBUG)
2190: else if (mat->insertmode != addv) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Cannot mix add values and insert values");
2191: if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2192: 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);
2193: #endif
2195: if (mat->assembled) {
2196: mat->was_assembled = PETSC_TRUE;
2197: mat->assembled = PETSC_FALSE;
2198: }
2199: #if defined(PETSC_USE_DEBUG)
2200: /* Condition on the mapping existing, because MatSetValuesBlockedLocal_IS does not require it to be set. */
2201: if (mat->rmap->mapping) {
2202: PetscInt irbs, rbs;
2203: MatGetBlockSizes(mat, &rbs, NULL);
2204: ISLocalToGlobalMappingGetBlockSize(mat->rmap->mapping,&irbs);
2205: if (rbs != irbs) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Different row block sizes! mat %D, row l2g map %D",rbs,irbs);
2206: }
2207: if (mat->cmap->mapping) {
2208: PetscInt icbs, cbs;
2209: MatGetBlockSizes(mat,NULL,&cbs);
2210: ISLocalToGlobalMappingGetBlockSize(mat->cmap->mapping,&icbs);
2211: if (cbs != icbs) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Different col block sizes! mat %D, col l2g map %D",cbs,icbs);
2212: }
2213: #endif
2214: PetscLogEventBegin(MAT_SetValues,mat,0,0,0);
2215: if (mat->ops->setvaluesblockedlocal) {
2216: (*mat->ops->setvaluesblockedlocal)(mat,nrow,irow,ncol,icol,y,addv);
2217: } else {
2218: PetscInt buf[8192],*bufr=0,*bufc=0,*irowm,*icolm;
2219: if ((nrow+ncol) <= (PetscInt)(sizeof(buf)/sizeof(PetscInt))) {
2220: irowm = buf; icolm = buf + nrow;
2221: } else {
2222: PetscMalloc2(nrow,&bufr,ncol,&bufc);
2223: irowm = bufr; icolm = bufc;
2224: }
2225: ISLocalToGlobalMappingApplyBlock(mat->rmap->mapping,nrow,irow,irowm);
2226: ISLocalToGlobalMappingApplyBlock(mat->cmap->mapping,ncol,icol,icolm);
2227: MatSetValuesBlocked(mat,nrow,irowm,ncol,icolm,y,addv);
2228: PetscFree2(bufr,bufc);
2229: }
2230: PetscLogEventEnd(MAT_SetValues,mat,0,0,0);
2231: return(0);
2232: }
2234: /*@
2235: MatMultDiagonalBlock - Computes the matrix-vector product, y = Dx. Where D is defined by the inode or block structure of the diagonal
2237: Collective on Mat
2239: Input Parameters:
2240: + mat - the matrix
2241: - x - the vector to be multiplied
2243: Output Parameters:
2244: . y - the result
2246: Notes:
2247: The vectors x and y cannot be the same. I.e., one cannot
2248: call MatMult(A,y,y).
2250: Level: developer
2252: .seealso: MatMultTranspose(), MatMultAdd(), MatMultTransposeAdd()
2253: @*/
2254: PetscErrorCode MatMultDiagonalBlock(Mat mat,Vec x,Vec y)
2255: {
2264: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2265: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2266: if (x == y) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"x and y must be different vectors");
2267: MatCheckPreallocated(mat,1);
2269: if (!mat->ops->multdiagonalblock) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"This matrix type does not have a multiply defined");
2270: (*mat->ops->multdiagonalblock)(mat,x,y);
2271: PetscObjectStateIncrease((PetscObject)y);
2272: return(0);
2273: }
2275: /* --------------------------------------------------------*/
2276: /*@
2277: MatMult - Computes the matrix-vector product, y = Ax.
2279: Neighbor-wise Collective on Mat
2281: Input Parameters:
2282: + mat - the matrix
2283: - x - the vector to be multiplied
2285: Output Parameters:
2286: . y - the result
2288: Notes:
2289: The vectors x and y cannot be the same. I.e., one cannot
2290: call MatMult(A,y,y).
2292: Level: beginner
2294: .seealso: MatMultTranspose(), MatMultAdd(), MatMultTransposeAdd()
2295: @*/
2296: PetscErrorCode MatMult(Mat mat,Vec x,Vec y)
2297: {
2305: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2306: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2307: if (x == y) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"x and y must be different vectors");
2308: #if !defined(PETSC_HAVE_CONSTRAINTS)
2309: 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);
2310: 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);
2311: 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);
2312: #endif
2313: VecSetErrorIfLocked(y,3);
2314: if (mat->erroriffailure) {VecValidValues(x,2,PETSC_TRUE);}
2315: MatCheckPreallocated(mat,1);
2317: VecLockReadPush(x);
2318: if (!mat->ops->mult) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"This matrix type does not have a multiply defined");
2319: PetscLogEventBegin(MAT_Mult,mat,x,y,0);
2320: (*mat->ops->mult)(mat,x,y);
2321: PetscLogEventEnd(MAT_Mult,mat,x,y,0);
2322: if (mat->erroriffailure) {VecValidValues(y,3,PETSC_FALSE);}
2323: VecLockReadPop(x);
2324: return(0);
2325: }
2327: /*@
2328: MatMultTranspose - Computes matrix transpose times a vector y = A^T * x.
2330: Neighbor-wise Collective on Mat
2332: Input Parameters:
2333: + mat - the matrix
2334: - x - the vector to be multiplied
2336: Output Parameters:
2337: . y - the result
2339: Notes:
2340: The vectors x and y cannot be the same. I.e., one cannot
2341: call MatMultTranspose(A,y,y).
2343: For complex numbers this does NOT compute the Hermitian (complex conjugate) transpose multiple,
2344: use MatMultHermitianTranspose()
2346: Level: beginner
2348: .seealso: MatMult(), MatMultAdd(), MatMultTransposeAdd(), MatMultHermitianTranspose(), MatTranspose()
2349: @*/
2350: PetscErrorCode MatMultTranspose(Mat mat,Vec x,Vec y)
2351: {
2360: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2361: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2362: if (x == y) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"x and y must be different vectors");
2363: #if !defined(PETSC_HAVE_CONSTRAINTS)
2364: 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);
2365: 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);
2366: #endif
2367: if (mat->erroriffailure) {VecValidValues(x,2,PETSC_TRUE);}
2368: MatCheckPreallocated(mat,1);
2370: if (!mat->ops->multtranspose) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"This matrix type does not have a multiply transpose defined");
2371: PetscLogEventBegin(MAT_MultTranspose,mat,x,y,0);
2372: VecLockReadPush(x);
2373: (*mat->ops->multtranspose)(mat,x,y);
2374: VecLockReadPop(x);
2375: PetscLogEventEnd(MAT_MultTranspose,mat,x,y,0);
2376: PetscObjectStateIncrease((PetscObject)y);
2377: if (mat->erroriffailure) {VecValidValues(y,3,PETSC_FALSE);}
2378: return(0);
2379: }
2381: /*@
2382: MatMultHermitianTranspose - Computes matrix Hermitian transpose times a vector.
2384: Neighbor-wise Collective on Mat
2386: Input Parameters:
2387: + mat - the matrix
2388: - x - the vector to be multilplied
2390: Output Parameters:
2391: . y - the result
2393: Notes:
2394: The vectors x and y cannot be the same. I.e., one cannot
2395: call MatMultHermitianTranspose(A,y,y).
2397: Also called the conjugate transpose, complex conjugate transpose, or adjoint.
2399: For real numbers MatMultTranspose() and MatMultHermitianTranspose() are identical.
2401: Level: beginner
2403: .seealso: MatMult(), MatMultAdd(), MatMultHermitianTransposeAdd(), MatMultTranspose()
2404: @*/
2405: PetscErrorCode MatMultHermitianTranspose(Mat mat,Vec x,Vec y)
2406: {
2408: Vec w;
2416: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2417: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2418: if (x == y) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"x and y must be different vectors");
2419: #if !defined(PETSC_HAVE_CONSTRAINTS)
2420: 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);
2421: 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);
2422: #endif
2423: MatCheckPreallocated(mat,1);
2425: PetscLogEventBegin(MAT_MultHermitianTranspose,mat,x,y,0);
2426: if (mat->ops->multhermitiantranspose) {
2427: VecLockReadPush(x);
2428: (*mat->ops->multhermitiantranspose)(mat,x,y);
2429: VecLockReadPop(x);
2430: } else {
2431: VecDuplicate(x,&w);
2432: VecCopy(x,w);
2433: VecConjugate(w);
2434: MatMultTranspose(mat,w,y);
2435: VecDestroy(&w);
2436: VecConjugate(y);
2437: }
2438: PetscLogEventEnd(MAT_MultHermitianTranspose,mat,x,y,0);
2439: PetscObjectStateIncrease((PetscObject)y);
2440: return(0);
2441: }
2443: /*@
2444: MatMultAdd - Computes v3 = v2 + A * v1.
2446: Neighbor-wise Collective on Mat
2448: Input Parameters:
2449: + mat - the matrix
2450: - v1, v2 - the vectors
2452: Output Parameters:
2453: . v3 - the result
2455: Notes:
2456: The vectors v1 and v3 cannot be the same. I.e., one cannot
2457: call MatMultAdd(A,v1,v2,v1).
2459: Level: beginner
2461: .seealso: MatMultTranspose(), MatMult(), MatMultTransposeAdd()
2462: @*/
2463: PetscErrorCode MatMultAdd(Mat mat,Vec v1,Vec v2,Vec v3)
2464: {
2474: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2475: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2476: 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);
2477: /* 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);
2478: 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); */
2479: 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);
2480: 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);
2481: if (v1 == v3) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"v1 and v3 must be different vectors");
2482: MatCheckPreallocated(mat,1);
2484: if (!mat->ops->multadd) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"No MatMultAdd() for matrix type '%s'",((PetscObject)mat)->type_name);
2485: PetscLogEventBegin(MAT_MultAdd,mat,v1,v2,v3);
2486: VecLockReadPush(v1);
2487: (*mat->ops->multadd)(mat,v1,v2,v3);
2488: VecLockReadPop(v1);
2489: PetscLogEventEnd(MAT_MultAdd,mat,v1,v2,v3);
2490: PetscObjectStateIncrease((PetscObject)v3);
2491: return(0);
2492: }
2494: /*@
2495: MatMultTransposeAdd - Computes v3 = v2 + A' * v1.
2497: Neighbor-wise Collective on Mat
2499: Input Parameters:
2500: + mat - the matrix
2501: - v1, v2 - the vectors
2503: Output Parameters:
2504: . v3 - the result
2506: Notes:
2507: The vectors v1 and v3 cannot be the same. I.e., one cannot
2508: call MatMultTransposeAdd(A,v1,v2,v1).
2510: Level: beginner
2512: .seealso: MatMultTranspose(), MatMultAdd(), MatMult()
2513: @*/
2514: PetscErrorCode MatMultTransposeAdd(Mat mat,Vec v1,Vec v2,Vec v3)
2515: {
2525: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2526: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2527: if (!mat->ops->multtransposeadd) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
2528: if (v1 == v3) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"v1 and v3 must be different vectors");
2529: 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);
2530: 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);
2531: 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);
2532: MatCheckPreallocated(mat,1);
2534: PetscLogEventBegin(MAT_MultTransposeAdd,mat,v1,v2,v3);
2535: VecLockReadPush(v1);
2536: (*mat->ops->multtransposeadd)(mat,v1,v2,v3);
2537: VecLockReadPop(v1);
2538: PetscLogEventEnd(MAT_MultTransposeAdd,mat,v1,v2,v3);
2539: PetscObjectStateIncrease((PetscObject)v3);
2540: return(0);
2541: }
2543: /*@
2544: MatMultHermitianTransposeAdd - Computes v3 = v2 + A^H * v1.
2546: Neighbor-wise Collective on Mat
2548: Input Parameters:
2549: + mat - the matrix
2550: - v1, v2 - the vectors
2552: Output Parameters:
2553: . v3 - the result
2555: Notes:
2556: The vectors v1 and v3 cannot be the same. I.e., one cannot
2557: call MatMultHermitianTransposeAdd(A,v1,v2,v1).
2559: Level: beginner
2561: .seealso: MatMultHermitianTranspose(), MatMultTranspose(), MatMultAdd(), MatMult()
2562: @*/
2563: PetscErrorCode MatMultHermitianTransposeAdd(Mat mat,Vec v1,Vec v2,Vec v3)
2564: {
2574: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2575: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2576: if (v1 == v3) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"v1 and v3 must be different vectors");
2577: 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);
2578: 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);
2579: 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);
2580: MatCheckPreallocated(mat,1);
2582: PetscLogEventBegin(MAT_MultHermitianTransposeAdd,mat,v1,v2,v3);
2583: VecLockReadPush(v1);
2584: if (mat->ops->multhermitiantransposeadd) {
2585: (*mat->ops->multhermitiantransposeadd)(mat,v1,v2,v3);
2586: } else {
2587: Vec w,z;
2588: VecDuplicate(v1,&w);
2589: VecCopy(v1,w);
2590: VecConjugate(w);
2591: VecDuplicate(v3,&z);
2592: MatMultTranspose(mat,w,z);
2593: VecDestroy(&w);
2594: VecConjugate(z);
2595: if (v2 != v3) {
2596: VecWAXPY(v3,1.0,v2,z);
2597: } else {
2598: VecAXPY(v3,1.0,z);
2599: }
2600: VecDestroy(&z);
2601: }
2602: VecLockReadPop(v1);
2603: PetscLogEventEnd(MAT_MultHermitianTransposeAdd,mat,v1,v2,v3);
2604: PetscObjectStateIncrease((PetscObject)v3);
2605: return(0);
2606: }
2608: /*@
2609: MatMultConstrained - The inner multiplication routine for a
2610: constrained matrix P^T A P.
2612: Neighbor-wise Collective on Mat
2614: Input Parameters:
2615: + mat - the matrix
2616: - x - the vector to be multilplied
2618: Output Parameters:
2619: . y - the result
2621: Notes:
2622: The vectors x and y cannot be the same. I.e., one cannot
2623: call MatMult(A,y,y).
2625: Level: beginner
2627: .seealso: MatMult(), MatMultTranspose(), MatMultAdd(), MatMultTransposeAdd()
2628: @*/
2629: PetscErrorCode MatMultConstrained(Mat mat,Vec x,Vec y)
2630: {
2637: if (!mat->assembled) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2638: if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2639: if (x == y) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"x and y must be different vectors");
2640: 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);
2641: 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);
2642: 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);
2644: PetscLogEventBegin(MAT_MultConstrained,mat,x,y,0);
2645: VecLockReadPush(x);
2646: (*mat->ops->multconstrained)(mat,x,y);
2647: VecLockReadPop(x);
2648: PetscLogEventEnd(MAT_MultConstrained,mat,x,y,0);
2649: PetscObjectStateIncrease((PetscObject)y);
2650: return(0);
2651: }
2653: /*@
2654: MatMultTransposeConstrained - The inner multiplication routine for a
2655: constrained matrix P^T A^T P.
2657: Neighbor-wise Collective on Mat
2659: Input Parameters:
2660: + mat - the matrix
2661: - x - the vector to be multilplied
2663: Output Parameters:
2664: . y - the result
2666: Notes:
2667: The vectors x and y cannot be the same. I.e., one cannot
2668: call MatMult(A,y,y).
2670: Level: beginner
2672: .seealso: MatMult(), MatMultTranspose(), MatMultAdd(), MatMultTransposeAdd()
2673: @*/
2674: PetscErrorCode MatMultTransposeConstrained(Mat mat,Vec x,Vec y)
2675: {
2682: if (!mat->assembled) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2683: if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2684: if (x == y) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"x and y must be different vectors");
2685: 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);
2686: 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);
2688: PetscLogEventBegin(MAT_MultConstrained,mat,x,y,0);
2689: (*mat->ops->multtransposeconstrained)(mat,x,y);
2690: PetscLogEventEnd(MAT_MultConstrained,mat,x,y,0);
2691: PetscObjectStateIncrease((PetscObject)y);
2692: return(0);
2693: }
2695: /*@C
2696: MatGetFactorType - gets the type of factorization it is
2698: Not Collective
2700: Input Parameters:
2701: . mat - the matrix
2703: Output Parameters:
2704: . t - the type, one of MAT_FACTOR_NONE, MAT_FACTOR_LU, MAT_FACTOR_CHOLESKY, MAT_FACTOR_ILU, MAT_FACTOR_ICC,MAT_FACTOR_ILUDT
2706: Level: intermediate
2708: .seealso: MatFactorType, MatGetFactor(), MatSetFactorType()
2709: @*/
2710: PetscErrorCode MatGetFactorType(Mat mat,MatFactorType *t)
2711: {
2716: *t = mat->factortype;
2717: return(0);
2718: }
2720: /*@C
2721: MatSetFactorType - sets the type of factorization it is
2723: Logically Collective on Mat
2725: Input Parameters:
2726: + mat - the matrix
2727: - t - the type, one of MAT_FACTOR_NONE, MAT_FACTOR_LU, MAT_FACTOR_CHOLESKY, MAT_FACTOR_ILU, MAT_FACTOR_ICC,MAT_FACTOR_ILUDT
2729: Level: intermediate
2731: .seealso: MatFactorType, MatGetFactor(), MatGetFactorType()
2732: @*/
2733: PetscErrorCode MatSetFactorType(Mat mat, MatFactorType t)
2734: {
2738: mat->factortype = t;
2739: return(0);
2740: }
2742: /* ------------------------------------------------------------*/
2743: /*@C
2744: MatGetInfo - Returns information about matrix storage (number of
2745: nonzeros, memory, etc.).
2747: Collective on Mat if MAT_GLOBAL_MAX or MAT_GLOBAL_SUM is used as the flag
2749: Input Parameters:
2750: . mat - the matrix
2752: Output Parameters:
2753: + flag - flag indicating the type of parameters to be returned
2754: (MAT_LOCAL - local matrix, MAT_GLOBAL_MAX - maximum over all processors,
2755: MAT_GLOBAL_SUM - sum over all processors)
2756: - info - matrix information context
2758: Notes:
2759: The MatInfo context contains a variety of matrix data, including
2760: number of nonzeros allocated and used, number of mallocs during
2761: matrix assembly, etc. Additional information for factored matrices
2762: is provided (such as the fill ratio, number of mallocs during
2763: factorization, etc.). Much of this info is printed to PETSC_STDOUT
2764: when using the runtime options
2765: $ -info -mat_view ::ascii_info
2767: Example for C/C++ Users:
2768: See the file ${PETSC_DIR}/include/petscmat.h for a complete list of
2769: data within the MatInfo context. For example,
2770: .vb
2771: MatInfo info;
2772: Mat A;
2773: double mal, nz_a, nz_u;
2775: MatGetInfo(A,MAT_LOCAL,&info);
2776: mal = info.mallocs;
2777: nz_a = info.nz_allocated;
2778: .ve
2780: Example for Fortran Users:
2781: Fortran users should declare info as a double precision
2782: array of dimension MAT_INFO_SIZE, and then extract the parameters
2783: of interest. See the file ${PETSC_DIR}/include/petsc/finclude/petscmat.h
2784: a complete list of parameter names.
2785: .vb
2786: double precision info(MAT_INFO_SIZE)
2787: double precision mal, nz_a
2788: Mat A
2789: integer ierr
2791: call MatGetInfo(A,MAT_LOCAL,info,ierr)
2792: mal = info(MAT_INFO_MALLOCS)
2793: nz_a = info(MAT_INFO_NZ_ALLOCATED)
2794: .ve
2796: Level: intermediate
2798: Developer Note: fortran interface is not autogenerated as the f90
2799: interface defintion cannot be generated correctly [due to MatInfo]
2801: .seealso: MatStashGetInfo()
2803: @*/
2804: PetscErrorCode MatGetInfo(Mat mat,MatInfoType flag,MatInfo *info)
2805: {
2812: if (!mat->ops->getinfo) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
2813: MatCheckPreallocated(mat,1);
2814: (*mat->ops->getinfo)(mat,flag,info);
2815: return(0);
2816: }
2818: /*
2819: This is used by external packages where it is not easy to get the info from the actual
2820: matrix factorization.
2821: */
2822: PetscErrorCode MatGetInfo_External(Mat A,MatInfoType flag,MatInfo *info)
2823: {
2827: PetscMemzero(info,sizeof(MatInfo));
2828: return(0);
2829: }
2831: /* ----------------------------------------------------------*/
2833: /*@C
2834: MatLUFactor - Performs in-place LU factorization of matrix.
2836: Collective on Mat
2838: Input Parameters:
2839: + mat - the matrix
2840: . row - row permutation
2841: . col - column permutation
2842: - info - options for factorization, includes
2843: $ fill - expected fill as ratio of original fill.
2844: $ dtcol - pivot tolerance (0 no pivot, 1 full column pivoting)
2845: $ Run with the option -info to determine an optimal value to use
2847: Notes:
2848: Most users should employ the simplified KSP interface for linear solvers
2849: instead of working directly with matrix algebra routines such as this.
2850: See, e.g., KSPCreate().
2852: This changes the state of the matrix to a factored matrix; it cannot be used
2853: for example with MatSetValues() unless one first calls MatSetUnfactored().
2855: Level: developer
2857: .seealso: MatLUFactorSymbolic(), MatLUFactorNumeric(), MatCholeskyFactor(),
2858: MatGetOrdering(), MatSetUnfactored(), MatFactorInfo, MatGetFactor()
2860: Developer Note: fortran interface is not autogenerated as the f90
2861: interface defintion cannot be generated correctly [due to MatFactorInfo]
2863: @*/
2864: PetscErrorCode MatLUFactor(Mat mat,IS row,IS col,const MatFactorInfo *info)
2865: {
2867: MatFactorInfo tinfo;
2875: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2876: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2877: if (!mat->ops->lufactor) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
2878: MatCheckPreallocated(mat,1);
2879: if (!info) {
2880: MatFactorInfoInitialize(&tinfo);
2881: info = &tinfo;
2882: }
2884: PetscLogEventBegin(MAT_LUFactor,mat,row,col,0);
2885: (*mat->ops->lufactor)(mat,row,col,info);
2886: PetscLogEventEnd(MAT_LUFactor,mat,row,col,0);
2887: PetscObjectStateIncrease((PetscObject)mat);
2888: return(0);
2889: }
2891: /*@C
2892: MatILUFactor - Performs in-place ILU factorization of matrix.
2894: Collective on Mat
2896: Input Parameters:
2897: + mat - the matrix
2898: . row - row permutation
2899: . col - column permutation
2900: - info - structure containing
2901: $ levels - number of levels of fill.
2902: $ expected fill - as ratio of original fill.
2903: $ 1 or 0 - indicating force fill on diagonal (improves robustness for matrices
2904: missing diagonal entries)
2906: Notes:
2907: Probably really in-place only when level of fill is zero, otherwise allocates
2908: new space to store factored matrix and deletes previous memory.
2910: Most users should employ the simplified KSP interface for linear solvers
2911: instead of working directly with matrix algebra routines such as this.
2912: See, e.g., KSPCreate().
2914: Level: developer
2916: .seealso: MatILUFactorSymbolic(), MatLUFactorNumeric(), MatCholeskyFactor(), MatFactorInfo
2918: Developer Note: fortran interface is not autogenerated as the f90
2919: interface defintion cannot be generated correctly [due to MatFactorInfo]
2921: @*/
2922: PetscErrorCode MatILUFactor(Mat mat,IS row,IS col,const MatFactorInfo *info)
2923: {
2932: if (mat->rmap->N != mat->cmap->N) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONG,"matrix must be square");
2933: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2934: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2935: if (!mat->ops->ilufactor) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
2936: MatCheckPreallocated(mat,1);
2938: PetscLogEventBegin(MAT_ILUFactor,mat,row,col,0);
2939: (*mat->ops->ilufactor)(mat,row,col,info);
2940: PetscLogEventEnd(MAT_ILUFactor,mat,row,col,0);
2941: PetscObjectStateIncrease((PetscObject)mat);
2942: return(0);
2943: }
2945: /*@C
2946: MatLUFactorSymbolic - Performs symbolic LU factorization of matrix.
2947: Call this routine before calling MatLUFactorNumeric().
2949: Collective on Mat
2951: Input Parameters:
2952: + fact - the factor matrix obtained with MatGetFactor()
2953: . mat - the matrix
2954: . row, col - row and column permutations
2955: - info - options for factorization, includes
2956: $ fill - expected fill as ratio of original fill.
2957: $ dtcol - pivot tolerance (0 no pivot, 1 full column pivoting)
2958: $ Run with the option -info to determine an optimal value to use
2961: Notes:
2962: See Users-Manual: ch_mat for additional information about choosing the fill factor for better efficiency.
2964: Most users should employ the simplified KSP interface for linear solvers
2965: instead of working directly with matrix algebra routines such as this.
2966: See, e.g., KSPCreate().
2968: Level: developer
2970: .seealso: MatLUFactor(), MatLUFactorNumeric(), MatCholeskyFactor(), MatFactorInfo, MatFactorInfoInitialize()
2972: Developer Note: fortran interface is not autogenerated as the f90
2973: interface defintion cannot be generated correctly [due to MatFactorInfo]
2975: @*/
2976: PetscErrorCode MatLUFactorSymbolic(Mat fact,Mat mat,IS row,IS col,const MatFactorInfo *info)
2977: {
2979: MatFactorInfo tinfo;
2988: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2989: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2990: if (!(fact)->ops->lufactorsymbolic) {
2991: MatSolverType spackage;
2992: MatFactorGetSolverType(fact,&spackage);
2993: SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Matrix type %s symbolic LU using solver package %s",((PetscObject)mat)->type_name,spackage);
2994: }
2995: MatCheckPreallocated(mat,2);
2996: if (!info) {
2997: MatFactorInfoInitialize(&tinfo);
2998: info = &tinfo;
2999: }
3001: PetscLogEventBegin(MAT_LUFactorSymbolic,mat,row,col,0);
3002: (fact->ops->lufactorsymbolic)(fact,mat,row,col,info);
3003: PetscLogEventEnd(MAT_LUFactorSymbolic,mat,row,col,0);
3004: PetscObjectStateIncrease((PetscObject)fact);
3005: return(0);
3006: }
3008: /*@C
3009: MatLUFactorNumeric - Performs numeric LU factorization of a matrix.
3010: Call this routine after first calling MatLUFactorSymbolic().
3012: Collective on Mat
3014: Input Parameters:
3015: + fact - the factor matrix obtained with MatGetFactor()
3016: . mat - the matrix
3017: - info - options for factorization
3019: Notes:
3020: See MatLUFactor() for in-place factorization. See
3021: MatCholeskyFactorNumeric() for the symmetric, positive definite case.
3023: Most users should employ the simplified KSP interface for linear solvers
3024: instead of working directly with matrix algebra routines such as this.
3025: See, e.g., KSPCreate().
3027: Level: developer
3029: .seealso: MatLUFactorSymbolic(), MatLUFactor(), MatCholeskyFactor()
3031: Developer Note: fortran interface is not autogenerated as the f90
3032: interface defintion cannot be generated correctly [due to MatFactorInfo]
3034: @*/
3035: PetscErrorCode MatLUFactorNumeric(Mat fact,Mat mat,const MatFactorInfo *info)
3036: {
3037: MatFactorInfo tinfo;
3045: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
3046: 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);
3048: if (!(fact)->ops->lufactornumeric) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s numeric LU",((PetscObject)mat)->type_name);
3049: MatCheckPreallocated(mat,2);
3050: if (!info) {
3051: MatFactorInfoInitialize(&tinfo);
3052: info = &tinfo;
3053: }
3055: PetscLogEventBegin(MAT_LUFactorNumeric,mat,fact,0,0);
3056: (fact->ops->lufactornumeric)(fact,mat,info);
3057: PetscLogEventEnd(MAT_LUFactorNumeric,mat,fact,0,0);
3058: MatViewFromOptions(fact,NULL,"-mat_factor_view");
3059: PetscObjectStateIncrease((PetscObject)fact);
3060: return(0);
3061: }
3063: /*@C
3064: MatCholeskyFactor - Performs in-place Cholesky factorization of a
3065: symmetric matrix.
3067: Collective on Mat
3069: Input Parameters:
3070: + mat - the matrix
3071: . perm - row and column permutations
3072: - f - expected fill as ratio of original fill
3074: Notes:
3075: See MatLUFactor() for the nonsymmetric case. See also
3076: MatCholeskyFactorSymbolic(), and MatCholeskyFactorNumeric().
3078: Most users should employ the simplified KSP interface for linear solvers
3079: instead of working directly with matrix algebra routines such as this.
3080: See, e.g., KSPCreate().
3082: Level: developer
3084: .seealso: MatLUFactor(), MatCholeskyFactorSymbolic(), MatCholeskyFactorNumeric()
3085: MatGetOrdering()
3087: Developer Note: fortran interface is not autogenerated as the f90
3088: interface defintion cannot be generated correctly [due to MatFactorInfo]
3090: @*/
3091: PetscErrorCode MatCholeskyFactor(Mat mat,IS perm,const MatFactorInfo *info)
3092: {
3094: MatFactorInfo tinfo;
3101: if (mat->rmap->N != mat->cmap->N) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONG,"Matrix must be square");
3102: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
3103: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
3104: 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);
3105: MatCheckPreallocated(mat,1);
3106: if (!info) {
3107: MatFactorInfoInitialize(&tinfo);
3108: info = &tinfo;
3109: }
3111: PetscLogEventBegin(MAT_CholeskyFactor,mat,perm,0,0);
3112: (*mat->ops->choleskyfactor)(mat,perm,info);
3113: PetscLogEventEnd(MAT_CholeskyFactor,mat,perm,0,0);
3114: PetscObjectStateIncrease((PetscObject)mat);
3115: return(0);
3116: }
3118: /*@C
3119: MatCholeskyFactorSymbolic - Performs symbolic Cholesky factorization
3120: of a symmetric matrix.
3122: Collective on Mat
3124: Input Parameters:
3125: + fact - the factor matrix obtained with MatGetFactor()
3126: . mat - the matrix
3127: . perm - row and column permutations
3128: - info - options for factorization, includes
3129: $ fill - expected fill as ratio of original fill.
3130: $ dtcol - pivot tolerance (0 no pivot, 1 full column pivoting)
3131: $ Run with the option -info to determine an optimal value to use
3133: Notes:
3134: See MatLUFactorSymbolic() for the nonsymmetric case. See also
3135: MatCholeskyFactor() and MatCholeskyFactorNumeric().
3137: Most users should employ the simplified KSP interface for linear solvers
3138: instead of working directly with matrix algebra routines such as this.
3139: See, e.g., KSPCreate().
3141: Level: developer
3143: .seealso: MatLUFactorSymbolic(), MatCholeskyFactor(), MatCholeskyFactorNumeric()
3144: MatGetOrdering()
3146: Developer Note: fortran interface is not autogenerated as the f90
3147: interface defintion cannot be generated correctly [due to MatFactorInfo]
3149: @*/
3150: PetscErrorCode MatCholeskyFactorSymbolic(Mat fact,Mat mat,IS perm,const MatFactorInfo *info)
3151: {
3153: MatFactorInfo tinfo;
3161: if (mat->rmap->N != mat->cmap->N) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONG,"Matrix must be square");
3162: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
3163: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
3164: if (!(fact)->ops->choleskyfactorsymbolic) {
3165: MatSolverType spackage;
3166: MatFactorGetSolverType(fact,&spackage);
3167: SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s symbolic factor Cholesky using solver package %s",((PetscObject)mat)->type_name,spackage);
3168: }
3169: MatCheckPreallocated(mat,2);
3170: if (!info) {
3171: MatFactorInfoInitialize(&tinfo);
3172: info = &tinfo;
3173: }
3175: PetscLogEventBegin(MAT_CholeskyFactorSymbolic,mat,perm,0,0);
3176: (fact->ops->choleskyfactorsymbolic)(fact,mat,perm,info);
3177: PetscLogEventEnd(MAT_CholeskyFactorSymbolic,mat,perm,0,0);
3178: PetscObjectStateIncrease((PetscObject)fact);
3179: return(0);
3180: }
3182: /*@C
3183: MatCholeskyFactorNumeric - Performs numeric Cholesky factorization
3184: of a symmetric matrix. Call this routine after first calling
3185: MatCholeskyFactorSymbolic().
3187: Collective on Mat
3189: Input Parameters:
3190: + fact - the factor matrix obtained with MatGetFactor()
3191: . mat - the initial matrix
3192: . info - options for factorization
3193: - fact - the symbolic factor of mat
3196: Notes:
3197: Most users should employ the simplified KSP interface for linear solvers
3198: instead of working directly with matrix algebra routines such as this.
3199: See, e.g., KSPCreate().
3201: Level: developer
3203: .seealso: MatCholeskyFactorSymbolic(), MatCholeskyFactor(), MatLUFactorNumeric()
3205: Developer Note: fortran interface is not autogenerated as the f90
3206: interface defintion cannot be generated correctly [due to MatFactorInfo]
3208: @*/
3209: PetscErrorCode MatCholeskyFactorNumeric(Mat fact,Mat mat,const MatFactorInfo *info)
3210: {
3211: MatFactorInfo tinfo;
3219: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
3220: if (!(fact)->ops->choleskyfactornumeric) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s numeric factor Cholesky",((PetscObject)mat)->type_name);
3221: 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);
3222: MatCheckPreallocated(mat,2);
3223: if (!info) {
3224: MatFactorInfoInitialize(&tinfo);
3225: info = &tinfo;
3226: }
3228: PetscLogEventBegin(MAT_CholeskyFactorNumeric,mat,fact,0,0);
3229: (fact->ops->choleskyfactornumeric)(fact,mat,info);
3230: PetscLogEventEnd(MAT_CholeskyFactorNumeric,mat,fact,0,0);
3231: MatViewFromOptions(fact,NULL,"-mat_factor_view");
3232: PetscObjectStateIncrease((PetscObject)fact);
3233: return(0);
3234: }
3236: /* ----------------------------------------------------------------*/
3237: /*@
3238: MatSolve - Solves A x = b, given a factored matrix.
3240: Neighbor-wise Collective on Mat
3242: Input Parameters:
3243: + mat - the factored matrix
3244: - b - the right-hand-side vector
3246: Output Parameter:
3247: . x - the result vector
3249: Notes:
3250: The vectors b and x cannot be the same. I.e., one cannot
3251: call MatSolve(A,x,x).
3253: Notes:
3254: Most users should employ the simplified KSP interface for linear solvers
3255: instead of working directly with matrix algebra routines such as this.
3256: See, e.g., KSPCreate().
3258: Level: developer
3260: .seealso: MatSolveAdd(), MatSolveTranspose(), MatSolveTransposeAdd()
3261: @*/
3262: PetscErrorCode MatSolve(Mat mat,Vec b,Vec x)
3263: {
3273: if (x == b) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"x and b must be different vectors");
3274: 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);
3275: 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);
3276: 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);
3277: if (!mat->rmap->N && !mat->cmap->N) return(0);
3278: if (!mat->ops->solve) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
3279: MatCheckPreallocated(mat,1);
3281: PetscLogEventBegin(MAT_Solve,mat,b,x,0);
3282: if (mat->factorerrortype) {
3283: PetscInfo1(mat,"MatFactorError %D\n",mat->factorerrortype);
3284: VecSetInf(x);
3285: } else {
3286: if (!mat->ops->solve) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
3287: (*mat->ops->solve)(mat,b,x);
3288: }
3289: PetscLogEventEnd(MAT_Solve,mat,b,x,0);
3290: PetscObjectStateIncrease((PetscObject)x);
3291: return(0);
3292: }
3294: static PetscErrorCode MatMatSolve_Basic(Mat A,Mat B,Mat X,PetscBool trans)
3295: {
3297: Vec b,x;
3298: PetscInt m,N,i;
3299: PetscScalar *bb,*xx;
3302: MatDenseGetArrayRead(B,(const PetscScalar**)&bb);
3303: MatDenseGetArray(X,&xx);
3304: MatGetLocalSize(B,&m,NULL); /* number local rows */
3305: MatGetSize(B,NULL,&N); /* total columns in dense matrix */
3306: MatCreateVecs(A,&x,&b);
3307: for (i=0; i<N; i++) {
3308: VecPlaceArray(b,bb + i*m);
3309: VecPlaceArray(x,xx + i*m);
3310: if (trans) {
3311: MatSolveTranspose(A,b,x);
3312: } else {
3313: MatSolve(A,b,x);
3314: }
3315: VecResetArray(x);
3316: VecResetArray(b);
3317: }
3318: VecDestroy(&b);
3319: VecDestroy(&x);
3320: MatDenseRestoreArrayRead(B,(const PetscScalar**)&bb);
3321: MatDenseRestoreArray(X,&xx);
3322: return(0);
3323: }
3325: /*@
3326: MatMatSolve - Solves A X = B, given a factored matrix.
3328: Neighbor-wise Collective on Mat
3330: Input Parameters:
3331: + A - the factored matrix
3332: - B - the right-hand-side matrix (dense matrix)
3334: Output Parameter:
3335: . X - the result matrix (dense matrix)
3337: Notes:
3338: The matrices b and x cannot be the same. I.e., one cannot
3339: call MatMatSolve(A,x,x).
3341: Notes:
3342: Most users should usually employ the simplified KSP interface for linear solvers
3343: instead of working directly with matrix algebra routines such as this.
3344: See, e.g., KSPCreate(). However KSP can only solve for one vector (column of X)
3345: at a time.
3347: When using SuperLU_Dist as a parallel solver PETSc will use the SuperLU_Dist functionality to solve multiple right hand sides simultaneously. For MUMPS
3348: it calls a separate solve for each right hand side since MUMPS does not yet support distributed right hand sides.
3350: Since the resulting matrix X must always be dense we do not support sparse representation of the matrix B.
3352: Level: developer
3354: .seealso: MatMatSolveTranspose(), MatLUFactor(), MatCholeskyFactor()
3355: @*/
3356: PetscErrorCode MatMatSolve(Mat A,Mat B,Mat X)
3357: {
3367: if (X == B) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_IDN,"X and B must be different matrices");
3368: 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);
3369: 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);
3370: 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");
3371: if (!A->rmap->N && !A->cmap->N) return(0);
3372: if (!A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
3373: MatCheckPreallocated(A,1);
3375: PetscLogEventBegin(MAT_MatSolve,A,B,X,0);
3376: if (!A->ops->matsolve) {
3377: PetscInfo1(A,"Mat type %s using basic MatMatSolve\n",((PetscObject)A)->type_name);
3378: MatMatSolve_Basic(A,B,X,PETSC_FALSE);
3379: } else {
3380: (*A->ops->matsolve)(A,B,X);
3381: }
3382: PetscLogEventEnd(MAT_MatSolve,A,B,X,0);
3383: PetscObjectStateIncrease((PetscObject)X);
3384: return(0);
3385: }
3387: /*@
3388: MatMatSolveTranspose - Solves A^T X = B, given a factored matrix.
3390: Neighbor-wise Collective on Mat
3392: Input Parameters:
3393: + A - the factored matrix
3394: - B - the right-hand-side matrix (dense matrix)
3396: Output Parameter:
3397: . X - the result matrix (dense matrix)
3399: Notes:
3400: The matrices B and X cannot be the same. I.e., one cannot
3401: call MatMatSolveTranspose(A,X,X).
3403: Notes:
3404: Most users should usually employ the simplified KSP interface for linear solvers
3405: instead of working directly with matrix algebra routines such as this.
3406: See, e.g., KSPCreate(). However KSP can only solve for one vector (column of X)
3407: at a time.
3409: When using SuperLU_Dist or MUMPS as a parallel solver, PETSc will use their functionality to solve multiple right hand sides simultaneously.
3411: Level: developer
3413: .seealso: MatMatSolve(), MatLUFactor(), MatCholeskyFactor()
3414: @*/
3415: PetscErrorCode MatMatSolveTranspose(Mat A,Mat B,Mat X)
3416: {
3426: if (X == B) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_IDN,"X and B must be different matrices");
3427: 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);
3428: 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);
3429: 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);
3430: 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");
3431: if (!A->rmap->N && !A->cmap->N) return(0);
3432: if (!A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
3433: MatCheckPreallocated(A,1);
3435: PetscLogEventBegin(MAT_MatSolve,A,B,X,0);
3436: if (!A->ops->matsolvetranspose) {
3437: PetscInfo1(A,"Mat type %s using basic MatMatSolveTranspose\n",((PetscObject)A)->type_name);
3438: MatMatSolve_Basic(A,B,X,PETSC_TRUE);
3439: } else {
3440: (*A->ops->matsolvetranspose)(A,B,X);
3441: }
3442: PetscLogEventEnd(MAT_MatSolve,A,B,X,0);
3443: PetscObjectStateIncrease((PetscObject)X);
3444: return(0);
3445: }
3447: /*@
3448: MatMatTransposeSolve - Solves A X = B^T, given a factored matrix.
3450: Neighbor-wise Collective on Mat
3452: Input Parameters:
3453: + A - the factored matrix
3454: - Bt - the transpose of right-hand-side matrix
3456: Output Parameter:
3457: . X - the result matrix (dense matrix)
3459: Notes:
3460: Most users should usually employ the simplified KSP interface for linear solvers
3461: instead of working directly with matrix algebra routines such as this.
3462: See, e.g., KSPCreate(). However KSP can only solve for one vector (column of X)
3463: at a time.
3465: 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().
3467: Level: developer
3469: .seealso: MatMatSolve(), MatMatSolveTranspose(), MatLUFactor(), MatCholeskyFactor()
3470: @*/
3471: PetscErrorCode MatMatTransposeSolve(Mat A,Mat Bt,Mat X)
3472: {
3483: if (X == Bt) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_IDN,"X and B must be different matrices");
3484: 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);
3485: 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);
3486: 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");
3487: if (!A->rmap->N && !A->cmap->N) return(0);
3488: if (!A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
3489: MatCheckPreallocated(A,1);
3491: if (!A->ops->mattransposesolve) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Mat type %s",((PetscObject)A)->type_name);
3492: PetscLogEventBegin(MAT_MatTrSolve,A,Bt,X,0);
3493: (*A->ops->mattransposesolve)(A,Bt,X);
3494: PetscLogEventEnd(MAT_MatTrSolve,A,Bt,X,0);
3495: PetscObjectStateIncrease((PetscObject)X);
3496: return(0);
3497: }
3499: /*@
3500: MatForwardSolve - Solves L x = b, given a factored matrix, A = LU, or
3501: U^T*D^(1/2) x = b, given a factored symmetric matrix, A = U^T*D*U,
3503: Neighbor-wise Collective on Mat
3505: Input Parameters:
3506: + mat - the factored matrix
3507: - b - the right-hand-side vector
3509: Output Parameter:
3510: . x - the result vector
3512: Notes:
3513: MatSolve() should be used for most applications, as it performs
3514: a forward solve followed by a backward solve.
3516: The vectors b and x cannot be the same, i.e., one cannot
3517: call MatForwardSolve(A,x,x).
3519: For matrix in seqsbaij format with block size larger than 1,
3520: the diagonal blocks are not implemented as D = D^(1/2) * D^(1/2) yet.
3521: MatForwardSolve() solves U^T*D y = b, and
3522: MatBackwardSolve() solves U x = y.
3523: Thus they do not provide a symmetric preconditioner.
3525: Most users should employ the simplified KSP interface for linear solvers
3526: instead of working directly with matrix algebra routines such as this.
3527: See, e.g., KSPCreate().
3529: Level: developer
3531: .seealso: MatSolve(), MatBackwardSolve()
3532: @*/
3533: PetscErrorCode MatForwardSolve(Mat mat,Vec b,Vec x)
3534: {
3544: if (x == b) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"x and b must be different vectors");
3545: 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);
3546: 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);
3547: 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);
3548: if (!mat->rmap->N && !mat->cmap->N) return(0);
3549: if (!mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
3550: MatCheckPreallocated(mat,1);
3552: if (!mat->ops->forwardsolve) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
3553: PetscLogEventBegin(MAT_ForwardSolve,mat,b,x,0);
3554: (*mat->ops->forwardsolve)(mat,b,x);
3555: PetscLogEventEnd(MAT_ForwardSolve,mat,b,x,0);
3556: PetscObjectStateIncrease((PetscObject)x);
3557: return(0);
3558: }
3560: /*@
3561: MatBackwardSolve - Solves U x = b, given a factored matrix, A = LU.
3562: D^(1/2) U x = b, given a factored symmetric matrix, A = U^T*D*U,
3564: Neighbor-wise Collective on Mat
3566: Input Parameters:
3567: + mat - the factored matrix
3568: - b - the right-hand-side vector
3570: Output Parameter:
3571: . x - the result vector
3573: Notes:
3574: MatSolve() should be used for most applications, as it performs
3575: a forward solve followed by a backward solve.
3577: The vectors b and x cannot be the same. I.e., one cannot
3578: call MatBackwardSolve(A,x,x).
3580: For matrix in seqsbaij format with block size larger than 1,
3581: the diagonal blocks are not implemented as D = D^(1/2) * D^(1/2) yet.
3582: MatForwardSolve() solves U^T*D y = b, and
3583: MatBackwardSolve() solves U x = y.
3584: Thus they do not provide a symmetric preconditioner.
3586: Most users should employ the simplified KSP interface for linear solvers
3587: instead of working directly with matrix algebra routines such as this.
3588: See, e.g., KSPCreate().
3590: Level: developer
3592: .seealso: MatSolve(), MatForwardSolve()
3593: @*/
3594: PetscErrorCode MatBackwardSolve(Mat mat,Vec b,Vec x)
3595: {
3605: if (x == b) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"x and b must be different vectors");
3606: 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);
3607: 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);
3608: 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);
3609: if (!mat->rmap->N && !mat->cmap->N) return(0);
3610: if (!mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
3611: MatCheckPreallocated(mat,1);
3613: if (!mat->ops->backwardsolve) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
3614: PetscLogEventBegin(MAT_BackwardSolve,mat,b,x,0);
3615: (*mat->ops->backwardsolve)(mat,b,x);
3616: PetscLogEventEnd(MAT_BackwardSolve,mat,b,x,0);
3617: PetscObjectStateIncrease((PetscObject)x);
3618: return(0);
3619: }
3621: /*@
3622: MatSolveAdd - Computes x = y + inv(A)*b, given a factored matrix.
3624: Neighbor-wise Collective on Mat
3626: Input Parameters:
3627: + mat - the factored matrix
3628: . b - the right-hand-side vector
3629: - y - the vector to be added to
3631: Output Parameter:
3632: . x - the result vector
3634: Notes:
3635: The vectors b and x cannot be the same. I.e., one cannot
3636: call MatSolveAdd(A,x,y,x).
3638: Most users should employ the simplified KSP interface for linear solvers
3639: instead of working directly with matrix algebra routines such as this.
3640: See, e.g., KSPCreate().
3642: Level: developer
3644: .seealso: MatSolve(), MatSolveTranspose(), MatSolveTransposeAdd()
3645: @*/
3646: PetscErrorCode MatSolveAdd(Mat mat,Vec b,Vec y,Vec x)
3647: {
3648: PetscScalar one = 1.0;
3649: Vec tmp;
3661: if (x == b) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"x and b must be different vectors");
3662: 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);
3663: 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);
3664: 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);
3665: 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);
3666: 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);
3667: if (!mat->rmap->N && !mat->cmap->N) return(0);
3668: if (!mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
3669: MatCheckPreallocated(mat,1);
3671: PetscLogEventBegin(MAT_SolveAdd,mat,b,x,y);
3672: if (mat->ops->solveadd) {
3673: (*mat->ops->solveadd)(mat,b,y,x);
3674: } else {
3675: /* do the solve then the add manually */
3676: if (x != y) {
3677: MatSolve(mat,b,x);
3678: VecAXPY(x,one,y);
3679: } else {
3680: VecDuplicate(x,&tmp);
3681: PetscLogObjectParent((PetscObject)mat,(PetscObject)tmp);
3682: VecCopy(x,tmp);
3683: MatSolve(mat,b,x);
3684: VecAXPY(x,one,tmp);
3685: VecDestroy(&tmp);
3686: }
3687: }
3688: PetscLogEventEnd(MAT_SolveAdd,mat,b,x,y);
3689: PetscObjectStateIncrease((PetscObject)x);
3690: return(0);
3691: }
3693: /*@
3694: MatSolveTranspose - Solves A' x = b, given a factored matrix.
3696: Neighbor-wise Collective on Mat
3698: Input Parameters:
3699: + mat - the factored matrix
3700: - b - the right-hand-side vector
3702: Output Parameter:
3703: . x - the result vector
3705: Notes:
3706: The vectors b and x cannot be the same. I.e., one cannot
3707: call MatSolveTranspose(A,x,x).
3709: Most users should employ the simplified KSP interface for linear solvers
3710: instead of working directly with matrix algebra routines such as this.
3711: See, e.g., KSPCreate().
3713: Level: developer
3715: .seealso: MatSolve(), MatSolveAdd(), MatSolveTransposeAdd()
3716: @*/
3717: PetscErrorCode MatSolveTranspose(Mat mat,Vec b,Vec x)
3718: {
3728: if (x == b) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"x and b must be different vectors");
3729: 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);
3730: 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);
3731: if (!mat->rmap->N && !mat->cmap->N) return(0);
3732: MatCheckPreallocated(mat,1);
3733: PetscLogEventBegin(MAT_SolveTranspose,mat,b,x,0);
3734: if (mat->factorerrortype) {
3735: PetscInfo1(mat,"MatFactorError %D\n",mat->factorerrortype);
3736: VecSetInf(x);
3737: } else {
3738: if (!mat->ops->solvetranspose) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Matrix type %s",((PetscObject)mat)->type_name);
3739: (*mat->ops->solvetranspose)(mat,b,x);
3740: }
3741: PetscLogEventEnd(MAT_SolveTranspose,mat,b,x,0);
3742: PetscObjectStateIncrease((PetscObject)x);
3743: return(0);
3744: }
3746: /*@
3747: MatSolveTransposeAdd - Computes x = y + inv(Transpose(A)) b, given a
3748: factored matrix.
3750: Neighbor-wise Collective on Mat
3752: Input Parameters:
3753: + mat - the factored matrix
3754: . b - the right-hand-side vector
3755: - y - the vector to be added to
3757: Output Parameter:
3758: . x - the result vector
3760: Notes:
3761: The vectors b and x cannot be the same. I.e., one cannot
3762: call MatSolveTransposeAdd(A,x,y,x).
3764: Most users should employ the simplified KSP interface for linear solvers
3765: instead of working directly with matrix algebra routines such as this.
3766: See, e.g., KSPCreate().
3768: Level: developer
3770: .seealso: MatSolve(), MatSolveAdd(), MatSolveTranspose()
3771: @*/
3772: PetscErrorCode MatSolveTransposeAdd(Mat mat,Vec b,Vec y,Vec x)
3773: {
3774: PetscScalar one = 1.0;
3776: Vec tmp;
3787: if (x == b) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"x and b must be different vectors");
3788: 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);
3789: 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);
3790: 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);
3791: 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);
3792: if (!mat->rmap->N && !mat->cmap->N) return(0);
3793: if (!mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
3794: MatCheckPreallocated(mat,1);
3796: PetscLogEventBegin(MAT_SolveTransposeAdd,mat,b,x,y);
3797: if (mat->ops->solvetransposeadd) {
3798: if (mat->factorerrortype) {
3799: PetscInfo1(mat,"MatFactorError %D\n",mat->factorerrortype);
3800: VecSetInf(x);
3801: } else {
3802: (*mat->ops->solvetransposeadd)(mat,b,y,x);
3803: }
3804: } else {
3805: /* do the solve then the add manually */
3806: if (x != y) {
3807: MatSolveTranspose(mat,b,x);
3808: VecAXPY(x,one,y);
3809: } else {
3810: VecDuplicate(x,&tmp);
3811: PetscLogObjectParent((PetscObject)mat,(PetscObject)tmp);
3812: VecCopy(x,tmp);
3813: MatSolveTranspose(mat,b,x);
3814: VecAXPY(x,one,tmp);
3815: VecDestroy(&tmp);
3816: }
3817: }
3818: PetscLogEventEnd(MAT_SolveTransposeAdd,mat,b,x,y);
3819: PetscObjectStateIncrease((PetscObject)x);
3820: return(0);
3821: }
3822: /* ----------------------------------------------------------------*/
3824: /*@
3825: MatSOR - Computes relaxation (SOR, Gauss-Seidel) sweeps.
3827: Neighbor-wise Collective on Mat
3829: Input Parameters:
3830: + mat - the matrix
3831: . b - the right hand side
3832: . omega - the relaxation factor
3833: . flag - flag indicating the type of SOR (see below)
3834: . shift - diagonal shift
3835: . its - the number of iterations
3836: - lits - the number of local iterations
3838: Output Parameters:
3839: . x - the solution (can contain an initial guess, use option SOR_ZERO_INITIAL_GUESS to indicate no guess)
3841: SOR Flags:
3842: + SOR_FORWARD_SWEEP - forward SOR
3843: . SOR_BACKWARD_SWEEP - backward SOR
3844: . SOR_SYMMETRIC_SWEEP - SSOR (symmetric SOR)
3845: . SOR_LOCAL_FORWARD_SWEEP - local forward SOR
3846: . SOR_LOCAL_BACKWARD_SWEEP - local forward SOR
3847: . SOR_LOCAL_SYMMETRIC_SWEEP - local SSOR
3848: . SOR_APPLY_UPPER, SOR_APPLY_LOWER - applies
3849: upper/lower triangular part of matrix to
3850: vector (with omega)
3851: - SOR_ZERO_INITIAL_GUESS - zero initial guess
3853: Notes:
3854: SOR_LOCAL_FORWARD_SWEEP, SOR_LOCAL_BACKWARD_SWEEP, and
3855: SOR_LOCAL_SYMMETRIC_SWEEP perform separate independent smoothings
3856: on each processor.
3858: Application programmers will not generally use MatSOR() directly,
3859: but instead will employ the KSP/PC interface.
3861: Notes:
3862: for BAIJ, SBAIJ, and AIJ matrices with Inodes this does a block SOR smoothing, otherwise it does a pointwise smoothing
3864: Notes for Advanced Users:
3865: The flags are implemented as bitwise inclusive or operations.
3866: For example, use (SOR_ZERO_INITIAL_GUESS | SOR_SYMMETRIC_SWEEP)
3867: to specify a zero initial guess for SSOR.
3869: Most users should employ the simplified KSP interface for linear solvers
3870: instead of working directly with matrix algebra routines such as this.
3871: See, e.g., KSPCreate().
3873: Vectors x and b CANNOT be the same
3875: Developer Note: We should add block SOR support for AIJ matrices with block size set to great than one and no inodes
3877: Level: developer
3879: @*/
3880: PetscErrorCode MatSOR(Mat mat,Vec b,PetscReal omega,MatSORType flag,PetscReal shift,PetscInt its,PetscInt lits,Vec x)
3881: {
3891: if (!mat->ops->sor) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
3892: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
3893: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
3894: 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);
3895: 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);
3896: 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);
3897: if (its <= 0) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONG,"Relaxation requires global its %D positive",its);
3898: if (lits <= 0) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONG,"Relaxation requires local its %D positive",lits);
3899: if (b == x) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_IDN,"b and x vector cannot be the same");
3901: MatCheckPreallocated(mat,1);
3902: PetscLogEventBegin(MAT_SOR,mat,b,x,0);
3903: ierr =(*mat->ops->sor)(mat,b,omega,flag,shift,its,lits,x);
3904: PetscLogEventEnd(MAT_SOR,mat,b,x,0);
3905: PetscObjectStateIncrease((PetscObject)x);
3906: return(0);
3907: }
3909: /*
3910: Default matrix copy routine.
3911: */
3912: PetscErrorCode MatCopy_Basic(Mat A,Mat B,MatStructure str)
3913: {
3914: PetscErrorCode ierr;
3915: PetscInt i,rstart = 0,rend = 0,nz;
3916: const PetscInt *cwork;
3917: const PetscScalar *vwork;
3920: if (B->assembled) {
3921: MatZeroEntries(B);
3922: }
3923: if (str == SAME_NONZERO_PATTERN) {
3924: MatGetOwnershipRange(A,&rstart,&rend);
3925: for (i=rstart; i<rend; i++) {
3926: MatGetRow(A,i,&nz,&cwork,&vwork);
3927: MatSetValues(B,1,&i,nz,cwork,vwork,INSERT_VALUES);
3928: MatRestoreRow(A,i,&nz,&cwork,&vwork);
3929: }
3930: } else {
3931: MatAYPX(B,0.0,A,str);
3932: }
3933: MatAssemblyBegin(B,MAT_FINAL_ASSEMBLY);
3934: MatAssemblyEnd(B,MAT_FINAL_ASSEMBLY);
3935: return(0);
3936: }
3938: /*@
3939: MatCopy - Copies a matrix to another matrix.
3941: Collective on Mat
3943: Input Parameters:
3944: + A - the matrix
3945: - str - SAME_NONZERO_PATTERN or DIFFERENT_NONZERO_PATTERN
3947: Output Parameter:
3948: . B - where the copy is put
3950: Notes:
3951: If you use SAME_NONZERO_PATTERN then the two matrices had better have the
3952: same nonzero pattern or the routine will crash.
3954: MatCopy() copies the matrix entries of a matrix to another existing
3955: matrix (after first zeroing the second matrix). A related routine is
3956: MatConvert(), which first creates a new matrix and then copies the data.
3958: Level: intermediate
3960: .seealso: MatConvert(), MatDuplicate()
3962: @*/
3963: PetscErrorCode MatCopy(Mat A,Mat B,MatStructure str)
3964: {
3966: PetscInt i;
3974: MatCheckPreallocated(B,2);
3975: if (!A->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
3976: if (A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
3977: 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);
3978: MatCheckPreallocated(A,1);
3979: if (A == B) return(0);
3981: PetscLogEventBegin(MAT_Copy,A,B,0,0);
3982: if (A->ops->copy) {
3983: (*A->ops->copy)(A,B,str);
3984: } else { /* generic conversion */
3985: MatCopy_Basic(A,B,str);
3986: }
3988: B->stencil.dim = A->stencil.dim;
3989: B->stencil.noc = A->stencil.noc;
3990: for (i=0; i<=A->stencil.dim; i++) {
3991: B->stencil.dims[i] = A->stencil.dims[i];
3992: B->stencil.starts[i] = A->stencil.starts[i];
3993: }
3995: PetscLogEventEnd(MAT_Copy,A,B,0,0);
3996: PetscObjectStateIncrease((PetscObject)B);
3997: return(0);
3998: }
4000: /*@C
4001: MatConvert - Converts a matrix to another matrix, either of the same
4002: or different type.
4004: Collective on Mat
4006: Input Parameters:
4007: + mat - the matrix
4008: . newtype - new matrix type. Use MATSAME to create a new matrix of the
4009: same type as the original matrix.
4010: - reuse - denotes if the destination matrix is to be created or reused.
4011: 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
4012: 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).
4014: Output Parameter:
4015: . M - pointer to place new matrix
4017: Notes:
4018: MatConvert() first creates a new matrix and then copies the data from
4019: the first matrix. A related routine is MatCopy(), which copies the matrix
4020: entries of one matrix to another already existing matrix context.
4022: Cannot be used to convert a sequential matrix to parallel or parallel to sequential,
4023: the MPI communicator of the generated matrix is always the same as the communicator
4024: of the input matrix.
4026: Level: intermediate
4028: .seealso: MatCopy(), MatDuplicate()
4029: @*/
4030: PetscErrorCode MatConvert(Mat mat, MatType newtype,MatReuse reuse,Mat *M)
4031: {
4033: PetscBool sametype,issame,flg;
4034: char convname[256],mtype[256];
4035: Mat B;
4041: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
4042: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
4043: MatCheckPreallocated(mat,1);
4045: PetscOptionsGetString(((PetscObject)mat)->options,((PetscObject)mat)->prefix,"-matconvert_type",mtype,256,&flg);
4046: if (flg) newtype = mtype;
4048: PetscObjectTypeCompare((PetscObject)mat,newtype,&sametype);
4049: PetscStrcmp(newtype,"same",&issame);
4050: if ((reuse == MAT_INPLACE_MATRIX) && (mat != *M)) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"MAT_INPLACE_MATRIX requires same input and output matrix");
4051: 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");
4053: if ((reuse == MAT_INPLACE_MATRIX) && (issame || sametype)) {
4054: PetscInfo3(mat,"Early return for inplace %s %d %d\n",((PetscObject)mat)->type_name,sametype,issame);
4055: return(0);
4056: }
4058: if ((sametype || issame) && (reuse==MAT_INITIAL_MATRIX) && mat->ops->duplicate) {
4059: PetscInfo3(mat,"Calling duplicate for initial matrix %s %d %d\n",((PetscObject)mat)->type_name,sametype,issame);
4060: (*mat->ops->duplicate)(mat,MAT_COPY_VALUES,M);
4061: } else {
4062: PetscErrorCode (*conv)(Mat, MatType,MatReuse,Mat*)=NULL;
4063: const char *prefix[3] = {"seq","mpi",""};
4064: PetscInt i;
4065: /*
4066: Order of precedence:
4067: 0) See if newtype is a superclass of the current matrix.
4068: 1) See if a specialized converter is known to the current matrix.
4069: 2) See if a specialized converter is known to the desired matrix class.
4070: 3) See if a good general converter is registered for the desired class
4071: (as of 6/27/03 only MATMPIADJ falls into this category).
4072: 4) See if a good general converter is known for the current matrix.
4073: 5) Use a really basic converter.
4074: */
4076: /* 0) See if newtype is a superclass of the current matrix.
4077: i.e mat is mpiaij and newtype is aij */
4078: for (i=0; i<2; i++) {
4079: PetscStrncpy(convname,prefix[i],sizeof(convname));
4080: PetscStrlcat(convname,newtype,sizeof(convname));
4081: PetscStrcmp(convname,((PetscObject)mat)->type_name,&flg);
4082: PetscInfo3(mat,"Check superclass %s %s -> %d\n",convname,((PetscObject)mat)->type_name,flg);
4083: if (flg) {
4084: if (reuse == MAT_INPLACE_MATRIX) {
4085: return(0);
4086: } else if (reuse == MAT_INITIAL_MATRIX && mat->ops->duplicate) {
4087: (*mat->ops->duplicate)(mat,MAT_COPY_VALUES,M);
4088: return(0);
4089: } else if (reuse == MAT_REUSE_MATRIX && mat->ops->copy) {
4090: MatCopy(mat,*M,SAME_NONZERO_PATTERN);
4091: return(0);
4092: }
4093: }
4094: }
4095: /* 1) See if a specialized converter is known to the current matrix and the desired class */
4096: for (i=0; i<3; i++) {
4097: PetscStrncpy(convname,"MatConvert_",sizeof(convname));
4098: PetscStrlcat(convname,((PetscObject)mat)->type_name,sizeof(convname));
4099: PetscStrlcat(convname,"_",sizeof(convname));
4100: PetscStrlcat(convname,prefix[i],sizeof(convname));
4101: PetscStrlcat(convname,issame ? ((PetscObject)mat)->type_name : newtype,sizeof(convname));
4102: PetscStrlcat(convname,"_C",sizeof(convname));
4103: PetscObjectQueryFunction((PetscObject)mat,convname,&conv);
4104: PetscInfo3(mat,"Check specialized (1) %s (%s) -> %d\n",convname,((PetscObject)mat)->type_name,!!conv);
4105: if (conv) goto foundconv;
4106: }
4108: /* 2) See if a specialized converter is known to the desired matrix class. */
4109: MatCreate(PetscObjectComm((PetscObject)mat),&B);
4110: MatSetSizes(B,mat->rmap->n,mat->cmap->n,mat->rmap->N,mat->cmap->N);
4111: MatSetType(B,newtype);
4112: for (i=0; i<3; i++) {
4113: PetscStrncpy(convname,"MatConvert_",sizeof(convname));
4114: PetscStrlcat(convname,((PetscObject)mat)->type_name,sizeof(convname));
4115: PetscStrlcat(convname,"_",sizeof(convname));
4116: PetscStrlcat(convname,prefix[i],sizeof(convname));
4117: PetscStrlcat(convname,newtype,sizeof(convname));
4118: PetscStrlcat(convname,"_C",sizeof(convname));
4119: PetscObjectQueryFunction((PetscObject)B,convname,&conv);
4120: PetscInfo3(mat,"Check specialized (2) %s (%s) -> %d\n",convname,((PetscObject)B)->type_name,!!conv);
4121: if (conv) {
4122: MatDestroy(&B);
4123: goto foundconv;
4124: }
4125: }
4127: /* 3) See if a good general converter is registered for the desired class */
4128: conv = B->ops->convertfrom;
4129: PetscInfo2(mat,"Check convertfrom (%s) -> %d\n",((PetscObject)B)->type_name,!!conv);
4130: MatDestroy(&B);
4131: if (conv) goto foundconv;
4133: /* 4) See if a good general converter is known for the current matrix */
4134: if (mat->ops->convert) {
4135: conv = mat->ops->convert;
4136: }
4137: PetscInfo2(mat,"Check general convert (%s) -> %d\n",((PetscObject)mat)->type_name,!!conv);
4138: if (conv) goto foundconv;
4140: /* 5) Use a really basic converter. */
4141: PetscInfo(mat,"Using MatConvert_Basic\n");
4142: conv = MatConvert_Basic;
4144: foundconv:
4145: PetscLogEventBegin(MAT_Convert,mat,0,0,0);
4146: (*conv)(mat,newtype,reuse,M);
4147: if (mat->rmap->mapping && mat->cmap->mapping && !(*M)->rmap->mapping && !(*M)->cmap->mapping) {
4148: /* the block sizes must be same if the mappings are copied over */
4149: (*M)->rmap->bs = mat->rmap->bs;
4150: (*M)->cmap->bs = mat->cmap->bs;
4151: PetscObjectReference((PetscObject)mat->rmap->mapping);
4152: PetscObjectReference((PetscObject)mat->cmap->mapping);
4153: (*M)->rmap->mapping = mat->rmap->mapping;
4154: (*M)->cmap->mapping = mat->cmap->mapping;
4155: }
4156: (*M)->stencil.dim = mat->stencil.dim;
4157: (*M)->stencil.noc = mat->stencil.noc;
4158: for (i=0; i<=mat->stencil.dim; i++) {
4159: (*M)->stencil.dims[i] = mat->stencil.dims[i];
4160: (*M)->stencil.starts[i] = mat->stencil.starts[i];
4161: }
4162: PetscLogEventEnd(MAT_Convert,mat,0,0,0);
4163: }
4164: PetscObjectStateIncrease((PetscObject)*M);
4166: /* Copy Mat options */
4167: if (mat->symmetric) {MatSetOption(*M,MAT_SYMMETRIC,PETSC_TRUE);}
4168: if (mat->hermitian) {MatSetOption(*M,MAT_HERMITIAN,PETSC_TRUE);}
4169: return(0);
4170: }
4172: /*@C
4173: MatFactorGetSolverType - Returns name of the package providing the factorization routines
4175: Not Collective
4177: Input Parameter:
4178: . mat - the matrix, must be a factored matrix
4180: Output Parameter:
4181: . type - the string name of the package (do not free this string)
4183: Notes:
4184: In Fortran you pass in a empty string and the package name will be copied into it.
4185: (Make sure the string is long enough)
4187: Level: intermediate
4189: .seealso: MatCopy(), MatDuplicate(), MatGetFactorAvailable(), MatGetFactor()
4190: @*/
4191: PetscErrorCode MatFactorGetSolverType(Mat mat, MatSolverType *type)
4192: {
4193: PetscErrorCode ierr, (*conv)(Mat,MatSolverType*);
4198: if (!mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Only for factored matrix");
4199: PetscObjectQueryFunction((PetscObject)mat,"MatFactorGetSolverType_C",&conv);
4200: if (!conv) {
4201: *type = MATSOLVERPETSC;
4202: } else {
4203: (*conv)(mat,type);
4204: }
4205: return(0);
4206: }
4208: typedef struct _MatSolverTypeForSpecifcType* MatSolverTypeForSpecifcType;
4209: struct _MatSolverTypeForSpecifcType {
4210: MatType mtype;
4211: PetscErrorCode (*getfactor[4])(Mat,MatFactorType,Mat*);
4212: MatSolverTypeForSpecifcType next;
4213: };
4215: typedef struct _MatSolverTypeHolder* MatSolverTypeHolder;
4216: struct _MatSolverTypeHolder {
4217: char *name;
4218: MatSolverTypeForSpecifcType handlers;
4219: MatSolverTypeHolder next;
4220: };
4222: static MatSolverTypeHolder MatSolverTypeHolders = NULL;
4224: /*@C
4225: MatSolvePackageRegister - Registers a MatSolverType that works for a particular matrix type
4227: Input Parameters:
4228: + package - name of the package, for example petsc or superlu
4229: . mtype - the matrix type that works with this package
4230: . ftype - the type of factorization supported by the package
4231: - getfactor - routine that will create the factored matrix ready to be used
4233: Level: intermediate
4235: .seealso: MatCopy(), MatDuplicate(), MatGetFactorAvailable()
4236: @*/
4237: PetscErrorCode MatSolverTypeRegister(MatSolverType package,MatType mtype,MatFactorType ftype,PetscErrorCode (*getfactor)(Mat,MatFactorType,Mat*))
4238: {
4239: PetscErrorCode ierr;
4240: MatSolverTypeHolder next = MatSolverTypeHolders,prev = NULL;
4241: PetscBool flg;
4242: MatSolverTypeForSpecifcType inext,iprev = NULL;
4245: MatInitializePackage();
4246: if (!next) {
4247: PetscNew(&MatSolverTypeHolders);
4248: PetscStrallocpy(package,&MatSolverTypeHolders->name);
4249: PetscNew(&MatSolverTypeHolders->handlers);
4250: PetscStrallocpy(mtype,(char **)&MatSolverTypeHolders->handlers->mtype);
4251: MatSolverTypeHolders->handlers->getfactor[(int)ftype-1] = getfactor;
4252: return(0);
4253: }
4254: while (next) {
4255: PetscStrcasecmp(package,next->name,&flg);
4256: if (flg) {
4257: if (!next->handlers) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_PLIB,"MatSolverTypeHolder is missing handlers");
4258: inext = next->handlers;
4259: while (inext) {
4260: PetscStrcasecmp(mtype,inext->mtype,&flg);
4261: if (flg) {
4262: inext->getfactor[(int)ftype-1] = getfactor;
4263: return(0);
4264: }
4265: iprev = inext;
4266: inext = inext->next;
4267: }
4268: PetscNew(&iprev->next);
4269: PetscStrallocpy(mtype,(char **)&iprev->next->mtype);
4270: iprev->next->getfactor[(int)ftype-1] = getfactor;
4271: return(0);
4272: }
4273: prev = next;
4274: next = next->next;
4275: }
4276: PetscNew(&prev->next);
4277: PetscStrallocpy(package,&prev->next->name);
4278: PetscNew(&prev->next->handlers);
4279: PetscStrallocpy(mtype,(char **)&prev->next->handlers->mtype);
4280: prev->next->handlers->getfactor[(int)ftype-1] = getfactor;
4281: return(0);
4282: }
4284: /*@C
4285: MatSolvePackageGet - Get's the function that creates the factor matrix if it exist
4287: Input Parameters:
4288: + package - name of the package, for example petsc or superlu
4289: . ftype - the type of factorization supported by the package
4290: - mtype - the matrix type that works with this package
4292: Output Parameters:
4293: + foundpackage - PETSC_TRUE if the package was registered
4294: . foundmtype - PETSC_TRUE if the package supports the requested mtype
4295: - getfactor - routine that will create the factored matrix ready to be used or NULL if not found
4297: Level: intermediate
4299: .seealso: MatCopy(), MatDuplicate(), MatGetFactorAvailable()
4300: @*/
4301: PetscErrorCode MatSolverTypeGet(MatSolverType package,MatType mtype,MatFactorType ftype,PetscBool *foundpackage,PetscBool *foundmtype,PetscErrorCode (**getfactor)(Mat,MatFactorType,Mat*))
4302: {
4303: PetscErrorCode ierr;
4304: MatSolverTypeHolder next = MatSolverTypeHolders;
4305: PetscBool flg;
4306: MatSolverTypeForSpecifcType inext;
4309: if (foundpackage) *foundpackage = PETSC_FALSE;
4310: if (foundmtype) *foundmtype = PETSC_FALSE;
4311: if (getfactor) *getfactor = NULL;
4313: if (package) {
4314: while (next) {
4315: PetscStrcasecmp(package,next->name,&flg);
4316: if (flg) {
4317: if (foundpackage) *foundpackage = PETSC_TRUE;
4318: inext = next->handlers;
4319: while (inext) {
4320: PetscStrbeginswith(mtype,inext->mtype,&flg);
4321: if (flg) {
4322: if (foundmtype) *foundmtype = PETSC_TRUE;
4323: if (getfactor) *getfactor = inext->getfactor[(int)ftype-1];
4324: return(0);
4325: }
4326: inext = inext->next;
4327: }
4328: }
4329: next = next->next;
4330: }
4331: } else {
4332: while (next) {
4333: inext = next->handlers;
4334: while (inext) {
4335: PetscStrbeginswith(mtype,inext->mtype,&flg);
4336: if (flg && inext->getfactor[(int)ftype-1]) {
4337: if (foundpackage) *foundpackage = PETSC_TRUE;
4338: if (foundmtype) *foundmtype = PETSC_TRUE;
4339: if (getfactor) *getfactor = inext->getfactor[(int)ftype-1];
4340: return(0);
4341: }
4342: inext = inext->next;
4343: }
4344: next = next->next;
4345: }
4346: }
4347: return(0);
4348: }
4350: PetscErrorCode MatSolverTypeDestroy(void)
4351: {
4352: PetscErrorCode ierr;
4353: MatSolverTypeHolder next = MatSolverTypeHolders,prev;
4354: MatSolverTypeForSpecifcType inext,iprev;
4357: while (next) {
4358: PetscFree(next->name);
4359: inext = next->handlers;
4360: while (inext) {
4361: PetscFree(inext->mtype);
4362: iprev = inext;
4363: inext = inext->next;
4364: PetscFree(iprev);
4365: }
4366: prev = next;
4367: next = next->next;
4368: PetscFree(prev);
4369: }
4370: MatSolverTypeHolders = NULL;
4371: return(0);
4372: }
4374: /*@C
4375: MatGetFactor - Returns a matrix suitable to calls to MatXXFactorSymbolic()
4377: Collective on Mat
4379: Input Parameters:
4380: + mat - the matrix
4381: . type - name of solver type, for example, superlu, petsc (to use PETSc's default)
4382: - ftype - factor type, MAT_FACTOR_LU, MAT_FACTOR_CHOLESKY, MAT_FACTOR_ICC, MAT_FACTOR_ILU,
4384: Output Parameters:
4385: . f - the factor matrix used with MatXXFactorSymbolic() calls
4387: Notes:
4388: Some PETSc matrix formats have alternative solvers available that are contained in alternative packages
4389: such as pastix, superlu, mumps etc.
4391: PETSc must have been ./configure to use the external solver, using the option --download-package
4393: Level: intermediate
4395: .seealso: MatCopy(), MatDuplicate(), MatGetFactorAvailable()
4396: @*/
4397: PetscErrorCode MatGetFactor(Mat mat, MatSolverType type,MatFactorType ftype,Mat *f)
4398: {
4399: PetscErrorCode ierr,(*conv)(Mat,MatFactorType,Mat*);
4400: PetscBool foundpackage,foundmtype;
4406: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
4407: MatCheckPreallocated(mat,1);
4409: MatSolverTypeGet(type,((PetscObject)mat)->type_name,ftype,&foundpackage,&foundmtype,&conv);
4410: if (!foundpackage) {
4411: if (type) {
4412: SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_MISSING_FACTOR,"Could not locate solver package %s. Perhaps you must ./configure with --download-%s",type,type);
4413: } else {
4414: SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_MISSING_FACTOR,"Could not locate a solver package. Perhaps you must ./configure with --download-<package>");
4415: }
4416: }
4418: if (!foundmtype) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_MISSING_FACTOR,"MatSolverType %s does not support matrix type %s",type,((PetscObject)mat)->type_name);
4419: 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);
4421: #if defined(PETSC_USE_COMPLEX)
4422: 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");
4423: #endif
4425: (*conv)(mat,ftype,f);
4426: return(0);
4427: }
4429: /*@C
4430: MatGetFactorAvailable - Returns a a flag if matrix supports particular package and factor type
4432: Not Collective
4434: Input Parameters:
4435: + mat - the matrix
4436: . type - name of solver type, for example, superlu, petsc (to use PETSc's default)
4437: - ftype - factor type, MAT_FACTOR_LU, MAT_FACTOR_CHOLESKY, MAT_FACTOR_ICC, MAT_FACTOR_ILU,
4439: Output Parameter:
4440: . flg - PETSC_TRUE if the factorization is available
4442: Notes:
4443: Some PETSc matrix formats have alternative solvers available that are contained in alternative packages
4444: such as pastix, superlu, mumps etc.
4446: PETSc must have been ./configure to use the external solver, using the option --download-package
4448: Level: intermediate
4450: .seealso: MatCopy(), MatDuplicate(), MatGetFactor()
4451: @*/
4452: PetscErrorCode MatGetFactorAvailable(Mat mat, MatSolverType type,MatFactorType ftype,PetscBool *flg)
4453: {
4454: PetscErrorCode ierr, (*gconv)(Mat,MatFactorType,Mat*);
4460: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
4461: MatCheckPreallocated(mat,1);
4463: *flg = PETSC_FALSE;
4464: MatSolverTypeGet(type,((PetscObject)mat)->type_name,ftype,NULL,NULL,&gconv);
4465: if (gconv) {
4466: *flg = PETSC_TRUE;
4467: }
4468: return(0);
4469: }
4471: #include <petscdmtypes.h>
4473: /*@
4474: MatDuplicate - Duplicates a matrix including the non-zero structure.
4476: Collective on Mat
4478: Input Parameters:
4479: + mat - the matrix
4480: - op - One of MAT_DO_NOT_COPY_VALUES, MAT_COPY_VALUES, or MAT_SHARE_NONZERO_PATTERN.
4481: See the manual page for MatDuplicateOption for an explanation of these options.
4483: Output Parameter:
4484: . M - pointer to place new matrix
4486: Level: intermediate
4488: Notes:
4489: You cannot change the nonzero pattern for the parent or child matrix if you use MAT_SHARE_NONZERO_PATTERN.
4490: 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.
4492: .seealso: MatCopy(), MatConvert(), MatDuplicateOption
4493: @*/
4494: PetscErrorCode MatDuplicate(Mat mat,MatDuplicateOption op,Mat *M)
4495: {
4497: Mat B;
4498: PetscInt i;
4499: DM dm;
4500: void (*viewf)(void);
4506: if (op == MAT_COPY_VALUES && !mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"MAT_COPY_VALUES not allowed for unassembled matrix");
4507: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
4508: MatCheckPreallocated(mat,1);
4510: *M = 0;
4511: if (!mat->ops->duplicate) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Not written for this matrix type");
4512: PetscLogEventBegin(MAT_Convert,mat,0,0,0);
4513: (*mat->ops->duplicate)(mat,op,M);
4514: B = *M;
4516: MatGetOperation(mat,MATOP_VIEW,&viewf);
4517: if (viewf) {
4518: MatSetOperation(B,MATOP_VIEW,viewf);
4519: }
4521: B->stencil.dim = mat->stencil.dim;
4522: B->stencil.noc = mat->stencil.noc;
4523: for (i=0; i<=mat->stencil.dim; i++) {
4524: B->stencil.dims[i] = mat->stencil.dims[i];
4525: B->stencil.starts[i] = mat->stencil.starts[i];
4526: }
4528: B->nooffproczerorows = mat->nooffproczerorows;
4529: B->nooffprocentries = mat->nooffprocentries;
4531: PetscObjectQuery((PetscObject) mat, "__PETSc_dm", (PetscObject*) &dm);
4532: if (dm) {
4533: PetscObjectCompose((PetscObject) B, "__PETSc_dm", (PetscObject) dm);
4534: }
4535: PetscLogEventEnd(MAT_Convert,mat,0,0,0);
4536: PetscObjectStateIncrease((PetscObject)B);
4537: return(0);
4538: }
4540: /*@
4541: MatGetDiagonal - Gets the diagonal of a matrix.
4543: Logically Collective on Mat
4545: Input Parameters:
4546: + mat - the matrix
4547: - v - the vector for storing the diagonal
4549: Output Parameter:
4550: . v - the diagonal of the matrix
4552: Level: intermediate
4554: Note:
4555: Currently only correct in parallel for square matrices.
4557: .seealso: MatGetRow(), MatCreateSubMatrices(), MatCreateSubMatrix(), MatGetRowMaxAbs()
4558: @*/
4559: PetscErrorCode MatGetDiagonal(Mat mat,Vec v)
4560: {
4567: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
4568: if (!mat->ops->getdiagonal) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
4569: MatCheckPreallocated(mat,1);
4571: (*mat->ops->getdiagonal)(mat,v);
4572: PetscObjectStateIncrease((PetscObject)v);
4573: return(0);
4574: }
4576: /*@C
4577: MatGetRowMin - Gets the minimum value (of the real part) of each
4578: row of the matrix
4580: Logically Collective on Mat
4582: Input Parameters:
4583: . mat - the matrix
4585: Output Parameter:
4586: + v - the vector for storing the maximums
4587: - idx - the indices of the column found for each row (optional)
4589: Level: intermediate
4591: Notes:
4592: The result of this call are the same as if one converted the matrix to dense format
4593: and found the minimum value in each row (i.e. the implicit zeros are counted as zeros).
4595: This code is only implemented for a couple of matrix formats.
4597: .seealso: MatGetDiagonal(), MatCreateSubMatrices(), MatCreateSubMatrix(), MatGetRowMaxAbs(),
4598: MatGetRowMax()
4599: @*/
4600: PetscErrorCode MatGetRowMin(Mat mat,Vec v,PetscInt idx[])
4601: {
4608: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
4609: if (!mat->ops->getrowmax) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
4610: MatCheckPreallocated(mat,1);
4612: (*mat->ops->getrowmin)(mat,v,idx);
4613: PetscObjectStateIncrease((PetscObject)v);
4614: return(0);
4615: }
4617: /*@C
4618: MatGetRowMinAbs - Gets the minimum value (in absolute value) of each
4619: row of the matrix
4621: Logically Collective on Mat
4623: Input Parameters:
4624: . mat - the matrix
4626: Output Parameter:
4627: + v - the vector for storing the minimums
4628: - idx - the indices of the column found for each row (or NULL if not needed)
4630: Level: intermediate
4632: Notes:
4633: if a row is completely empty or has only 0.0 values then the idx[] value for that
4634: row is 0 (the first column).
4636: This code is only implemented for a couple of matrix formats.
4638: .seealso: MatGetDiagonal(), MatCreateSubMatrices(), MatCreateSubMatrix(), MatGetRowMax(), MatGetRowMaxAbs(), MatGetRowMin()
4639: @*/
4640: PetscErrorCode MatGetRowMinAbs(Mat mat,Vec v,PetscInt idx[])
4641: {
4648: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
4649: if (!mat->ops->getrowminabs) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
4650: MatCheckPreallocated(mat,1);
4651: if (idx) {PetscArrayzero(idx,mat->rmap->n);}
4653: (*mat->ops->getrowminabs)(mat,v,idx);
4654: PetscObjectStateIncrease((PetscObject)v);
4655: return(0);
4656: }
4658: /*@C
4659: MatGetRowMax - Gets the maximum value (of the real part) of each
4660: row of the matrix
4662: Logically Collective on Mat
4664: Input Parameters:
4665: . mat - the matrix
4667: Output Parameter:
4668: + v - the vector for storing the maximums
4669: - idx - the indices of the column found for each row (optional)
4671: Level: intermediate
4673: Notes:
4674: The result of this call are the same as if one converted the matrix to dense format
4675: and found the minimum value in each row (i.e. the implicit zeros are counted as zeros).
4677: This code is only implemented for a couple of matrix formats.
4679: .seealso: MatGetDiagonal(), MatCreateSubMatrices(), MatCreateSubMatrix(), MatGetRowMaxAbs(), MatGetRowMin()
4680: @*/
4681: PetscErrorCode MatGetRowMax(Mat mat,Vec v,PetscInt idx[])
4682: {
4689: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
4690: if (!mat->ops->getrowmax) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
4691: MatCheckPreallocated(mat,1);
4693: (*mat->ops->getrowmax)(mat,v,idx);
4694: PetscObjectStateIncrease((PetscObject)v);
4695: return(0);
4696: }
4698: /*@C
4699: MatGetRowMaxAbs - Gets the maximum value (in absolute value) of each
4700: row of the matrix
4702: Logically Collective on Mat
4704: Input Parameters:
4705: . mat - the matrix
4707: Output Parameter:
4708: + v - the vector for storing the maximums
4709: - idx - the indices of the column found for each row (or NULL if not needed)
4711: Level: intermediate
4713: Notes:
4714: if a row is completely empty or has only 0.0 values then the idx[] value for that
4715: row is 0 (the first column).
4717: This code is only implemented for a couple of matrix formats.
4719: .seealso: MatGetDiagonal(), MatCreateSubMatrices(), MatCreateSubMatrix(), MatGetRowMax(), MatGetRowMin()
4720: @*/
4721: PetscErrorCode MatGetRowMaxAbs(Mat mat,Vec v,PetscInt idx[])
4722: {
4729: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
4730: if (!mat->ops->getrowmaxabs) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
4731: MatCheckPreallocated(mat,1);
4732: if (idx) {PetscArrayzero(idx,mat->rmap->n);}
4734: (*mat->ops->getrowmaxabs)(mat,v,idx);
4735: PetscObjectStateIncrease((PetscObject)v);
4736: return(0);
4737: }
4739: /*@
4740: MatGetRowSum - Gets the sum of each row of the matrix
4742: Logically or Neighborhood Collective on Mat
4744: Input Parameters:
4745: . mat - the matrix
4747: Output Parameter:
4748: . v - the vector for storing the sum of rows
4750: Level: intermediate
4752: Notes:
4753: This code is slow since it is not currently specialized for different formats
4755: .seealso: MatGetDiagonal(), MatCreateSubMatrices(), MatCreateSubMatrix(), MatGetRowMax(), MatGetRowMin()
4756: @*/
4757: PetscErrorCode MatGetRowSum(Mat mat, Vec v)
4758: {
4759: Vec ones;
4766: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
4767: MatCheckPreallocated(mat,1);
4768: MatCreateVecs(mat,&ones,NULL);
4769: VecSet(ones,1.);
4770: MatMult(mat,ones,v);
4771: VecDestroy(&ones);
4772: return(0);
4773: }
4775: /*@
4776: MatTranspose - Computes an in-place or out-of-place transpose of a matrix.
4778: Collective on Mat
4780: Input Parameter:
4781: + mat - the matrix to transpose
4782: - reuse - either MAT_INITIAL_MATRIX, MAT_REUSE_MATRIX, or MAT_INPLACE_MATRIX
4784: Output Parameters:
4785: . B - the transpose
4787: Notes:
4788: If you use MAT_INPLACE_MATRIX then you must pass in &mat for B
4790: MAT_REUSE_MATRIX causes the B matrix from a previous call to this function with MAT_INITIAL_MATRIX to be used
4792: Consider using MatCreateTranspose() instead if you only need a matrix that behaves like the transpose, but don't need the storage to be changed.
4794: Level: intermediate
4796: .seealso: MatMultTranspose(), MatMultTransposeAdd(), MatIsTranspose(), MatReuse
4797: @*/
4798: PetscErrorCode MatTranspose(Mat mat,MatReuse reuse,Mat *B)
4799: {
4805: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
4806: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
4807: if (!mat->ops->transpose) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
4808: if (reuse == MAT_INPLACE_MATRIX && mat != *B) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"MAT_INPLACE_MATRIX requires last matrix to match first");
4809: if (reuse == MAT_REUSE_MATRIX && mat == *B) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Perhaps you mean MAT_INPLACE_MATRIX");
4810: MatCheckPreallocated(mat,1);
4812: PetscLogEventBegin(MAT_Transpose,mat,0,0,0);
4813: (*mat->ops->transpose)(mat,reuse,B);
4814: PetscLogEventEnd(MAT_Transpose,mat,0,0,0);
4815: if (B) {PetscObjectStateIncrease((PetscObject)*B);}
4816: return(0);
4817: }
4819: /*@
4820: MatIsTranspose - Test whether a matrix is another one's transpose,
4821: or its own, in which case it tests symmetry.
4823: Collective on Mat
4825: Input Parameter:
4826: + A - the matrix to test
4827: - B - the matrix to test against, this can equal the first parameter
4829: Output Parameters:
4830: . flg - the result
4832: Notes:
4833: Only available for SeqAIJ/MPIAIJ matrices. The sequential algorithm
4834: has a running time of the order of the number of nonzeros; the parallel
4835: test involves parallel copies of the block-offdiagonal parts of the matrix.
4837: Level: intermediate
4839: .seealso: MatTranspose(), MatIsSymmetric(), MatIsHermitian()
4840: @*/
4841: PetscErrorCode MatIsTranspose(Mat A,Mat B,PetscReal tol,PetscBool *flg)
4842: {
4843: PetscErrorCode ierr,(*f)(Mat,Mat,PetscReal,PetscBool*),(*g)(Mat,Mat,PetscReal,PetscBool*);
4849: PetscObjectQueryFunction((PetscObject)A,"MatIsTranspose_C",&f);
4850: PetscObjectQueryFunction((PetscObject)B,"MatIsTranspose_C",&g);
4851: *flg = PETSC_FALSE;
4852: if (f && g) {
4853: if (f == g) {
4854: (*f)(A,B,tol,flg);
4855: } else SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_NOTSAMETYPE,"Matrices do not have the same comparator for symmetry test");
4856: } else {
4857: MatType mattype;
4858: if (!f) {
4859: MatGetType(A,&mattype);
4860: } else {
4861: MatGetType(B,&mattype);
4862: }
4863: SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Matrix of type <%s> does not support checking for transpose",mattype);
4864: }
4865: return(0);
4866: }
4868: /*@
4869: MatHermitianTranspose - Computes an in-place or out-of-place transpose of a matrix in complex conjugate.
4871: Collective on Mat
4873: Input Parameter:
4874: + mat - the matrix to transpose and complex conjugate
4875: - reuse - MAT_INITIAL_MATRIX to create a new matrix, MAT_INPLACE_MATRIX to reuse the first argument to store the transpose
4877: Output Parameters:
4878: . B - the Hermitian
4880: Level: intermediate
4882: .seealso: MatTranspose(), MatMultTranspose(), MatMultTransposeAdd(), MatIsTranspose(), MatReuse
4883: @*/
4884: PetscErrorCode MatHermitianTranspose(Mat mat,MatReuse reuse,Mat *B)
4885: {
4889: MatTranspose(mat,reuse,B);
4890: #if defined(PETSC_USE_COMPLEX)
4891: MatConjugate(*B);
4892: #endif
4893: return(0);
4894: }
4896: /*@
4897: MatIsHermitianTranspose - Test whether a matrix is another one's Hermitian transpose,
4899: Collective on Mat
4901: Input Parameter:
4902: + A - the matrix to test
4903: - B - the matrix to test against, this can equal the first parameter
4905: Output Parameters:
4906: . flg - the result
4908: Notes:
4909: Only available for SeqAIJ/MPIAIJ matrices. The sequential algorithm
4910: has a running time of the order of the number of nonzeros; the parallel
4911: test involves parallel copies of the block-offdiagonal parts of the matrix.
4913: Level: intermediate
4915: .seealso: MatTranspose(), MatIsSymmetric(), MatIsHermitian(), MatIsTranspose()
4916: @*/
4917: PetscErrorCode MatIsHermitianTranspose(Mat A,Mat B,PetscReal tol,PetscBool *flg)
4918: {
4919: PetscErrorCode ierr,(*f)(Mat,Mat,PetscReal,PetscBool*),(*g)(Mat,Mat,PetscReal,PetscBool*);
4925: PetscObjectQueryFunction((PetscObject)A,"MatIsHermitianTranspose_C",&f);
4926: PetscObjectQueryFunction((PetscObject)B,"MatIsHermitianTranspose_C",&g);
4927: if (f && g) {
4928: if (f==g) {
4929: (*f)(A,B,tol,flg);
4930: } else SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_NOTSAMETYPE,"Matrices do not have the same comparator for Hermitian test");
4931: }
4932: return(0);
4933: }
4935: /*@
4936: MatPermute - Creates a new matrix with rows and columns permuted from the
4937: original.
4939: Collective on Mat
4941: Input Parameters:
4942: + mat - the matrix to permute
4943: . row - row permutation, each processor supplies only the permutation for its rows
4944: - col - column permutation, each processor supplies only the permutation for its columns
4946: Output Parameters:
4947: . B - the permuted matrix
4949: Level: advanced
4951: Note:
4952: The index sets map from row/col of permuted matrix to row/col of original matrix.
4953: The index sets should be on the same communicator as Mat and have the same local sizes.
4955: .seealso: MatGetOrdering(), ISAllGather()
4957: @*/
4958: PetscErrorCode MatPermute(Mat mat,IS row,IS col,Mat *B)
4959: {
4968: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
4969: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
4970: if (!mat->ops->permute) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"MatPermute not available for Mat type %s",((PetscObject)mat)->type_name);
4971: MatCheckPreallocated(mat,1);
4973: (*mat->ops->permute)(mat,row,col,B);
4974: PetscObjectStateIncrease((PetscObject)*B);
4975: return(0);
4976: }
4978: /*@
4979: MatEqual - Compares two matrices.
4981: Collective on Mat
4983: Input Parameters:
4984: + A - the first matrix
4985: - B - the second matrix
4987: Output Parameter:
4988: . flg - PETSC_TRUE if the matrices are equal; PETSC_FALSE otherwise.
4990: Level: intermediate
4992: @*/
4993: PetscErrorCode MatEqual(Mat A,Mat B,PetscBool *flg)
4994: {
5004: MatCheckPreallocated(B,2);
5005: if (!A->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
5006: if (!B->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
5007: 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);
5008: if (!A->ops->equal) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Mat type %s",((PetscObject)A)->type_name);
5009: if (!B->ops->equal) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Mat type %s",((PetscObject)B)->type_name);
5010: 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);
5011: MatCheckPreallocated(A,1);
5013: (*A->ops->equal)(A,B,flg);
5014: return(0);
5015: }
5017: /*@
5018: MatDiagonalScale - Scales a matrix on the left and right by diagonal
5019: matrices that are stored as vectors. Either of the two scaling
5020: matrices can be NULL.
5022: Collective on Mat
5024: Input Parameters:
5025: + mat - the matrix to be scaled
5026: . l - the left scaling vector (or NULL)
5027: - r - the right scaling vector (or NULL)
5029: Notes:
5030: MatDiagonalScale() computes A = LAR, where
5031: L = a diagonal matrix (stored as a vector), R = a diagonal matrix (stored as a vector)
5032: The L scales the rows of the matrix, the R scales the columns of the matrix.
5034: Level: intermediate
5037: .seealso: MatScale(), MatShift(), MatDiagonalSet()
5038: @*/
5039: PetscErrorCode MatDiagonalScale(Mat mat,Vec l,Vec r)
5040: {
5046: if (!mat->ops->diagonalscale) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
5049: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
5050: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
5051: MatCheckPreallocated(mat,1);
5053: PetscLogEventBegin(MAT_Scale,mat,0,0,0);
5054: (*mat->ops->diagonalscale)(mat,l,r);
5055: PetscLogEventEnd(MAT_Scale,mat,0,0,0);
5056: PetscObjectStateIncrease((PetscObject)mat);
5057: return(0);
5058: }
5060: /*@
5061: MatScale - Scales all elements of a matrix by a given number.
5063: Logically Collective on Mat
5065: Input Parameters:
5066: + mat - the matrix to be scaled
5067: - a - the scaling value
5069: Output Parameter:
5070: . mat - the scaled matrix
5072: Level: intermediate
5074: .seealso: MatDiagonalScale()
5075: @*/
5076: PetscErrorCode MatScale(Mat mat,PetscScalar a)
5077: {
5083: if (a != (PetscScalar)1.0 && !mat->ops->scale) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
5084: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
5085: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
5087: MatCheckPreallocated(mat,1);
5089: PetscLogEventBegin(MAT_Scale,mat,0,0,0);
5090: if (a != (PetscScalar)1.0) {
5091: (*mat->ops->scale)(mat,a);
5092: PetscObjectStateIncrease((PetscObject)mat);
5093: }
5094: PetscLogEventEnd(MAT_Scale,mat,0,0,0);
5095: return(0);
5096: }
5098: /*@
5099: MatNorm - Calculates various norms of a matrix.
5101: Collective on Mat
5103: Input Parameters:
5104: + mat - the matrix
5105: - type - the type of norm, NORM_1, NORM_FROBENIUS, NORM_INFINITY
5107: Output Parameters:
5108: . nrm - the resulting norm
5110: Level: intermediate
5112: @*/
5113: PetscErrorCode MatNorm(Mat mat,NormType type,PetscReal *nrm)
5114: {
5122: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
5123: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
5124: if (!mat->ops->norm) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
5125: MatCheckPreallocated(mat,1);
5127: (*mat->ops->norm)(mat,type,nrm);
5128: return(0);
5129: }
5131: /*
5132: This variable is used to prevent counting of MatAssemblyBegin() that
5133: are called from within a MatAssemblyEnd().
5134: */
5135: static PetscInt MatAssemblyEnd_InUse = 0;
5136: /*@
5137: MatAssemblyBegin - Begins assembling the matrix. This routine should
5138: be called after completing all calls to MatSetValues().
5140: Collective on Mat
5142: Input Parameters:
5143: + mat - the matrix
5144: - type - type of assembly, either MAT_FLUSH_ASSEMBLY or MAT_FINAL_ASSEMBLY
5146: Notes:
5147: MatSetValues() generally caches the values. The matrix is ready to
5148: use only after MatAssemblyBegin() and MatAssemblyEnd() have been called.
5149: Use MAT_FLUSH_ASSEMBLY when switching between ADD_VALUES and INSERT_VALUES
5150: in MatSetValues(); use MAT_FINAL_ASSEMBLY for the final assembly before
5151: using the matrix.
5153: ALL processes that share a matrix MUST call MatAssemblyBegin() and MatAssemblyEnd() the SAME NUMBER of times, and each time with the
5154: 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
5155: a global collective operation requring all processes that share the matrix.
5157: Space for preallocated nonzeros that is not filled by a call to MatSetValues() or a related routine are compressed
5158: out by assembly. If you intend to use that extra space on a subsequent assembly, be sure to insert explicit zeros
5159: before MAT_FINAL_ASSEMBLY so the space is not compressed out.
5161: Level: beginner
5163: .seealso: MatAssemblyEnd(), MatSetValues(), MatAssembled()
5164: @*/
5165: PetscErrorCode MatAssemblyBegin(Mat mat,MatAssemblyType type)
5166: {
5172: MatCheckPreallocated(mat,1);
5173: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix.\nDid you forget to call MatSetUnfactored()?");
5174: if (mat->assembled) {
5175: mat->was_assembled = PETSC_TRUE;
5176: mat->assembled = PETSC_FALSE;
5177: }
5179: if (!MatAssemblyEnd_InUse) {
5180: PetscLogEventBegin(MAT_AssemblyBegin,mat,0,0,0);
5181: if (mat->ops->assemblybegin) {(*mat->ops->assemblybegin)(mat,type);}
5182: PetscLogEventEnd(MAT_AssemblyBegin,mat,0,0,0);
5183: } else if (mat->ops->assemblybegin) {
5184: (*mat->ops->assemblybegin)(mat,type);
5185: }
5186: return(0);
5187: }
5189: /*@
5190: MatAssembled - Indicates if a matrix has been assembled and is ready for
5191: use; for example, in matrix-vector product.
5193: Not Collective
5195: Input Parameter:
5196: . mat - the matrix
5198: Output Parameter:
5199: . assembled - PETSC_TRUE or PETSC_FALSE
5201: Level: advanced
5203: .seealso: MatAssemblyEnd(), MatSetValues(), MatAssemblyBegin()
5204: @*/
5205: PetscErrorCode MatAssembled(Mat mat,PetscBool *assembled)
5206: {
5210: *assembled = mat->assembled;
5211: return(0);
5212: }
5214: /*@
5215: MatAssemblyEnd - Completes assembling the matrix. This routine should
5216: be called after MatAssemblyBegin().
5218: Collective on Mat
5220: Input Parameters:
5221: + mat - the matrix
5222: - type - type of assembly, either MAT_FLUSH_ASSEMBLY or MAT_FINAL_ASSEMBLY
5224: Options Database Keys:
5225: + -mat_view ::ascii_info - Prints info on matrix at conclusion of MatEndAssembly()
5226: . -mat_view ::ascii_info_detail - Prints more detailed info
5227: . -mat_view - Prints matrix in ASCII format
5228: . -mat_view ::ascii_matlab - Prints matrix in Matlab format
5229: . -mat_view draw - PetscDraws nonzero structure of matrix, using MatView() and PetscDrawOpenX().
5230: . -display <name> - Sets display name (default is host)
5231: . -draw_pause <sec> - Sets number of seconds to pause after display
5232: . -mat_view socket - Sends matrix to socket, can be accessed from Matlab (See Users-Manual: Chapter 12 Using MATLAB with PETSc )
5233: . -viewer_socket_machine <machine> - Machine to use for socket
5234: . -viewer_socket_port <port> - Port number to use for socket
5235: - -mat_view binary:filename[:append] - Save matrix to file in binary format
5237: Notes:
5238: MatSetValues() generally caches the values. The matrix is ready to
5239: use only after MatAssemblyBegin() and MatAssemblyEnd() have been called.
5240: Use MAT_FLUSH_ASSEMBLY when switching between ADD_VALUES and INSERT_VALUES
5241: in MatSetValues(); use MAT_FINAL_ASSEMBLY for the final assembly before
5242: using the matrix.
5244: Space for preallocated nonzeros that is not filled by a call to MatSetValues() or a related routine are compressed
5245: out by assembly. If you intend to use that extra space on a subsequent assembly, be sure to insert explicit zeros
5246: before MAT_FINAL_ASSEMBLY so the space is not compressed out.
5248: Level: beginner
5250: .seealso: MatAssemblyBegin(), MatSetValues(), PetscDrawOpenX(), PetscDrawCreate(), MatView(), MatAssembled(), PetscViewerSocketOpen()
5251: @*/
5252: PetscErrorCode MatAssemblyEnd(Mat mat,MatAssemblyType type)
5253: {
5254: PetscErrorCode ierr;
5255: static PetscInt inassm = 0;
5256: PetscBool flg = PETSC_FALSE;
5262: inassm++;
5263: MatAssemblyEnd_InUse++;
5264: if (MatAssemblyEnd_InUse == 1) { /* Do the logging only the first time through */
5265: PetscLogEventBegin(MAT_AssemblyEnd,mat,0,0,0);
5266: if (mat->ops->assemblyend) {
5267: (*mat->ops->assemblyend)(mat,type);
5268: }
5269: PetscLogEventEnd(MAT_AssemblyEnd,mat,0,0,0);
5270: } else if (mat->ops->assemblyend) {
5271: (*mat->ops->assemblyend)(mat,type);
5272: }
5274: /* Flush assembly is not a true assembly */
5275: if (type != MAT_FLUSH_ASSEMBLY) {
5276: mat->num_ass++;
5277: mat->assembled = PETSC_TRUE;
5278: mat->ass_nonzerostate = mat->nonzerostate;
5279: }
5281: mat->insertmode = NOT_SET_VALUES;
5282: MatAssemblyEnd_InUse--;
5283: PetscObjectStateIncrease((PetscObject)mat);
5284: if (!mat->symmetric_eternal) {
5285: mat->symmetric_set = PETSC_FALSE;
5286: mat->hermitian_set = PETSC_FALSE;
5287: mat->structurally_symmetric_set = PETSC_FALSE;
5288: }
5289: if (inassm == 1 && type != MAT_FLUSH_ASSEMBLY) {
5290: MatViewFromOptions(mat,NULL,"-mat_view");
5292: if (mat->checksymmetryonassembly) {
5293: MatIsSymmetric(mat,mat->checksymmetrytol,&flg);
5294: if (flg) {
5295: PetscPrintf(PetscObjectComm((PetscObject)mat),"Matrix is symmetric (tolerance %g)\n",(double)mat->checksymmetrytol);
5296: } else {
5297: PetscPrintf(PetscObjectComm((PetscObject)mat),"Matrix is not symmetric (tolerance %g)\n",(double)mat->checksymmetrytol);
5298: }
5299: }
5300: if (mat->nullsp && mat->checknullspaceonassembly) {
5301: MatNullSpaceTest(mat->nullsp,mat,NULL);
5302: }
5303: }
5304: inassm--;
5305: return(0);
5306: }
5308: /*@
5309: MatSetOption - Sets a parameter option for a matrix. Some options
5310: may be specific to certain storage formats. Some options
5311: determine how values will be inserted (or added). Sorted,
5312: row-oriented input will generally assemble the fastest. The default
5313: is row-oriented.
5315: Logically Collective on Mat for certain operations, such as MAT_SPD, not collective for MAT_ROW_ORIENTED, see MatOption
5317: Input Parameters:
5318: + mat - the matrix
5319: . option - the option, one of those listed below (and possibly others),
5320: - flg - turn the option on (PETSC_TRUE) or off (PETSC_FALSE)
5322: Options Describing Matrix Structure:
5323: + MAT_SPD - symmetric positive definite
5324: . MAT_SYMMETRIC - symmetric in terms of both structure and value
5325: . MAT_HERMITIAN - transpose is the complex conjugation
5326: . MAT_STRUCTURALLY_SYMMETRIC - symmetric nonzero structure
5327: - MAT_SYMMETRY_ETERNAL - if you would like the symmetry/Hermitian flag
5328: you set to be kept with all future use of the matrix
5329: including after MatAssemblyBegin/End() which could
5330: potentially change the symmetry structure, i.e. you
5331: KNOW the matrix will ALWAYS have the property you set.
5334: Options For Use with MatSetValues():
5335: Insert a logically dense subblock, which can be
5336: . MAT_ROW_ORIENTED - row-oriented (default)
5338: Note these options reflect the data you pass in with MatSetValues(); it has
5339: nothing to do with how the data is stored internally in the matrix
5340: data structure.
5342: When (re)assembling a matrix, we can restrict the input for
5343: efficiency/debugging purposes. These options include:
5344: + MAT_NEW_NONZERO_LOCATIONS - additional insertions will be allowed if they generate a new nonzero (slow)
5345: . MAT_NEW_DIAGONALS - new diagonals will be allowed (for block diagonal format only)
5346: . MAT_IGNORE_OFF_PROC_ENTRIES - drops off-processor entries
5347: . MAT_NEW_NONZERO_LOCATION_ERR - generates an error for new matrix entry
5348: . MAT_USE_HASH_TABLE - uses a hash table to speed up matrix assembly
5349: . MAT_NO_OFF_PROC_ENTRIES - you know each process will only set values for its own rows, will generate an error if
5350: any process sets values for another process. This avoids all reductions in the MatAssembly routines and thus improves
5351: performance for very large process counts.
5352: - MAT_SUBSET_OFF_PROC_ENTRIES - you know that the first assembly after setting this flag will set a superset
5353: of the off-process entries required for all subsequent assemblies. This avoids a rendezvous step in the MatAssembly
5354: functions, instead sending only neighbor messages.
5356: Notes:
5357: Except for MAT_UNUSED_NONZERO_LOCATION_ERR and MAT_ROW_ORIENTED all processes that share the matrix must pass the same value in flg!
5359: Some options are relevant only for particular matrix types and
5360: are thus ignored by others. Other options are not supported by
5361: certain matrix types and will generate an error message if set.
5363: If using a Fortran 77 module to compute a matrix, one may need to
5364: use the column-oriented option (or convert to the row-oriented
5365: format).
5367: MAT_NEW_NONZERO_LOCATIONS set to PETSC_FALSE indicates that any add or insertion
5368: that would generate a new entry in the nonzero structure is instead
5369: ignored. Thus, if memory has not alredy been allocated for this particular
5370: data, then the insertion is ignored. For dense matrices, in which
5371: the entire array is allocated, no entries are ever ignored.
5372: Set after the first MatAssemblyEnd(). If this option is set then the MatAssemblyBegin/End() processes has one less global reduction
5374: MAT_NEW_NONZERO_LOCATION_ERR set to PETSC_TRUE indicates that any add or insertion
5375: that would generate a new entry in the nonzero structure instead produces
5376: 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
5378: MAT_NEW_NONZERO_ALLOCATION_ERR set to PETSC_TRUE indicates that any add or insertion
5379: that would generate a new entry that has not been preallocated will
5380: instead produce an error. (Currently supported for AIJ and BAIJ formats
5381: only.) This is a useful flag when debugging matrix memory preallocation.
5382: If this option is set then the MatAssemblyBegin/End() processes has one less global reduction
5384: MAT_IGNORE_OFF_PROC_ENTRIES set to PETSC_TRUE indicates entries destined for
5385: other processors should be dropped, rather than stashed.
5386: This is useful if you know that the "owning" processor is also
5387: always generating the correct matrix entries, so that PETSc need
5388: not transfer duplicate entries generated on another processor.
5390: MAT_USE_HASH_TABLE indicates that a hash table be used to improve the
5391: searches during matrix assembly. When this flag is set, the hash table
5392: is created during the first Matrix Assembly. This hash table is
5393: used the next time through, during MatSetVaules()/MatSetVaulesBlocked()
5394: to improve the searching of indices. MAT_NEW_NONZERO_LOCATIONS flag
5395: should be used with MAT_USE_HASH_TABLE flag. This option is currently
5396: supported by MATMPIBAIJ format only.
5398: MAT_KEEP_NONZERO_PATTERN indicates when MatZeroRows() is called the zeroed entries
5399: are kept in the nonzero structure
5401: MAT_IGNORE_ZERO_ENTRIES - for AIJ/IS matrices this will stop zero values from creating
5402: a zero location in the matrix
5404: MAT_USE_INODES - indicates using inode version of the code - works with AIJ matrix types
5406: MAT_NO_OFF_PROC_ZERO_ROWS - you know each process will only zero its own rows. This avoids all reductions in the
5407: zero row routines and thus improves performance for very large process counts.
5409: MAT_IGNORE_LOWER_TRIANGULAR - For SBAIJ matrices will ignore any insertions you make in the lower triangular
5410: part of the matrix (since they should match the upper triangular part).
5412: MAT_SORTED_FULL - each process provides exactly its local rows; all column indices for a given row are passed in a
5413: single call to MatSetValues(), preallocation is perfect, row oriented, INSERT_VALUES is used. Common
5414: with finite difference schemes with non-periodic boundary conditions.
5415: Notes:
5416: Can only be called after MatSetSizes() and MatSetType() have been set.
5418: Level: intermediate
5420: .seealso: MatOption, Mat
5422: @*/
5423: PetscErrorCode MatSetOption(Mat mat,MatOption op,PetscBool flg)
5424: {
5430: if (op > 0) {
5433: }
5435: 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);
5436: 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()");
5438: switch (op) {
5439: case MAT_NO_OFF_PROC_ENTRIES:
5440: mat->nooffprocentries = flg;
5441: return(0);
5442: break;
5443: case MAT_SUBSET_OFF_PROC_ENTRIES:
5444: mat->assembly_subset = flg;
5445: if (!mat->assembly_subset) { /* See the same logic in VecAssembly wrt VEC_SUBSET_OFF_PROC_ENTRIES */
5446: #if !defined(PETSC_HAVE_MPIUNI)
5447: MatStashScatterDestroy_BTS(&mat->stash);
5448: #endif
5449: mat->stash.first_assembly_done = PETSC_FALSE;
5450: }
5451: return(0);
5452: case MAT_NO_OFF_PROC_ZERO_ROWS:
5453: mat->nooffproczerorows = flg;
5454: return(0);
5455: break;
5456: case MAT_SPD:
5457: mat->spd_set = PETSC_TRUE;
5458: mat->spd = flg;
5459: if (flg) {
5460: mat->symmetric = PETSC_TRUE;
5461: mat->structurally_symmetric = PETSC_TRUE;
5462: mat->symmetric_set = PETSC_TRUE;
5463: mat->structurally_symmetric_set = PETSC_TRUE;
5464: }
5465: break;
5466: case MAT_SYMMETRIC:
5467: mat->symmetric = flg;
5468: if (flg) mat->structurally_symmetric = PETSC_TRUE;
5469: mat->symmetric_set = PETSC_TRUE;
5470: mat->structurally_symmetric_set = flg;
5471: #if !defined(PETSC_USE_COMPLEX)
5472: mat->hermitian = flg;
5473: mat->hermitian_set = PETSC_TRUE;
5474: #endif
5475: break;
5476: case MAT_HERMITIAN:
5477: mat->hermitian = flg;
5478: if (flg) mat->structurally_symmetric = PETSC_TRUE;
5479: mat->hermitian_set = PETSC_TRUE;
5480: mat->structurally_symmetric_set = flg;
5481: #if !defined(PETSC_USE_COMPLEX)
5482: mat->symmetric = flg;
5483: mat->symmetric_set = PETSC_TRUE;
5484: #endif
5485: break;
5486: case MAT_STRUCTURALLY_SYMMETRIC:
5487: mat->structurally_symmetric = flg;
5488: mat->structurally_symmetric_set = PETSC_TRUE;
5489: break;
5490: case MAT_SYMMETRY_ETERNAL:
5491: mat->symmetric_eternal = flg;
5492: break;
5493: case MAT_STRUCTURE_ONLY:
5494: mat->structure_only = flg;
5495: break;
5496: case MAT_SORTED_FULL:
5497: mat->sortedfull = flg;
5498: break;
5499: default:
5500: break;
5501: }
5502: if (mat->ops->setoption) {
5503: (*mat->ops->setoption)(mat,op,flg);
5504: }
5505: return(0);
5506: }
5508: /*@
5509: MatGetOption - Gets a parameter option that has been set for a matrix.
5511: Logically Collective on Mat for certain operations, such as MAT_SPD, not collective for MAT_ROW_ORIENTED, see MatOption
5513: Input Parameters:
5514: + mat - the matrix
5515: - option - the option, this only responds to certain options, check the code for which ones
5517: Output Parameter:
5518: . flg - turn the option on (PETSC_TRUE) or off (PETSC_FALSE)
5520: Notes:
5521: Can only be called after MatSetSizes() and MatSetType() have been set.
5523: Level: intermediate
5525: .seealso: MatOption, MatSetOption()
5527: @*/
5528: PetscErrorCode MatGetOption(Mat mat,MatOption op,PetscBool *flg)
5529: {
5534: 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);
5535: 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()");
5537: switch (op) {
5538: case MAT_NO_OFF_PROC_ENTRIES:
5539: *flg = mat->nooffprocentries;
5540: break;
5541: case MAT_NO_OFF_PROC_ZERO_ROWS:
5542: *flg = mat->nooffproczerorows;
5543: break;
5544: case MAT_SYMMETRIC:
5545: *flg = mat->symmetric;
5546: break;
5547: case MAT_HERMITIAN:
5548: *flg = mat->hermitian;
5549: break;
5550: case MAT_STRUCTURALLY_SYMMETRIC:
5551: *flg = mat->structurally_symmetric;
5552: break;
5553: case MAT_SYMMETRY_ETERNAL:
5554: *flg = mat->symmetric_eternal;
5555: break;
5556: case MAT_SPD:
5557: *flg = mat->spd;
5558: break;
5559: default:
5560: break;
5561: }
5562: return(0);
5563: }
5565: /*@
5566: MatZeroEntries - Zeros all entries of a matrix. For sparse matrices
5567: this routine retains the old nonzero structure.
5569: Logically Collective on Mat
5571: Input Parameters:
5572: . mat - the matrix
5574: Level: intermediate
5576: Notes:
5577: 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.
5578: See the Performance chapter of the users manual for information on preallocating matrices.
5580: .seealso: MatZeroRows()
5581: @*/
5582: PetscErrorCode MatZeroEntries(Mat mat)
5583: {
5589: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
5590: 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");
5591: if (!mat->ops->zeroentries) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
5592: MatCheckPreallocated(mat,1);
5594: PetscLogEventBegin(MAT_ZeroEntries,mat,0,0,0);
5595: (*mat->ops->zeroentries)(mat);
5596: PetscLogEventEnd(MAT_ZeroEntries,mat,0,0,0);
5597: PetscObjectStateIncrease((PetscObject)mat);
5598: return(0);
5599: }
5601: /*@
5602: MatZeroRowsColumns - Zeros all entries (except possibly the main diagonal)
5603: of a set of rows and columns of a matrix.
5605: Collective on Mat
5607: Input Parameters:
5608: + mat - the matrix
5609: . numRows - the number of rows to remove
5610: . rows - the global row indices
5611: . diag - value put in all diagonals of eliminated rows (0.0 will even eliminate diagonal entry)
5612: . x - optional vector of solutions for zeroed rows (other entries in vector are not used)
5613: - b - optional vector of right hand side, that will be adjusted by provided solution
5615: Notes:
5616: This does not change the nonzero structure of the matrix, it merely zeros those entries in the matrix.
5618: The user can set a value in the diagonal entry (or for the AIJ and
5619: row formats can optionally remove the main diagonal entry from the
5620: nonzero structure as well, by passing 0.0 as the final argument).
5622: For the parallel case, all processes that share the matrix (i.e.,
5623: those in the communicator used for matrix creation) MUST call this
5624: routine, regardless of whether any rows being zeroed are owned by
5625: them.
5627: Each processor can indicate any rows in the entire matrix to be zeroed (i.e. each process does NOT have to
5628: list only rows local to itself).
5630: The option MAT_NO_OFF_PROC_ZERO_ROWS does not apply to this routine.
5632: Level: intermediate
5634: .seealso: MatZeroRowsIS(), MatZeroRows(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
5635: MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
5636: @*/
5637: PetscErrorCode MatZeroRowsColumns(Mat mat,PetscInt numRows,const PetscInt rows[],PetscScalar diag,Vec x,Vec b)
5638: {
5645: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
5646: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
5647: if (!mat->ops->zerorowscolumns) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
5648: MatCheckPreallocated(mat,1);
5650: (*mat->ops->zerorowscolumns)(mat,numRows,rows,diag,x,b);
5651: MatViewFromOptions(mat,NULL,"-mat_view");
5652: PetscObjectStateIncrease((PetscObject)mat);
5653: return(0);
5654: }
5656: /*@
5657: MatZeroRowsColumnsIS - Zeros all entries (except possibly the main diagonal)
5658: of a set of rows and columns of a matrix.
5660: Collective on Mat
5662: Input Parameters:
5663: + mat - the matrix
5664: . is - the rows to zero
5665: . diag - value put in all diagonals of eliminated rows (0.0 will even eliminate diagonal entry)
5666: . x - optional vector of solutions for zeroed rows (other entries in vector are not used)
5667: - b - optional vector of right hand side, that will be adjusted by provided solution
5669: Notes:
5670: This does not change the nonzero structure of the matrix, it merely zeros those entries in the matrix.
5672: The user can set a value in the diagonal entry (or for the AIJ and
5673: row formats can optionally remove the main diagonal entry from the
5674: nonzero structure as well, by passing 0.0 as the final argument).
5676: For the parallel case, all processes that share the matrix (i.e.,
5677: those in the communicator used for matrix creation) MUST call this
5678: routine, regardless of whether any rows being zeroed are owned by
5679: them.
5681: Each processor can indicate any rows in the entire matrix to be zeroed (i.e. each process does NOT have to
5682: list only rows local to itself).
5684: The option MAT_NO_OFF_PROC_ZERO_ROWS does not apply to this routine.
5686: Level: intermediate
5688: .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
5689: MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRows(), MatZeroRowsColumnsStencil()
5690: @*/
5691: PetscErrorCode MatZeroRowsColumnsIS(Mat mat,IS is,PetscScalar diag,Vec x,Vec b)
5692: {
5694: PetscInt numRows;
5695: const PetscInt *rows;
5702: ISGetLocalSize(is,&numRows);
5703: ISGetIndices(is,&rows);
5704: MatZeroRowsColumns(mat,numRows,rows,diag,x,b);
5705: ISRestoreIndices(is,&rows);
5706: return(0);
5707: }
5709: /*@
5710: MatZeroRows - Zeros all entries (except possibly the main diagonal)
5711: of a set of rows of a matrix.
5713: Collective on Mat
5715: Input Parameters:
5716: + mat - the matrix
5717: . numRows - the number of rows to remove
5718: . rows - the global row indices
5719: . diag - value put in all diagonals of eliminated rows (0.0 will even eliminate diagonal entry)
5720: . x - optional vector of solutions for zeroed rows (other entries in vector are not used)
5721: - b - optional vector of right hand side, that will be adjusted by provided solution
5723: Notes:
5724: For the AIJ and BAIJ matrix formats this removes the old nonzero structure,
5725: but does not release memory. For the dense and block diagonal
5726: formats this does not alter the nonzero structure.
5728: If the option MatSetOption(mat,MAT_KEEP_NONZERO_PATTERN,PETSC_TRUE) the nonzero structure
5729: of the matrix is not changed (even for AIJ and BAIJ matrices) the values are
5730: merely zeroed.
5732: The user can set a value in the diagonal entry (or for the AIJ and
5733: row formats can optionally remove the main diagonal entry from the
5734: nonzero structure as well, by passing 0.0 as the final argument).
5736: For the parallel case, all processes that share the matrix (i.e.,
5737: those in the communicator used for matrix creation) MUST call this
5738: routine, regardless of whether any rows being zeroed are owned by
5739: them.
5741: Each processor can indicate any rows in the entire matrix to be zeroed (i.e. each process does NOT have to
5742: list only rows local to itself).
5744: You can call MatSetOption(mat,MAT_NO_OFF_PROC_ZERO_ROWS,PETSC_TRUE) if each process indicates only rows it
5745: owns that are to be zeroed. This saves a global synchronization in the implementation.
5747: Level: intermediate
5749: .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
5750: MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
5751: @*/
5752: PetscErrorCode MatZeroRows(Mat mat,PetscInt numRows,const PetscInt rows[],PetscScalar diag,Vec x,Vec b)
5753: {
5760: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
5761: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
5762: if (!mat->ops->zerorows) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
5763: MatCheckPreallocated(mat,1);
5765: (*mat->ops->zerorows)(mat,numRows,rows,diag,x,b);
5766: MatViewFromOptions(mat,NULL,"-mat_view");
5767: PetscObjectStateIncrease((PetscObject)mat);
5768: return(0);
5769: }
5771: /*@
5772: MatZeroRowsIS - Zeros all entries (except possibly the main diagonal)
5773: of a set of rows of a matrix.
5775: Collective on Mat
5777: Input Parameters:
5778: + mat - the matrix
5779: . is - index set of rows to remove
5780: . diag - value put in all diagonals of eliminated rows
5781: . x - optional vector of solutions for zeroed rows (other entries in vector are not used)
5782: - b - optional vector of right hand side, that will be adjusted by provided solution
5784: Notes:
5785: For the AIJ and BAIJ matrix formats this removes the old nonzero structure,
5786: but does not release memory. For the dense and block diagonal
5787: formats this does not alter the nonzero structure.
5789: If the option MatSetOption(mat,MAT_KEEP_NONZERO_PATTERN,PETSC_TRUE) the nonzero structure
5790: of the matrix is not changed (even for AIJ and BAIJ matrices) the values are
5791: merely zeroed.
5793: The user can set a value in the diagonal entry (or for the AIJ and
5794: row formats can optionally remove the main diagonal entry from the
5795: nonzero structure as well, by passing 0.0 as the final argument).
5797: For the parallel case, all processes that share the matrix (i.e.,
5798: those in the communicator used for matrix creation) MUST call this
5799: routine, regardless of whether any rows being zeroed are owned by
5800: them.
5802: Each processor can indicate any rows in the entire matrix to be zeroed (i.e. each process does NOT have to
5803: list only rows local to itself).
5805: You can call MatSetOption(mat,MAT_NO_OFF_PROC_ZERO_ROWS,PETSC_TRUE) if each process indicates only rows it
5806: owns that are to be zeroed. This saves a global synchronization in the implementation.
5808: Level: intermediate
5810: .seealso: MatZeroRows(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
5811: MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
5812: @*/
5813: PetscErrorCode MatZeroRowsIS(Mat mat,IS is,PetscScalar diag,Vec x,Vec b)
5814: {
5815: PetscInt numRows;
5816: const PetscInt *rows;
5823: ISGetLocalSize(is,&numRows);
5824: ISGetIndices(is,&rows);
5825: MatZeroRows(mat,numRows,rows,diag,x,b);
5826: ISRestoreIndices(is,&rows);
5827: return(0);
5828: }
5830: /*@
5831: MatZeroRowsStencil - Zeros all entries (except possibly the main diagonal)
5832: of a set of rows of a matrix. These rows must be local to the process.
5834: Collective on Mat
5836: Input Parameters:
5837: + mat - the matrix
5838: . numRows - the number of rows to remove
5839: . rows - the grid coordinates (and component number when dof > 1) for matrix rows
5840: . diag - value put in all diagonals of eliminated rows (0.0 will even eliminate diagonal entry)
5841: . x - optional vector of solutions for zeroed rows (other entries in vector are not used)
5842: - b - optional vector of right hand side, that will be adjusted by provided solution
5844: Notes:
5845: For the AIJ and BAIJ matrix formats this removes the old nonzero structure,
5846: but does not release memory. For the dense and block diagonal
5847: formats this does not alter the nonzero structure.
5849: If the option MatSetOption(mat,MAT_KEEP_NONZERO_PATTERN,PETSC_TRUE) the nonzero structure
5850: of the matrix is not changed (even for AIJ and BAIJ matrices) the values are
5851: merely zeroed.
5853: The user can set a value in the diagonal entry (or for the AIJ and
5854: row formats can optionally remove the main diagonal entry from the
5855: nonzero structure as well, by passing 0.0 as the final argument).
5857: For the parallel case, all processes that share the matrix (i.e.,
5858: those in the communicator used for matrix creation) MUST call this
5859: routine, regardless of whether any rows being zeroed are owned by
5860: them.
5862: Each processor can indicate any rows in the entire matrix to be zeroed (i.e. each process does NOT have to
5863: list only rows local to itself).
5865: The grid coordinates are across the entire grid, not just the local portion
5867: In Fortran idxm and idxn should be declared as
5868: $ MatStencil idxm(4,m)
5869: and the values inserted using
5870: $ idxm(MatStencil_i,1) = i
5871: $ idxm(MatStencil_j,1) = j
5872: $ idxm(MatStencil_k,1) = k
5873: $ idxm(MatStencil_c,1) = c
5874: etc
5876: For periodic boundary conditions use negative indices for values to the left (below 0; that are to be
5877: obtained by wrapping values from right edge). For values to the right of the last entry using that index plus one
5878: etc to obtain values that obtained by wrapping the values from the left edge. This does not work for anything but the
5879: DM_BOUNDARY_PERIODIC boundary type.
5881: 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
5882: a single value per point) you can skip filling those indices.
5884: Level: intermediate
5886: .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsl(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
5887: MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
5888: @*/
5889: PetscErrorCode MatZeroRowsStencil(Mat mat,PetscInt numRows,const MatStencil rows[],PetscScalar diag,Vec x,Vec b)
5890: {
5891: PetscInt dim = mat->stencil.dim;
5892: PetscInt sdim = dim - (1 - (PetscInt) mat->stencil.noc);
5893: PetscInt *dims = mat->stencil.dims+1;
5894: PetscInt *starts = mat->stencil.starts;
5895: PetscInt *dxm = (PetscInt*) rows;
5896: PetscInt *jdxm, i, j, tmp, numNewRows = 0;
5904: PetscMalloc1(numRows, &jdxm);
5905: for (i = 0; i < numRows; ++i) {
5906: /* Skip unused dimensions (they are ordered k, j, i, c) */
5907: for (j = 0; j < 3-sdim; ++j) dxm++;
5908: /* Local index in X dir */
5909: tmp = *dxm++ - starts[0];
5910: /* Loop over remaining dimensions */
5911: for (j = 0; j < dim-1; ++j) {
5912: /* If nonlocal, set index to be negative */
5913: if ((*dxm++ - starts[j+1]) < 0 || tmp < 0) tmp = PETSC_MIN_INT;
5914: /* Update local index */
5915: else tmp = tmp*dims[j] + *(dxm-1) - starts[j+1];
5916: }
5917: /* Skip component slot if necessary */
5918: if (mat->stencil.noc) dxm++;
5919: /* Local row number */
5920: if (tmp >= 0) {
5921: jdxm[numNewRows++] = tmp;
5922: }
5923: }
5924: MatZeroRowsLocal(mat,numNewRows,jdxm,diag,x,b);
5925: PetscFree(jdxm);
5926: return(0);
5927: }
5929: /*@
5930: MatZeroRowsColumnsStencil - Zeros all row and column entries (except possibly the main diagonal)
5931: of a set of rows and columns of a matrix.
5933: Collective on Mat
5935: Input Parameters:
5936: + mat - the matrix
5937: . numRows - the number of rows/columns to remove
5938: . rows - the grid coordinates (and component number when dof > 1) for matrix rows
5939: . diag - value put in all diagonals of eliminated rows (0.0 will even eliminate diagonal entry)
5940: . x - optional vector of solutions for zeroed rows (other entries in vector are not used)
5941: - b - optional vector of right hand side, that will be adjusted by provided solution
5943: Notes:
5944: For the AIJ and BAIJ matrix formats this removes the old nonzero structure,
5945: but does not release memory. For the dense and block diagonal
5946: formats this does not alter the nonzero structure.
5948: If the option MatSetOption(mat,MAT_KEEP_NONZERO_PATTERN,PETSC_TRUE) the nonzero structure
5949: of the matrix is not changed (even for AIJ and BAIJ matrices) the values are
5950: merely zeroed.
5952: The user can set a value in the diagonal entry (or for the AIJ and
5953: row formats can optionally remove the main diagonal entry from the
5954: nonzero structure as well, by passing 0.0 as the final argument).
5956: For the parallel case, all processes that share the matrix (i.e.,
5957: those in the communicator used for matrix creation) MUST call this
5958: routine, regardless of whether any rows being zeroed are owned by
5959: them.
5961: Each processor can indicate any rows in the entire matrix to be zeroed (i.e. each process does NOT have to
5962: list only rows local to itself, but the row/column numbers are given in local numbering).
5964: The grid coordinates are across the entire grid, not just the local portion
5966: In Fortran idxm and idxn should be declared as
5967: $ MatStencil idxm(4,m)
5968: and the values inserted using
5969: $ idxm(MatStencil_i,1) = i
5970: $ idxm(MatStencil_j,1) = j
5971: $ idxm(MatStencil_k,1) = k
5972: $ idxm(MatStencil_c,1) = c
5973: etc
5975: For periodic boundary conditions use negative indices for values to the left (below 0; that are to be
5976: obtained by wrapping values from right edge). For values to the right of the last entry using that index plus one
5977: etc to obtain values that obtained by wrapping the values from the left edge. This does not work for anything but the
5978: DM_BOUNDARY_PERIODIC boundary type.
5980: 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
5981: a single value per point) you can skip filling those indices.
5983: Level: intermediate
5985: .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
5986: MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRows()
5987: @*/
5988: PetscErrorCode MatZeroRowsColumnsStencil(Mat mat,PetscInt numRows,const MatStencil rows[],PetscScalar diag,Vec x,Vec b)
5989: {
5990: PetscInt dim = mat->stencil.dim;
5991: PetscInt sdim = dim - (1 - (PetscInt) mat->stencil.noc);
5992: PetscInt *dims = mat->stencil.dims+1;
5993: PetscInt *starts = mat->stencil.starts;
5994: PetscInt *dxm = (PetscInt*) rows;
5995: PetscInt *jdxm, i, j, tmp, numNewRows = 0;
6003: PetscMalloc1(numRows, &jdxm);
6004: for (i = 0; i < numRows; ++i) {
6005: /* Skip unused dimensions (they are ordered k, j, i, c) */
6006: for (j = 0; j < 3-sdim; ++j) dxm++;
6007: /* Local index in X dir */
6008: tmp = *dxm++ - starts[0];
6009: /* Loop over remaining dimensions */
6010: for (j = 0; j < dim-1; ++j) {
6011: /* If nonlocal, set index to be negative */
6012: if ((*dxm++ - starts[j+1]) < 0 || tmp < 0) tmp = PETSC_MIN_INT;
6013: /* Update local index */
6014: else tmp = tmp*dims[j] + *(dxm-1) - starts[j+1];
6015: }
6016: /* Skip component slot if necessary */
6017: if (mat->stencil.noc) dxm++;
6018: /* Local row number */
6019: if (tmp >= 0) {
6020: jdxm[numNewRows++] = tmp;
6021: }
6022: }
6023: MatZeroRowsColumnsLocal(mat,numNewRows,jdxm,diag,x,b);
6024: PetscFree(jdxm);
6025: return(0);
6026: }
6028: /*@C
6029: MatZeroRowsLocal - Zeros all entries (except possibly the main diagonal)
6030: of a set of rows of a matrix; using local numbering of rows.
6032: Collective on Mat
6034: Input Parameters:
6035: + mat - the matrix
6036: . numRows - the number of rows to remove
6037: . rows - the global row indices
6038: . diag - value put in all diagonals of eliminated rows
6039: . x - optional vector of solutions for zeroed rows (other entries in vector are not used)
6040: - b - optional vector of right hand side, that will be adjusted by provided solution
6042: Notes:
6043: Before calling MatZeroRowsLocal(), the user must first set the
6044: local-to-global mapping by calling MatSetLocalToGlobalMapping().
6046: For the AIJ matrix formats this removes the old nonzero structure,
6047: but does not release memory. For the dense and block diagonal
6048: formats this does not alter the nonzero structure.
6050: If the option MatSetOption(mat,MAT_KEEP_NONZERO_PATTERN,PETSC_TRUE) the nonzero structure
6051: of the matrix is not changed (even for AIJ and BAIJ matrices) the values are
6052: merely zeroed.
6054: The user can set a value in the diagonal entry (or for the AIJ and
6055: row formats can optionally remove the main diagonal entry from the
6056: nonzero structure as well, by passing 0.0 as the final argument).
6058: You can call MatSetOption(mat,MAT_NO_OFF_PROC_ZERO_ROWS,PETSC_TRUE) if each process indicates only rows it
6059: owns that are to be zeroed. This saves a global synchronization in the implementation.
6061: Level: intermediate
6063: .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRows(), MatSetOption(),
6064: MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
6065: @*/
6066: PetscErrorCode MatZeroRowsLocal(Mat mat,PetscInt numRows,const PetscInt rows[],PetscScalar diag,Vec x,Vec b)
6067: {
6074: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6075: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6076: MatCheckPreallocated(mat,1);
6078: if (mat->ops->zerorowslocal) {
6079: (*mat->ops->zerorowslocal)(mat,numRows,rows,diag,x,b);
6080: } else {
6081: IS is, newis;
6082: const PetscInt *newRows;
6084: if (!mat->rmap->mapping) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Need to provide local to global mapping to matrix first");
6085: ISCreateGeneral(PETSC_COMM_SELF,numRows,rows,PETSC_COPY_VALUES,&is);
6086: ISLocalToGlobalMappingApplyIS(mat->rmap->mapping,is,&newis);
6087: ISGetIndices(newis,&newRows);
6088: (*mat->ops->zerorows)(mat,numRows,newRows,diag,x,b);
6089: ISRestoreIndices(newis,&newRows);
6090: ISDestroy(&newis);
6091: ISDestroy(&is);
6092: }
6093: PetscObjectStateIncrease((PetscObject)mat);
6094: return(0);
6095: }
6097: /*@
6098: MatZeroRowsLocalIS - Zeros all entries (except possibly the main diagonal)
6099: of a set of rows of a matrix; using local numbering of rows.
6101: Collective on Mat
6103: Input Parameters:
6104: + mat - the matrix
6105: . is - index set of rows to remove
6106: . diag - value put in all diagonals of eliminated rows
6107: . x - optional vector of solutions for zeroed rows (other entries in vector are not used)
6108: - b - optional vector of right hand side, that will be adjusted by provided solution
6110: Notes:
6111: Before calling MatZeroRowsLocalIS(), the user must first set the
6112: local-to-global mapping by calling MatSetLocalToGlobalMapping().
6114: For the AIJ matrix formats this removes the old nonzero structure,
6115: but does not release memory. For the dense and block diagonal
6116: formats this does not alter the nonzero structure.
6118: If the option MatSetOption(mat,MAT_KEEP_NONZERO_PATTERN,PETSC_TRUE) the nonzero structure
6119: of the matrix is not changed (even for AIJ and BAIJ matrices) the values are
6120: merely zeroed.
6122: The user can set a value in the diagonal entry (or for the AIJ and
6123: row formats can optionally remove the main diagonal entry from the
6124: nonzero structure as well, by passing 0.0 as the final argument).
6126: You can call MatSetOption(mat,MAT_NO_OFF_PROC_ZERO_ROWS,PETSC_TRUE) if each process indicates only rows it
6127: owns that are to be zeroed. This saves a global synchronization in the implementation.
6129: Level: intermediate
6131: .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRows(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
6132: MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
6133: @*/
6134: PetscErrorCode MatZeroRowsLocalIS(Mat mat,IS is,PetscScalar diag,Vec x,Vec b)
6135: {
6137: PetscInt numRows;
6138: const PetscInt *rows;
6144: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6145: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6146: MatCheckPreallocated(mat,1);
6148: ISGetLocalSize(is,&numRows);
6149: ISGetIndices(is,&rows);
6150: MatZeroRowsLocal(mat,numRows,rows,diag,x,b);
6151: ISRestoreIndices(is,&rows);
6152: return(0);
6153: }
6155: /*@
6156: MatZeroRowsColumnsLocal - Zeros all entries (except possibly the main diagonal)
6157: of a set of rows and columns of a matrix; using local numbering of rows.
6159: Collective on Mat
6161: Input Parameters:
6162: + mat - the matrix
6163: . numRows - the number of rows to remove
6164: . rows - the global row indices
6165: . diag - value put in all diagonals of eliminated rows
6166: . x - optional vector of solutions for zeroed rows (other entries in vector are not used)
6167: - b - optional vector of right hand side, that will be adjusted by provided solution
6169: Notes:
6170: Before calling MatZeroRowsColumnsLocal(), the user must first set the
6171: local-to-global mapping by calling MatSetLocalToGlobalMapping().
6173: The user can set a value in the diagonal entry (or for the AIJ and
6174: row formats can optionally remove the main diagonal entry from the
6175: nonzero structure as well, by passing 0.0 as the final argument).
6177: Level: intermediate
6179: .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
6180: MatZeroRows(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
6181: @*/
6182: PetscErrorCode MatZeroRowsColumnsLocal(Mat mat,PetscInt numRows,const PetscInt rows[],PetscScalar diag,Vec x,Vec b)
6183: {
6185: IS is, newis;
6186: const PetscInt *newRows;
6192: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6193: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6194: MatCheckPreallocated(mat,1);
6196: if (!mat->cmap->mapping) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Need to provide local to global mapping to matrix first");
6197: ISCreateGeneral(PETSC_COMM_SELF,numRows,rows,PETSC_COPY_VALUES,&is);
6198: ISLocalToGlobalMappingApplyIS(mat->cmap->mapping,is,&newis);
6199: ISGetIndices(newis,&newRows);
6200: (*mat->ops->zerorowscolumns)(mat,numRows,newRows,diag,x,b);
6201: ISRestoreIndices(newis,&newRows);
6202: ISDestroy(&newis);
6203: ISDestroy(&is);
6204: PetscObjectStateIncrease((PetscObject)mat);
6205: return(0);
6206: }
6208: /*@
6209: MatZeroRowsColumnsLocalIS - Zeros all entries (except possibly the main diagonal)
6210: of a set of rows and columns of a matrix; using local numbering of rows.
6212: Collective on Mat
6214: Input Parameters:
6215: + mat - the matrix
6216: . is - index set of rows to remove
6217: . diag - value put in all diagonals of eliminated rows
6218: . x - optional vector of solutions for zeroed rows (other entries in vector are not used)
6219: - b - optional vector of right hand side, that will be adjusted by provided solution
6221: Notes:
6222: Before calling MatZeroRowsColumnsLocalIS(), the user must first set the
6223: local-to-global mapping by calling MatSetLocalToGlobalMapping().
6225: The user can set a value in the diagonal entry (or for the AIJ and
6226: row formats can optionally remove the main diagonal entry from the
6227: nonzero structure as well, by passing 0.0 as the final argument).
6229: Level: intermediate
6231: .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
6232: MatZeroRowsColumnsLocal(), MatZeroRows(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
6233: @*/
6234: PetscErrorCode MatZeroRowsColumnsLocalIS(Mat mat,IS is,PetscScalar diag,Vec x,Vec b)
6235: {
6237: PetscInt numRows;
6238: const PetscInt *rows;
6244: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6245: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6246: MatCheckPreallocated(mat,1);
6248: ISGetLocalSize(is,&numRows);
6249: ISGetIndices(is,&rows);
6250: MatZeroRowsColumnsLocal(mat,numRows,rows,diag,x,b);
6251: ISRestoreIndices(is,&rows);
6252: return(0);
6253: }
6255: /*@C
6256: MatGetSize - Returns the numbers of rows and columns in a matrix.
6258: Not Collective
6260: Input Parameter:
6261: . mat - the matrix
6263: Output Parameters:
6264: + m - the number of global rows
6265: - n - the number of global columns
6267: Note: both output parameters can be NULL on input.
6269: Level: beginner
6271: .seealso: MatGetLocalSize()
6272: @*/
6273: PetscErrorCode MatGetSize(Mat mat,PetscInt *m,PetscInt *n)
6274: {
6277: if (m) *m = mat->rmap->N;
6278: if (n) *n = mat->cmap->N;
6279: return(0);
6280: }
6282: /*@C
6283: MatGetLocalSize - Returns the number of rows and columns in a matrix
6284: stored locally. This information may be implementation dependent, so
6285: use with care.
6287: Not Collective
6289: Input Parameters:
6290: . mat - the matrix
6292: Output Parameters:
6293: + m - the number of local rows
6294: - n - the number of local columns
6296: Note: both output parameters can be NULL on input.
6298: Level: beginner
6300: .seealso: MatGetSize()
6301: @*/
6302: PetscErrorCode MatGetLocalSize(Mat mat,PetscInt *m,PetscInt *n)
6303: {
6308: if (m) *m = mat->rmap->n;
6309: if (n) *n = mat->cmap->n;
6310: return(0);
6311: }
6313: /*@C
6314: MatGetOwnershipRangeColumn - Returns the range of matrix columns associated with rows of a vector one multiplies by that owned by
6315: this processor. (The columns of the "diagonal block")
6317: Not Collective, unless matrix has not been allocated, then collective on Mat
6319: Input Parameters:
6320: . mat - the matrix
6322: Output Parameters:
6323: + m - the global index of the first local column
6324: - n - one more than the global index of the last local column
6326: Notes:
6327: both output parameters can be NULL on input.
6329: Level: developer
6331: .seealso: MatGetOwnershipRange(), MatGetOwnershipRanges(), MatGetOwnershipRangesColumn()
6333: @*/
6334: PetscErrorCode MatGetOwnershipRangeColumn(Mat mat,PetscInt *m,PetscInt *n)
6335: {
6341: MatCheckPreallocated(mat,1);
6342: if (m) *m = mat->cmap->rstart;
6343: if (n) *n = mat->cmap->rend;
6344: return(0);
6345: }
6347: /*@C
6348: MatGetOwnershipRange - Returns the range of matrix rows owned by
6349: this processor, assuming that the matrix is laid out with the first
6350: n1 rows on the first processor, the next n2 rows on the second, etc.
6351: For certain parallel layouts this range may not be well defined.
6353: Not Collective
6355: Input Parameters:
6356: . mat - the matrix
6358: Output Parameters:
6359: + m - the global index of the first local row
6360: - n - one more than the global index of the last local row
6362: Note: Both output parameters can be NULL on input.
6363: $ This function requires that the matrix be preallocated. If you have not preallocated, consider using
6364: $ PetscSplitOwnership(MPI_Comm comm, PetscInt *n, PetscInt *N)
6365: $ and then MPI_Scan() to calculate prefix sums of the local sizes.
6367: Level: beginner
6369: .seealso: MatGetOwnershipRanges(), MatGetOwnershipRangeColumn(), MatGetOwnershipRangesColumn(), PetscSplitOwnership(), PetscSplitOwnershipBlock()
6371: @*/
6372: PetscErrorCode MatGetOwnershipRange(Mat mat,PetscInt *m,PetscInt *n)
6373: {
6379: MatCheckPreallocated(mat,1);
6380: if (m) *m = mat->rmap->rstart;
6381: if (n) *n = mat->rmap->rend;
6382: return(0);
6383: }
6385: /*@C
6386: MatGetOwnershipRanges - Returns the range of matrix rows owned by
6387: each process
6389: Not Collective, unless matrix has not been allocated, then collective on Mat
6391: Input Parameters:
6392: . mat - the matrix
6394: Output Parameters:
6395: . ranges - start of each processors portion plus one more than the total length at the end
6397: Level: beginner
6399: .seealso: MatGetOwnershipRange(), MatGetOwnershipRangeColumn(), MatGetOwnershipRangesColumn()
6401: @*/
6402: PetscErrorCode MatGetOwnershipRanges(Mat mat,const PetscInt **ranges)
6403: {
6409: MatCheckPreallocated(mat,1);
6410: PetscLayoutGetRanges(mat->rmap,ranges);
6411: return(0);
6412: }
6414: /*@C
6415: MatGetOwnershipRangesColumn - Returns the range of matrix columns associated with rows of a vector one multiplies by that owned by
6416: this processor. (The columns of the "diagonal blocks" for each process)
6418: Not Collective, unless matrix has not been allocated, then collective on Mat
6420: Input Parameters:
6421: . mat - the matrix
6423: Output Parameters:
6424: . ranges - start of each processors portion plus one more then the total length at the end
6426: Level: beginner
6428: .seealso: MatGetOwnershipRange(), MatGetOwnershipRangeColumn(), MatGetOwnershipRanges()
6430: @*/
6431: PetscErrorCode MatGetOwnershipRangesColumn(Mat mat,const PetscInt **ranges)
6432: {
6438: MatCheckPreallocated(mat,1);
6439: PetscLayoutGetRanges(mat->cmap,ranges);
6440: return(0);
6441: }
6443: /*@C
6444: MatGetOwnershipIS - Get row and column ownership as index sets
6446: Not Collective
6448: Input Arguments:
6449: . A - matrix of type Elemental
6451: Output Arguments:
6452: + rows - rows in which this process owns elements
6453: - cols - columns in which this process owns elements
6455: Level: intermediate
6457: .seealso: MatGetOwnershipRange(), MatGetOwnershipRangeColumn(), MatSetValues(), MATELEMENTAL
6458: @*/
6459: PetscErrorCode MatGetOwnershipIS(Mat A,IS *rows,IS *cols)
6460: {
6461: PetscErrorCode ierr,(*f)(Mat,IS*,IS*);
6464: MatCheckPreallocated(A,1);
6465: PetscObjectQueryFunction((PetscObject)A,"MatGetOwnershipIS_C",&f);
6466: if (f) {
6467: (*f)(A,rows,cols);
6468: } else { /* Create a standard row-based partition, each process is responsible for ALL columns in their row block */
6469: if (rows) {ISCreateStride(PETSC_COMM_SELF,A->rmap->n,A->rmap->rstart,1,rows);}
6470: if (cols) {ISCreateStride(PETSC_COMM_SELF,A->cmap->N,0,1,cols);}
6471: }
6472: return(0);
6473: }
6475: /*@C
6476: MatILUFactorSymbolic - Performs symbolic ILU factorization of a matrix.
6477: Uses levels of fill only, not drop tolerance. Use MatLUFactorNumeric()
6478: to complete the factorization.
6480: Collective on Mat
6482: Input Parameters:
6483: + mat - the matrix
6484: . row - row permutation
6485: . column - column permutation
6486: - info - structure containing
6487: $ levels - number of levels of fill.
6488: $ expected fill - as ratio of original fill.
6489: $ 1 or 0 - indicating force fill on diagonal (improves robustness for matrices
6490: missing diagonal entries)
6492: Output Parameters:
6493: . fact - new matrix that has been symbolically factored
6495: Notes:
6496: See Users-Manual: ch_mat for additional information about choosing the fill factor for better efficiency.
6498: Most users should employ the simplified KSP interface for linear solvers
6499: instead of working directly with matrix algebra routines such as this.
6500: See, e.g., KSPCreate().
6502: Level: developer
6504: .seealso: MatLUFactorSymbolic(), MatLUFactorNumeric(), MatCholeskyFactor()
6505: MatGetOrdering(), MatFactorInfo
6507: Note: this uses the definition of level of fill as in Y. Saad, 2003
6509: Developer Note: fortran interface is not autogenerated as the f90
6510: interface defintion cannot be generated correctly [due to MatFactorInfo]
6512: References:
6513: Y. Saad, Iterative methods for sparse linear systems Philadelphia: Society for Industrial and Applied Mathematics, 2003
6514: @*/
6515: PetscErrorCode MatILUFactorSymbolic(Mat fact,Mat mat,IS row,IS col,const MatFactorInfo *info)
6516: {
6526: if (info->levels < 0) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_OUTOFRANGE,"Levels of fill negative %D",(PetscInt)info->levels);
6527: if (info->fill < 1.0) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_OUTOFRANGE,"Expected fill less than 1.0 %g",(double)info->fill);
6528: if (!(fact)->ops->ilufactorsymbolic) {
6529: MatSolverType spackage;
6530: MatFactorGetSolverType(fact,&spackage);
6531: SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Matrix type %s symbolic ILU using solver package %s",((PetscObject)mat)->type_name,spackage);
6532: }
6533: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6534: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6535: MatCheckPreallocated(mat,2);
6537: PetscLogEventBegin(MAT_ILUFactorSymbolic,mat,row,col,0);
6538: (fact->ops->ilufactorsymbolic)(fact,mat,row,col,info);
6539: PetscLogEventEnd(MAT_ILUFactorSymbolic,mat,row,col,0);
6540: return(0);
6541: }
6543: /*@C
6544: MatICCFactorSymbolic - Performs symbolic incomplete
6545: Cholesky factorization for a symmetric matrix. Use
6546: MatCholeskyFactorNumeric() to complete the factorization.
6548: Collective on Mat
6550: Input Parameters:
6551: + mat - the matrix
6552: . perm - row and column permutation
6553: - info - structure containing
6554: $ levels - number of levels of fill.
6555: $ expected fill - as ratio of original fill.
6557: Output Parameter:
6558: . fact - the factored matrix
6560: Notes:
6561: Most users should employ the KSP interface for linear solvers
6562: instead of working directly with matrix algebra routines such as this.
6563: See, e.g., KSPCreate().
6565: Level: developer
6567: .seealso: MatCholeskyFactorNumeric(), MatCholeskyFactor(), MatFactorInfo
6569: Note: this uses the definition of level of fill as in Y. Saad, 2003
6571: Developer Note: fortran interface is not autogenerated as the f90
6572: interface defintion cannot be generated correctly [due to MatFactorInfo]
6574: References:
6575: Y. Saad, Iterative methods for sparse linear systems Philadelphia: Society for Industrial and Applied Mathematics, 2003
6576: @*/
6577: PetscErrorCode MatICCFactorSymbolic(Mat fact,Mat mat,IS perm,const MatFactorInfo *info)
6578: {
6587: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6588: if (info->levels < 0) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_OUTOFRANGE,"Levels negative %D",(PetscInt) info->levels);
6589: if (info->fill < 1.0) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_OUTOFRANGE,"Expected fill less than 1.0 %g",(double)info->fill);
6590: if (!(fact)->ops->iccfactorsymbolic) {
6591: MatSolverType spackage;
6592: MatFactorGetSolverType(fact,&spackage);
6593: SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Matrix type %s symbolic ICC using solver package %s",((PetscObject)mat)->type_name,spackage);
6594: }
6595: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6596: MatCheckPreallocated(mat,2);
6598: PetscLogEventBegin(MAT_ICCFactorSymbolic,mat,perm,0,0);
6599: (fact->ops->iccfactorsymbolic)(fact,mat,perm,info);
6600: PetscLogEventEnd(MAT_ICCFactorSymbolic,mat,perm,0,0);
6601: return(0);
6602: }
6604: /*@C
6605: MatCreateSubMatrices - Extracts several submatrices from a matrix. If submat
6606: points to an array of valid matrices, they may be reused to store the new
6607: submatrices.
6609: Collective on Mat
6611: Input Parameters:
6612: + mat - the matrix
6613: . n - the number of submatrixes to be extracted (on this processor, may be zero)
6614: . irow, icol - index sets of rows and columns to extract
6615: - scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
6617: Output Parameter:
6618: . submat - the array of submatrices
6620: Notes:
6621: MatCreateSubMatrices() can extract ONLY sequential submatrices
6622: (from both sequential and parallel matrices). Use MatCreateSubMatrix()
6623: to extract a parallel submatrix.
6625: Some matrix types place restrictions on the row and column
6626: indices, such as that they be sorted or that they be equal to each other.
6628: The index sets may not have duplicate entries.
6630: When extracting submatrices from a parallel matrix, each processor can
6631: form a different submatrix by setting the rows and columns of its
6632: individual index sets according to the local submatrix desired.
6634: When finished using the submatrices, the user should destroy
6635: them with MatDestroySubMatrices().
6637: MAT_REUSE_MATRIX can only be used when the nonzero structure of the
6638: original matrix has not changed from that last call to MatCreateSubMatrices().
6640: This routine creates the matrices in submat; you should NOT create them before
6641: calling it. It also allocates the array of matrix pointers submat.
6643: For BAIJ matrices the index sets must respect the block structure, that is if they
6644: request one row/column in a block, they must request all rows/columns that are in
6645: that block. For example, if the block size is 2 you cannot request just row 0 and
6646: column 0.
6648: Fortran Note:
6649: The Fortran interface is slightly different from that given below; it
6650: requires one to pass in as submat a Mat (integer) array of size at least n+1.
6652: Level: advanced
6655: .seealso: MatDestroySubMatrices(), MatCreateSubMatrix(), MatGetRow(), MatGetDiagonal(), MatReuse
6656: @*/
6657: PetscErrorCode MatCreateSubMatrices(Mat mat,PetscInt n,const IS irow[],const IS icol[],MatReuse scall,Mat *submat[])
6658: {
6660: PetscInt i;
6661: PetscBool eq;
6666: if (n) {
6671: }
6673: if (n && scall == MAT_REUSE_MATRIX) {
6676: }
6677: if (!mat->ops->createsubmatrices) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
6678: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6679: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6680: MatCheckPreallocated(mat,1);
6682: PetscLogEventBegin(MAT_CreateSubMats,mat,0,0,0);
6683: (*mat->ops->createsubmatrices)(mat,n,irow,icol,scall,submat);
6684: PetscLogEventEnd(MAT_CreateSubMats,mat,0,0,0);
6685: for (i=0; i<n; i++) {
6686: (*submat)[i]->factortype = MAT_FACTOR_NONE; /* in case in place factorization was previously done on submatrix */
6687: if (mat->symmetric || mat->structurally_symmetric || mat->hermitian) {
6688: ISEqual(irow[i],icol[i],&eq);
6689: if (eq) {
6690: if (mat->symmetric) {
6691: MatSetOption((*submat)[i],MAT_SYMMETRIC,PETSC_TRUE);
6692: } else if (mat->hermitian) {
6693: MatSetOption((*submat)[i],MAT_HERMITIAN,PETSC_TRUE);
6694: } else if (mat->structurally_symmetric) {
6695: MatSetOption((*submat)[i],MAT_STRUCTURALLY_SYMMETRIC,PETSC_TRUE);
6696: }
6697: }
6698: }
6699: }
6700: return(0);
6701: }
6703: /*@C
6704: MatCreateSubMatricesMPI - Extracts MPI submatrices across a sub communicator of mat (by pairs of IS that may live on subcomms).
6706: Collective on Mat
6708: Input Parameters:
6709: + mat - the matrix
6710: . n - the number of submatrixes to be extracted
6711: . irow, icol - index sets of rows and columns to extract
6712: - scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
6714: Output Parameter:
6715: . submat - the array of submatrices
6717: Level: advanced
6720: .seealso: MatCreateSubMatrices(), MatCreateSubMatrix(), MatGetRow(), MatGetDiagonal(), MatReuse
6721: @*/
6722: PetscErrorCode MatCreateSubMatricesMPI(Mat mat,PetscInt n,const IS irow[],const IS icol[],MatReuse scall,Mat *submat[])
6723: {
6725: PetscInt i;
6726: PetscBool eq;
6731: if (n) {
6736: }
6738: if (n && scall == MAT_REUSE_MATRIX) {
6741: }
6742: if (!mat->ops->createsubmatricesmpi) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
6743: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6744: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6745: MatCheckPreallocated(mat,1);
6747: PetscLogEventBegin(MAT_CreateSubMats,mat,0,0,0);
6748: (*mat->ops->createsubmatricesmpi)(mat,n,irow,icol,scall,submat);
6749: PetscLogEventEnd(MAT_CreateSubMats,mat,0,0,0);
6750: for (i=0; i<n; i++) {
6751: if (mat->symmetric || mat->structurally_symmetric || mat->hermitian) {
6752: ISEqual(irow[i],icol[i],&eq);
6753: if (eq) {
6754: if (mat->symmetric) {
6755: MatSetOption((*submat)[i],MAT_SYMMETRIC,PETSC_TRUE);
6756: } else if (mat->hermitian) {
6757: MatSetOption((*submat)[i],MAT_HERMITIAN,PETSC_TRUE);
6758: } else if (mat->structurally_symmetric) {
6759: MatSetOption((*submat)[i],MAT_STRUCTURALLY_SYMMETRIC,PETSC_TRUE);
6760: }
6761: }
6762: }
6763: }
6764: return(0);
6765: }
6767: /*@C
6768: MatDestroyMatrices - Destroys an array of matrices.
6770: Collective on Mat
6772: Input Parameters:
6773: + n - the number of local matrices
6774: - mat - the matrices (note that this is a pointer to the array of matrices)
6776: Level: advanced
6778: Notes:
6779: Frees not only the matrices, but also the array that contains the matrices
6780: In Fortran will not free the array.
6782: .seealso: MatCreateSubMatrices() MatDestroySubMatrices()
6783: @*/
6784: PetscErrorCode MatDestroyMatrices(PetscInt n,Mat *mat[])
6785: {
6787: PetscInt i;
6790: if (!*mat) return(0);
6791: if (n < 0) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Trying to destroy negative number of matrices %D",n);
6794: for (i=0; i<n; i++) {
6795: MatDestroy(&(*mat)[i]);
6796: }
6798: /* memory is allocated even if n = 0 */
6799: PetscFree(*mat);
6800: return(0);
6801: }
6803: /*@C
6804: MatDestroySubMatrices - Destroys a set of matrices obtained with MatCreateSubMatrices().
6806: Collective on Mat
6808: Input Parameters:
6809: + n - the number of local matrices
6810: - mat - the matrices (note that this is a pointer to the array of matrices, just to match the calling
6811: sequence of MatCreateSubMatrices())
6813: Level: advanced
6815: Notes:
6816: Frees not only the matrices, but also the array that contains the matrices
6817: In Fortran will not free the array.
6819: .seealso: MatCreateSubMatrices()
6820: @*/
6821: PetscErrorCode MatDestroySubMatrices(PetscInt n,Mat *mat[])
6822: {
6824: Mat mat0;
6827: if (!*mat) return(0);
6828: /* mat[] is an array of length n+1, see MatCreateSubMatrices_xxx() */
6829: if (n < 0) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Trying to destroy negative number of matrices %D",n);
6832: mat0 = (*mat)[0];
6833: if (mat0 && mat0->ops->destroysubmatrices) {
6834: (mat0->ops->destroysubmatrices)(n,mat);
6835: } else {
6836: MatDestroyMatrices(n,mat);
6837: }
6838: return(0);
6839: }
6841: /*@C
6842: MatGetSeqNonzeroStructure - Extracts the sequential nonzero structure from a matrix.
6844: Collective on Mat
6846: Input Parameters:
6847: . mat - the matrix
6849: Output Parameter:
6850: . matstruct - the sequential matrix with the nonzero structure of mat
6852: Level: intermediate
6854: .seealso: MatDestroySeqNonzeroStructure(), MatCreateSubMatrices(), MatDestroyMatrices()
6855: @*/
6856: PetscErrorCode MatGetSeqNonzeroStructure(Mat mat,Mat *matstruct)
6857: {
6865: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6866: MatCheckPreallocated(mat,1);
6868: if (!mat->ops->getseqnonzerostructure) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Not for matrix type %s\n",((PetscObject)mat)->type_name);
6869: PetscLogEventBegin(MAT_GetSeqNonzeroStructure,mat,0,0,0);
6870: (*mat->ops->getseqnonzerostructure)(mat,matstruct);
6871: PetscLogEventEnd(MAT_GetSeqNonzeroStructure,mat,0,0,0);
6872: return(0);
6873: }
6875: /*@C
6876: MatDestroySeqNonzeroStructure - Destroys matrix obtained with MatGetSeqNonzeroStructure().
6878: Collective on Mat
6880: Input Parameters:
6881: . mat - the matrix (note that this is a pointer to the array of matrices, just to match the calling
6882: sequence of MatGetSequentialNonzeroStructure())
6884: Level: advanced
6886: Notes:
6887: Frees not only the matrices, but also the array that contains the matrices
6889: .seealso: MatGetSeqNonzeroStructure()
6890: @*/
6891: PetscErrorCode MatDestroySeqNonzeroStructure(Mat *mat)
6892: {
6897: MatDestroy(mat);
6898: return(0);
6899: }
6901: /*@
6902: MatIncreaseOverlap - Given a set of submatrices indicated by index sets,
6903: replaces the index sets by larger ones that represent submatrices with
6904: additional overlap.
6906: Collective on Mat
6908: Input Parameters:
6909: + mat - the matrix
6910: . n - the number of index sets
6911: . is - the array of index sets (these index sets will changed during the call)
6912: - ov - the additional overlap requested
6914: Options Database:
6915: . -mat_increase_overlap_scalable - use a scalable algorithm to compute the overlap (supported by MPIAIJ matrix)
6917: Level: developer
6920: .seealso: MatCreateSubMatrices()
6921: @*/
6922: PetscErrorCode MatIncreaseOverlap(Mat mat,PetscInt n,IS is[],PetscInt ov)
6923: {
6929: if (n < 0) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Must have one or more domains, you have %D",n);
6930: if (n) {
6933: }
6934: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6935: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6936: MatCheckPreallocated(mat,1);
6938: if (!ov) return(0);
6939: if (!mat->ops->increaseoverlap) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
6940: PetscLogEventBegin(MAT_IncreaseOverlap,mat,0,0,0);
6941: (*mat->ops->increaseoverlap)(mat,n,is,ov);
6942: PetscLogEventEnd(MAT_IncreaseOverlap,mat,0,0,0);
6943: return(0);
6944: }
6947: PetscErrorCode MatIncreaseOverlapSplit_Single(Mat,IS*,PetscInt);
6949: /*@
6950: MatIncreaseOverlapSplit - Given a set of submatrices indicated by index sets across
6951: a sub communicator, replaces the index sets by larger ones that represent submatrices with
6952: additional overlap.
6954: Collective on Mat
6956: Input Parameters:
6957: + mat - the matrix
6958: . n - the number of index sets
6959: . is - the array of index sets (these index sets will changed during the call)
6960: - ov - the additional overlap requested
6962: Options Database:
6963: . -mat_increase_overlap_scalable - use a scalable algorithm to compute the overlap (supported by MPIAIJ matrix)
6965: Level: developer
6968: .seealso: MatCreateSubMatrices()
6969: @*/
6970: PetscErrorCode MatIncreaseOverlapSplit(Mat mat,PetscInt n,IS is[],PetscInt ov)
6971: {
6972: PetscInt i;
6978: if (n < 0) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Must have one or more domains, you have %D",n);
6979: if (n) {
6982: }
6983: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6984: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6985: MatCheckPreallocated(mat,1);
6986: if (!ov) return(0);
6987: PetscLogEventBegin(MAT_IncreaseOverlap,mat,0,0,0);
6988: for(i=0; i<n; i++){
6989: MatIncreaseOverlapSplit_Single(mat,&is[i],ov);
6990: }
6991: PetscLogEventEnd(MAT_IncreaseOverlap,mat,0,0,0);
6992: return(0);
6993: }
6998: /*@
6999: MatGetBlockSize - Returns the matrix block size.
7001: Not Collective
7003: Input Parameter:
7004: . mat - the matrix
7006: Output Parameter:
7007: . bs - block size
7009: Notes:
7010: Block row formats are MATSEQBAIJ, MATMPIBAIJ, MATSEQSBAIJ, MATMPISBAIJ. These formats ALWAYS have square block storage in the matrix.
7012: If the block size has not been set yet this routine returns 1.
7014: Level: intermediate
7016: .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSizes()
7017: @*/
7018: PetscErrorCode MatGetBlockSize(Mat mat,PetscInt *bs)
7019: {
7023: *bs = PetscAbs(mat->rmap->bs);
7024: return(0);
7025: }
7027: /*@
7028: MatGetBlockSizes - Returns the matrix block row and column sizes.
7030: Not Collective
7032: Input Parameter:
7033: . mat - the matrix
7035: Output Parameter:
7036: + rbs - row block size
7037: - cbs - column block size
7039: Notes:
7040: Block row formats are MATSEQBAIJ, MATMPIBAIJ, MATSEQSBAIJ, MATMPISBAIJ. These formats ALWAYS have square block storage in the matrix.
7041: If you pass a different block size for the columns than the rows, the row block size determines the square block storage.
7043: If a block size has not been set yet this routine returns 1.
7045: Level: intermediate
7047: .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSize(), MatSetBlockSize(), MatSetBlockSizes()
7048: @*/
7049: PetscErrorCode MatGetBlockSizes(Mat mat,PetscInt *rbs, PetscInt *cbs)
7050: {
7055: if (rbs) *rbs = PetscAbs(mat->rmap->bs);
7056: if (cbs) *cbs = PetscAbs(mat->cmap->bs);
7057: return(0);
7058: }
7060: /*@
7061: MatSetBlockSize - Sets the matrix block size.
7063: Logically Collective on Mat
7065: Input Parameters:
7066: + mat - the matrix
7067: - bs - block size
7069: Notes:
7070: Block row formats are MATSEQBAIJ, MATMPIBAIJ, MATSEQSBAIJ, MATMPISBAIJ. These formats ALWAYS have square block storage in the matrix.
7071: This must be called before MatSetUp() or MatXXXSetPreallocation() (or will default to 1) and the block size cannot be changed later.
7073: For MATMPIAIJ and MATSEQAIJ matrix formats, this function can be called at a later stage, provided that the specified block size
7074: is compatible with the matrix local sizes.
7076: Level: intermediate
7078: .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSize(), MatSetBlockSizes(), MatGetBlockSizes()
7079: @*/
7080: PetscErrorCode MatSetBlockSize(Mat mat,PetscInt bs)
7081: {
7087: MatSetBlockSizes(mat,bs,bs);
7088: return(0);
7089: }
7091: /*@
7092: MatSetVariableBlockSizes - Sets a diagonal blocks of the matrix that need not be of the same size
7094: Logically Collective on Mat
7096: Input Parameters:
7097: + mat - the matrix
7098: . nblocks - the number of blocks on this process
7099: - bsizes - the block sizes
7101: Notes:
7102: Currently used by PCVPBJACOBI for SeqAIJ matrices
7104: Level: intermediate
7106: .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSize(), MatSetBlockSizes(), MatGetBlockSizes(), MatGetVariableBlockSizes()
7107: @*/
7108: PetscErrorCode MatSetVariableBlockSizes(Mat mat,PetscInt nblocks,PetscInt *bsizes)
7109: {
7111: PetscInt i,ncnt = 0, nlocal;
7115: if (nblocks < 0) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Number of local blocks must be great than or equal to zero");
7116: MatGetLocalSize(mat,&nlocal,NULL);
7117: for (i=0; i<nblocks; i++) ncnt += bsizes[i];
7118: 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);
7119: PetscFree(mat->bsizes);
7120: mat->nblocks = nblocks;
7121: PetscMalloc1(nblocks,&mat->bsizes);
7122: PetscArraycpy(mat->bsizes,bsizes,nblocks);
7123: return(0);
7124: }
7126: /*@C
7127: MatGetVariableBlockSizes - Gets a diagonal blocks of the matrix that need not be of the same size
7129: Logically Collective on Mat
7131: Input Parameters:
7132: . mat - the matrix
7134: Output Parameters:
7135: + nblocks - the number of blocks on this process
7136: - bsizes - the block sizes
7138: Notes: Currently not supported from Fortran
7140: Level: intermediate
7142: .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSize(), MatSetBlockSizes(), MatGetBlockSizes(), MatSetVariableBlockSizes()
7143: @*/
7144: PetscErrorCode MatGetVariableBlockSizes(Mat mat,PetscInt *nblocks,const PetscInt **bsizes)
7145: {
7148: *nblocks = mat->nblocks;
7149: *bsizes = mat->bsizes;
7150: return(0);
7151: }
7153: /*@
7154: MatSetBlockSizes - Sets the matrix block row and column sizes.
7156: Logically Collective on Mat
7158: Input Parameters:
7159: + mat - the matrix
7160: - rbs - row block size
7161: - cbs - column block size
7163: Notes:
7164: Block row formats are MATSEQBAIJ, MATMPIBAIJ, MATSEQSBAIJ, MATMPISBAIJ. These formats ALWAYS have square block storage in the matrix.
7165: If you pass a different block size for the columns than the rows, the row block size determines the square block storage.
7166: This must be called before MatSetUp() or MatXXXSetPreallocation() (or will default to 1) and the block size cannot be changed later
7168: For MATMPIAIJ and MATSEQAIJ matrix formats, this function can be called at a later stage, provided that the specified block sizes
7169: are compatible with the matrix local sizes.
7171: The row and column block size determine the blocksize of the "row" and "column" vectors returned by MatCreateVecs().
7173: Level: intermediate
7175: .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSize(), MatSetBlockSize(), MatGetBlockSizes()
7176: @*/
7177: PetscErrorCode MatSetBlockSizes(Mat mat,PetscInt rbs,PetscInt cbs)
7178: {
7185: if (mat->ops->setblocksizes) {
7186: (*mat->ops->setblocksizes)(mat,rbs,cbs);
7187: }
7188: if (mat->rmap->refcnt) {
7189: ISLocalToGlobalMapping l2g = NULL;
7190: PetscLayout nmap = NULL;
7192: PetscLayoutDuplicate(mat->rmap,&nmap);
7193: if (mat->rmap->mapping) {
7194: ISLocalToGlobalMappingDuplicate(mat->rmap->mapping,&l2g);
7195: }
7196: PetscLayoutDestroy(&mat->rmap);
7197: mat->rmap = nmap;
7198: mat->rmap->mapping = l2g;
7199: }
7200: if (mat->cmap->refcnt) {
7201: ISLocalToGlobalMapping l2g = NULL;
7202: PetscLayout nmap = NULL;
7204: PetscLayoutDuplicate(mat->cmap,&nmap);
7205: if (mat->cmap->mapping) {
7206: ISLocalToGlobalMappingDuplicate(mat->cmap->mapping,&l2g);
7207: }
7208: PetscLayoutDestroy(&mat->cmap);
7209: mat->cmap = nmap;
7210: mat->cmap->mapping = l2g;
7211: }
7212: PetscLayoutSetBlockSize(mat->rmap,rbs);
7213: PetscLayoutSetBlockSize(mat->cmap,cbs);
7214: return(0);
7215: }
7217: /*@
7218: MatSetBlockSizesFromMats - Sets the matrix block row and column sizes to match a pair of matrices
7220: Logically Collective on Mat
7222: Input Parameters:
7223: + mat - the matrix
7224: . fromRow - matrix from which to copy row block size
7225: - fromCol - matrix from which to copy column block size (can be same as fromRow)
7227: Level: developer
7229: .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSize(), MatSetBlockSizes()
7230: @*/
7231: PetscErrorCode MatSetBlockSizesFromMats(Mat mat,Mat fromRow,Mat fromCol)
7232: {
7239: if (fromRow->rmap->bs > 0) {PetscLayoutSetBlockSize(mat->rmap,fromRow->rmap->bs);}
7240: if (fromCol->cmap->bs > 0) {PetscLayoutSetBlockSize(mat->cmap,fromCol->cmap->bs);}
7241: return(0);
7242: }
7244: /*@
7245: MatResidual - Default routine to calculate the residual.
7247: Collective on Mat
7249: Input Parameters:
7250: + mat - the matrix
7251: . b - the right-hand-side
7252: - x - the approximate solution
7254: Output Parameter:
7255: . r - location to store the residual
7257: Level: developer
7259: .seealso: PCMGSetResidual()
7260: @*/
7261: PetscErrorCode MatResidual(Mat mat,Vec b,Vec x,Vec r)
7262: {
7271: MatCheckPreallocated(mat,1);
7272: PetscLogEventBegin(MAT_Residual,mat,0,0,0);
7273: if (!mat->ops->residual) {
7274: MatMult(mat,x,r);
7275: VecAYPX(r,-1.0,b);
7276: } else {
7277: (*mat->ops->residual)(mat,b,x,r);
7278: }
7279: PetscLogEventEnd(MAT_Residual,mat,0,0,0);
7280: return(0);
7281: }
7283: /*@C
7284: MatGetRowIJ - Returns the compressed row storage i and j indices for sequential matrices.
7286: Collective on Mat
7288: Input Parameters:
7289: + mat - the matrix
7290: . shift - 0 or 1 indicating we want the indices starting at 0 or 1
7291: . symmetric - PETSC_TRUE or PETSC_FALSE indicating the matrix data structure should be symmetrized
7292: - inodecompressed - PETSC_TRUE or PETSC_FALSE indicating if the nonzero structure of the
7293: inodes or the nonzero elements is wanted. For BAIJ matrices the compressed version is
7294: always used.
7296: Output Parameters:
7297: + n - number of rows in the (possibly compressed) matrix
7298: . ia - the row pointers; that is ia[0] = 0, ia[row] = ia[row-1] + number of elements in that row of the matrix
7299: . ja - the column indices
7300: - done - indicates if the routine actually worked and returned appropriate ia[] and ja[] arrays; callers
7301: are responsible for handling the case when done == PETSC_FALSE and ia and ja are not set
7303: Level: developer
7305: Notes:
7306: You CANNOT change any of the ia[] or ja[] values.
7308: Use MatRestoreRowIJ() when you are finished accessing the ia[] and ja[] values.
7310: Fortran Notes:
7311: In Fortran use
7312: $
7313: $ PetscInt ia(1), ja(1)
7314: $ PetscOffset iia, jja
7315: $ call MatGetRowIJ(mat,shift,symmetric,inodecompressed,n,ia,iia,ja,jja,done,ierr)
7316: $ ! Access the ith and jth entries via ia(iia + i) and ja(jja + j)
7318: or
7319: $
7320: $ PetscInt, pointer :: ia(:),ja(:)
7321: $ call MatGetRowIJF90(mat,shift,symmetric,inodecompressed,n,ia,ja,done,ierr)
7322: $ ! Access the ith and jth entries via ia(i) and ja(j)
7324: .seealso: MatGetColumnIJ(), MatRestoreRowIJ(), MatSeqAIJGetArray()
7325: @*/
7326: PetscErrorCode MatGetRowIJ(Mat mat,PetscInt shift,PetscBool symmetric,PetscBool inodecompressed,PetscInt *n,const PetscInt *ia[],const PetscInt *ja[],PetscBool *done)
7327: {
7337: MatCheckPreallocated(mat,1);
7338: if (!mat->ops->getrowij) *done = PETSC_FALSE;
7339: else {
7340: *done = PETSC_TRUE;
7341: PetscLogEventBegin(MAT_GetRowIJ,mat,0,0,0);
7342: (*mat->ops->getrowij)(mat,shift,symmetric,inodecompressed,n,ia,ja,done);
7343: PetscLogEventEnd(MAT_GetRowIJ,mat,0,0,0);
7344: }
7345: return(0);
7346: }
7348: /*@C
7349: MatGetColumnIJ - Returns the compressed column storage i and j indices for sequential matrices.
7351: Collective on Mat
7353: Input Parameters:
7354: + mat - the matrix
7355: . shift - 1 or zero indicating we want the indices starting at 0 or 1
7356: . symmetric - PETSC_TRUE or PETSC_FALSE indicating the matrix data structure should be
7357: symmetrized
7358: . inodecompressed - PETSC_TRUE or PETSC_FALSE indicating if the nonzero structure of the
7359: inodes or the nonzero elements is wanted. For BAIJ matrices the compressed version is
7360: always used.
7361: . n - number of columns in the (possibly compressed) matrix
7362: . ia - the column pointers; that is ia[0] = 0, ia[col] = i[col-1] + number of elements in that col of the matrix
7363: - ja - the row indices
7365: Output Parameters:
7366: . done - PETSC_TRUE or PETSC_FALSE, indicating whether the values have been returned
7368: Level: developer
7370: .seealso: MatGetRowIJ(), MatRestoreColumnIJ()
7371: @*/
7372: PetscErrorCode MatGetColumnIJ(Mat mat,PetscInt shift,PetscBool symmetric,PetscBool inodecompressed,PetscInt *n,const PetscInt *ia[],const PetscInt *ja[],PetscBool *done)
7373: {
7383: MatCheckPreallocated(mat,1);
7384: if (!mat->ops->getcolumnij) *done = PETSC_FALSE;
7385: else {
7386: *done = PETSC_TRUE;
7387: (*mat->ops->getcolumnij)(mat,shift,symmetric,inodecompressed,n,ia,ja,done);
7388: }
7389: return(0);
7390: }
7392: /*@C
7393: MatRestoreRowIJ - Call after you are completed with the ia,ja indices obtained with
7394: MatGetRowIJ().
7396: Collective on Mat
7398: Input Parameters:
7399: + mat - the matrix
7400: . shift - 1 or zero indicating we want the indices starting at 0 or 1
7401: . symmetric - PETSC_TRUE or PETSC_FALSE indicating the matrix data structure should be
7402: symmetrized
7403: . inodecompressed - PETSC_TRUE or PETSC_FALSE indicating if the nonzero structure of the
7404: inodes or the nonzero elements is wanted. For BAIJ matrices the compressed version is
7405: always used.
7406: . n - size of (possibly compressed) matrix
7407: . ia - the row pointers
7408: - ja - the column indices
7410: Output Parameters:
7411: . done - PETSC_TRUE or PETSC_FALSE indicated that the values have been returned
7413: Note:
7414: This routine zeros out n, ia, and ja. This is to prevent accidental
7415: us of the array after it has been restored. If you pass NULL, it will
7416: not zero the pointers. Use of ia or ja after MatRestoreRowIJ() is invalid.
7418: Level: developer
7420: .seealso: MatGetRowIJ(), MatRestoreColumnIJ()
7421: @*/
7422: PetscErrorCode MatRestoreRowIJ(Mat mat,PetscInt shift,PetscBool symmetric,PetscBool inodecompressed,PetscInt *n,const PetscInt *ia[],const PetscInt *ja[],PetscBool *done)
7423: {
7432: MatCheckPreallocated(mat,1);
7434: if (!mat->ops->restorerowij) *done = PETSC_FALSE;
7435: else {
7436: *done = PETSC_TRUE;
7437: (*mat->ops->restorerowij)(mat,shift,symmetric,inodecompressed,n,ia,ja,done);
7438: if (n) *n = 0;
7439: if (ia) *ia = NULL;
7440: if (ja) *ja = NULL;
7441: }
7442: return(0);
7443: }
7445: /*@C
7446: MatRestoreColumnIJ - Call after you are completed with the ia,ja indices obtained with
7447: MatGetColumnIJ().
7449: Collective on Mat
7451: Input Parameters:
7452: + mat - the matrix
7453: . shift - 1 or zero indicating we want the indices starting at 0 or 1
7454: - symmetric - PETSC_TRUE or PETSC_FALSE indicating the matrix data structure should be
7455: symmetrized
7456: - inodecompressed - PETSC_TRUE or PETSC_FALSE indicating if the nonzero structure of the
7457: inodes or the nonzero elements is wanted. For BAIJ matrices the compressed version is
7458: always used.
7460: Output Parameters:
7461: + n - size of (possibly compressed) matrix
7462: . ia - the column pointers
7463: . ja - the row indices
7464: - done - PETSC_TRUE or PETSC_FALSE indicated that the values have been returned
7466: Level: developer
7468: .seealso: MatGetColumnIJ(), MatRestoreRowIJ()
7469: @*/
7470: PetscErrorCode MatRestoreColumnIJ(Mat mat,PetscInt shift,PetscBool symmetric,PetscBool inodecompressed,PetscInt *n,const PetscInt *ia[],const PetscInt *ja[],PetscBool *done)
7471: {
7480: MatCheckPreallocated(mat,1);
7482: if (!mat->ops->restorecolumnij) *done = PETSC_FALSE;
7483: else {
7484: *done = PETSC_TRUE;
7485: (*mat->ops->restorecolumnij)(mat,shift,symmetric,inodecompressed,n,ia,ja,done);
7486: if (n) *n = 0;
7487: if (ia) *ia = NULL;
7488: if (ja) *ja = NULL;
7489: }
7490: return(0);
7491: }
7493: /*@C
7494: MatColoringPatch -Used inside matrix coloring routines that
7495: use MatGetRowIJ() and/or MatGetColumnIJ().
7497: Collective on Mat
7499: Input Parameters:
7500: + mat - the matrix
7501: . ncolors - max color value
7502: . n - number of entries in colorarray
7503: - colorarray - array indicating color for each column
7505: Output Parameters:
7506: . iscoloring - coloring generated using colorarray information
7508: Level: developer
7510: .seealso: MatGetRowIJ(), MatGetColumnIJ()
7512: @*/
7513: PetscErrorCode MatColoringPatch(Mat mat,PetscInt ncolors,PetscInt n,ISColoringValue colorarray[],ISColoring *iscoloring)
7514: {
7522: MatCheckPreallocated(mat,1);
7524: if (!mat->ops->coloringpatch) {
7525: ISColoringCreate(PetscObjectComm((PetscObject)mat),ncolors,n,colorarray,PETSC_OWN_POINTER,iscoloring);
7526: } else {
7527: (*mat->ops->coloringpatch)(mat,ncolors,n,colorarray,iscoloring);
7528: }
7529: return(0);
7530: }
7533: /*@
7534: MatSetUnfactored - Resets a factored matrix to be treated as unfactored.
7536: Logically Collective on Mat
7538: Input Parameter:
7539: . mat - the factored matrix to be reset
7541: Notes:
7542: This routine should be used only with factored matrices formed by in-place
7543: factorization via ILU(0) (or by in-place LU factorization for the MATSEQDENSE
7544: format). This option can save memory, for example, when solving nonlinear
7545: systems with a matrix-free Newton-Krylov method and a matrix-based, in-place
7546: ILU(0) preconditioner.
7548: Note that one can specify in-place ILU(0) factorization by calling
7549: .vb
7550: PCType(pc,PCILU);
7551: PCFactorSeUseInPlace(pc);
7552: .ve
7553: or by using the options -pc_type ilu -pc_factor_in_place
7555: In-place factorization ILU(0) can also be used as a local
7556: solver for the blocks within the block Jacobi or additive Schwarz
7557: methods (runtime option: -sub_pc_factor_in_place). See Users-Manual: ch_pc
7558: for details on setting local solver options.
7560: Most users should employ the simplified KSP interface for linear solvers
7561: instead of working directly with matrix algebra routines such as this.
7562: See, e.g., KSPCreate().
7564: Level: developer
7566: .seealso: PCFactorSetUseInPlace(), PCFactorGetUseInPlace()
7568: @*/
7569: PetscErrorCode MatSetUnfactored(Mat mat)
7570: {
7576: MatCheckPreallocated(mat,1);
7577: mat->factortype = MAT_FACTOR_NONE;
7578: if (!mat->ops->setunfactored) return(0);
7579: (*mat->ops->setunfactored)(mat);
7580: return(0);
7581: }
7583: /*MC
7584: MatDenseGetArrayF90 - Accesses a matrix array from Fortran90.
7586: Synopsis:
7587: MatDenseGetArrayF90(Mat x,{Scalar, pointer :: xx_v(:,:)},integer ierr)
7589: Not collective
7591: Input Parameter:
7592: . x - matrix
7594: Output Parameters:
7595: + xx_v - the Fortran90 pointer to the array
7596: - ierr - error code
7598: Example of Usage:
7599: .vb
7600: PetscScalar, pointer xx_v(:,:)
7601: ....
7602: call MatDenseGetArrayF90(x,xx_v,ierr)
7603: a = xx_v(3)
7604: call MatDenseRestoreArrayF90(x,xx_v,ierr)
7605: .ve
7607: Level: advanced
7609: .seealso: MatDenseRestoreArrayF90(), MatDenseGetArray(), MatDenseRestoreArray(), MatSeqAIJGetArrayF90()
7611: M*/
7613: /*MC
7614: MatDenseRestoreArrayF90 - Restores a matrix array that has been
7615: accessed with MatDenseGetArrayF90().
7617: Synopsis:
7618: MatDenseRestoreArrayF90(Mat x,{Scalar, pointer :: xx_v(:,:)},integer ierr)
7620: Not collective
7622: Input Parameters:
7623: + x - matrix
7624: - xx_v - the Fortran90 pointer to the array
7626: Output Parameter:
7627: . ierr - error code
7629: Example of Usage:
7630: .vb
7631: PetscScalar, pointer xx_v(:,:)
7632: ....
7633: call MatDenseGetArrayF90(x,xx_v,ierr)
7634: a = xx_v(3)
7635: call MatDenseRestoreArrayF90(x,xx_v,ierr)
7636: .ve
7638: Level: advanced
7640: .seealso: MatDenseGetArrayF90(), MatDenseGetArray(), MatDenseRestoreArray(), MatSeqAIJRestoreArrayF90()
7642: M*/
7645: /*MC
7646: MatSeqAIJGetArrayF90 - Accesses a matrix array from Fortran90.
7648: Synopsis:
7649: MatSeqAIJGetArrayF90(Mat x,{Scalar, pointer :: xx_v(:)},integer ierr)
7651: Not collective
7653: Input Parameter:
7654: . x - matrix
7656: Output Parameters:
7657: + xx_v - the Fortran90 pointer to the array
7658: - ierr - error code
7660: Example of Usage:
7661: .vb
7662: PetscScalar, pointer xx_v(:)
7663: ....
7664: call MatSeqAIJGetArrayF90(x,xx_v,ierr)
7665: a = xx_v(3)
7666: call MatSeqAIJRestoreArrayF90(x,xx_v,ierr)
7667: .ve
7669: Level: advanced
7671: .seealso: MatSeqAIJRestoreArrayF90(), MatSeqAIJGetArray(), MatSeqAIJRestoreArray(), MatDenseGetArrayF90()
7673: M*/
7675: /*MC
7676: MatSeqAIJRestoreArrayF90 - Restores a matrix array that has been
7677: accessed with MatSeqAIJGetArrayF90().
7679: Synopsis:
7680: MatSeqAIJRestoreArrayF90(Mat x,{Scalar, pointer :: xx_v(:)},integer ierr)
7682: Not collective
7684: Input Parameters:
7685: + x - matrix
7686: - xx_v - the Fortran90 pointer to the array
7688: Output Parameter:
7689: . ierr - error code
7691: Example of Usage:
7692: .vb
7693: PetscScalar, pointer xx_v(:)
7694: ....
7695: call MatSeqAIJGetArrayF90(x,xx_v,ierr)
7696: a = xx_v(3)
7697: call MatSeqAIJRestoreArrayF90(x,xx_v,ierr)
7698: .ve
7700: Level: advanced
7702: .seealso: MatSeqAIJGetArrayF90(), MatSeqAIJGetArray(), MatSeqAIJRestoreArray(), MatDenseRestoreArrayF90()
7704: M*/
7707: /*@
7708: MatCreateSubMatrix - Gets a single submatrix on the same number of processors
7709: as the original matrix.
7711: Collective on Mat
7713: Input Parameters:
7714: + mat - the original matrix
7715: . isrow - parallel IS containing the rows this processor should obtain
7716: . 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.
7717: - cll - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
7719: Output Parameter:
7720: . newmat - the new submatrix, of the same type as the old
7722: Level: advanced
7724: Notes:
7725: The submatrix will be able to be multiplied with vectors using the same layout as iscol.
7727: Some matrix types place restrictions on the row and column indices, such
7728: as that they be sorted or that they be equal to each other.
7730: The index sets may not have duplicate entries.
7732: The first time this is called you should use a cll of MAT_INITIAL_MATRIX,
7733: the MatCreateSubMatrix() routine will create the newmat for you. Any additional calls
7734: to this routine with a mat of the same nonzero structure and with a call of MAT_REUSE_MATRIX
7735: will reuse the matrix generated the first time. You should call MatDestroy() on newmat when
7736: you are finished using it.
7738: The communicator of the newly obtained matrix is ALWAYS the same as the communicator of
7739: the input matrix.
7741: If iscol is NULL then all columns are obtained (not supported in Fortran).
7743: Example usage:
7744: Consider the following 8x8 matrix with 34 non-zero values, that is
7745: assembled across 3 processors. Let's assume that proc0 owns 3 rows,
7746: proc1 owns 3 rows, proc2 owns 2 rows. This division can be shown
7747: as follows:
7749: .vb
7750: 1 2 0 | 0 3 0 | 0 4
7751: Proc0 0 5 6 | 7 0 0 | 8 0
7752: 9 0 10 | 11 0 0 | 12 0
7753: -------------------------------------
7754: 13 0 14 | 15 16 17 | 0 0
7755: Proc1 0 18 0 | 19 20 21 | 0 0
7756: 0 0 0 | 22 23 0 | 24 0
7757: -------------------------------------
7758: Proc2 25 26 27 | 0 0 28 | 29 0
7759: 30 0 0 | 31 32 33 | 0 34
7760: .ve
7762: Suppose isrow = [0 1 | 4 | 6 7] and iscol = [1 2 | 3 4 5 | 6]. The resulting submatrix is
7764: .vb
7765: 2 0 | 0 3 0 | 0
7766: Proc0 5 6 | 7 0 0 | 8
7767: -------------------------------
7768: Proc1 18 0 | 19 20 21 | 0
7769: -------------------------------
7770: Proc2 26 27 | 0 0 28 | 29
7771: 0 0 | 31 32 33 | 0
7772: .ve
7775: .seealso: MatCreateSubMatrices(), MatCreateSubMatricesMPI(), MatCreateSubMatrixVirtual(), MatSubMatrixVirtualUpdate()
7776: @*/
7777: PetscErrorCode MatCreateSubMatrix(Mat mat,IS isrow,IS iscol,MatReuse cll,Mat *newmat)
7778: {
7780: PetscMPIInt size;
7781: Mat *local;
7782: IS iscoltmp;
7791: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
7792: if (cll == MAT_IGNORE_MATRIX) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Cannot use MAT_IGNORE_MATRIX");
7794: MatCheckPreallocated(mat,1);
7795: MPI_Comm_size(PetscObjectComm((PetscObject)mat),&size);
7797: if (!iscol || isrow == iscol) {
7798: PetscBool stride;
7799: PetscMPIInt grabentirematrix = 0,grab;
7800: PetscObjectTypeCompare((PetscObject)isrow,ISSTRIDE,&stride);
7801: if (stride) {
7802: PetscInt first,step,n,rstart,rend;
7803: ISStrideGetInfo(isrow,&first,&step);
7804: if (step == 1) {
7805: MatGetOwnershipRange(mat,&rstart,&rend);
7806: if (rstart == first) {
7807: ISGetLocalSize(isrow,&n);
7808: if (n == rend-rstart) {
7809: grabentirematrix = 1;
7810: }
7811: }
7812: }
7813: }
7814: MPIU_Allreduce(&grabentirematrix,&grab,1,MPI_INT,MPI_MIN,PetscObjectComm((PetscObject)mat));
7815: if (grab) {
7816: PetscInfo(mat,"Getting entire matrix as submatrix\n");
7817: if (cll == MAT_INITIAL_MATRIX) {
7818: *newmat = mat;
7819: PetscObjectReference((PetscObject)mat);
7820: }
7821: return(0);
7822: }
7823: }
7825: if (!iscol) {
7826: ISCreateStride(PetscObjectComm((PetscObject)mat),mat->cmap->n,mat->cmap->rstart,1,&iscoltmp);
7827: } else {
7828: iscoltmp = iscol;
7829: }
7831: /* if original matrix is on just one processor then use submatrix generated */
7832: if (mat->ops->createsubmatrices && !mat->ops->createsubmatrix && size == 1 && cll == MAT_REUSE_MATRIX) {
7833: MatCreateSubMatrices(mat,1,&isrow,&iscoltmp,MAT_REUSE_MATRIX,&newmat);
7834: goto setproperties;
7835: } else if (mat->ops->createsubmatrices && !mat->ops->createsubmatrix && size == 1) {
7836: MatCreateSubMatrices(mat,1,&isrow,&iscoltmp,MAT_INITIAL_MATRIX,&local);
7837: *newmat = *local;
7838: PetscFree(local);
7839: goto setproperties;
7840: } else if (!mat->ops->createsubmatrix) {
7841: /* Create a new matrix type that implements the operation using the full matrix */
7842: PetscLogEventBegin(MAT_CreateSubMat,mat,0,0,0);
7843: switch (cll) {
7844: case MAT_INITIAL_MATRIX:
7845: MatCreateSubMatrixVirtual(mat,isrow,iscoltmp,newmat);
7846: break;
7847: case MAT_REUSE_MATRIX:
7848: MatSubMatrixVirtualUpdate(*newmat,mat,isrow,iscoltmp);
7849: break;
7850: default: SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_OUTOFRANGE,"Invalid MatReuse, must be either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX");
7851: }
7852: PetscLogEventEnd(MAT_CreateSubMat,mat,0,0,0);
7853: goto setproperties;
7854: }
7856: if (!mat->ops->createsubmatrix) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
7857: PetscLogEventBegin(MAT_CreateSubMat,mat,0,0,0);
7858: (*mat->ops->createsubmatrix)(mat,isrow,iscoltmp,cll,newmat);
7859: PetscLogEventEnd(MAT_CreateSubMat,mat,0,0,0);
7861: /* Propagate symmetry information for diagonal blocks */
7862: setproperties:
7863: if (isrow == iscoltmp) {
7864: if (mat->symmetric_set && mat->symmetric) {
7865: MatSetOption(*newmat,MAT_SYMMETRIC,PETSC_TRUE);
7866: }
7867: if (mat->structurally_symmetric_set && mat->structurally_symmetric) {
7868: MatSetOption(*newmat,MAT_STRUCTURALLY_SYMMETRIC,PETSC_TRUE);
7869: }
7870: if (mat->hermitian_set && mat->hermitian) {
7871: MatSetOption(*newmat,MAT_HERMITIAN,PETSC_TRUE);
7872: }
7873: if (mat->spd_set && mat->spd) {
7874: MatSetOption(*newmat,MAT_SPD,PETSC_TRUE);
7875: }
7876: }
7878: if (!iscol) {ISDestroy(&iscoltmp);}
7879: if (*newmat && cll == MAT_INITIAL_MATRIX) {PetscObjectStateIncrease((PetscObject)*newmat);}
7880: return(0);
7881: }
7883: /*@
7884: MatStashSetInitialSize - sets the sizes of the matrix stash, that is
7885: used during the assembly process to store values that belong to
7886: other processors.
7888: Not Collective
7890: Input Parameters:
7891: + mat - the matrix
7892: . size - the initial size of the stash.
7893: - bsize - the initial size of the block-stash(if used).
7895: Options Database Keys:
7896: + -matstash_initial_size <size> or <size0,size1,...sizep-1>
7897: - -matstash_block_initial_size <bsize> or <bsize0,bsize1,...bsizep-1>
7899: Level: intermediate
7901: Notes:
7902: The block-stash is used for values set with MatSetValuesBlocked() while
7903: the stash is used for values set with MatSetValues()
7905: Run with the option -info and look for output of the form
7906: MatAssemblyBegin_MPIXXX:Stash has MM entries, uses nn mallocs.
7907: to determine the appropriate value, MM, to use for size and
7908: MatAssemblyBegin_MPIXXX:Block-Stash has BMM entries, uses nn mallocs.
7909: to determine the value, BMM to use for bsize
7912: .seealso: MatAssemblyBegin(), MatAssemblyEnd(), Mat, MatStashGetInfo()
7914: @*/
7915: PetscErrorCode MatStashSetInitialSize(Mat mat,PetscInt size, PetscInt bsize)
7916: {
7922: MatStashSetInitialSize_Private(&mat->stash,size);
7923: MatStashSetInitialSize_Private(&mat->bstash,bsize);
7924: return(0);
7925: }
7927: /*@
7928: MatInterpolateAdd - w = y + A*x or A'*x depending on the shape of
7929: the matrix
7931: Neighbor-wise Collective on Mat
7933: Input Parameters:
7934: + mat - the matrix
7935: . x,y - the vectors
7936: - w - where the result is stored
7938: Level: intermediate
7940: Notes:
7941: w may be the same vector as y.
7943: This allows one to use either the restriction or interpolation (its transpose)
7944: matrix to do the interpolation
7946: .seealso: MatMultAdd(), MatMultTransposeAdd(), MatRestrict()
7948: @*/
7949: PetscErrorCode MatInterpolateAdd(Mat A,Vec x,Vec y,Vec w)
7950: {
7952: PetscInt M,N,Ny;
7960: MatCheckPreallocated(A,1);
7961: MatGetSize(A,&M,&N);
7962: VecGetSize(y,&Ny);
7963: if (M == Ny) {
7964: MatMultAdd(A,x,y,w);
7965: } else {
7966: MatMultTransposeAdd(A,x,y,w);
7967: }
7968: return(0);
7969: }
7971: /*@
7972: MatInterpolate - y = A*x or A'*x depending on the shape of
7973: the matrix
7975: Neighbor-wise Collective on Mat
7977: Input Parameters:
7978: + mat - the matrix
7979: - x,y - the vectors
7981: Level: intermediate
7983: Notes:
7984: This allows one to use either the restriction or interpolation (its transpose)
7985: matrix to do the interpolation
7987: .seealso: MatMultAdd(), MatMultTransposeAdd(), MatRestrict()
7989: @*/
7990: PetscErrorCode MatInterpolate(Mat A,Vec x,Vec y)
7991: {
7993: PetscInt M,N,Ny;
8000: MatCheckPreallocated(A,1);
8001: MatGetSize(A,&M,&N);
8002: VecGetSize(y,&Ny);
8003: if (M == Ny) {
8004: MatMult(A,x,y);
8005: } else {
8006: MatMultTranspose(A,x,y);
8007: }
8008: return(0);
8009: }
8011: /*@
8012: MatRestrict - y = A*x or A'*x
8014: Neighbor-wise Collective on Mat
8016: Input Parameters:
8017: + mat - the matrix
8018: - x,y - the vectors
8020: Level: intermediate
8022: Notes:
8023: This allows one to use either the restriction or interpolation (its transpose)
8024: matrix to do the restriction
8026: .seealso: MatMultAdd(), MatMultTransposeAdd(), MatInterpolate()
8028: @*/
8029: PetscErrorCode MatRestrict(Mat A,Vec x,Vec y)
8030: {
8032: PetscInt M,N,Ny;
8039: MatCheckPreallocated(A,1);
8041: MatGetSize(A,&M,&N);
8042: VecGetSize(y,&Ny);
8043: if (M == Ny) {
8044: MatMult(A,x,y);
8045: } else {
8046: MatMultTranspose(A,x,y);
8047: }
8048: return(0);
8049: }
8051: /*@
8052: MatGetNullSpace - retrieves the null space of a matrix.
8054: Logically Collective on Mat
8056: Input Parameters:
8057: + mat - the matrix
8058: - nullsp - the null space object
8060: Level: developer
8062: .seealso: MatCreate(), MatNullSpaceCreate(), MatSetNearNullSpace(), MatSetNullSpace()
8063: @*/
8064: PetscErrorCode MatGetNullSpace(Mat mat, MatNullSpace *nullsp)
8065: {
8069: *nullsp = (mat->symmetric_set && mat->symmetric && !mat->nullsp) ? mat->transnullsp : mat->nullsp;
8070: return(0);
8071: }
8073: /*@
8074: MatSetNullSpace - attaches a null space to a matrix.
8076: Logically Collective on Mat
8078: Input Parameters:
8079: + mat - the matrix
8080: - nullsp - the null space object
8082: Level: advanced
8084: Notes:
8085: This null space is used by the linear solvers. Overwrites any previous null space that may have been attached
8087: For inconsistent singular systems (linear systems where the right hand side is not in the range of the operator) you also likely should
8088: call MatSetTransposeNullSpace(). This allows the linear system to be solved in a least squares sense.
8090: You can remove the null space by calling this routine with an nullsp of NULL
8093: The fundamental theorem of linear algebra (Gilbert Strang, Introduction to Applied Mathematics, page 72) states that
8094: 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).
8095: 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
8096: 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
8097: 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).
8099: Krylov solvers can produce the minimal norm solution to the least squares problem by utilizing MatNullSpaceRemove().
8101: 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
8102: routine also automatically calls MatSetTransposeNullSpace().
8104: .seealso: MatCreate(), MatNullSpaceCreate(), MatSetNearNullSpace(), MatGetNullSpace(), MatSetTransposeNullSpace(), MatGetTransposeNullSpace(), MatNullSpaceRemove()
8105: @*/
8106: PetscErrorCode MatSetNullSpace(Mat mat,MatNullSpace nullsp)
8107: {
8113: if (nullsp) {PetscObjectReference((PetscObject)nullsp);}
8114: MatNullSpaceDestroy(&mat->nullsp);
8115: mat->nullsp = nullsp;
8116: if (mat->symmetric_set && mat->symmetric) {
8117: MatSetTransposeNullSpace(mat,nullsp);
8118: }
8119: return(0);
8120: }
8122: /*@
8123: MatGetTransposeNullSpace - retrieves the null space of the transpose of a matrix.
8125: Logically Collective on Mat
8127: Input Parameters:
8128: + mat - the matrix
8129: - nullsp - the null space object
8131: Level: developer
8133: .seealso: MatCreate(), MatNullSpaceCreate(), MatSetNearNullSpace(), MatSetTransposeNullSpace(), MatSetNullSpace(), MatGetNullSpace()
8134: @*/
8135: PetscErrorCode MatGetTransposeNullSpace(Mat mat, MatNullSpace *nullsp)
8136: {
8141: *nullsp = (mat->symmetric_set && mat->symmetric && !mat->transnullsp) ? mat->nullsp : mat->transnullsp;
8142: return(0);
8143: }
8145: /*@
8146: MatSetTransposeNullSpace - attaches a null space to a matrix.
8148: Logically Collective on Mat
8150: Input Parameters:
8151: + mat - the matrix
8152: - nullsp - the null space object
8154: Level: advanced
8156: Notes:
8157: 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.
8158: You must also call MatSetNullSpace()
8161: The fundamental theorem of linear algebra (Gilbert Strang, Introduction to Applied Mathematics, page 72) states that
8162: 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).
8163: 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
8164: 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
8165: 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).
8167: Krylov solvers can produce the minimal norm solution to the least squares problem by utilizing MatNullSpaceRemove().
8169: .seealso: MatCreate(), MatNullSpaceCreate(), MatSetNearNullSpace(), MatGetNullSpace(), MatSetNullSpace(), MatGetTransposeNullSpace(), MatNullSpaceRemove()
8170: @*/
8171: PetscErrorCode MatSetTransposeNullSpace(Mat mat,MatNullSpace nullsp)
8172: {
8178: if (nullsp) {PetscObjectReference((PetscObject)nullsp);}
8179: MatNullSpaceDestroy(&mat->transnullsp);
8180: mat->transnullsp = nullsp;
8181: return(0);
8182: }
8184: /*@
8185: MatSetNearNullSpace - attaches a null space to a matrix, which is often the null space (rigid body modes) of the operator without boundary conditions
8186: This null space will be used to provide near null space vectors to a multigrid preconditioner built from this matrix.
8188: Logically Collective on Mat
8190: Input Parameters:
8191: + mat - the matrix
8192: - nullsp - the null space object
8194: Level: advanced
8196: Notes:
8197: Overwrites any previous near null space that may have been attached
8199: You can remove the null space by calling this routine with an nullsp of NULL
8201: .seealso: MatCreate(), MatNullSpaceCreate(), MatSetNullSpace(), MatNullSpaceCreateRigidBody(), MatGetNearNullSpace()
8202: @*/
8203: PetscErrorCode MatSetNearNullSpace(Mat mat,MatNullSpace nullsp)
8204: {
8211: MatCheckPreallocated(mat,1);
8212: if (nullsp) {PetscObjectReference((PetscObject)nullsp);}
8213: MatNullSpaceDestroy(&mat->nearnullsp);
8214: mat->nearnullsp = nullsp;
8215: return(0);
8216: }
8218: /*@
8219: MatGetNearNullSpace -Get null space attached with MatSetNearNullSpace()
8221: Not Collective
8223: Input Parameters:
8224: . mat - the matrix
8226: Output Parameters:
8227: . nullsp - the null space object, NULL if not set
8229: Level: developer
8231: .seealso: MatSetNearNullSpace(), MatGetNullSpace(), MatNullSpaceCreate()
8232: @*/
8233: PetscErrorCode MatGetNearNullSpace(Mat mat,MatNullSpace *nullsp)
8234: {
8239: MatCheckPreallocated(mat,1);
8240: *nullsp = mat->nearnullsp;
8241: return(0);
8242: }
8244: /*@C
8245: MatICCFactor - Performs in-place incomplete Cholesky factorization of matrix.
8247: Collective on Mat
8249: Input Parameters:
8250: + mat - the matrix
8251: . row - row/column permutation
8252: . fill - expected fill factor >= 1.0
8253: - level - level of fill, for ICC(k)
8255: Notes:
8256: Probably really in-place only when level of fill is zero, otherwise allocates
8257: new space to store factored matrix and deletes previous memory.
8259: Most users should employ the simplified KSP interface for linear solvers
8260: instead of working directly with matrix algebra routines such as this.
8261: See, e.g., KSPCreate().
8263: Level: developer
8266: .seealso: MatICCFactorSymbolic(), MatLUFactorNumeric(), MatCholeskyFactor()
8268: Developer Note: fortran interface is not autogenerated as the f90
8269: interface defintion cannot be generated correctly [due to MatFactorInfo]
8271: @*/
8272: PetscErrorCode MatICCFactor(Mat mat,IS row,const MatFactorInfo *info)
8273: {
8281: if (mat->rmap->N != mat->cmap->N) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONG,"matrix must be square");
8282: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
8283: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
8284: if (!mat->ops->iccfactor) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
8285: MatCheckPreallocated(mat,1);
8286: (*mat->ops->iccfactor)(mat,row,info);
8287: PetscObjectStateIncrease((PetscObject)mat);
8288: return(0);
8289: }
8291: /*@
8292: MatDiagonalScaleLocal - Scales columns of a matrix given the scaling values including the
8293: ghosted ones.
8295: Not Collective
8297: Input Parameters:
8298: + mat - the matrix
8299: - diag = the diagonal values, including ghost ones
8301: Level: developer
8303: Notes:
8304: Works only for MPIAIJ and MPIBAIJ matrices
8306: .seealso: MatDiagonalScale()
8307: @*/
8308: PetscErrorCode MatDiagonalScaleLocal(Mat mat,Vec diag)
8309: {
8311: PetscMPIInt size;
8318: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Matrix must be already assembled");
8319: PetscLogEventBegin(MAT_Scale,mat,0,0,0);
8320: MPI_Comm_size(PetscObjectComm((PetscObject)mat),&size);
8321: if (size == 1) {
8322: PetscInt n,m;
8323: VecGetSize(diag,&n);
8324: MatGetSize(mat,0,&m);
8325: if (m == n) {
8326: MatDiagonalScale(mat,0,diag);
8327: } else SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"Only supported for sequential matrices when no ghost points/periodic conditions");
8328: } else {
8329: PetscUseMethod(mat,"MatDiagonalScaleLocal_C",(Mat,Vec),(mat,diag));
8330: }
8331: PetscLogEventEnd(MAT_Scale,mat,0,0,0);
8332: PetscObjectStateIncrease((PetscObject)mat);
8333: return(0);
8334: }
8336: /*@
8337: MatGetInertia - Gets the inertia from a factored matrix
8339: Collective on Mat
8341: Input Parameter:
8342: . mat - the matrix
8344: Output Parameters:
8345: + nneg - number of negative eigenvalues
8346: . nzero - number of zero eigenvalues
8347: - npos - number of positive eigenvalues
8349: Level: advanced
8351: Notes:
8352: Matrix must have been factored by MatCholeskyFactor()
8355: @*/
8356: PetscErrorCode MatGetInertia(Mat mat,PetscInt *nneg,PetscInt *nzero,PetscInt *npos)
8357: {
8363: if (!mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
8364: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Numeric factor mat is not assembled");
8365: if (!mat->ops->getinertia) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
8366: (*mat->ops->getinertia)(mat,nneg,nzero,npos);
8367: return(0);
8368: }
8370: /* ----------------------------------------------------------------*/
8371: /*@C
8372: MatSolves - Solves A x = b, given a factored matrix, for a collection of vectors
8374: Neighbor-wise Collective on Mats
8376: Input Parameters:
8377: + mat - the factored matrix
8378: - b - the right-hand-side vectors
8380: Output Parameter:
8381: . x - the result vectors
8383: Notes:
8384: The vectors b and x cannot be the same. I.e., one cannot
8385: call MatSolves(A,x,x).
8387: Notes:
8388: Most users should employ the simplified KSP interface for linear solvers
8389: instead of working directly with matrix algebra routines such as this.
8390: See, e.g., KSPCreate().
8392: Level: developer
8394: .seealso: MatSolveAdd(), MatSolveTranspose(), MatSolveTransposeAdd(), MatSolve()
8395: @*/
8396: PetscErrorCode MatSolves(Mat mat,Vecs b,Vecs x)
8397: {
8403: if (x == b) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"x and b must be different vectors");
8404: if (!mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
8405: if (!mat->rmap->N && !mat->cmap->N) return(0);
8407: if (!mat->ops->solves) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
8408: MatCheckPreallocated(mat,1);
8409: PetscLogEventBegin(MAT_Solves,mat,0,0,0);
8410: (*mat->ops->solves)(mat,b,x);
8411: PetscLogEventEnd(MAT_Solves,mat,0,0,0);
8412: return(0);
8413: }
8415: /*@
8416: MatIsSymmetric - Test whether a matrix is symmetric
8418: Collective on Mat
8420: Input Parameter:
8421: + A - the matrix to test
8422: - tol - difference between value and its transpose less than this amount counts as equal (use 0.0 for exact transpose)
8424: Output Parameters:
8425: . flg - the result
8427: Notes:
8428: For real numbers MatIsSymmetric() and MatIsHermitian() return identical results
8430: Level: intermediate
8432: .seealso: MatTranspose(), MatIsTranspose(), MatIsHermitian(), MatIsStructurallySymmetric(), MatSetOption(), MatIsSymmetricKnown()
8433: @*/
8434: PetscErrorCode MatIsSymmetric(Mat A,PetscReal tol,PetscBool *flg)
8435: {
8442: if (!A->symmetric_set) {
8443: if (!A->ops->issymmetric) {
8444: MatType mattype;
8445: MatGetType(A,&mattype);
8446: SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Matrix of type <%s> does not support checking for symmetric",mattype);
8447: }
8448: (*A->ops->issymmetric)(A,tol,flg);
8449: if (!tol) {
8450: A->symmetric_set = PETSC_TRUE;
8451: A->symmetric = *flg;
8452: if (A->symmetric) {
8453: A->structurally_symmetric_set = PETSC_TRUE;
8454: A->structurally_symmetric = PETSC_TRUE;
8455: }
8456: }
8457: } else if (A->symmetric) {
8458: *flg = PETSC_TRUE;
8459: } else if (!tol) {
8460: *flg = PETSC_FALSE;
8461: } else {
8462: if (!A->ops->issymmetric) {
8463: MatType mattype;
8464: MatGetType(A,&mattype);
8465: SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Matrix of type <%s> does not support checking for symmetric",mattype);
8466: }
8467: (*A->ops->issymmetric)(A,tol,flg);
8468: }
8469: return(0);
8470: }
8472: /*@
8473: MatIsHermitian - Test whether a matrix is Hermitian
8475: Collective on Mat
8477: Input Parameter:
8478: + A - the matrix to test
8479: - tol - difference between value and its transpose less than this amount counts as equal (use 0.0 for exact Hermitian)
8481: Output Parameters:
8482: . flg - the result
8484: Level: intermediate
8486: .seealso: MatTranspose(), MatIsTranspose(), MatIsHermitian(), MatIsStructurallySymmetric(), MatSetOption(),
8487: MatIsSymmetricKnown(), MatIsSymmetric()
8488: @*/
8489: PetscErrorCode MatIsHermitian(Mat A,PetscReal tol,PetscBool *flg)
8490: {
8497: if (!A->hermitian_set) {
8498: if (!A->ops->ishermitian) {
8499: MatType mattype;
8500: MatGetType(A,&mattype);
8501: SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Matrix of type <%s> does not support checking for hermitian",mattype);
8502: }
8503: (*A->ops->ishermitian)(A,tol,flg);
8504: if (!tol) {
8505: A->hermitian_set = PETSC_TRUE;
8506: A->hermitian = *flg;
8507: if (A->hermitian) {
8508: A->structurally_symmetric_set = PETSC_TRUE;
8509: A->structurally_symmetric = PETSC_TRUE;
8510: }
8511: }
8512: } else if (A->hermitian) {
8513: *flg = PETSC_TRUE;
8514: } else if (!tol) {
8515: *flg = PETSC_FALSE;
8516: } else {
8517: if (!A->ops->ishermitian) {
8518: MatType mattype;
8519: MatGetType(A,&mattype);
8520: SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Matrix of type <%s> does not support checking for hermitian",mattype);
8521: }
8522: (*A->ops->ishermitian)(A,tol,flg);
8523: }
8524: return(0);
8525: }
8527: /*@
8528: MatIsSymmetricKnown - Checks the flag on the matrix to see if it is symmetric.
8530: Not Collective
8532: Input Parameter:
8533: . A - the matrix to check
8535: Output Parameters:
8536: + set - if the symmetric flag is set (this tells you if the next flag is valid)
8537: - flg - the result
8539: Level: advanced
8541: Note: Does not check the matrix values directly, so this may return unknown (set = PETSC_FALSE). Use MatIsSymmetric()
8542: if you want it explicitly checked
8544: .seealso: MatTranspose(), MatIsTranspose(), MatIsHermitian(), MatIsStructurallySymmetric(), MatSetOption(), MatIsSymmetric()
8545: @*/
8546: PetscErrorCode MatIsSymmetricKnown(Mat A,PetscBool *set,PetscBool *flg)
8547: {
8552: if (A->symmetric_set) {
8553: *set = PETSC_TRUE;
8554: *flg = A->symmetric;
8555: } else {
8556: *set = PETSC_FALSE;
8557: }
8558: return(0);
8559: }
8561: /*@
8562: MatIsHermitianKnown - Checks the flag on the matrix to see if it is hermitian.
8564: Not Collective
8566: Input Parameter:
8567: . A - the matrix to check
8569: Output Parameters:
8570: + set - if the hermitian flag is set (this tells you if the next flag is valid)
8571: - flg - the result
8573: Level: advanced
8575: Note: Does not check the matrix values directly, so this may return unknown (set = PETSC_FALSE). Use MatIsHermitian()
8576: if you want it explicitly checked
8578: .seealso: MatTranspose(), MatIsTranspose(), MatIsHermitian(), MatIsStructurallySymmetric(), MatSetOption(), MatIsSymmetric()
8579: @*/
8580: PetscErrorCode MatIsHermitianKnown(Mat A,PetscBool *set,PetscBool *flg)
8581: {
8586: if (A->hermitian_set) {
8587: *set = PETSC_TRUE;
8588: *flg = A->hermitian;
8589: } else {
8590: *set = PETSC_FALSE;
8591: }
8592: return(0);
8593: }
8595: /*@
8596: MatIsStructurallySymmetric - Test whether a matrix is structurally symmetric
8598: Collective on Mat
8600: Input Parameter:
8601: . A - the matrix to test
8603: Output Parameters:
8604: . flg - the result
8606: Level: intermediate
8608: .seealso: MatTranspose(), MatIsTranspose(), MatIsHermitian(), MatIsSymmetric(), MatSetOption()
8609: @*/
8610: PetscErrorCode MatIsStructurallySymmetric(Mat A,PetscBool *flg)
8611: {
8617: if (!A->structurally_symmetric_set) {
8618: if (!A->ops->isstructurallysymmetric) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Matrix does not support checking for structural symmetric");
8619: (*A->ops->isstructurallysymmetric)(A,&A->structurally_symmetric);
8621: A->structurally_symmetric_set = PETSC_TRUE;
8622: }
8623: *flg = A->structurally_symmetric;
8624: return(0);
8625: }
8627: /*@
8628: MatStashGetInfo - Gets how many values are currently in the matrix stash, i.e. need
8629: to be communicated to other processors during the MatAssemblyBegin/End() process
8631: Not collective
8633: Input Parameter:
8634: . vec - the vector
8636: Output Parameters:
8637: + nstash - the size of the stash
8638: . reallocs - the number of additional mallocs incurred.
8639: . bnstash - the size of the block stash
8640: - breallocs - the number of additional mallocs incurred.in the block stash
8642: Level: advanced
8644: .seealso: MatAssemblyBegin(), MatAssemblyEnd(), Mat, MatStashSetInitialSize()
8646: @*/
8647: PetscErrorCode MatStashGetInfo(Mat mat,PetscInt *nstash,PetscInt *reallocs,PetscInt *bnstash,PetscInt *breallocs)
8648: {
8652: MatStashGetInfo_Private(&mat->stash,nstash,reallocs);
8653: MatStashGetInfo_Private(&mat->bstash,bnstash,breallocs);
8654: return(0);
8655: }
8657: /*@C
8658: MatCreateVecs - Get vector(s) compatible with the matrix, i.e. with the same
8659: parallel layout
8661: Collective on Mat
8663: Input Parameter:
8664: . mat - the matrix
8666: Output Parameter:
8667: + right - (optional) vector that the matrix can be multiplied against
8668: - left - (optional) vector that the matrix vector product can be stored in
8670: Notes:
8671: 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().
8673: Notes:
8674: These are new vectors which are not owned by the Mat, they should be destroyed in VecDestroy() when no longer needed
8676: Level: advanced
8678: .seealso: MatCreate(), VecDestroy()
8679: @*/
8680: PetscErrorCode MatCreateVecs(Mat mat,Vec *right,Vec *left)
8681: {
8687: if (mat->ops->getvecs) {
8688: (*mat->ops->getvecs)(mat,right,left);
8689: } else {
8690: PetscInt rbs,cbs;
8691: MatGetBlockSizes(mat,&rbs,&cbs);
8692: if (right) {
8693: if (mat->cmap->n < 0) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"PetscLayout for columns not yet setup");
8694: VecCreate(PetscObjectComm((PetscObject)mat),right);
8695: VecSetSizes(*right,mat->cmap->n,PETSC_DETERMINE);
8696: VecSetBlockSize(*right,cbs);
8697: VecSetType(*right,mat->defaultvectype);
8698: PetscLayoutReference(mat->cmap,&(*right)->map);
8699: }
8700: if (left) {
8701: if (mat->rmap->n < 0) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"PetscLayout for rows not yet setup");
8702: VecCreate(PetscObjectComm((PetscObject)mat),left);
8703: VecSetSizes(*left,mat->rmap->n,PETSC_DETERMINE);
8704: VecSetBlockSize(*left,rbs);
8705: VecSetType(*left,mat->defaultvectype);
8706: PetscLayoutReference(mat->rmap,&(*left)->map);
8707: }
8708: }
8709: return(0);
8710: }
8712: /*@C
8713: MatFactorInfoInitialize - Initializes a MatFactorInfo data structure
8714: with default values.
8716: Not Collective
8718: Input Parameters:
8719: . info - the MatFactorInfo data structure
8722: Notes:
8723: The solvers are generally used through the KSP and PC objects, for example
8724: PCLU, PCILU, PCCHOLESKY, PCICC
8726: Level: developer
8728: .seealso: MatFactorInfo
8730: Developer Note: fortran interface is not autogenerated as the f90
8731: interface defintion cannot be generated correctly [due to MatFactorInfo]
8733: @*/
8735: PetscErrorCode MatFactorInfoInitialize(MatFactorInfo *info)
8736: {
8740: PetscMemzero(info,sizeof(MatFactorInfo));
8741: return(0);
8742: }
8744: /*@
8745: MatFactorSetSchurIS - Set indices corresponding to the Schur complement you wish to have computed
8747: Collective on Mat
8749: Input Parameters:
8750: + mat - the factored matrix
8751: - is - the index set defining the Schur indices (0-based)
8753: Notes:
8754: Call MatFactorSolveSchurComplement() or MatFactorSolveSchurComplementTranspose() after this call to solve a Schur complement system.
8756: You can call MatFactorGetSchurComplement() or MatFactorCreateSchurComplement() after this call.
8758: Level: developer
8760: .seealso: MatGetFactor(), MatFactorGetSchurComplement(), MatFactorRestoreSchurComplement(), MatFactorCreateSchurComplement(), MatFactorSolveSchurComplement(),
8761: MatFactorSolveSchurComplementTranspose(), MatFactorSolveSchurComplement()
8763: @*/
8764: PetscErrorCode MatFactorSetSchurIS(Mat mat,IS is)
8765: {
8766: PetscErrorCode ierr,(*f)(Mat,IS);
8774: if (!mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Only for factored matrix");
8775: PetscObjectQueryFunction((PetscObject)mat,"MatFactorSetSchurIS_C",&f);
8776: 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");
8777: MatDestroy(&mat->schur);
8778: (*f)(mat,is);
8779: if (!mat->schur) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_PLIB,"Schur complement has not been created");
8780: return(0);
8781: }
8783: /*@
8784: MatFactorCreateSchurComplement - Create a Schur complement matrix object using Schur data computed during the factorization step
8786: Logically Collective on Mat
8788: Input Parameters:
8789: + F - the factored matrix obtained by calling MatGetFactor() from PETSc-MUMPS interface
8790: . S - location where to return the Schur complement, can be NULL
8791: - status - the status of the Schur complement matrix, can be NULL
8793: Notes:
8794: You must call MatFactorSetSchurIS() before calling this routine.
8796: The routine provides a copy of the Schur matrix stored within the solver data structures.
8797: The caller must destroy the object when it is no longer needed.
8798: If MatFactorInvertSchurComplement() has been called, the routine gets back the inverse.
8800: 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)
8802: Developer Notes:
8803: The reason this routine exists is because the representation of the Schur complement within the factor matrix may be different than a standard PETSc
8804: matrix representation and we normally do not want to use the time or memory to make a copy as a regular PETSc matrix.
8806: See MatCreateSchurComplement() or MatGetSchurComplement() for ways to create virtual or approximate Schur complements.
8808: Level: advanced
8810: References:
8812: .seealso: MatGetFactor(), MatFactorSetSchurIS(), MatFactorGetSchurComplement(), MatFactorSchurStatus
8813: @*/
8814: PetscErrorCode MatFactorCreateSchurComplement(Mat F,Mat* S,MatFactorSchurStatus* status)
8815: {
8822: if (S) {
8823: PetscErrorCode (*f)(Mat,Mat*);
8825: PetscObjectQueryFunction((PetscObject)F,"MatFactorCreateSchurComplement_C",&f);
8826: if (f) {
8827: (*f)(F,S);
8828: } else {
8829: MatDuplicate(F->schur,MAT_COPY_VALUES,S);
8830: }
8831: }
8832: if (status) *status = F->schur_status;
8833: return(0);
8834: }
8836: /*@
8837: MatFactorGetSchurComplement - Gets access to a Schur complement matrix using the current Schur data within a factored matrix
8839: Logically Collective on Mat
8841: Input Parameters:
8842: + F - the factored matrix obtained by calling MatGetFactor()
8843: . *S - location where to return the Schur complement, can be NULL
8844: - status - the status of the Schur complement matrix, can be NULL
8846: Notes:
8847: You must call MatFactorSetSchurIS() before calling this routine.
8849: Schur complement mode is currently implemented for sequential matrices.
8850: The routine returns a the Schur Complement stored within the data strutures of the solver.
8851: If MatFactorInvertSchurComplement() has previously been called, the returned matrix is actually the inverse of the Schur complement.
8852: The returned matrix should not be destroyed; the caller should call MatFactorRestoreSchurComplement() when the object is no longer needed.
8854: Use MatFactorCreateSchurComplement() to create a copy of the Schur complement matrix that is within a factored matrix
8856: See MatCreateSchurComplement() or MatGetSchurComplement() for ways to create virtual or approximate Schur complements.
8858: Level: advanced
8860: References:
8862: .seealso: MatGetFactor(), MatFactorSetSchurIS(), MatFactorRestoreSchurComplement(), MatFactorCreateSchurComplement(), MatFactorSchurStatus
8863: @*/
8864: PetscErrorCode MatFactorGetSchurComplement(Mat F,Mat* S,MatFactorSchurStatus* status)
8865: {
8870: if (S) *S = F->schur;
8871: if (status) *status = F->schur_status;
8872: return(0);
8873: }
8875: /*@
8876: MatFactorRestoreSchurComplement - Restore the Schur complement matrix object obtained from a call to MatFactorGetSchurComplement
8878: Logically Collective on Mat
8880: Input Parameters:
8881: + F - the factored matrix obtained by calling MatGetFactor()
8882: . *S - location where the Schur complement is stored
8883: - status - the status of the Schur complement matrix (see MatFactorSchurStatus)
8885: Notes:
8887: Level: advanced
8889: References:
8891: .seealso: MatGetFactor(), MatFactorSetSchurIS(), MatFactorRestoreSchurComplement(), MatFactorCreateSchurComplement(), MatFactorSchurStatus
8892: @*/
8893: PetscErrorCode MatFactorRestoreSchurComplement(Mat F,Mat* S,MatFactorSchurStatus status)
8894: {
8899: if (S) {
8901: *S = NULL;
8902: }
8903: F->schur_status = status;
8904: MatFactorUpdateSchurStatus_Private(F);
8905: return(0);
8906: }
8908: /*@
8909: MatFactorSolveSchurComplementTranspose - Solve the transpose of the Schur complement system computed during the factorization step
8911: Logically Collective on Mat
8913: Input Parameters:
8914: + F - the factored matrix obtained by calling MatGetFactor()
8915: . rhs - location where the right hand side of the Schur complement system is stored
8916: - sol - location where the solution of the Schur complement system has to be returned
8918: Notes:
8919: The sizes of the vectors should match the size of the Schur complement
8921: Must be called after MatFactorSetSchurIS()
8923: Level: advanced
8925: References:
8927: .seealso: MatGetFactor(), MatFactorSetSchurIS(), MatFactorSolveSchurComplement()
8928: @*/
8929: PetscErrorCode MatFactorSolveSchurComplementTranspose(Mat F, Vec rhs, Vec sol)
8930: {
8942: MatFactorFactorizeSchurComplement(F);
8943: switch (F->schur_status) {
8944: case MAT_FACTOR_SCHUR_FACTORED:
8945: MatSolveTranspose(F->schur,rhs,sol);
8946: break;
8947: case MAT_FACTOR_SCHUR_INVERTED:
8948: MatMultTranspose(F->schur,rhs,sol);
8949: break;
8950: default:
8951: SETERRQ1(PetscObjectComm((PetscObject)F),PETSC_ERR_SUP,"Unhandled MatFactorSchurStatus %D",F->schur_status);
8952: break;
8953: }
8954: return(0);
8955: }
8957: /*@
8958: MatFactorSolveSchurComplement - Solve the Schur complement system computed during the factorization step
8960: Logically Collective on Mat
8962: Input Parameters:
8963: + F - the factored matrix obtained by calling MatGetFactor()
8964: . rhs - location where the right hand side of the Schur complement system is stored
8965: - sol - location where the solution of the Schur complement system has to be returned
8967: Notes:
8968: The sizes of the vectors should match the size of the Schur complement
8970: Must be called after MatFactorSetSchurIS()
8972: Level: advanced
8974: References:
8976: .seealso: MatGetFactor(), MatFactorSetSchurIS(), MatFactorSolveSchurComplementTranspose()
8977: @*/
8978: PetscErrorCode MatFactorSolveSchurComplement(Mat F, Vec rhs, Vec sol)
8979: {
8991: MatFactorFactorizeSchurComplement(F);
8992: switch (F->schur_status) {
8993: case MAT_FACTOR_SCHUR_FACTORED:
8994: MatSolve(F->schur,rhs,sol);
8995: break;
8996: case MAT_FACTOR_SCHUR_INVERTED:
8997: MatMult(F->schur,rhs,sol);
8998: break;
8999: default:
9000: SETERRQ1(PetscObjectComm((PetscObject)F),PETSC_ERR_SUP,"Unhandled MatFactorSchurStatus %D",F->schur_status);
9001: break;
9002: }
9003: return(0);
9004: }
9006: /*@
9007: MatFactorInvertSchurComplement - Invert the Schur complement matrix computed during the factorization step
9009: Logically Collective on Mat
9011: Input Parameters:
9012: . F - the factored matrix obtained by calling MatGetFactor()
9014: Notes:
9015: Must be called after MatFactorSetSchurIS().
9017: Call MatFactorGetSchurComplement() or MatFactorCreateSchurComplement() AFTER this call to actually compute the inverse and get access to it.
9019: Level: advanced
9021: References:
9023: .seealso: MatGetFactor(), MatFactorSetSchurIS(), MatFactorGetSchurComplement(), MatFactorCreateSchurComplement()
9024: @*/
9025: PetscErrorCode MatFactorInvertSchurComplement(Mat F)
9026: {
9032: if (F->schur_status == MAT_FACTOR_SCHUR_INVERTED) return(0);
9033: MatFactorFactorizeSchurComplement(F);
9034: MatFactorInvertSchurComplement_Private(F);
9035: F->schur_status = MAT_FACTOR_SCHUR_INVERTED;
9036: return(0);
9037: }
9039: /*@
9040: MatFactorFactorizeSchurComplement - Factorize the Schur complement matrix computed during the factorization step
9042: Logically Collective on Mat
9044: Input Parameters:
9045: . F - the factored matrix obtained by calling MatGetFactor()
9047: Notes:
9048: Must be called after MatFactorSetSchurIS().
9050: Level: advanced
9052: References:
9054: .seealso: MatGetFactor(), MatFactorSetSchurIS(), MatFactorInvertSchurComplement()
9055: @*/
9056: PetscErrorCode MatFactorFactorizeSchurComplement(Mat F)
9057: {
9063: if (F->schur_status == MAT_FACTOR_SCHUR_INVERTED || F->schur_status == MAT_FACTOR_SCHUR_FACTORED) return(0);
9064: MatFactorFactorizeSchurComplement_Private(F);
9065: F->schur_status = MAT_FACTOR_SCHUR_FACTORED;
9066: return(0);
9067: }
9069: PetscErrorCode MatPtAP_Basic(Mat A,Mat P,MatReuse scall,PetscReal fill,Mat *C)
9070: {
9071: Mat AP;
9075: PetscInfo2(A,"Mat types %s and %s using basic PtAP\n",((PetscObject)A)->type_name,((PetscObject)P)->type_name);
9076: MatMatMult(A,P,MAT_INITIAL_MATRIX,PETSC_DEFAULT,&AP);
9077: MatTransposeMatMult(P,AP,scall,fill,C);
9078: MatDestroy(&AP);
9079: return(0);
9080: }
9082: /*@
9083: MatPtAP - Creates the matrix product C = P^T * A * P
9085: Neighbor-wise Collective on Mat
9087: Input Parameters:
9088: + A - the matrix
9089: . P - the projection matrix
9090: . scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
9091: - fill - expected fill as ratio of nnz(C)/(nnz(A) + nnz(P)), use PETSC_DEFAULT if you do not have a good estimate
9092: if the result is a dense matrix this is irrelevent
9094: Output Parameters:
9095: . C - the product matrix
9097: Notes:
9098: C will be created and must be destroyed by the user with MatDestroy().
9100: For matrix types without special implementation the function fallbacks to MatMatMult() followed by MatTransposeMatMult().
9102: Level: intermediate
9104: .seealso: MatPtAPSymbolic(), MatPtAPNumeric(), MatMatMult(), MatRARt()
9105: @*/
9106: PetscErrorCode MatPtAP(Mat A,Mat P,MatReuse scall,PetscReal fill,Mat *C)
9107: {
9109: PetscErrorCode (*fA)(Mat,Mat,MatReuse,PetscReal,Mat*);
9110: PetscErrorCode (*fP)(Mat,Mat,MatReuse,PetscReal,Mat*);
9111: PetscErrorCode (*ptap)(Mat,Mat,MatReuse,PetscReal,Mat*)=NULL;
9112: PetscBool sametype;
9117: MatCheckPreallocated(A,1);
9118: if (scall == MAT_INPLACE_MATRIX) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Inplace product not supported");
9119: if (!A->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
9120: if (A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
9123: MatCheckPreallocated(P,2);
9124: if (!P->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
9125: if (P->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
9127: 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);
9128: 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);
9129: if (fill == PETSC_DEFAULT || fill == PETSC_DECIDE) fill = 2.0;
9130: if (fill < 1.0) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Expected fill=%g must be >= 1.0",(double)fill);
9132: if (scall == MAT_REUSE_MATRIX) {
9136: PetscLogEventBegin(MAT_PtAP,A,P,0,0);
9137: PetscLogEventBegin(MAT_PtAPNumeric,A,P,0,0);
9138: if ((*C)->ops->ptapnumeric) {
9139: (*(*C)->ops->ptapnumeric)(A,P,*C);
9140: } else {
9141: MatPtAP_Basic(A,P,scall,fill,C);
9142: }
9143: PetscLogEventEnd(MAT_PtAPNumeric,A,P,0,0);
9144: PetscLogEventEnd(MAT_PtAP,A,P,0,0);
9145: return(0);
9146: }
9148: if (fill == PETSC_DEFAULT || fill == PETSC_DECIDE) fill = 2.0;
9149: if (fill < 1.0) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Expected fill=%g must be >= 1.0",(double)fill);
9151: fA = A->ops->ptap;
9152: fP = P->ops->ptap;
9153: PetscStrcmp(((PetscObject)A)->type_name,((PetscObject)P)->type_name,&sametype);
9154: if (fP == fA && sametype) {
9155: ptap = fA;
9156: } else {
9157: /* dispatch based on the type of A and P from their PetscObject's PetscFunctionLists. */
9158: char ptapname[256];
9159: PetscStrncpy(ptapname,"MatPtAP_",sizeof(ptapname));
9160: PetscStrlcat(ptapname,((PetscObject)A)->type_name,sizeof(ptapname));
9161: PetscStrlcat(ptapname,"_",sizeof(ptapname));
9162: PetscStrlcat(ptapname,((PetscObject)P)->type_name,sizeof(ptapname));
9163: PetscStrlcat(ptapname,"_C",sizeof(ptapname)); /* e.g., ptapname = "MatPtAP_seqdense_seqaij_C" */
9164: PetscObjectQueryFunction((PetscObject)P,ptapname,&ptap);
9165: }
9167: if (!ptap) ptap = MatPtAP_Basic;
9168: PetscLogEventBegin(MAT_PtAP,A,P,0,0);
9169: (*ptap)(A,P,scall,fill,C);
9170: PetscLogEventEnd(MAT_PtAP,A,P,0,0);
9171: if (A->symmetric_set && A->symmetric) {
9172: MatSetOption(*C,MAT_SYMMETRIC,PETSC_TRUE);
9173: }
9174: return(0);
9175: }
9177: /*@
9178: MatPtAPNumeric - Computes the matrix product C = P^T * A * P
9180: Neighbor-wise Collective on Mat
9182: Input Parameters:
9183: + A - the matrix
9184: - P - the projection matrix
9186: Output Parameters:
9187: . C - the product matrix
9189: Notes:
9190: C must have been created by calling MatPtAPSymbolic and must be destroyed by
9191: the user using MatDeatroy().
9193: This routine is currently only implemented for pairs of AIJ matrices and classes
9194: which inherit from AIJ. C will be of type MATAIJ.
9196: Level: intermediate
9198: .seealso: MatPtAP(), MatPtAPSymbolic(), MatMatMultNumeric()
9199: @*/
9200: PetscErrorCode MatPtAPNumeric(Mat A,Mat P,Mat C)
9201: {
9207: if (!A->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
9208: if (A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
9211: MatCheckPreallocated(P,2);
9212: if (!P->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
9213: if (P->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
9216: MatCheckPreallocated(C,3);
9217: if (C->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
9218: 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);
9219: 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);
9220: 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);
9221: 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);
9222: MatCheckPreallocated(A,1);
9224: if (!C->ops->ptapnumeric) SETERRQ(PetscObjectComm((PetscObject)C),PETSC_ERR_ARG_WRONGSTATE,"MatPtAPNumeric implementation is missing. You should call MatPtAPSymbolic first");
9225: PetscLogEventBegin(MAT_PtAPNumeric,A,P,0,0);
9226: (*C->ops->ptapnumeric)(A,P,C);
9227: PetscLogEventEnd(MAT_PtAPNumeric,A,P,0,0);
9228: return(0);
9229: }
9231: /*@
9232: MatPtAPSymbolic - Creates the (i,j) structure of the matrix product C = P^T * A * P
9234: Neighbor-wise Collective on Mat
9236: Input Parameters:
9237: + A - the matrix
9238: - P - the projection matrix
9240: Output Parameters:
9241: . C - the (i,j) structure of the product matrix
9243: Notes:
9244: C will be created and must be destroyed by the user with MatDestroy().
9246: This routine is currently only implemented for pairs of SeqAIJ matrices and classes
9247: which inherit from SeqAIJ. C will be of type MATSEQAIJ. The product is computed using
9248: this (i,j) structure by calling MatPtAPNumeric().
9250: Level: intermediate
9252: .seealso: MatPtAP(), MatPtAPNumeric(), MatMatMultSymbolic()
9253: @*/
9254: PetscErrorCode MatPtAPSymbolic(Mat A,Mat P,PetscReal fill,Mat *C)
9255: {
9261: if (!A->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
9262: if (A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
9263: if (fill <1.0) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Expected fill=%g must be >= 1.0",(double)fill);
9266: MatCheckPreallocated(P,2);
9267: if (!P->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
9268: if (P->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
9271: 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);
9272: 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);
9273: MatCheckPreallocated(A,1);
9275: if (!A->ops->ptapsymbolic) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"MatType %s",((PetscObject)A)->type_name);
9276: PetscLogEventBegin(MAT_PtAPSymbolic,A,P,0,0);
9277: (*A->ops->ptapsymbolic)(A,P,fill,C);
9278: PetscLogEventEnd(MAT_PtAPSymbolic,A,P,0,0);
9280: /* MatSetBlockSize(*C,A->rmap->bs); NO! this is not always true -ma */
9281: return(0);
9282: }
9284: /*@
9285: MatRARt - Creates the matrix product C = R * A * R^T
9287: Neighbor-wise Collective on Mat
9289: Input Parameters:
9290: + A - the matrix
9291: . R - the projection matrix
9292: . scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
9293: - fill - expected fill as ratio of nnz(C)/nnz(A), use PETSC_DEFAULT if you do not have a good estimate
9294: if the result is a dense matrix this is irrelevent
9296: Output Parameters:
9297: . C - the product matrix
9299: Notes:
9300: C will be created and must be destroyed by the user with MatDestroy().
9302: This routine is currently only implemented for pairs of AIJ matrices and classes
9303: which inherit from AIJ. Due to PETSc sparse matrix block row distribution among processes,
9304: parallel MatRARt is implemented via explicit transpose of R, which could be very expensive.
9305: We recommend using MatPtAP().
9307: Level: intermediate
9309: .seealso: MatRARtSymbolic(), MatRARtNumeric(), MatMatMult(), MatPtAP()
9310: @*/
9311: PetscErrorCode MatRARt(Mat A,Mat R,MatReuse scall,PetscReal fill,Mat *C)
9312: {
9318: if (scall == MAT_INPLACE_MATRIX) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Inplace product not supported");
9319: if (!A->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
9320: if (A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
9323: MatCheckPreallocated(R,2);
9324: if (!R->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
9325: if (R->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
9327: 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);
9329: if (fill == PETSC_DEFAULT || fill == PETSC_DECIDE) fill = 2.0;
9330: if (fill < 1.0) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Expected fill=%g must be >= 1.0",(double)fill);
9331: MatCheckPreallocated(A,1);
9333: if (!A->ops->rart) {
9334: Mat Rt;
9335: MatTranspose(R,MAT_INITIAL_MATRIX,&Rt);
9336: MatMatMatMult(R,A,Rt,scall,fill,C);
9337: MatDestroy(&Rt);
9338: return(0);
9339: }
9340: PetscLogEventBegin(MAT_RARt,A,R,0,0);
9341: (*A->ops->rart)(A,R,scall,fill,C);
9342: PetscLogEventEnd(MAT_RARt,A,R,0,0);
9343: return(0);
9344: }
9346: /*@
9347: MatRARtNumeric - Computes the matrix product C = R * A * R^T
9349: Neighbor-wise Collective on Mat
9351: Input Parameters:
9352: + A - the matrix
9353: - R - the projection matrix
9355: Output Parameters:
9356: . C - the product matrix
9358: Notes:
9359: C must have been created by calling MatRARtSymbolic and must be destroyed by
9360: the user using MatDestroy().
9362: This routine is currently only implemented for pairs of AIJ matrices and classes
9363: which inherit from AIJ. C will be of type MATAIJ.
9365: Level: intermediate
9367: .seealso: MatRARt(), MatRARtSymbolic(), MatMatMultNumeric()
9368: @*/
9369: PetscErrorCode MatRARtNumeric(Mat A,Mat R,Mat C)
9370: {
9376: if (!A->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
9377: if (A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
9380: MatCheckPreallocated(R,2);
9381: if (!R->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
9382: if (R->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
9385: MatCheckPreallocated(C,3);
9386: if (C->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
9387: 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);
9388: 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);
9389: 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);
9390: 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);
9391: MatCheckPreallocated(A,1);
9393: PetscLogEventBegin(MAT_RARtNumeric,A,R,0,0);
9394: (*A->ops->rartnumeric)(A,R,C);
9395: PetscLogEventEnd(MAT_RARtNumeric,A,R,0,0);
9396: return(0);
9397: }
9399: /*@
9400: MatRARtSymbolic - Creates the (i,j) structure of the matrix product C = R * A * R^T
9402: Neighbor-wise Collective on Mat
9404: Input Parameters:
9405: + A - the matrix
9406: - R - the projection matrix
9408: Output Parameters:
9409: . C - the (i,j) structure of the product matrix
9411: Notes:
9412: C will be created and must be destroyed by the user with MatDestroy().
9414: This routine is currently only implemented for pairs of SeqAIJ matrices and classes
9415: which inherit from SeqAIJ. C will be of type MATSEQAIJ. The product is computed using
9416: this (i,j) structure by calling MatRARtNumeric().
9418: Level: intermediate
9420: .seealso: MatRARt(), MatRARtNumeric(), MatMatMultSymbolic()
9421: @*/
9422: PetscErrorCode MatRARtSymbolic(Mat A,Mat R,PetscReal fill,Mat *C)
9423: {
9429: if (!A->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
9430: if (A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
9431: if (fill <1.0) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Expected fill=%g must be >= 1.0",(double)fill);
9434: MatCheckPreallocated(R,2);
9435: if (!R->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
9436: if (R->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
9439: 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);
9440: 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);
9441: MatCheckPreallocated(A,1);
9442: PetscLogEventBegin(MAT_RARtSymbolic,A,R,0,0);
9443: (*A->ops->rartsymbolic)(A,R,fill,C);
9444: PetscLogEventEnd(MAT_RARtSymbolic,A,R,0,0);
9446: MatSetBlockSizes(*C,PetscAbs(R->rmap->bs),PetscAbs(R->rmap->bs));
9447: return(0);
9448: }
9450: /*@
9451: MatMatMult - Performs Matrix-Matrix Multiplication C=A*B.
9453: Neighbor-wise Collective on Mat
9455: Input Parameters:
9456: + A - the left matrix
9457: . B - the right matrix
9458: . scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
9459: - fill - expected fill as ratio of nnz(C)/(nnz(A) + nnz(B)), use PETSC_DEFAULT if you do not have a good estimate
9460: if the result is a dense matrix this is irrelevent
9462: Output Parameters:
9463: . C - the product matrix
9465: Notes:
9466: Unless scall is MAT_REUSE_MATRIX C will be created.
9468: 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
9469: call to this function with either MAT_INITIAL_MATRIX or MatMatMultSymbolic()
9471: To determine the correct fill value, run with -info and search for the string "Fill ratio" to see the value
9472: actually needed.
9474: If you have many matrices with the same non-zero structure to multiply, you
9475: should either
9476: $ 1) use MAT_REUSE_MATRIX in all calls but the first or
9477: $ 2) call MatMatMultSymbolic() once and then MatMatMultNumeric() for each product needed
9478: 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
9479: with MAT_REUSE_MATRIX, rather than first having MatMatMult() create it for you. You can NEVER do this if the matrix C is sparse.
9481: Level: intermediate
9483: .seealso: MatMatMultSymbolic(), MatMatMultNumeric(), MatTransposeMatMult(), MatMatTransposeMult(), MatPtAP()
9484: @*/
9485: PetscErrorCode MatMatMult(Mat A,Mat B,MatReuse scall,PetscReal fill,Mat *C)
9486: {
9488: PetscErrorCode (*fA)(Mat,Mat,MatReuse,PetscReal,Mat*);
9489: PetscErrorCode (*fB)(Mat,Mat,MatReuse,PetscReal,Mat*);
9490: PetscErrorCode (*mult)(Mat,Mat,MatReuse,PetscReal,Mat*)=NULL;
9491: Mat T;
9492: PetscBool istrans;
9497: MatCheckPreallocated(A,1);
9498: if (!A->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
9499: if (A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
9502: MatCheckPreallocated(B,2);
9503: if (!B->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
9504: if (B->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
9506: if (scall == MAT_INPLACE_MATRIX) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Inplace product not supported");
9507: 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);
9508: PetscObjectTypeCompare((PetscObject)A,MATTRANSPOSEMAT,&istrans);
9509: if (istrans) {
9510: MatTransposeGetMat(A,&T);
9511: MatTransposeMatMult(T,B,scall,fill,C);
9512: return(0);
9513: } else {
9514: PetscObjectTypeCompare((PetscObject)B,MATTRANSPOSEMAT,&istrans);
9515: if (istrans) {
9516: MatTransposeGetMat(B,&T);
9517: MatMatTransposeMult(A,T,scall,fill,C);
9518: return(0);
9519: }
9520: }
9521: if (scall == MAT_REUSE_MATRIX) {
9524: PetscLogEventBegin(MAT_MatMult,A,B,0,0);
9525: PetscLogEventBegin(MAT_MatMultNumeric,A,B,0,0);
9526: (*(*C)->ops->matmultnumeric)(A,B,*C);
9527: PetscLogEventEnd(MAT_MatMultNumeric,A,B,0,0);
9528: PetscLogEventEnd(MAT_MatMult,A,B,0,0);
9529: return(0);
9530: }
9531: if (fill == PETSC_DEFAULT || fill == PETSC_DECIDE) fill = 2.0;
9532: if (fill < 1.0) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Expected fill=%g must be >= 1.0",(double)fill);
9534: fA = A->ops->matmult;
9535: fB = B->ops->matmult;
9536: if (fB == fA && fB) mult = fB;
9537: else {
9538: /* dispatch based on the type of A and B from their PetscObject's PetscFunctionLists. */
9539: char multname[256];
9540: PetscStrncpy(multname,"MatMatMult_",sizeof(multname));
9541: PetscStrlcat(multname,((PetscObject)A)->type_name,sizeof(multname));
9542: PetscStrlcat(multname,"_",sizeof(multname));
9543: PetscStrlcat(multname,((PetscObject)B)->type_name,sizeof(multname));
9544: PetscStrlcat(multname,"_C",sizeof(multname)); /* e.g., multname = "MatMatMult_seqdense_seqaij_C" */
9545: PetscObjectQueryFunction((PetscObject)B,multname,&mult);
9546: if (!mult) {
9547: PetscObjectQueryFunction((PetscObject)A,multname,&mult);
9548: }
9549: 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);
9550: }
9551: PetscLogEventBegin(MAT_MatMult,A,B,0,0);
9552: (*mult)(A,B,scall,fill,C);
9553: PetscLogEventEnd(MAT_MatMult,A,B,0,0);
9554: return(0);
9555: }
9557: /*@
9558: MatMatMultSymbolic - Performs construction, preallocation, and computes the ij structure
9559: of the matrix-matrix product C=A*B. Call this routine before calling MatMatMultNumeric().
9561: Neighbor-wise Collective on Mat
9563: Input Parameters:
9564: + A - the left matrix
9565: . B - the right matrix
9566: - fill - expected fill as ratio of nnz(C)/(nnz(A) + nnz(B)), use PETSC_DEFAULT if you do not have a good estimate,
9567: if C is a dense matrix this is irrelevent
9569: Output Parameters:
9570: . C - the product matrix
9572: Notes:
9573: To determine the correct fill value, run with -info and search for the string "Fill ratio" to see the value
9574: actually needed.
9576: This routine is currently implemented for
9577: - pairs of AIJ matrices and classes which inherit from AIJ, C will be of type AIJ
9578: - pairs of AIJ (A) and Dense (B) matrix, C will be of type Dense.
9579: - pairs of Dense (A) and AIJ (B) matrix, C will be of type Dense.
9581: Level: intermediate
9583: Developers Note: There are ways to estimate the number of nonzeros in the resulting product, see for example, https://arxiv.org/abs/1006.4173
9584: We should incorporate them into PETSc.
9586: .seealso: MatMatMult(), MatMatMultNumeric()
9587: @*/
9588: PetscErrorCode MatMatMultSymbolic(Mat A,Mat B,PetscReal fill,Mat *C)
9589: {
9591: PetscErrorCode (*Asymbolic)(Mat,Mat,PetscReal,Mat*);
9592: PetscErrorCode (*Bsymbolic)(Mat,Mat,PetscReal,Mat*);
9593: PetscErrorCode (*symbolic)(Mat,Mat,PetscReal,Mat*)=NULL;
9598: if (!A->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
9599: if (A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
9603: MatCheckPreallocated(B,2);
9604: if (!B->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
9605: if (B->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
9608: 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);
9609: if (fill == PETSC_DEFAULT) fill = 2.0;
9610: if (fill < 1.0) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Expected fill=%g must be > 1.0",(double)fill);
9611: MatCheckPreallocated(A,1);
9613: Asymbolic = A->ops->matmultsymbolic;
9614: Bsymbolic = B->ops->matmultsymbolic;
9615: if (Asymbolic == Bsymbolic) {
9616: if (!Bsymbolic) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"C=A*B not implemented for B of type %s",((PetscObject)B)->type_name);
9617: symbolic = Bsymbolic;
9618: } else { /* dispatch based on the type of A and B */
9619: char symbolicname[256];
9620: PetscStrncpy(symbolicname,"MatMatMultSymbolic_",sizeof(symbolicname));
9621: PetscStrlcat(symbolicname,((PetscObject)A)->type_name,sizeof(symbolicname));
9622: PetscStrlcat(symbolicname,"_",sizeof(symbolicname));
9623: PetscStrlcat(symbolicname,((PetscObject)B)->type_name,sizeof(symbolicname));
9624: PetscStrlcat(symbolicname,"_C",sizeof(symbolicname));
9625: PetscObjectQueryFunction((PetscObject)B,symbolicname,&symbolic);
9626: 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);
9627: }
9628: PetscLogEventBegin(MAT_MatMultSymbolic,A,B,0,0);
9629: *C = NULL;
9630: (*symbolic)(A,B,fill,C);
9631: PetscLogEventEnd(MAT_MatMultSymbolic,A,B,0,0);
9632: return(0);
9633: }
9635: /*@
9636: MatMatMultNumeric - Performs the numeric matrix-matrix product.
9637: Call this routine after first calling MatMatMultSymbolic().
9639: Neighbor-wise Collective on Mat
9641: Input Parameters:
9642: + A - the left matrix
9643: - B - the right matrix
9645: Output Parameters:
9646: . C - the product matrix, which was created by from MatMatMultSymbolic() or a call to MatMatMult().
9648: Notes:
9649: C must have been created with MatMatMultSymbolic().
9651: This routine is currently implemented for
9652: - pairs of AIJ matrices and classes which inherit from AIJ, C will be of type MATAIJ.
9653: - pairs of AIJ (A) and Dense (B) matrix, C will be of type Dense.
9654: - pairs of Dense (A) and AIJ (B) matrix, C will be of type Dense.
9656: Level: intermediate
9658: .seealso: MatMatMult(), MatMatMultSymbolic()
9659: @*/
9660: PetscErrorCode MatMatMultNumeric(Mat A,Mat B,Mat C)
9661: {
9665: MatMatMult(A,B,MAT_REUSE_MATRIX,0.0,&C);
9666: return(0);
9667: }
9669: /*@
9670: MatMatTransposeMult - Performs Matrix-Matrix Multiplication C=A*B^T.
9672: Neighbor-wise Collective on Mat
9674: Input Parameters:
9675: + A - the left matrix
9676: . B - the right matrix
9677: . scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
9678: - fill - expected fill as ratio of nnz(C)/(nnz(A) + nnz(B)), use PETSC_DEFAULT if not known
9680: Output Parameters:
9681: . C - the product matrix
9683: Notes:
9684: C will be created if MAT_INITIAL_MATRIX and must be destroyed by the user with MatDestroy().
9686: MAT_REUSE_MATRIX can only be used if the matrices A and B have the same nonzero pattern as in the previous call
9688: To determine the correct fill value, run with -info and search for the string "Fill ratio" to see the value
9689: actually needed.
9691: This routine is currently only implemented for pairs of SeqAIJ matrices, for the SeqDense class,
9692: and for pairs of MPIDense matrices.
9694: Options Database Keys:
9695: . -matmattransmult_mpidense_mpidense_via {allgatherv,cyclic} - Choose between algorthims for MPIDense matrices: the
9696: first redundantly copies the transposed B matrix on each process and requiers O(log P) communication complexity;
9697: the second never stores more than one portion of the B matrix at a time by requires O(P) communication complexity.
9699: Level: intermediate
9701: .seealso: MatMatTransposeMultSymbolic(), MatMatTransposeMultNumeric(), MatMatMult(), MatTransposeMatMult() MatPtAP()
9702: @*/
9703: PetscErrorCode MatMatTransposeMult(Mat A,Mat B,MatReuse scall,PetscReal fill,Mat *C)
9704: {
9706: PetscErrorCode (*fA)(Mat,Mat,MatReuse,PetscReal,Mat*);
9707: PetscErrorCode (*fB)(Mat,Mat,MatReuse,PetscReal,Mat*);
9708: Mat T;
9709: PetscBool istrans;
9714: if (scall == MAT_INPLACE_MATRIX) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Inplace product not supported");
9715: if (!A->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
9716: if (A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
9719: MatCheckPreallocated(B,2);
9720: if (!B->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
9721: if (B->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
9723: 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);
9724: if (fill == PETSC_DEFAULT || fill == PETSC_DECIDE) fill = 2.0;
9725: if (fill < 1.0) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Expected fill=%g must be > 1.0",(double)fill);
9726: MatCheckPreallocated(A,1);
9728: PetscObjectTypeCompare((PetscObject)B,MATTRANSPOSEMAT,&istrans);
9729: if (istrans) {
9730: MatTransposeGetMat(B,&T);
9731: MatMatMult(A,T,scall,fill,C);
9732: return(0);
9733: }
9734: fA = A->ops->mattransposemult;
9735: if (!fA) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"MatMatTransposeMult not supported for A of type %s",((PetscObject)A)->type_name);
9736: fB = B->ops->mattransposemult;
9737: if (!fB) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"MatMatTransposeMult not supported for B of type %s",((PetscObject)B)->type_name);
9738: 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);
9740: PetscLogEventBegin(MAT_MatTransposeMult,A,B,0,0);
9741: if (scall == MAT_INITIAL_MATRIX) {
9742: PetscLogEventBegin(MAT_MatTransposeMultSymbolic,A,B,0,0);
9743: (*A->ops->mattransposemultsymbolic)(A,B,fill,C);
9744: PetscLogEventEnd(MAT_MatTransposeMultSymbolic,A,B,0,0);
9745: }
9746: PetscLogEventBegin(MAT_MatTransposeMultNumeric,A,B,0,0);
9747: (*A->ops->mattransposemultnumeric)(A,B,*C);
9748: PetscLogEventEnd(MAT_MatTransposeMultNumeric,A,B,0,0);
9749: PetscLogEventEnd(MAT_MatTransposeMult,A,B,0,0);
9750: return(0);
9751: }
9753: /*@
9754: MatTransposeMatMult - Performs Matrix-Matrix Multiplication C=A^T*B.
9756: Neighbor-wise Collective on Mat
9758: Input Parameters:
9759: + A - the left matrix
9760: . B - the right matrix
9761: . scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
9762: - fill - expected fill as ratio of nnz(C)/(nnz(A) + nnz(B)), use PETSC_DEFAULT if not known
9764: Output Parameters:
9765: . C - the product matrix
9767: Notes:
9768: C will be created if MAT_INITIAL_MATRIX and must be destroyed by the user with MatDestroy().
9770: MAT_REUSE_MATRIX can only be used if the matrices A and B have the same nonzero pattern as in the previous call
9772: To determine the correct fill value, run with -info and search for the string "Fill ratio" to see the value
9773: actually needed.
9775: This routine is currently implemented for pairs of AIJ matrices and pairs of SeqDense matrices and classes
9776: which inherit from SeqAIJ. C will be of same type as the input matrices.
9778: Level: intermediate
9780: .seealso: MatTransposeMatMultSymbolic(), MatTransposeMatMultNumeric(), MatMatMult(), MatMatTransposeMult(), MatPtAP()
9781: @*/
9782: PetscErrorCode MatTransposeMatMult(Mat A,Mat B,MatReuse scall,PetscReal fill,Mat *C)
9783: {
9785: PetscErrorCode (*fA)(Mat,Mat,MatReuse,PetscReal,Mat*);
9786: PetscErrorCode (*fB)(Mat,Mat,MatReuse,PetscReal,Mat*);
9787: PetscErrorCode (*transposematmult)(Mat,Mat,MatReuse,PetscReal,Mat*) = NULL;
9788: Mat T;
9789: PetscBool istrans;
9794: if (scall == MAT_INPLACE_MATRIX) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Inplace product not supported");
9795: if (!A->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
9796: if (A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
9799: MatCheckPreallocated(B,2);
9800: if (!B->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
9801: if (B->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
9803: 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);
9804: if (fill == PETSC_DEFAULT || fill == PETSC_DECIDE) fill = 2.0;
9805: if (fill < 1.0) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Expected fill=%g must be > 1.0",(double)fill);
9806: MatCheckPreallocated(A,1);
9808: PetscObjectTypeCompare((PetscObject)A,MATTRANSPOSEMAT,&istrans);
9809: if (istrans) {
9810: MatTransposeGetMat(A,&T);
9811: MatMatMult(T,B,scall,fill,C);
9812: return(0);
9813: }
9814: fA = A->ops->transposematmult;
9815: fB = B->ops->transposematmult;
9816: if (fB == fA && fA) transposematmult = fA;
9817: else {
9818: /* dispatch based on the type of A and B from their PetscObject's PetscFunctionLists. */
9819: char multname[256];
9820: PetscStrncpy(multname,"MatTransposeMatMult_",sizeof(multname));
9821: PetscStrlcat(multname,((PetscObject)A)->type_name,sizeof(multname));
9822: PetscStrlcat(multname,"_",sizeof(multname));
9823: PetscStrlcat(multname,((PetscObject)B)->type_name,sizeof(multname));
9824: PetscStrlcat(multname,"_C",sizeof(multname)); /* e.g., multname = "MatMatMult_seqdense_seqaij_C" */
9825: PetscObjectQueryFunction((PetscObject)B,multname,&transposematmult);
9826: if (!transposematmult) {
9827: PetscObjectQueryFunction((PetscObject)A,multname,&transposematmult);
9828: }
9829: 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);
9830: }
9831: PetscLogEventBegin(MAT_TransposeMatMult,A,B,0,0);
9832: (*transposematmult)(A,B,scall,fill,C);
9833: PetscLogEventEnd(MAT_TransposeMatMult,A,B,0,0);
9834: return(0);
9835: }
9837: /*@
9838: MatMatMatMult - Performs Matrix-Matrix-Matrix Multiplication D=A*B*C.
9840: Neighbor-wise Collective on Mat
9842: Input Parameters:
9843: + A - the left matrix
9844: . B - the middle matrix
9845: . C - the right matrix
9846: . scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
9847: - 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
9848: if the result is a dense matrix this is irrelevent
9850: Output Parameters:
9851: . D - the product matrix
9853: Notes:
9854: Unless scall is MAT_REUSE_MATRIX D will be created.
9856: MAT_REUSE_MATRIX can only be used if the matrices A, B and C have the same nonzero pattern as in the previous call
9858: To determine the correct fill value, run with -info and search for the string "Fill ratio" to see the value
9859: actually needed.
9861: If you have many matrices with the same non-zero structure to multiply, you
9862: should use MAT_REUSE_MATRIX in all calls but the first or
9864: Level: intermediate
9866: .seealso: MatMatMult, MatPtAP()
9867: @*/
9868: PetscErrorCode MatMatMatMult(Mat A,Mat B,Mat C,MatReuse scall,PetscReal fill,Mat *D)
9869: {
9871: PetscErrorCode (*fA)(Mat,Mat,Mat,MatReuse,PetscReal,Mat*);
9872: PetscErrorCode (*fB)(Mat,Mat,Mat,MatReuse,PetscReal,Mat*);
9873: PetscErrorCode (*fC)(Mat,Mat,Mat,MatReuse,PetscReal,Mat*);
9874: PetscErrorCode (*mult)(Mat,Mat,Mat,MatReuse,PetscReal,Mat*)=NULL;
9879: MatCheckPreallocated(A,1);
9880: if (scall == MAT_INPLACE_MATRIX) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Inplace product not supported");
9881: if (!A->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
9882: if (A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
9885: MatCheckPreallocated(B,2);
9886: if (!B->assembled) SETERRQ(PetscObjectComm((PetscObject)B),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
9887: if (B->factortype) SETERRQ(PetscObjectComm((PetscObject)B),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
9890: MatCheckPreallocated(C,3);
9891: if (!C->assembled) SETERRQ(PetscObjectComm((PetscObject)C),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
9892: if (C->factortype) SETERRQ(PetscObjectComm((PetscObject)C),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
9893: 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);
9894: 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);
9895: if (scall == MAT_REUSE_MATRIX) {
9898: PetscLogEventBegin(MAT_MatMatMult,A,B,0,0);
9899: (*(*D)->ops->matmatmult)(A,B,C,scall,fill,D);
9900: PetscLogEventEnd(MAT_MatMatMult,A,B,0,0);
9901: return(0);
9902: }
9903: if (fill == PETSC_DEFAULT || fill == PETSC_DECIDE) fill = 2.0;
9904: if (fill < 1.0) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Expected fill=%g must be >= 1.0",(double)fill);
9906: fA = A->ops->matmatmult;
9907: fB = B->ops->matmatmult;
9908: fC = C->ops->matmatmult;
9909: if (fA == fB && fA == fC) {
9910: if (!fA) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"MatMatMatMult not supported for A of type %s",((PetscObject)A)->type_name);
9911: mult = fA;
9912: } else {
9913: /* dispatch based on the type of A, B and C from their PetscObject's PetscFunctionLists. */
9914: char multname[256];
9915: PetscStrncpy(multname,"MatMatMatMult_",sizeof(multname));
9916: PetscStrlcat(multname,((PetscObject)A)->type_name,sizeof(multname));
9917: PetscStrlcat(multname,"_",sizeof(multname));
9918: PetscStrlcat(multname,((PetscObject)B)->type_name,sizeof(multname));
9919: PetscStrlcat(multname,"_",sizeof(multname));
9920: PetscStrlcat(multname,((PetscObject)C)->type_name,sizeof(multname));
9921: PetscStrlcat(multname,"_C",sizeof(multname));
9922: PetscObjectQueryFunction((PetscObject)B,multname,&mult);
9923: 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);
9924: }
9925: PetscLogEventBegin(MAT_MatMatMult,A,B,0,0);
9926: (*mult)(A,B,C,scall,fill,D);
9927: PetscLogEventEnd(MAT_MatMatMult,A,B,0,0);
9928: return(0);
9929: }
9931: /*@
9932: MatCreateRedundantMatrix - Create redundant matrices and put them into processors of subcommunicators.
9934: Collective on Mat
9936: Input Parameters:
9937: + mat - the matrix
9938: . nsubcomm - the number of subcommunicators (= number of redundant parallel or sequential matrices)
9939: . subcomm - MPI communicator split from the communicator where mat resides in (or MPI_COMM_NULL if nsubcomm is used)
9940: - reuse - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
9942: Output Parameter:
9943: . matredundant - redundant matrix
9945: Notes:
9946: MAT_REUSE_MATRIX can only be used when the nonzero structure of the
9947: original matrix has not changed from that last call to MatCreateRedundantMatrix().
9949: This routine creates the duplicated matrices in subcommunicators; you should NOT create them before
9950: calling it.
9952: Level: advanced
9955: .seealso: MatDestroy()
9956: @*/
9957: PetscErrorCode MatCreateRedundantMatrix(Mat mat,PetscInt nsubcomm,MPI_Comm subcomm,MatReuse reuse,Mat *matredundant)
9958: {
9960: MPI_Comm comm;
9961: PetscMPIInt size;
9962: PetscInt mloc_sub,nloc_sub,rstart,rend,M=mat->rmap->N,N=mat->cmap->N,bs=mat->rmap->bs;
9963: Mat_Redundant *redund=NULL;
9964: PetscSubcomm psubcomm=NULL;
9965: MPI_Comm subcomm_in=subcomm;
9966: Mat *matseq;
9967: IS isrow,iscol;
9968: PetscBool newsubcomm=PETSC_FALSE;
9972: if (nsubcomm && reuse == MAT_REUSE_MATRIX) {
9975: }
9977: MPI_Comm_size(PetscObjectComm((PetscObject)mat),&size);
9978: if (size == 1 || nsubcomm == 1) {
9979: if (reuse == MAT_INITIAL_MATRIX) {
9980: MatDuplicate(mat,MAT_COPY_VALUES,matredundant);
9981: } else {
9982: 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");
9983: MatCopy(mat,*matredundant,SAME_NONZERO_PATTERN);
9984: }
9985: return(0);
9986: }
9988: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
9989: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
9990: MatCheckPreallocated(mat,1);
9992: PetscLogEventBegin(MAT_RedundantMat,mat,0,0,0);
9993: if (subcomm_in == MPI_COMM_NULL && reuse == MAT_INITIAL_MATRIX) { /* get subcomm if user does not provide subcomm */
9994: /* create psubcomm, then get subcomm */
9995: PetscObjectGetComm((PetscObject)mat,&comm);
9996: MPI_Comm_size(comm,&size);
9997: if (nsubcomm < 1 || nsubcomm > size) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"nsubcomm must between 1 and %D",size);
9999: PetscSubcommCreate(comm,&psubcomm);
10000: PetscSubcommSetNumber(psubcomm,nsubcomm);
10001: PetscSubcommSetType(psubcomm,PETSC_SUBCOMM_CONTIGUOUS);
10002: PetscSubcommSetFromOptions(psubcomm);
10003: PetscCommDuplicate(PetscSubcommChild(psubcomm),&subcomm,NULL);
10004: newsubcomm = PETSC_TRUE;
10005: PetscSubcommDestroy(&psubcomm);
10006: }
10008: /* get isrow, iscol and a local sequential matrix matseq[0] */
10009: if (reuse == MAT_INITIAL_MATRIX) {
10010: mloc_sub = PETSC_DECIDE;
10011: nloc_sub = PETSC_DECIDE;
10012: if (bs < 1) {
10013: PetscSplitOwnership(subcomm,&mloc_sub,&M);
10014: PetscSplitOwnership(subcomm,&nloc_sub,&N);
10015: } else {
10016: PetscSplitOwnershipBlock(subcomm,bs,&mloc_sub,&M);
10017: PetscSplitOwnershipBlock(subcomm,bs,&nloc_sub,&N);
10018: }
10019: MPI_Scan(&mloc_sub,&rend,1,MPIU_INT,MPI_SUM,subcomm);
10020: rstart = rend - mloc_sub;
10021: ISCreateStride(PETSC_COMM_SELF,mloc_sub,rstart,1,&isrow);
10022: ISCreateStride(PETSC_COMM_SELF,N,0,1,&iscol);
10023: } else { /* reuse == MAT_REUSE_MATRIX */
10024: 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");
10025: /* retrieve subcomm */
10026: PetscObjectGetComm((PetscObject)(*matredundant),&subcomm);
10027: redund = (*matredundant)->redundant;
10028: isrow = redund->isrow;
10029: iscol = redund->iscol;
10030: matseq = redund->matseq;
10031: }
10032: MatCreateSubMatrices(mat,1,&isrow,&iscol,reuse,&matseq);
10034: /* get matredundant over subcomm */
10035: if (reuse == MAT_INITIAL_MATRIX) {
10036: MatCreateMPIMatConcatenateSeqMat(subcomm,matseq[0],nloc_sub,reuse,matredundant);
10038: /* create a supporting struct and attach it to C for reuse */
10039: PetscNewLog(*matredundant,&redund);
10040: (*matredundant)->redundant = redund;
10041: redund->isrow = isrow;
10042: redund->iscol = iscol;
10043: redund->matseq = matseq;
10044: if (newsubcomm) {
10045: redund->subcomm = subcomm;
10046: } else {
10047: redund->subcomm = MPI_COMM_NULL;
10048: }
10049: } else {
10050: MatCreateMPIMatConcatenateSeqMat(subcomm,matseq[0],PETSC_DECIDE,reuse,matredundant);
10051: }
10052: PetscLogEventEnd(MAT_RedundantMat,mat,0,0,0);
10053: return(0);
10054: }
10056: /*@C
10057: MatGetMultiProcBlock - Create multiple [bjacobi] 'parallel submatrices' from
10058: a given 'mat' object. Each submatrix can span multiple procs.
10060: Collective on Mat
10062: Input Parameters:
10063: + mat - the matrix
10064: . subcomm - the subcommunicator obtained by com_split(comm)
10065: - scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
10067: Output Parameter:
10068: . subMat - 'parallel submatrices each spans a given subcomm
10070: Notes:
10071: The submatrix partition across processors is dictated by 'subComm' a
10072: communicator obtained by com_split(comm). The comm_split
10073: is not restriced to be grouped with consecutive original ranks.
10075: Due the comm_split() usage, the parallel layout of the submatrices
10076: map directly to the layout of the original matrix [wrt the local
10077: row,col partitioning]. So the original 'DiagonalMat' naturally maps
10078: into the 'DiagonalMat' of the subMat, hence it is used directly from
10079: the subMat. However the offDiagMat looses some columns - and this is
10080: reconstructed with MatSetValues()
10082: Level: advanced
10085: .seealso: MatCreateSubMatrices()
10086: @*/
10087: PetscErrorCode MatGetMultiProcBlock(Mat mat, MPI_Comm subComm, MatReuse scall,Mat *subMat)
10088: {
10090: PetscMPIInt commsize,subCommSize;
10093: MPI_Comm_size(PetscObjectComm((PetscObject)mat),&commsize);
10094: MPI_Comm_size(subComm,&subCommSize);
10095: if (subCommSize > commsize) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_OUTOFRANGE,"CommSize %D < SubCommZize %D",commsize,subCommSize);
10097: 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");
10098: PetscLogEventBegin(MAT_GetMultiProcBlock,mat,0,0,0);
10099: (*mat->ops->getmultiprocblock)(mat,subComm,scall,subMat);
10100: PetscLogEventEnd(MAT_GetMultiProcBlock,mat,0,0,0);
10101: return(0);
10102: }
10104: /*@
10105: MatGetLocalSubMatrix - Gets a reference to a submatrix specified in local numbering
10107: Not Collective
10109: Input Arguments:
10110: + mat - matrix to extract local submatrix from
10111: . isrow - local row indices for submatrix
10112: - iscol - local column indices for submatrix
10114: Output Arguments:
10115: . submat - the submatrix
10117: Level: intermediate
10119: Notes:
10120: The submat should be returned with MatRestoreLocalSubMatrix().
10122: Depending on the format of mat, the returned submat may not implement MatMult(). Its communicator may be
10123: the same as mat, it may be PETSC_COMM_SELF, or some other subcomm of mat's.
10125: The submat always implements MatSetValuesLocal(). If isrow and iscol have the same block size, then
10126: MatSetValuesBlockedLocal() will also be implemented.
10128: The mat must have had a ISLocalToGlobalMapping provided to it with MatSetLocalToGlobalMapping(). Note that
10129: matrices obtained with DMCreateMatrix() generally already have the local to global mapping provided.
10131: .seealso: MatRestoreLocalSubMatrix(), MatCreateLocalRef(), MatSetLocalToGlobalMapping()
10132: @*/
10133: PetscErrorCode MatGetLocalSubMatrix(Mat mat,IS isrow,IS iscol,Mat *submat)
10134: {
10143: if (!mat->rmap->mapping) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Matrix must have local to global mapping provided before this call");
10145: if (mat->ops->getlocalsubmatrix) {
10146: (*mat->ops->getlocalsubmatrix)(mat,isrow,iscol,submat);
10147: } else {
10148: MatCreateLocalRef(mat,isrow,iscol,submat);
10149: }
10150: return(0);
10151: }
10153: /*@
10154: MatRestoreLocalSubMatrix - Restores a reference to a submatrix specified in local numbering
10156: Not Collective
10158: Input Arguments:
10159: mat - matrix to extract local submatrix from
10160: isrow - local row indices for submatrix
10161: iscol - local column indices for submatrix
10162: submat - the submatrix
10164: Level: intermediate
10166: .seealso: MatGetLocalSubMatrix()
10167: @*/
10168: PetscErrorCode MatRestoreLocalSubMatrix(Mat mat,IS isrow,IS iscol,Mat *submat)
10169: {
10178: if (*submat) {
10180: }
10182: if (mat->ops->restorelocalsubmatrix) {
10183: (*mat->ops->restorelocalsubmatrix)(mat,isrow,iscol,submat);
10184: } else {
10185: MatDestroy(submat);
10186: }
10187: *submat = NULL;
10188: return(0);
10189: }
10191: /* --------------------------------------------------------*/
10192: /*@
10193: MatFindZeroDiagonals - Finds all the rows of a matrix that have zero or no diagonal entry in the matrix
10195: Collective on Mat
10197: Input Parameter:
10198: . mat - the matrix
10200: Output Parameter:
10201: . is - if any rows have zero diagonals this contains the list of them
10203: Level: developer
10205: .seealso: MatMultTranspose(), MatMultAdd(), MatMultTransposeAdd()
10206: @*/
10207: PetscErrorCode MatFindZeroDiagonals(Mat mat,IS *is)
10208: {
10214: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
10215: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
10217: if (!mat->ops->findzerodiagonals) {
10218: Vec diag;
10219: const PetscScalar *a;
10220: PetscInt *rows;
10221: PetscInt rStart, rEnd, r, nrow = 0;
10223: MatCreateVecs(mat, &diag, NULL);
10224: MatGetDiagonal(mat, diag);
10225: MatGetOwnershipRange(mat, &rStart, &rEnd);
10226: VecGetArrayRead(diag, &a);
10227: for (r = 0; r < rEnd-rStart; ++r) if (a[r] == 0.0) ++nrow;
10228: PetscMalloc1(nrow, &rows);
10229: nrow = 0;
10230: for (r = 0; r < rEnd-rStart; ++r) if (a[r] == 0.0) rows[nrow++] = r+rStart;
10231: VecRestoreArrayRead(diag, &a);
10232: VecDestroy(&diag);
10233: ISCreateGeneral(PetscObjectComm((PetscObject) mat), nrow, rows, PETSC_OWN_POINTER, is);
10234: } else {
10235: (*mat->ops->findzerodiagonals)(mat, is);
10236: }
10237: return(0);
10238: }
10240: /*@
10241: MatFindOffBlockDiagonalEntries - Finds all the rows of a matrix that have entries outside of the main diagonal block (defined by the matrix block size)
10243: Collective on Mat
10245: Input Parameter:
10246: . mat - the matrix
10248: Output Parameter:
10249: . is - contains the list of rows with off block diagonal entries
10251: Level: developer
10253: .seealso: MatMultTranspose(), MatMultAdd(), MatMultTransposeAdd()
10254: @*/
10255: PetscErrorCode MatFindOffBlockDiagonalEntries(Mat mat,IS *is)
10256: {
10262: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
10263: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
10265: if (!mat->ops->findoffblockdiagonalentries) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"This matrix type does not have a find off block diagonal entries defined");
10266: (*mat->ops->findoffblockdiagonalentries)(mat,is);
10267: return(0);
10268: }
10270: /*@C
10271: MatInvertBlockDiagonal - Inverts the block diagonal entries.
10273: Collective on Mat
10275: Input Parameters:
10276: . mat - the matrix
10278: Output Parameters:
10279: . values - the block inverses in column major order (FORTRAN-like)
10281: Note:
10282: This routine is not available from Fortran.
10284: Level: advanced
10286: .seealso: MatInvertBockDiagonalMat
10287: @*/
10288: PetscErrorCode MatInvertBlockDiagonal(Mat mat,const PetscScalar **values)
10289: {
10294: if (!mat->assembled) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
10295: if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
10296: if (!mat->ops->invertblockdiagonal) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"Not supported");
10297: (*mat->ops->invertblockdiagonal)(mat,values);
10298: return(0);
10299: }
10301: /*@C
10302: MatInvertVariableBlockDiagonal - Inverts the block diagonal entries.
10304: Collective on Mat
10306: Input Parameters:
10307: + mat - the matrix
10308: . nblocks - the number of blocks
10309: - bsizes - the size of each block
10311: Output Parameters:
10312: . values - the block inverses in column major order (FORTRAN-like)
10314: Note:
10315: This routine is not available from Fortran.
10317: Level: advanced
10319: .seealso: MatInvertBockDiagonal()
10320: @*/
10321: PetscErrorCode MatInvertVariableBlockDiagonal(Mat mat,PetscInt nblocks,const PetscInt *bsizes,PetscScalar *values)
10322: {
10327: if (!mat->assembled) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
10328: if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
10329: if (!mat->ops->invertvariableblockdiagonal) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"Not supported");
10330: (*mat->ops->invertvariableblockdiagonal)(mat,nblocks,bsizes,values);
10331: return(0);
10332: }
10334: /*@
10335: MatInvertBlockDiagonalMat - set matrix C to be the inverted block diagonal of matrix A
10337: Collective on Mat
10339: Input Parameters:
10340: . A - the matrix
10342: Output Parameters:
10343: . C - matrix with inverted block diagonal of A. This matrix should be created and may have its type set.
10345: Notes: the blocksize of the matrix is used to determine the blocks on the diagonal of C
10347: Level: advanced
10349: .seealso: MatInvertBockDiagonal()
10350: @*/
10351: PetscErrorCode MatInvertBlockDiagonalMat(Mat A,Mat C)
10352: {
10353: PetscErrorCode ierr;
10354: const PetscScalar *vals;
10355: PetscInt *dnnz;
10356: PetscInt M,N,m,n,rstart,rend,bs,i,j;
10359: MatInvertBlockDiagonal(A,&vals);
10360: MatGetBlockSize(A,&bs);
10361: MatGetSize(A,&M,&N);
10362: MatGetLocalSize(A,&m,&n);
10363: MatSetSizes(C,m,n,M,N);
10364: MatSetBlockSize(C,bs);
10365: PetscMalloc1(m/bs,&dnnz);
10366: for (j = 0; j < m/bs; j++) dnnz[j] = 1;
10367: MatXAIJSetPreallocation(C,bs,dnnz,NULL,NULL,NULL);
10368: PetscFree(dnnz);
10369: MatGetOwnershipRange(C,&rstart,&rend);
10370: MatSetOption(C,MAT_ROW_ORIENTED,PETSC_FALSE);
10371: for (i = rstart/bs; i < rend/bs; i++) {
10372: MatSetValuesBlocked(C,1,&i,1,&i,&vals[(i-rstart/bs)*bs*bs],INSERT_VALUES);
10373: }
10374: MatAssemblyBegin(C,MAT_FINAL_ASSEMBLY);
10375: MatAssemblyEnd(C,MAT_FINAL_ASSEMBLY);
10376: MatSetOption(C,MAT_ROW_ORIENTED,PETSC_TRUE);
10377: return(0);
10378: }
10380: /*@C
10381: MatTransposeColoringDestroy - Destroys a coloring context for matrix product C=A*B^T that was created
10382: via MatTransposeColoringCreate().
10384: Collective on MatTransposeColoring
10386: Input Parameter:
10387: . c - coloring context
10389: Level: intermediate
10391: .seealso: MatTransposeColoringCreate()
10392: @*/
10393: PetscErrorCode MatTransposeColoringDestroy(MatTransposeColoring *c)
10394: {
10395: PetscErrorCode ierr;
10396: MatTransposeColoring matcolor=*c;
10399: if (!matcolor) return(0);
10400: if (--((PetscObject)matcolor)->refct > 0) {matcolor = 0; return(0);}
10402: PetscFree3(matcolor->ncolumns,matcolor->nrows,matcolor->colorforrow);
10403: PetscFree(matcolor->rows);
10404: PetscFree(matcolor->den2sp);
10405: PetscFree(matcolor->colorforcol);
10406: PetscFree(matcolor->columns);
10407: if (matcolor->brows>0) {
10408: PetscFree(matcolor->lstart);
10409: }
10410: PetscHeaderDestroy(c);
10411: return(0);
10412: }
10414: /*@C
10415: MatTransColoringApplySpToDen - Given a symbolic matrix product C=A*B^T for which
10416: a MatTransposeColoring context has been created, computes a dense B^T by Apply
10417: MatTransposeColoring to sparse B.
10419: Collective on MatTransposeColoring
10421: Input Parameters:
10422: + B - sparse matrix B
10423: . Btdense - symbolic dense matrix B^T
10424: - coloring - coloring context created with MatTransposeColoringCreate()
10426: Output Parameter:
10427: . Btdense - dense matrix B^T
10429: Level: advanced
10431: Notes:
10432: These are used internally for some implementations of MatRARt()
10434: .seealso: MatTransposeColoringCreate(), MatTransposeColoringDestroy(), MatTransColoringApplyDenToSp()
10436: @*/
10437: PetscErrorCode MatTransColoringApplySpToDen(MatTransposeColoring coloring,Mat B,Mat Btdense)
10438: {
10446: if (!B->ops->transcoloringapplysptoden) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Not supported for this matrix type %s",((PetscObject)B)->type_name);
10447: (B->ops->transcoloringapplysptoden)(coloring,B,Btdense);
10448: return(0);
10449: }
10451: /*@C
10452: MatTransColoringApplyDenToSp - Given a symbolic matrix product Csp=A*B^T for which
10453: a MatTransposeColoring context has been created and a dense matrix Cden=A*Btdense
10454: in which Btdens is obtained from MatTransColoringApplySpToDen(), recover sparse matrix
10455: Csp from Cden.
10457: Collective on MatTransposeColoring
10459: Input Parameters:
10460: + coloring - coloring context created with MatTransposeColoringCreate()
10461: - Cden - matrix product of a sparse matrix and a dense matrix Btdense
10463: Output Parameter:
10464: . Csp - sparse matrix
10466: Level: advanced
10468: Notes:
10469: These are used internally for some implementations of MatRARt()
10471: .seealso: MatTransposeColoringCreate(), MatTransposeColoringDestroy(), MatTransColoringApplySpToDen()
10473: @*/
10474: PetscErrorCode MatTransColoringApplyDenToSp(MatTransposeColoring matcoloring,Mat Cden,Mat Csp)
10475: {
10483: if (!Csp->ops->transcoloringapplydentosp) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Not supported for this matrix type %s",((PetscObject)Csp)->type_name);
10484: (Csp->ops->transcoloringapplydentosp)(matcoloring,Cden,Csp);
10485: return(0);
10486: }
10488: /*@C
10489: MatTransposeColoringCreate - Creates a matrix coloring context for matrix product C=A*B^T.
10491: Collective on Mat
10493: Input Parameters:
10494: + mat - the matrix product C
10495: - iscoloring - the coloring of the matrix; usually obtained with MatColoringCreate() or DMCreateColoring()
10497: Output Parameter:
10498: . color - the new coloring context
10500: Level: intermediate
10502: .seealso: MatTransposeColoringDestroy(), MatTransColoringApplySpToDen(),
10503: MatTransColoringApplyDenToSp()
10504: @*/
10505: PetscErrorCode MatTransposeColoringCreate(Mat mat,ISColoring iscoloring,MatTransposeColoring *color)
10506: {
10507: MatTransposeColoring c;
10508: MPI_Comm comm;
10509: PetscErrorCode ierr;
10512: PetscLogEventBegin(MAT_TransposeColoringCreate,mat,0,0,0);
10513: PetscObjectGetComm((PetscObject)mat,&comm);
10514: PetscHeaderCreate(c,MAT_TRANSPOSECOLORING_CLASSID,"MatTransposeColoring","Matrix product C=A*B^T via coloring","Mat",comm,MatTransposeColoringDestroy,NULL);
10516: c->ctype = iscoloring->ctype;
10517: if (mat->ops->transposecoloringcreate) {
10518: (*mat->ops->transposecoloringcreate)(mat,iscoloring,c);
10519: } else SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Code not yet written for this matrix type");
10521: *color = c;
10522: PetscLogEventEnd(MAT_TransposeColoringCreate,mat,0,0,0);
10523: return(0);
10524: }
10526: /*@
10527: MatGetNonzeroState - Returns a 64 bit integer representing the current state of nonzeros in the matrix. If the
10528: matrix has had no new nonzero locations added to the matrix since the previous call then the value will be the
10529: same, otherwise it will be larger
10531: Not Collective
10533: Input Parameter:
10534: . A - the matrix
10536: Output Parameter:
10537: . state - the current state
10539: Notes:
10540: You can only compare states from two different calls to the SAME matrix, you cannot compare calls between
10541: different matrices
10543: Level: intermediate
10545: @*/
10546: PetscErrorCode MatGetNonzeroState(Mat mat,PetscObjectState *state)
10547: {
10550: *state = mat->nonzerostate;
10551: return(0);
10552: }
10554: /*@
10555: MatCreateMPIMatConcatenateSeqMat - Creates a single large PETSc matrix by concatenating sequential
10556: matrices from each processor
10558: Collective
10560: Input Parameters:
10561: + comm - the communicators the parallel matrix will live on
10562: . seqmat - the input sequential matrices
10563: . n - number of local columns (or PETSC_DECIDE)
10564: - reuse - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
10566: Output Parameter:
10567: . mpimat - the parallel matrix generated
10569: Level: advanced
10571: Notes:
10572: The number of columns of the matrix in EACH processor MUST be the same.
10574: @*/
10575: PetscErrorCode MatCreateMPIMatConcatenateSeqMat(MPI_Comm comm,Mat seqmat,PetscInt n,MatReuse reuse,Mat *mpimat)
10576: {
10580: if (!seqmat->ops->creatempimatconcatenateseqmat) SETERRQ1(PetscObjectComm((PetscObject)seqmat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)seqmat)->type_name);
10581: 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");
10583: PetscLogEventBegin(MAT_Merge,seqmat,0,0,0);
10584: (*seqmat->ops->creatempimatconcatenateseqmat)(comm,seqmat,n,reuse,mpimat);
10585: PetscLogEventEnd(MAT_Merge,seqmat,0,0,0);
10586: return(0);
10587: }
10589: /*@
10590: MatSubdomainsCreateCoalesce - Creates index subdomains by coalescing adjacent
10591: ranks' ownership ranges.
10593: Collective on A
10595: Input Parameters:
10596: + A - the matrix to create subdomains from
10597: - N - requested number of subdomains
10600: Output Parameters:
10601: + n - number of subdomains resulting on this rank
10602: - iss - IS list with indices of subdomains on this rank
10604: Level: advanced
10606: Notes:
10607: number of subdomains must be smaller than the communicator size
10608: @*/
10609: PetscErrorCode MatSubdomainsCreateCoalesce(Mat A,PetscInt N,PetscInt *n,IS *iss[])
10610: {
10611: MPI_Comm comm,subcomm;
10612: PetscMPIInt size,rank,color;
10613: PetscInt rstart,rend,k;
10614: PetscErrorCode ierr;
10617: PetscObjectGetComm((PetscObject)A,&comm);
10618: MPI_Comm_size(comm,&size);
10619: MPI_Comm_rank(comm,&rank);
10620: 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);
10621: *n = 1;
10622: k = ((PetscInt)size)/N + ((PetscInt)size%N>0); /* There are up to k ranks to a color */
10623: color = rank/k;
10624: MPI_Comm_split(comm,color,rank,&subcomm);
10625: PetscMalloc1(1,iss);
10626: MatGetOwnershipRange(A,&rstart,&rend);
10627: ISCreateStride(subcomm,rend-rstart,rstart,1,iss[0]);
10628: MPI_Comm_free(&subcomm);
10629: return(0);
10630: }
10632: /*@
10633: MatGalerkin - Constructs the coarse grid problem via Galerkin projection.
10635: If the interpolation and restriction operators are the same, uses MatPtAP.
10636: If they are not the same, use MatMatMatMult.
10638: Once the coarse grid problem is constructed, correct for interpolation operators
10639: that are not of full rank, which can legitimately happen in the case of non-nested
10640: geometric multigrid.
10642: Input Parameters:
10643: + restrct - restriction operator
10644: . dA - fine grid matrix
10645: . interpolate - interpolation operator
10646: . reuse - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
10647: - fill - expected fill, use PETSC_DEFAULT if you do not have a good estimate
10649: Output Parameters:
10650: . A - the Galerkin coarse matrix
10652: Options Database Key:
10653: . -pc_mg_galerkin <both,pmat,mat,none>
10655: Level: developer
10657: .seealso: MatPtAP(), MatMatMatMult()
10658: @*/
10659: PetscErrorCode MatGalerkin(Mat restrct, Mat dA, Mat interpolate, MatReuse reuse, PetscReal fill, Mat *A)
10660: {
10662: IS zerorows;
10663: Vec diag;
10666: if (reuse == MAT_INPLACE_MATRIX) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Inplace product not supported");
10667: /* Construct the coarse grid matrix */
10668: if (interpolate == restrct) {
10669: MatPtAP(dA,interpolate,reuse,fill,A);
10670: } else {
10671: MatMatMatMult(restrct,dA,interpolate,reuse,fill,A);
10672: }
10674: /* If the interpolation matrix is not of full rank, A will have zero rows.
10675: This can legitimately happen in the case of non-nested geometric multigrid.
10676: In that event, we set the rows of the matrix to the rows of the identity,
10677: ignoring the equations (as the RHS will also be zero). */
10679: MatFindZeroRows(*A, &zerorows);
10681: if (zerorows != NULL) { /* if there are any zero rows */
10682: MatCreateVecs(*A, &diag, NULL);
10683: MatGetDiagonal(*A, diag);
10684: VecISSet(diag, zerorows, 1.0);
10685: MatDiagonalSet(*A, diag, INSERT_VALUES);
10686: VecDestroy(&diag);
10687: ISDestroy(&zerorows);
10688: }
10689: return(0);
10690: }
10692: /*@C
10693: MatSetOperation - Allows user to set a matrix operation for any matrix type
10695: Logically Collective on Mat
10697: Input Parameters:
10698: + mat - the matrix
10699: . op - the name of the operation
10700: - f - the function that provides the operation
10702: Level: developer
10704: Usage:
10705: $ extern PetscErrorCode usermult(Mat,Vec,Vec);
10706: $ MatCreateXXX(comm,...&A);
10707: $ MatSetOperation(A,MATOP_MULT,(void(*)(void))usermult);
10709: Notes:
10710: See the file include/petscmat.h for a complete list of matrix
10711: operations, which all have the form MATOP_<OPERATION>, where
10712: <OPERATION> is the name (in all capital letters) of the
10713: user interface routine (e.g., MatMult() -> MATOP_MULT).
10715: All user-provided functions (except for MATOP_DESTROY) should have the same calling
10716: sequence as the usual matrix interface routines, since they
10717: are intended to be accessed via the usual matrix interface
10718: routines, e.g.,
10719: $ MatMult(Mat,Vec,Vec) -> usermult(Mat,Vec,Vec)
10721: In particular each function MUST return an error code of 0 on success and
10722: nonzero on failure.
10724: This routine is distinct from MatShellSetOperation() in that it can be called on any matrix type.
10726: .seealso: MatGetOperation(), MatCreateShell(), MatShellSetContext(), MatShellSetOperation()
10727: @*/
10728: PetscErrorCode MatSetOperation(Mat mat,MatOperation op,void (*f)(void))
10729: {
10732: if (op == MATOP_VIEW && !mat->ops->viewnative && f != (void (*)(void))(mat->ops->view)) {
10733: mat->ops->viewnative = mat->ops->view;
10734: }
10735: (((void(**)(void))mat->ops)[op]) = f;
10736: return(0);
10737: }
10739: /*@C
10740: MatGetOperation - Gets a matrix operation for any matrix type.
10742: Not Collective
10744: Input Parameters:
10745: + mat - the matrix
10746: - op - the name of the operation
10748: Output Parameter:
10749: . f - the function that provides the operation
10751: Level: developer
10753: Usage:
10754: $ PetscErrorCode (*usermult)(Mat,Vec,Vec);
10755: $ MatGetOperation(A,MATOP_MULT,(void(**)(void))&usermult);
10757: Notes:
10758: See the file include/petscmat.h for a complete list of matrix
10759: operations, which all have the form MATOP_<OPERATION>, where
10760: <OPERATION> is the name (in all capital letters) of the
10761: user interface routine (e.g., MatMult() -> MATOP_MULT).
10763: This routine is distinct from MatShellGetOperation() in that it can be called on any matrix type.
10765: .seealso: MatSetOperation(), MatCreateShell(), MatShellGetContext(), MatShellGetOperation()
10766: @*/
10767: PetscErrorCode MatGetOperation(Mat mat,MatOperation op,void(**f)(void))
10768: {
10771: *f = (((void (**)(void))mat->ops)[op]);
10772: return(0);
10773: }
10775: /*@
10776: MatHasOperation - Determines whether the given matrix supports the particular
10777: operation.
10779: Not Collective
10781: Input Parameters:
10782: + mat - the matrix
10783: - op - the operation, for example, MATOP_GET_DIAGONAL
10785: Output Parameter:
10786: . has - either PETSC_TRUE or PETSC_FALSE
10788: Level: advanced
10790: Notes:
10791: See the file include/petscmat.h for a complete list of matrix
10792: operations, which all have the form MATOP_<OPERATION>, where
10793: <OPERATION> is the name (in all capital letters) of the
10794: user-level routine. E.g., MatNorm() -> MATOP_NORM.
10796: .seealso: MatCreateShell()
10797: @*/
10798: PetscErrorCode MatHasOperation(Mat mat,MatOperation op,PetscBool *has)
10799: {
10806: if (mat->ops->hasoperation) {
10807: (*mat->ops->hasoperation)(mat,op,has);
10808: } else {
10809: if (((void**)mat->ops)[op]) *has = PETSC_TRUE;
10810: else {
10811: *has = PETSC_FALSE;
10812: if (op == MATOP_CREATE_SUBMATRIX) {
10813: PetscMPIInt size;
10815: MPI_Comm_size(PetscObjectComm((PetscObject)mat),&size);
10816: if (size == 1) {
10817: MatHasOperation(mat,MATOP_CREATE_SUBMATRICES,has);
10818: }
10819: }
10820: }
10821: }
10822: return(0);
10823: }
10825: /*@
10826: MatHasCongruentLayouts - Determines whether the rows and columns layouts
10827: of the matrix are congruent
10829: Collective on mat
10831: Input Parameters:
10832: . mat - the matrix
10834: Output Parameter:
10835: . cong - either PETSC_TRUE or PETSC_FALSE
10837: Level: beginner
10839: Notes:
10841: .seealso: MatCreate(), MatSetSizes()
10842: @*/
10843: PetscErrorCode MatHasCongruentLayouts(Mat mat,PetscBool *cong)
10844: {
10851: if (!mat->rmap || !mat->cmap) {
10852: *cong = mat->rmap == mat->cmap ? PETSC_TRUE : PETSC_FALSE;
10853: return(0);
10854: }
10855: if (mat->congruentlayouts == PETSC_DECIDE) { /* first time we compare rows and cols layouts */
10856: PetscLayoutCompare(mat->rmap,mat->cmap,cong);
10857: if (*cong) mat->congruentlayouts = 1;
10858: else mat->congruentlayouts = 0;
10859: } else *cong = mat->congruentlayouts ? PETSC_TRUE : PETSC_FALSE;
10860: return(0);
10861: }
10863: /*@
10864: MatFreeIntermediateDataStructures - Free intermediate data structures created for reuse,
10865: e.g., matrx product of MatPtAP.
10867: Collective on mat
10869: Input Parameters:
10870: . mat - the matrix
10872: Output Parameter:
10873: . mat - the matrix with intermediate data structures released
10875: Level: advanced
10877: Notes:
10879: .seealso: MatPtAP(), MatMatMult()
10880: @*/
10881: PetscErrorCode MatFreeIntermediateDataStructures(Mat mat)
10882: {
10888: if (mat->ops->freeintermediatedatastructures) {
10889: (*mat->ops->freeintermediatedatastructures)(mat);
10890: }
10891: return(0);
10892: }