Actual source code: matrix.c
petsc-master 2019-12-13
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 - Gets 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
873: /*@C
874: MatViewFromOptions - View from Options
876: Collective on Mat
878: Input Parameters:
879: + A - the Mat context
880: . obj - Optional object
881: - name - command line option
883: Level: intermediate
884: .seealso: Mat, MatView, PetscObjectViewFromOptions(), MatCreate()
885: @*/
886: PetscErrorCode MatViewFromOptions(Mat A,PetscObject obj,const char name[])
887: {
892: PetscObjectViewFromOptions((PetscObject)A,obj,name);
893: return(0);
894: }
896: /*@C
897: MatView - Visualizes a matrix object.
899: Collective on Mat
901: Input Parameters:
902: + mat - the matrix
903: - viewer - visualization context
905: Notes:
906: The available visualization contexts include
907: + PETSC_VIEWER_STDOUT_SELF - for sequential matrices
908: . PETSC_VIEWER_STDOUT_WORLD - for parallel matrices created on PETSC_COMM_WORLD
909: . PETSC_VIEWER_STDOUT_(comm) - for matrices created on MPI communicator comm
910: - PETSC_VIEWER_DRAW_WORLD - graphical display of nonzero structure
912: The user can open alternative visualization contexts with
913: + PetscViewerASCIIOpen() - Outputs matrix to a specified file
914: . PetscViewerBinaryOpen() - Outputs matrix in binary to a
915: specified file; corresponding input uses MatLoad()
916: . PetscViewerDrawOpen() - Outputs nonzero matrix structure to
917: an X window display
918: - PetscViewerSocketOpen() - Outputs matrix to Socket viewer.
919: Currently only the sequential dense and AIJ
920: matrix types support the Socket viewer.
922: The user can call PetscViewerPushFormat() to specify the output
923: format of ASCII printed objects (when using PETSC_VIEWER_STDOUT_SELF,
924: PETSC_VIEWER_STDOUT_WORLD and PetscViewerASCIIOpen). Available formats include
925: + PETSC_VIEWER_DEFAULT - default, prints matrix contents
926: . PETSC_VIEWER_ASCII_MATLAB - prints matrix contents in Matlab format
927: . PETSC_VIEWER_ASCII_DENSE - prints entire matrix including zeros
928: . PETSC_VIEWER_ASCII_COMMON - prints matrix contents, using a sparse
929: format common among all matrix types
930: . PETSC_VIEWER_ASCII_IMPL - prints matrix contents, using an implementation-specific
931: format (which is in many cases the same as the default)
932: . PETSC_VIEWER_ASCII_INFO - prints basic information about the matrix
933: size and structure (not the matrix entries)
934: - PETSC_VIEWER_ASCII_INFO_DETAIL - prints more detailed information about
935: the matrix structure
937: Options Database Keys:
938: + -mat_view ::ascii_info - Prints info on matrix at conclusion of MatAssemblyEnd()
939: . -mat_view ::ascii_info_detail - Prints more detailed info
940: . -mat_view - Prints matrix in ASCII format
941: . -mat_view ::ascii_matlab - Prints matrix in Matlab format
942: . -mat_view draw - PetscDraws nonzero structure of matrix, using MatView() and PetscDrawOpenX().
943: . -display <name> - Sets display name (default is host)
944: . -draw_pause <sec> - Sets number of seconds to pause after display
945: . -mat_view socket - Sends matrix to socket, can be accessed from Matlab (see Users-Manual: Chapter 12 Using MATLAB with PETSc for details)
946: . -viewer_socket_machine <machine> -
947: . -viewer_socket_port <port> -
948: . -mat_view binary - save matrix to file in binary format
949: - -viewer_binary_filename <name> -
950: Level: beginner
952: Notes:
953: The ASCII viewers are only recommended for small matrices on at most a moderate number of processes,
954: the program will seemingly hang and take hours for larger matrices, for larger matrices one should use the binary format.
956: See the manual page for MatLoad() for the exact format of the binary file when the binary
957: viewer is used.
959: See share/petsc/matlab/PetscBinaryRead.m for a Matlab code that can read in the binary file when the binary
960: viewer is used.
962: One can use '-mat_view draw -draw_pause -1' to pause the graphical display of matrix nonzero structure,
963: and then use the following mouse functions.
964: + left mouse: zoom in
965: . middle mouse: zoom out
966: - right mouse: continue with the simulation
968: .seealso: PetscViewerPushFormat(), PetscViewerASCIIOpen(), PetscViewerDrawOpen(),
969: PetscViewerSocketOpen(), PetscViewerBinaryOpen(), MatLoad()
970: @*/
971: PetscErrorCode MatView(Mat mat,PetscViewer viewer)
972: {
973: PetscErrorCode ierr;
974: PetscInt rows,cols,rbs,cbs;
975: PetscBool iascii,ibinary,isstring;
976: PetscViewerFormat format;
977: PetscMPIInt size;
978: #if defined(PETSC_HAVE_SAWS)
979: PetscBool issaws;
980: #endif
985: if (!viewer) {
986: PetscViewerASCIIGetStdout(PetscObjectComm((PetscObject)mat),&viewer);
987: }
990: MatCheckPreallocated(mat,1);
991: PetscViewerGetFormat(viewer,&format);
992: MPI_Comm_size(PetscObjectComm((PetscObject)mat),&size);
993: if (size == 1 && format == PETSC_VIEWER_LOAD_BALANCE) return(0);
994: PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERBINARY,&ibinary);
995: PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERSTRING,&isstring);
996: if (ibinary) {
997: PetscBool mpiio;
998: PetscViewerBinaryGetUseMPIIO(viewer,&mpiio);
999: if (mpiio) SETERRQ(PetscObjectComm((PetscObject)viewer),PETSC_ERR_SUP,"PETSc matrix viewers do not support using MPI-IO, turn off that flag");
1000: }
1002: PetscLogEventBegin(MAT_View,mat,viewer,0,0);
1003: PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERASCII,&iascii);
1004: if ((!iascii || (format != PETSC_VIEWER_ASCII_INFO || format == PETSC_VIEWER_ASCII_INFO_DETAIL)) && mat->factortype) {
1005: SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"No viewers for factored matrix except ASCII info or info_detailed");
1006: }
1008: #if defined(PETSC_HAVE_SAWS)
1009: PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERSAWS,&issaws);
1010: #endif
1011: if (iascii) {
1012: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ORDER,"Must call MatAssemblyBegin/End() before viewing matrix");
1013: PetscObjectPrintClassNamePrefixType((PetscObject)mat,viewer);
1014: if (format == PETSC_VIEWER_ASCII_INFO || format == PETSC_VIEWER_ASCII_INFO_DETAIL) {
1015: MatNullSpace nullsp,transnullsp;
1017: PetscViewerASCIIPushTab(viewer);
1018: MatGetSize(mat,&rows,&cols);
1019: MatGetBlockSizes(mat,&rbs,&cbs);
1020: if (rbs != 1 || cbs != 1) {
1021: if (rbs != cbs) {PetscViewerASCIIPrintf(viewer,"rows=%D, cols=%D, rbs=%D, cbs=%D\n",rows,cols,rbs,cbs);}
1022: else {PetscViewerASCIIPrintf(viewer,"rows=%D, cols=%D, bs=%D\n",rows,cols,rbs);}
1023: } else {
1024: PetscViewerASCIIPrintf(viewer,"rows=%D, cols=%D\n",rows,cols);
1025: }
1026: if (mat->factortype) {
1027: MatSolverType solver;
1028: MatFactorGetSolverType(mat,&solver);
1029: PetscViewerASCIIPrintf(viewer,"package used to perform factorization: %s\n",solver);
1030: }
1031: if (mat->ops->getinfo) {
1032: MatInfo info;
1033: MatGetInfo(mat,MAT_GLOBAL_SUM,&info);
1034: PetscViewerASCIIPrintf(viewer,"total: nonzeros=%.f, allocated nonzeros=%.f\n",info.nz_used,info.nz_allocated);
1035: PetscViewerASCIIPrintf(viewer,"total number of mallocs used during MatSetValues calls=%D\n",(PetscInt)info.mallocs);
1036: }
1037: MatGetNullSpace(mat,&nullsp);
1038: MatGetTransposeNullSpace(mat,&transnullsp);
1039: if (nullsp) {PetscViewerASCIIPrintf(viewer," has attached null space\n");}
1040: if (transnullsp && transnullsp != nullsp) {PetscViewerASCIIPrintf(viewer," has attached transposed null space\n");}
1041: MatGetNearNullSpace(mat,&nullsp);
1042: if (nullsp) {PetscViewerASCIIPrintf(viewer," has attached near null space\n");}
1043: }
1044: #if defined(PETSC_HAVE_SAWS)
1045: } else if (issaws) {
1046: PetscMPIInt rank;
1048: PetscObjectName((PetscObject)mat);
1049: MPI_Comm_rank(PETSC_COMM_WORLD,&rank);
1050: if (!((PetscObject)mat)->amsmem && !rank) {
1051: PetscObjectViewSAWs((PetscObject)mat,viewer);
1052: }
1053: #endif
1054: } else if (isstring) {
1055: const char *type;
1056: MatGetType(mat,&type);
1057: PetscViewerStringSPrintf(viewer," MatType: %-7.7s",type);
1058: if (mat->ops->view) {(*mat->ops->view)(mat,viewer);}
1059: }
1060: if ((format == PETSC_VIEWER_NATIVE || format == PETSC_VIEWER_LOAD_BALANCE) && mat->ops->viewnative) {
1061: PetscViewerASCIIPushTab(viewer);
1062: (*mat->ops->viewnative)(mat,viewer);
1063: PetscViewerASCIIPopTab(viewer);
1064: } else if (mat->ops->view) {
1065: PetscViewerASCIIPushTab(viewer);
1066: (*mat->ops->view)(mat,viewer);
1067: PetscViewerASCIIPopTab(viewer);
1068: }
1069: if (iascii) {
1070: PetscViewerGetFormat(viewer,&format);
1071: if (format == PETSC_VIEWER_ASCII_INFO || format == PETSC_VIEWER_ASCII_INFO_DETAIL) {
1072: PetscViewerASCIIPopTab(viewer);
1073: }
1074: }
1075: PetscLogEventEnd(MAT_View,mat,viewer,0,0);
1076: return(0);
1077: }
1079: #if defined(PETSC_USE_DEBUG)
1080: #include <../src/sys/totalview/tv_data_display.h>
1081: PETSC_UNUSED static int TV_display_type(const struct _p_Mat *mat)
1082: {
1083: TV_add_row("Local rows", "int", &mat->rmap->n);
1084: TV_add_row("Local columns", "int", &mat->cmap->n);
1085: TV_add_row("Global rows", "int", &mat->rmap->N);
1086: TV_add_row("Global columns", "int", &mat->cmap->N);
1087: TV_add_row("Typename", TV_ascii_string_type, ((PetscObject)mat)->type_name);
1088: return TV_format_OK;
1089: }
1090: #endif
1092: /*@C
1093: MatLoad - Loads a matrix that has been stored in binary/HDF5 format
1094: with MatView(). The matrix format is determined from the options database.
1095: Generates a parallel MPI matrix if the communicator has more than one
1096: processor. The default matrix type is AIJ.
1098: Collective on PetscViewer
1100: Input Parameters:
1101: + newmat - the newly loaded matrix, this needs to have been created with MatCreate()
1102: or some related function before a call to MatLoad()
1103: - viewer - binary/HDF5 file viewer
1105: Options Database Keys:
1106: Used with block matrix formats (MATSEQBAIJ, ...) to specify
1107: block size
1108: . -matload_block_size <bs>
1110: Level: beginner
1112: Notes:
1113: If the Mat type has not yet been given then MATAIJ is used, call MatSetFromOptions() on the
1114: Mat before calling this routine if you wish to set it from the options database.
1116: MatLoad() automatically loads into the options database any options
1117: given in the file filename.info where filename is the name of the file
1118: that was passed to the PetscViewerBinaryOpen(). The options in the info
1119: file will be ignored if you use the -viewer_binary_skip_info option.
1121: If the type or size of newmat is not set before a call to MatLoad, PETSc
1122: sets the default matrix type AIJ and sets the local and global sizes.
1123: If type and/or size is already set, then the same are used.
1125: In parallel, each processor can load a subset of rows (or the
1126: entire matrix). This routine is especially useful when a large
1127: matrix is stored on disk and only part of it is desired on each
1128: processor. For example, a parallel solver may access only some of
1129: the rows from each processor. The algorithm used here reads
1130: relatively small blocks of data rather than reading the entire
1131: matrix and then subsetting it.
1133: Viewer's PetscViewerType must be either PETSCVIEWERBINARY or PETSCVIEWERHDF5.
1134: Such viewer can be created using PetscViewerBinaryOpen()/PetscViewerHDF5Open(),
1135: or the sequence like
1136: $ PetscViewer v;
1137: $ PetscViewerCreate(PETSC_COMM_WORLD,&v);
1138: $ PetscViewerSetType(v,PETSCVIEWERBINARY);
1139: $ PetscViewerSetFromOptions(v);
1140: $ PetscViewerFileSetMode(v,FILE_MODE_READ);
1141: $ PetscViewerFileSetName(v,"datafile");
1142: The optional PetscViewerSetFromOptions() call allows to override PetscViewerSetType() using option
1143: $ -viewer_type {binary,hdf5}
1145: See the example src/ksp/ksp/examples/tutorials/ex27.c with the first approach,
1146: and src/mat/examples/tutorials/ex10.c with the second approach.
1148: Notes about the PETSc binary format:
1149: In case of PETSCVIEWERBINARY, a native PETSc binary format is used. Each of the blocks
1150: is read onto rank 0 and then shipped to its destination rank, one after another.
1151: Multiple objects, both matrices and vectors, can be stored within the same file.
1152: Their PetscObject name is ignored; they are loaded in the order of their storage.
1154: Most users should not need to know the details of the binary storage
1155: format, since MatLoad() and MatView() completely hide these details.
1156: But for anyone who's interested, the standard binary matrix storage
1157: format is
1159: $ PetscInt MAT_FILE_CLASSID
1160: $ PetscInt number of rows
1161: $ PetscInt number of columns
1162: $ PetscInt total number of nonzeros
1163: $ PetscInt *number nonzeros in each row
1164: $ PetscInt *column indices of all nonzeros (starting index is zero)
1165: $ PetscScalar *values of all nonzeros
1167: PETSc automatically does the byte swapping for
1168: machines that store the bytes reversed, e.g. DEC alpha, freebsd,
1169: linux, Windows and the paragon; thus if you write your own binary
1170: read/write routines you have to swap the bytes; see PetscBinaryRead()
1171: and PetscBinaryWrite() to see how this may be done.
1173: Notes about the HDF5 (MATLAB MAT-File Version 7.3) format:
1174: In case of PETSCVIEWERHDF5, a parallel HDF5 reader is used.
1175: Each processor's chunk is loaded independently by its owning rank.
1176: Multiple objects, both matrices and vectors, can be stored within the same file.
1177: They are looked up by their PetscObject name.
1179: As the MATLAB MAT-File Version 7.3 format is also a HDF5 flavor, we decided to use
1180: by default the same structure and naming of the AIJ arrays and column count
1181: within the HDF5 file. This means that a MAT file saved with -v7.3 flag, e.g.
1182: $ save example.mat A b -v7.3
1183: can be directly read by this routine (see Reference 1 for details).
1184: Note that depending on your MATLAB version, this format might be a default,
1185: otherwise you can set it as default in Preferences.
1187: Unless -nocompression flag is used to save the file in MATLAB,
1188: PETSc must be configured with ZLIB package.
1190: See also examples src/mat/examples/tutorials/ex10.c and src/ksp/ksp/examples/tutorials/ex27.c
1192: Current HDF5 (MAT-File) limitations:
1193: This reader currently supports only real MATSEQAIJ, MATMPIAIJ, MATSEQDENSE and MATMPIDENSE matrices.
1195: Corresponding MatView() is not yet implemented.
1197: The loaded matrix is actually a transpose of the original one in MATLAB,
1198: unless you push PETSC_VIEWER_HDF5_MAT format (see examples above).
1199: With this format, matrix is automatically transposed by PETSc,
1200: unless the matrix is marked as SPD or symmetric
1201: (see MatSetOption(), MAT_SPD, MAT_SYMMETRIC).
1203: References:
1204: 1. MATLAB(R) Documentation, manual page of save(), https://www.mathworks.com/help/matlab/ref/save.html#btox10b-1-version
1206: .seealso: PetscViewerBinaryOpen(), PetscViewerSetType(), MatView(), VecLoad()
1208: @*/
1209: PetscErrorCode MatLoad(Mat newmat,PetscViewer viewer)
1210: {
1212: PetscBool flg;
1218: if (!((PetscObject)newmat)->type_name) {
1219: MatSetType(newmat,MATAIJ);
1220: }
1222: flg = PETSC_FALSE;
1223: PetscOptionsGetBool(((PetscObject)newmat)->options,((PetscObject)newmat)->prefix,"-matload_symmetric",&flg,NULL);
1224: if (flg) {
1225: MatSetOption(newmat,MAT_SYMMETRIC,PETSC_TRUE);
1226: MatSetOption(newmat,MAT_SYMMETRY_ETERNAL,PETSC_TRUE);
1227: }
1228: flg = PETSC_FALSE;
1229: PetscOptionsGetBool(((PetscObject)newmat)->options,((PetscObject)newmat)->prefix,"-matload_spd",&flg,NULL);
1230: if (flg) {
1231: MatSetOption(newmat,MAT_SPD,PETSC_TRUE);
1232: }
1234: if (!newmat->ops->load) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"MatLoad is not supported for type");
1235: PetscLogEventBegin(MAT_Load,viewer,0,0,0);
1236: (*newmat->ops->load)(newmat,viewer);
1237: PetscLogEventEnd(MAT_Load,viewer,0,0,0);
1238: return(0);
1239: }
1241: PetscErrorCode MatDestroy_Redundant(Mat_Redundant **redundant)
1242: {
1244: Mat_Redundant *redund = *redundant;
1245: PetscInt i;
1248: if (redund){
1249: if (redund->matseq) { /* via MatCreateSubMatrices() */
1250: ISDestroy(&redund->isrow);
1251: ISDestroy(&redund->iscol);
1252: MatDestroySubMatrices(1,&redund->matseq);
1253: } else {
1254: PetscFree2(redund->send_rank,redund->recv_rank);
1255: PetscFree(redund->sbuf_j);
1256: PetscFree(redund->sbuf_a);
1257: for (i=0; i<redund->nrecvs; i++) {
1258: PetscFree(redund->rbuf_j[i]);
1259: PetscFree(redund->rbuf_a[i]);
1260: }
1261: PetscFree4(redund->sbuf_nz,redund->rbuf_nz,redund->rbuf_j,redund->rbuf_a);
1262: }
1264: if (redund->subcomm) {
1265: PetscCommDestroy(&redund->subcomm);
1266: }
1267: PetscFree(redund);
1268: }
1269: return(0);
1270: }
1272: /*@
1273: MatDestroy - Frees space taken by a matrix.
1275: Collective on Mat
1277: Input Parameter:
1278: . A - the matrix
1280: Level: beginner
1282: @*/
1283: PetscErrorCode MatDestroy(Mat *A)
1284: {
1288: if (!*A) return(0);
1290: if (--((PetscObject)(*A))->refct > 0) {*A = NULL; return(0);}
1292: /* if memory was published with SAWs then destroy it */
1293: PetscObjectSAWsViewOff((PetscObject)*A);
1294: if ((*A)->ops->destroy) {
1295: (*(*A)->ops->destroy)(*A);
1296: }
1298: PetscFree((*A)->defaultvectype);
1299: PetscFree((*A)->bsizes);
1300: PetscFree((*A)->solvertype);
1301: MatDestroy_Redundant(&(*A)->redundant);
1302: MatNullSpaceDestroy(&(*A)->nullsp);
1303: MatNullSpaceDestroy(&(*A)->transnullsp);
1304: MatNullSpaceDestroy(&(*A)->nearnullsp);
1305: MatDestroy(&(*A)->schur);
1306: PetscLayoutDestroy(&(*A)->rmap);
1307: PetscLayoutDestroy(&(*A)->cmap);
1308: PetscHeaderDestroy(A);
1309: return(0);
1310: }
1312: /*@C
1313: MatSetValues - Inserts or adds a block of values into a matrix.
1314: These values may be cached, so MatAssemblyBegin() and MatAssemblyEnd()
1315: MUST be called after all calls to MatSetValues() have been completed.
1317: Not Collective
1319: Input Parameters:
1320: + mat - the matrix
1321: . v - a logically two-dimensional array of values
1322: . m, idxm - the number of rows and their global indices
1323: . n, idxn - the number of columns and their global indices
1324: - addv - either ADD_VALUES or INSERT_VALUES, where
1325: ADD_VALUES adds values to any existing entries, and
1326: INSERT_VALUES replaces existing entries with new values
1328: Notes:
1329: If you create the matrix yourself (that is not with a call to DMCreateMatrix()) then you MUST call MatXXXXSetPreallocation() or
1330: MatSetUp() before using this routine
1332: By default the values, v, are row-oriented. See MatSetOption() for other options.
1334: Calls to MatSetValues() with the INSERT_VALUES and ADD_VALUES
1335: options cannot be mixed without intervening calls to the assembly
1336: routines.
1338: MatSetValues() uses 0-based row and column numbers in Fortran
1339: as well as in C.
1341: Negative indices may be passed in idxm and idxn, these rows and columns are
1342: simply ignored. This allows easily inserting element stiffness matrices
1343: with homogeneous Dirchlet boundary conditions that you don't want represented
1344: in the matrix.
1346: Efficiency Alert:
1347: The routine MatSetValuesBlocked() may offer much better efficiency
1348: for users of block sparse formats (MATSEQBAIJ and MATMPIBAIJ).
1350: Level: beginner
1352: Developer Notes:
1353: This is labeled with C so does not automatically generate Fortran stubs and interfaces
1354: because it requires multiple Fortran interfaces depending on which arguments are scalar or arrays.
1356: .seealso: MatSetOption(), MatAssemblyBegin(), MatAssemblyEnd(), MatSetValuesBlocked(), MatSetValuesLocal(),
1357: InsertMode, INSERT_VALUES, ADD_VALUES
1358: @*/
1359: PetscErrorCode MatSetValues(Mat mat,PetscInt m,const PetscInt idxm[],PetscInt n,const PetscInt idxn[],const PetscScalar v[],InsertMode addv)
1360: {
1362: #if defined(PETSC_USE_DEBUG)
1363: PetscInt i,j;
1364: #endif
1369: if (!m || !n) return(0); /* no values to insert */
1372: MatCheckPreallocated(mat,1);
1374: if (mat->insertmode == NOT_SET_VALUES) {
1375: mat->insertmode = addv;
1376: }
1377: #if defined(PETSC_USE_DEBUG)
1378: else if (mat->insertmode != addv) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Cannot mix add values and insert values");
1379: if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
1380: if (!mat->ops->setvalues) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
1382: for (i=0; i<m; i++) {
1383: for (j=0; j<n; j++) {
1384: if (mat->erroriffailure && PetscIsInfOrNanScalar(v[i*n+j]))
1385: #if defined(PETSC_USE_COMPLEX)
1386: 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]);
1387: #else
1388: SETERRQ3(PETSC_COMM_SELF,PETSC_ERR_FP,"Inserting %g at matrix entry (%D,%D)",(double)v[i*n+j],idxm[i],idxn[j]);
1389: #endif
1390: }
1391: }
1392: #endif
1394: if (mat->assembled) {
1395: mat->was_assembled = PETSC_TRUE;
1396: mat->assembled = PETSC_FALSE;
1397: }
1398: PetscLogEventBegin(MAT_SetValues,mat,0,0,0);
1399: (*mat->ops->setvalues)(mat,m,idxm,n,idxn,v,addv);
1400: PetscLogEventEnd(MAT_SetValues,mat,0,0,0);
1401: return(0);
1402: }
1405: /*@
1406: MatSetValuesRowLocal - Inserts a row (block row for BAIJ matrices) of nonzero
1407: values into a matrix
1409: Not Collective
1411: Input Parameters:
1412: + mat - the matrix
1413: . row - the (block) row to set
1414: - v - a logically two-dimensional array of values
1416: Notes:
1417: By the values, v, are column-oriented (for the block version) and sorted
1419: All the nonzeros in the row must be provided
1421: The matrix must have previously had its column indices set
1423: The row must belong to this process
1425: Level: intermediate
1427: .seealso: MatSetOption(), MatAssemblyBegin(), MatAssemblyEnd(), MatSetValuesBlocked(), MatSetValuesLocal(),
1428: InsertMode, INSERT_VALUES, ADD_VALUES, MatSetValues(), MatSetValuesRow(), MatSetLocalToGlobalMapping()
1429: @*/
1430: PetscErrorCode MatSetValuesRowLocal(Mat mat,PetscInt row,const PetscScalar v[])
1431: {
1433: PetscInt globalrow;
1439: ISLocalToGlobalMappingApply(mat->rmap->mapping,1,&row,&globalrow);
1440: MatSetValuesRow(mat,globalrow,v);
1441: return(0);
1442: }
1444: /*@
1445: MatSetValuesRow - Inserts a row (block row for BAIJ matrices) of nonzero
1446: values into a matrix
1448: Not Collective
1450: Input Parameters:
1451: + mat - the matrix
1452: . row - the (block) row to set
1453: - 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
1455: Notes:
1456: The values, v, are column-oriented for the block version.
1458: All the nonzeros in the row must be provided
1460: THE MATRIX MUST HAVE PREVIOUSLY HAD ITS COLUMN INDICES SET. IT IS RARE THAT THIS ROUTINE IS USED, usually MatSetValues() is used.
1462: The row must belong to this process
1464: Level: advanced
1466: .seealso: MatSetOption(), MatAssemblyBegin(), MatAssemblyEnd(), MatSetValuesBlocked(), MatSetValuesLocal(),
1467: InsertMode, INSERT_VALUES, ADD_VALUES, MatSetValues()
1468: @*/
1469: PetscErrorCode MatSetValuesRow(Mat mat,PetscInt row,const PetscScalar v[])
1470: {
1476: MatCheckPreallocated(mat,1);
1478: #if defined(PETSC_USE_DEBUG)
1479: if (mat->insertmode == ADD_VALUES) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Cannot mix add and insert values");
1480: if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
1481: #endif
1482: mat->insertmode = INSERT_VALUES;
1484: if (mat->assembled) {
1485: mat->was_assembled = PETSC_TRUE;
1486: mat->assembled = PETSC_FALSE;
1487: }
1488: PetscLogEventBegin(MAT_SetValues,mat,0,0,0);
1489: if (!mat->ops->setvaluesrow) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
1490: (*mat->ops->setvaluesrow)(mat,row,v);
1491: PetscLogEventEnd(MAT_SetValues,mat,0,0,0);
1492: return(0);
1493: }
1495: /*@
1496: MatSetValuesStencil - Inserts or adds a block of values into a matrix.
1497: Using structured grid indexing
1499: Not Collective
1501: Input Parameters:
1502: + mat - the matrix
1503: . m - number of rows being entered
1504: . idxm - grid coordinates (and component number when dof > 1) for matrix rows being entered
1505: . n - number of columns being entered
1506: . idxn - grid coordinates (and component number when dof > 1) for matrix columns being entered
1507: . v - a logically two-dimensional array of values
1508: - addv - either ADD_VALUES or INSERT_VALUES, where
1509: ADD_VALUES adds values to any existing entries, and
1510: INSERT_VALUES replaces existing entries with new values
1512: Notes:
1513: By default the values, v, are row-oriented. See MatSetOption() for other options.
1515: Calls to MatSetValuesStencil() with the INSERT_VALUES and ADD_VALUES
1516: options cannot be mixed without intervening calls to the assembly
1517: routines.
1519: The grid coordinates are across the entire grid, not just the local portion
1521: MatSetValuesStencil() uses 0-based row and column numbers in Fortran
1522: as well as in C.
1524: For setting/accessing vector values via array coordinates you can use the DMDAVecGetArray() routine
1526: In order to use this routine you must either obtain the matrix with DMCreateMatrix()
1527: or call MatSetLocalToGlobalMapping() and MatSetStencil() first.
1529: The columns and rows in the stencil passed in MUST be contained within the
1530: ghost region of the given process as set with DMDACreateXXX() or MatSetStencil(). For example,
1531: if you create a DMDA with an overlap of one grid level and on a particular process its first
1532: local nonghost x logical coordinate is 6 (so its first ghost x logical coordinate is 5) the
1533: first i index you can use in your column and row indices in MatSetStencil() is 5.
1535: In Fortran idxm and idxn should be declared as
1536: $ MatStencil idxm(4,m),idxn(4,n)
1537: and the values inserted using
1538: $ idxm(MatStencil_i,1) = i
1539: $ idxm(MatStencil_j,1) = j
1540: $ idxm(MatStencil_k,1) = k
1541: $ idxm(MatStencil_c,1) = c
1542: etc
1544: For periodic boundary conditions use negative indices for values to the left (below 0; that are to be
1545: obtained by wrapping values from right edge). For values to the right of the last entry using that index plus one
1546: etc to obtain values that obtained by wrapping the values from the left edge. This does not work for anything but the
1547: DM_BOUNDARY_PERIODIC boundary type.
1549: 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
1550: a single value per point) you can skip filling those indices.
1552: Inspired by the structured grid interface to the HYPRE package
1553: (https://computation.llnl.gov/projects/hypre-scalable-linear-solvers-multigrid-methods)
1555: Efficiency Alert:
1556: The routine MatSetValuesBlockedStencil() may offer much better efficiency
1557: for users of block sparse formats (MATSEQBAIJ and MATMPIBAIJ).
1559: Level: beginner
1561: .seealso: MatSetOption(), MatAssemblyBegin(), MatAssemblyEnd(), MatSetValuesBlocked(), MatSetValuesLocal()
1562: MatSetValues(), MatSetValuesBlockedStencil(), MatSetStencil(), DMCreateMatrix(), DMDAVecGetArray(), MatStencil
1563: @*/
1564: PetscErrorCode MatSetValuesStencil(Mat mat,PetscInt m,const MatStencil idxm[],PetscInt n,const MatStencil idxn[],const PetscScalar v[],InsertMode addv)
1565: {
1567: PetscInt buf[8192],*bufm=0,*bufn=0,*jdxm,*jdxn;
1568: PetscInt j,i,dim = mat->stencil.dim,*dims = mat->stencil.dims+1,tmp;
1569: PetscInt *starts = mat->stencil.starts,*dxm = (PetscInt*)idxm,*dxn = (PetscInt*)idxn,sdim = dim - (1 - (PetscInt)mat->stencil.noc);
1572: if (!m || !n) return(0); /* no values to insert */
1578: if ((m+n) <= (PetscInt)(sizeof(buf)/sizeof(PetscInt))) {
1579: jdxm = buf; jdxn = buf+m;
1580: } else {
1581: PetscMalloc2(m,&bufm,n,&bufn);
1582: jdxm = bufm; jdxn = bufn;
1583: }
1584: for (i=0; i<m; i++) {
1585: for (j=0; j<3-sdim; j++) dxm++;
1586: tmp = *dxm++ - starts[0];
1587: for (j=0; j<dim-1; j++) {
1588: if ((*dxm++ - starts[j+1]) < 0 || tmp < 0) tmp = -1;
1589: else tmp = tmp*dims[j] + *(dxm-1) - starts[j+1];
1590: }
1591: if (mat->stencil.noc) dxm++;
1592: jdxm[i] = tmp;
1593: }
1594: for (i=0; i<n; i++) {
1595: for (j=0; j<3-sdim; j++) dxn++;
1596: tmp = *dxn++ - starts[0];
1597: for (j=0; j<dim-1; j++) {
1598: if ((*dxn++ - starts[j+1]) < 0 || tmp < 0) tmp = -1;
1599: else tmp = tmp*dims[j] + *(dxn-1) - starts[j+1];
1600: }
1601: if (mat->stencil.noc) dxn++;
1602: jdxn[i] = tmp;
1603: }
1604: MatSetValuesLocal(mat,m,jdxm,n,jdxn,v,addv);
1605: PetscFree2(bufm,bufn);
1606: return(0);
1607: }
1609: /*@
1610: MatSetValuesBlockedStencil - Inserts or adds a block of values into a matrix.
1611: Using structured grid indexing
1613: Not Collective
1615: Input Parameters:
1616: + mat - the matrix
1617: . m - number of rows being entered
1618: . idxm - grid coordinates for matrix rows being entered
1619: . n - number of columns being entered
1620: . idxn - grid coordinates for matrix columns being entered
1621: . v - a logically two-dimensional array of values
1622: - addv - either ADD_VALUES or INSERT_VALUES, where
1623: ADD_VALUES adds values to any existing entries, and
1624: INSERT_VALUES replaces existing entries with new values
1626: Notes:
1627: By default the values, v, are row-oriented and unsorted.
1628: See MatSetOption() for other options.
1630: Calls to MatSetValuesBlockedStencil() with the INSERT_VALUES and ADD_VALUES
1631: options cannot be mixed without intervening calls to the assembly
1632: routines.
1634: The grid coordinates are across the entire grid, not just the local portion
1636: MatSetValuesBlockedStencil() uses 0-based row and column numbers in Fortran
1637: as well as in C.
1639: For setting/accessing vector values via array coordinates you can use the DMDAVecGetArray() routine
1641: In order to use this routine you must either obtain the matrix with DMCreateMatrix()
1642: or call MatSetBlockSize(), MatSetLocalToGlobalMapping() and MatSetStencil() first.
1644: The columns and rows in the stencil passed in MUST be contained within the
1645: ghost region of the given process as set with DMDACreateXXX() or MatSetStencil(). For example,
1646: if you create a DMDA with an overlap of one grid level and on a particular process its first
1647: local nonghost x logical coordinate is 6 (so its first ghost x logical coordinate is 5) the
1648: first i index you can use in your column and row indices in MatSetStencil() is 5.
1650: In Fortran idxm and idxn should be declared as
1651: $ MatStencil idxm(4,m),idxn(4,n)
1652: and the values inserted using
1653: $ idxm(MatStencil_i,1) = i
1654: $ idxm(MatStencil_j,1) = j
1655: $ idxm(MatStencil_k,1) = k
1656: etc
1658: Negative indices may be passed in idxm and idxn, these rows and columns are
1659: simply ignored. This allows easily inserting element stiffness matrices
1660: with homogeneous Dirchlet boundary conditions that you don't want represented
1661: in the matrix.
1663: Inspired by the structured grid interface to the HYPRE package
1664: (https://computation.llnl.gov/projects/hypre-scalable-linear-solvers-multigrid-methods)
1666: Level: beginner
1668: .seealso: MatSetOption(), MatAssemblyBegin(), MatAssemblyEnd(), MatSetValuesBlocked(), MatSetValuesLocal()
1669: MatSetValues(), MatSetValuesStencil(), MatSetStencil(), DMCreateMatrix(), DMDAVecGetArray(), MatStencil,
1670: MatSetBlockSize(), MatSetLocalToGlobalMapping()
1671: @*/
1672: PetscErrorCode MatSetValuesBlockedStencil(Mat mat,PetscInt m,const MatStencil idxm[],PetscInt n,const MatStencil idxn[],const PetscScalar v[],InsertMode addv)
1673: {
1675: PetscInt buf[8192],*bufm=0,*bufn=0,*jdxm,*jdxn;
1676: PetscInt j,i,dim = mat->stencil.dim,*dims = mat->stencil.dims+1,tmp;
1677: PetscInt *starts = mat->stencil.starts,*dxm = (PetscInt*)idxm,*dxn = (PetscInt*)idxn,sdim = dim - (1 - (PetscInt)mat->stencil.noc);
1680: if (!m || !n) return(0); /* no values to insert */
1687: if ((m+n) <= (PetscInt)(sizeof(buf)/sizeof(PetscInt))) {
1688: jdxm = buf; jdxn = buf+m;
1689: } else {
1690: PetscMalloc2(m,&bufm,n,&bufn);
1691: jdxm = bufm; jdxn = bufn;
1692: }
1693: for (i=0; i<m; i++) {
1694: for (j=0; j<3-sdim; j++) dxm++;
1695: tmp = *dxm++ - starts[0];
1696: for (j=0; j<sdim-1; j++) {
1697: if ((*dxm++ - starts[j+1]) < 0 || tmp < 0) tmp = -1;
1698: else tmp = tmp*dims[j] + *(dxm-1) - starts[j+1];
1699: }
1700: dxm++;
1701: jdxm[i] = tmp;
1702: }
1703: for (i=0; i<n; i++) {
1704: for (j=0; j<3-sdim; j++) dxn++;
1705: tmp = *dxn++ - starts[0];
1706: for (j=0; j<sdim-1; j++) {
1707: if ((*dxn++ - starts[j+1]) < 0 || tmp < 0) tmp = -1;
1708: else tmp = tmp*dims[j] + *(dxn-1) - starts[j+1];
1709: }
1710: dxn++;
1711: jdxn[i] = tmp;
1712: }
1713: MatSetValuesBlockedLocal(mat,m,jdxm,n,jdxn,v,addv);
1714: PetscFree2(bufm,bufn);
1715: return(0);
1716: }
1718: /*@
1719: MatSetStencil - Sets the grid information for setting values into a matrix via
1720: MatSetValuesStencil()
1722: Not Collective
1724: Input Parameters:
1725: + mat - the matrix
1726: . dim - dimension of the grid 1, 2, or 3
1727: . dims - number of grid points in x, y, and z direction, including ghost points on your processor
1728: . starts - starting point of ghost nodes on your processor in x, y, and z direction
1729: - dof - number of degrees of freedom per node
1732: Inspired by the structured grid interface to the HYPRE package
1733: (www.llnl.gov/CASC/hyper)
1735: For matrices generated with DMCreateMatrix() this routine is automatically called and so not needed by the
1736: user.
1738: Level: beginner
1740: .seealso: MatSetOption(), MatAssemblyBegin(), MatAssemblyEnd(), MatSetValuesBlocked(), MatSetValuesLocal()
1741: MatSetValues(), MatSetValuesBlockedStencil(), MatSetValuesStencil()
1742: @*/
1743: PetscErrorCode MatSetStencil(Mat mat,PetscInt dim,const PetscInt dims[],const PetscInt starts[],PetscInt dof)
1744: {
1745: PetscInt i;
1752: mat->stencil.dim = dim + (dof > 1);
1753: for (i=0; i<dim; i++) {
1754: mat->stencil.dims[i] = dims[dim-i-1]; /* copy the values in backwards */
1755: mat->stencil.starts[i] = starts[dim-i-1];
1756: }
1757: mat->stencil.dims[dim] = dof;
1758: mat->stencil.starts[dim] = 0;
1759: mat->stencil.noc = (PetscBool)(dof == 1);
1760: return(0);
1761: }
1763: /*@C
1764: MatSetValuesBlocked - Inserts or adds a block of values into a matrix.
1766: Not Collective
1768: Input Parameters:
1769: + mat - the matrix
1770: . v - a logically two-dimensional array of values
1771: . m, idxm - the number of block rows and their global block indices
1772: . n, idxn - the number of block columns and their global block indices
1773: - addv - either ADD_VALUES or INSERT_VALUES, where
1774: ADD_VALUES adds values to any existing entries, and
1775: INSERT_VALUES replaces existing entries with new values
1777: Notes:
1778: If you create the matrix yourself (that is not with a call to DMCreateMatrix()) then you MUST call
1779: MatXXXXSetPreallocation() or MatSetUp() before using this routine.
1781: The m and n count the NUMBER of blocks in the row direction and column direction,
1782: NOT the total number of rows/columns; for example, if the block size is 2 and
1783: you are passing in values for rows 2,3,4,5 then m would be 2 (not 4).
1784: The values in idxm would be 1 2; that is the first index for each block divided by
1785: the block size.
1787: Note that you must call MatSetBlockSize() when constructing this matrix (before
1788: preallocating it).
1790: By default the values, v, are row-oriented, so the layout of
1791: v is the same as for MatSetValues(). See MatSetOption() for other options.
1793: Calls to MatSetValuesBlocked() with the INSERT_VALUES and ADD_VALUES
1794: options cannot be mixed without intervening calls to the assembly
1795: routines.
1797: MatSetValuesBlocked() uses 0-based row and column numbers in Fortran
1798: as well as in C.
1800: Negative indices may be passed in idxm and idxn, these rows and columns are
1801: simply ignored. This allows easily inserting element stiffness matrices
1802: with homogeneous Dirchlet boundary conditions that you don't want represented
1803: in the matrix.
1805: Each time an entry is set within a sparse matrix via MatSetValues(),
1806: internal searching must be done to determine where to place the
1807: data in the matrix storage space. By instead inserting blocks of
1808: entries via MatSetValuesBlocked(), the overhead of matrix assembly is
1809: reduced.
1811: Example:
1812: $ Suppose m=n=2 and block size(bs) = 2 The array is
1813: $
1814: $ 1 2 | 3 4
1815: $ 5 6 | 7 8
1816: $ - - - | - - -
1817: $ 9 10 | 11 12
1818: $ 13 14 | 15 16
1819: $
1820: $ v[] should be passed in like
1821: $ v[] = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]
1822: $
1823: $ If you are not using row oriented storage of v (that is you called MatSetOption(mat,MAT_ROW_ORIENTED,PETSC_FALSE)) then
1824: $ v[] = [1,5,9,13,2,6,10,14,3,7,11,15,4,8,12,16]
1826: Level: intermediate
1828: .seealso: MatSetBlockSize(), MatSetOption(), MatAssemblyBegin(), MatAssemblyEnd(), MatSetValues(), MatSetValuesBlockedLocal()
1829: @*/
1830: PetscErrorCode MatSetValuesBlocked(Mat mat,PetscInt m,const PetscInt idxm[],PetscInt n,const PetscInt idxn[],const PetscScalar v[],InsertMode addv)
1831: {
1837: if (!m || !n) return(0); /* no values to insert */
1841: MatCheckPreallocated(mat,1);
1842: if (mat->insertmode == NOT_SET_VALUES) {
1843: mat->insertmode = addv;
1844: }
1845: #if defined(PETSC_USE_DEBUG)
1846: else if (mat->insertmode != addv) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Cannot mix add values and insert values");
1847: if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
1848: if (!mat->ops->setvaluesblocked && !mat->ops->setvalues) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
1849: #endif
1851: if (mat->assembled) {
1852: mat->was_assembled = PETSC_TRUE;
1853: mat->assembled = PETSC_FALSE;
1854: }
1855: PetscLogEventBegin(MAT_SetValues,mat,0,0,0);
1856: if (mat->ops->setvaluesblocked) {
1857: (*mat->ops->setvaluesblocked)(mat,m,idxm,n,idxn,v,addv);
1858: } else {
1859: PetscInt buf[8192],*bufr=0,*bufc=0,*iidxm,*iidxn;
1860: PetscInt i,j,bs,cbs;
1861: MatGetBlockSizes(mat,&bs,&cbs);
1862: if (m*bs+n*cbs <= (PetscInt)(sizeof(buf)/sizeof(PetscInt))) {
1863: iidxm = buf; iidxn = buf + m*bs;
1864: } else {
1865: PetscMalloc2(m*bs,&bufr,n*cbs,&bufc);
1866: iidxm = bufr; iidxn = bufc;
1867: }
1868: for (i=0; i<m; i++) {
1869: for (j=0; j<bs; j++) {
1870: iidxm[i*bs+j] = bs*idxm[i] + j;
1871: }
1872: }
1873: for (i=0; i<n; i++) {
1874: for (j=0; j<cbs; j++) {
1875: iidxn[i*cbs+j] = cbs*idxn[i] + j;
1876: }
1877: }
1878: MatSetValues(mat,m*bs,iidxm,n*cbs,iidxn,v,addv);
1879: PetscFree2(bufr,bufc);
1880: }
1881: PetscLogEventEnd(MAT_SetValues,mat,0,0,0);
1882: return(0);
1883: }
1885: /*@
1886: MatGetValues - Gets a block of values from a matrix.
1888: Not Collective; currently only returns a local block
1890: Input Parameters:
1891: + mat - the matrix
1892: . v - a logically two-dimensional array for storing the values
1893: . m, idxm - the number of rows and their global indices
1894: - n, idxn - the number of columns and their global indices
1896: Notes:
1897: The user must allocate space (m*n PetscScalars) for the values, v.
1898: The values, v, are then returned in a row-oriented format,
1899: analogous to that used by default in MatSetValues().
1901: MatGetValues() uses 0-based row and column numbers in
1902: Fortran as well as in C.
1904: MatGetValues() requires that the matrix has been assembled
1905: with MatAssemblyBegin()/MatAssemblyEnd(). Thus, calls to
1906: MatSetValues() and MatGetValues() CANNOT be made in succession
1907: without intermediate matrix assembly.
1909: Negative row or column indices will be ignored and those locations in v[] will be
1910: left unchanged.
1912: Level: advanced
1914: .seealso: MatGetRow(), MatCreateSubMatrices(), MatSetValues()
1915: @*/
1916: PetscErrorCode MatGetValues(Mat mat,PetscInt m,const PetscInt idxm[],PetscInt n,const PetscInt idxn[],PetscScalar v[])
1917: {
1923: if (!m || !n) return(0);
1927: if (!mat->assembled) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
1928: if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
1929: if (!mat->ops->getvalues) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
1930: MatCheckPreallocated(mat,1);
1932: PetscLogEventBegin(MAT_GetValues,mat,0,0,0);
1933: (*mat->ops->getvalues)(mat,m,idxm,n,idxn,v);
1934: PetscLogEventEnd(MAT_GetValues,mat,0,0,0);
1935: return(0);
1936: }
1938: /*@
1939: MatSetValuesBatch - Adds (ADD_VALUES) many blocks of values into a matrix at once. The blocks must all be square and
1940: the same size. Currently, this can only be called once and creates the given matrix.
1942: Not Collective
1944: Input Parameters:
1945: + mat - the matrix
1946: . nb - the number of blocks
1947: . bs - the number of rows (and columns) in each block
1948: . rows - a concatenation of the rows for each block
1949: - v - a concatenation of logically two-dimensional arrays of values
1951: Notes:
1952: In the future, we will extend this routine to handle rectangular blocks, and to allow multiple calls for a given matrix.
1954: Level: advanced
1956: .seealso: MatSetOption(), MatAssemblyBegin(), MatAssemblyEnd(), MatSetValuesBlocked(), MatSetValuesLocal(),
1957: InsertMode, INSERT_VALUES, ADD_VALUES, MatSetValues()
1958: @*/
1959: PetscErrorCode MatSetValuesBatch(Mat mat, PetscInt nb, PetscInt bs, PetscInt rows[], const PetscScalar v[])
1960: {
1968: #if defined(PETSC_USE_DEBUG)
1969: if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
1970: #endif
1972: PetscLogEventBegin(MAT_SetValuesBatch,mat,0,0,0);
1973: if (mat->ops->setvaluesbatch) {
1974: (*mat->ops->setvaluesbatch)(mat,nb,bs,rows,v);
1975: } else {
1976: PetscInt b;
1977: for (b = 0; b < nb; ++b) {
1978: MatSetValues(mat, bs, &rows[b*bs], bs, &rows[b*bs], &v[b*bs*bs], ADD_VALUES);
1979: }
1980: }
1981: PetscLogEventEnd(MAT_SetValuesBatch,mat,0,0,0);
1982: return(0);
1983: }
1985: /*@
1986: MatSetLocalToGlobalMapping - Sets a local-to-global numbering for use by
1987: the routine MatSetValuesLocal() to allow users to insert matrix entries
1988: using a local (per-processor) numbering.
1990: Not Collective
1992: Input Parameters:
1993: + x - the matrix
1994: . rmapping - row mapping created with ISLocalToGlobalMappingCreate() or ISLocalToGlobalMappingCreateIS()
1995: - cmapping - column mapping
1997: Level: intermediate
2000: .seealso: MatAssemblyBegin(), MatAssemblyEnd(), MatSetValues(), MatSetValuesLocal()
2001: @*/
2002: PetscErrorCode MatSetLocalToGlobalMapping(Mat x,ISLocalToGlobalMapping rmapping,ISLocalToGlobalMapping cmapping)
2003: {
2012: if (x->ops->setlocaltoglobalmapping) {
2013: (*x->ops->setlocaltoglobalmapping)(x,rmapping,cmapping);
2014: } else {
2015: PetscLayoutSetISLocalToGlobalMapping(x->rmap,rmapping);
2016: PetscLayoutSetISLocalToGlobalMapping(x->cmap,cmapping);
2017: }
2018: return(0);
2019: }
2022: /*@
2023: MatGetLocalToGlobalMapping - Gets the local-to-global numbering set by MatSetLocalToGlobalMapping()
2025: Not Collective
2027: Input Parameters:
2028: . A - the matrix
2030: Output Parameters:
2031: + rmapping - row mapping
2032: - cmapping - column mapping
2034: Level: advanced
2037: .seealso: MatSetValuesLocal()
2038: @*/
2039: PetscErrorCode MatGetLocalToGlobalMapping(Mat A,ISLocalToGlobalMapping *rmapping,ISLocalToGlobalMapping *cmapping)
2040: {
2046: if (rmapping) *rmapping = A->rmap->mapping;
2047: if (cmapping) *cmapping = A->cmap->mapping;
2048: return(0);
2049: }
2051: /*@
2052: MatGetLayouts - Gets the PetscLayout objects for rows and columns
2054: Not Collective
2056: Input Parameters:
2057: . A - the matrix
2059: Output Parameters:
2060: + rmap - row layout
2061: - cmap - column layout
2063: Level: advanced
2065: .seealso: MatCreateVecs(), MatGetLocalToGlobalMapping()
2066: @*/
2067: PetscErrorCode MatGetLayouts(Mat A,PetscLayout *rmap,PetscLayout *cmap)
2068: {
2074: if (rmap) *rmap = A->rmap;
2075: if (cmap) *cmap = A->cmap;
2076: return(0);
2077: }
2079: /*@C
2080: MatSetValuesLocal - Inserts or adds values into certain locations of a matrix,
2081: using a local ordering of the nodes.
2083: Not Collective
2085: Input Parameters:
2086: + mat - the matrix
2087: . nrow, irow - number of rows and their local indices
2088: . ncol, icol - number of columns and their local indices
2089: . y - a logically two-dimensional array of values
2090: - addv - either INSERT_VALUES or ADD_VALUES, where
2091: ADD_VALUES adds values to any existing entries, and
2092: INSERT_VALUES replaces existing entries with new values
2094: Notes:
2095: If you create the matrix yourself (that is not with a call to DMCreateMatrix()) then you MUST call MatXXXXSetPreallocation() or
2096: MatSetUp() before using this routine
2098: If you create the matrix yourself (that is not with a call to DMCreateMatrix()) then you MUST call MatSetLocalToGlobalMapping() before using this routine
2100: Calls to MatSetValuesLocal() with the INSERT_VALUES and ADD_VALUES
2101: options cannot be mixed without intervening calls to the assembly
2102: routines.
2104: These values may be cached, so MatAssemblyBegin() and MatAssemblyEnd()
2105: MUST be called after all calls to MatSetValuesLocal() have been completed.
2107: Level: intermediate
2109: Developer Notes:
2110: This is labeled with C so does not automatically generate Fortran stubs and interfaces
2111: because it requires multiple Fortran interfaces depending on which arguments are scalar or arrays.
2113: .seealso: MatAssemblyBegin(), MatAssemblyEnd(), MatSetValues(), MatSetLocalToGlobalMapping(),
2114: MatSetValueLocal()
2115: @*/
2116: PetscErrorCode MatSetValuesLocal(Mat mat,PetscInt nrow,const PetscInt irow[],PetscInt ncol,const PetscInt icol[],const PetscScalar y[],InsertMode addv)
2117: {
2123: MatCheckPreallocated(mat,1);
2124: if (!nrow || !ncol) return(0); /* no values to insert */
2127: if (mat->insertmode == NOT_SET_VALUES) {
2128: mat->insertmode = addv;
2129: }
2130: #if defined(PETSC_USE_DEBUG)
2131: else if (mat->insertmode != addv) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Cannot mix add values and insert values");
2132: if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2133: if (!mat->ops->setvalueslocal && !mat->ops->setvalues) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
2134: #endif
2136: if (mat->assembled) {
2137: mat->was_assembled = PETSC_TRUE;
2138: mat->assembled = PETSC_FALSE;
2139: }
2140: PetscLogEventBegin(MAT_SetValues,mat,0,0,0);
2141: if (mat->ops->setvalueslocal) {
2142: (*mat->ops->setvalueslocal)(mat,nrow,irow,ncol,icol,y,addv);
2143: } else {
2144: PetscInt buf[8192],*bufr=0,*bufc=0,*irowm,*icolm;
2145: if ((nrow+ncol) <= (PetscInt)(sizeof(buf)/sizeof(PetscInt))) {
2146: irowm = buf; icolm = buf+nrow;
2147: } else {
2148: PetscMalloc2(nrow,&bufr,ncol,&bufc);
2149: irowm = bufr; icolm = bufc;
2150: }
2151: ISLocalToGlobalMappingApply(mat->rmap->mapping,nrow,irow,irowm);
2152: ISLocalToGlobalMappingApply(mat->cmap->mapping,ncol,icol,icolm);
2153: MatSetValues(mat,nrow,irowm,ncol,icolm,y,addv);
2154: PetscFree2(bufr,bufc);
2155: }
2156: PetscLogEventEnd(MAT_SetValues,mat,0,0,0);
2157: return(0);
2158: }
2160: /*@C
2161: MatSetValuesBlockedLocal - Inserts or adds values into certain locations of a matrix,
2162: using a local ordering of the nodes a block at a time.
2164: Not Collective
2166: Input Parameters:
2167: + x - the matrix
2168: . nrow, irow - number of rows and their local indices
2169: . ncol, icol - number of columns and their local indices
2170: . y - a logically two-dimensional array of values
2171: - addv - either INSERT_VALUES or ADD_VALUES, where
2172: ADD_VALUES adds values to any existing entries, and
2173: INSERT_VALUES replaces existing entries with new values
2175: Notes:
2176: If you create the matrix yourself (that is not with a call to DMCreateMatrix()) then you MUST call MatXXXXSetPreallocation() or
2177: MatSetUp() before using this routine
2179: If you create the matrix yourself (that is not with a call to DMCreateMatrix()) then you MUST call MatSetBlockSize() and MatSetLocalToGlobalMapping()
2180: before using this routineBefore calling MatSetValuesLocal(), the user must first set the
2182: Calls to MatSetValuesBlockedLocal() with the INSERT_VALUES and ADD_VALUES
2183: options cannot be mixed without intervening calls to the assembly
2184: routines.
2186: These values may be cached, so MatAssemblyBegin() and MatAssemblyEnd()
2187: MUST be called after all calls to MatSetValuesBlockedLocal() have been completed.
2189: Level: intermediate
2191: Developer Notes:
2192: This is labeled with C so does not automatically generate Fortran stubs and interfaces
2193: because it requires multiple Fortran interfaces depending on which arguments are scalar or arrays.
2195: .seealso: MatSetBlockSize(), MatSetLocalToGlobalMapping(), MatAssemblyBegin(), MatAssemblyEnd(),
2196: MatSetValuesLocal(), MatSetValuesBlocked()
2197: @*/
2198: PetscErrorCode MatSetValuesBlockedLocal(Mat mat,PetscInt nrow,const PetscInt irow[],PetscInt ncol,const PetscInt icol[],const PetscScalar y[],InsertMode addv)
2199: {
2205: MatCheckPreallocated(mat,1);
2206: if (!nrow || !ncol) return(0); /* no values to insert */
2210: if (mat->insertmode == NOT_SET_VALUES) {
2211: mat->insertmode = addv;
2212: }
2213: #if defined(PETSC_USE_DEBUG)
2214: else if (mat->insertmode != addv) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Cannot mix add values and insert values");
2215: if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2216: 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);
2217: #endif
2219: if (mat->assembled) {
2220: mat->was_assembled = PETSC_TRUE;
2221: mat->assembled = PETSC_FALSE;
2222: }
2223: #if defined(PETSC_USE_DEBUG)
2224: /* Condition on the mapping existing, because MatSetValuesBlockedLocal_IS does not require it to be set. */
2225: if (mat->rmap->mapping) {
2226: PetscInt irbs, rbs;
2227: MatGetBlockSizes(mat, &rbs, NULL);
2228: ISLocalToGlobalMappingGetBlockSize(mat->rmap->mapping,&irbs);
2229: if (rbs != irbs) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Different row block sizes! mat %D, row l2g map %D",rbs,irbs);
2230: }
2231: if (mat->cmap->mapping) {
2232: PetscInt icbs, cbs;
2233: MatGetBlockSizes(mat,NULL,&cbs);
2234: ISLocalToGlobalMappingGetBlockSize(mat->cmap->mapping,&icbs);
2235: if (cbs != icbs) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Different col block sizes! mat %D, col l2g map %D",cbs,icbs);
2236: }
2237: #endif
2238: PetscLogEventBegin(MAT_SetValues,mat,0,0,0);
2239: if (mat->ops->setvaluesblockedlocal) {
2240: (*mat->ops->setvaluesblockedlocal)(mat,nrow,irow,ncol,icol,y,addv);
2241: } else {
2242: PetscInt buf[8192],*bufr=0,*bufc=0,*irowm,*icolm;
2243: if ((nrow+ncol) <= (PetscInt)(sizeof(buf)/sizeof(PetscInt))) {
2244: irowm = buf; icolm = buf + nrow;
2245: } else {
2246: PetscMalloc2(nrow,&bufr,ncol,&bufc);
2247: irowm = bufr; icolm = bufc;
2248: }
2249: ISLocalToGlobalMappingApplyBlock(mat->rmap->mapping,nrow,irow,irowm);
2250: ISLocalToGlobalMappingApplyBlock(mat->cmap->mapping,ncol,icol,icolm);
2251: MatSetValuesBlocked(mat,nrow,irowm,ncol,icolm,y,addv);
2252: PetscFree2(bufr,bufc);
2253: }
2254: PetscLogEventEnd(MAT_SetValues,mat,0,0,0);
2255: return(0);
2256: }
2258: /*@
2259: MatMultDiagonalBlock - Computes the matrix-vector product, y = Dx. Where D is defined by the inode or block structure of the diagonal
2261: Collective on Mat
2263: Input Parameters:
2264: + mat - the matrix
2265: - x - the vector to be multiplied
2267: Output Parameters:
2268: . y - the result
2270: Notes:
2271: The vectors x and y cannot be the same. I.e., one cannot
2272: call MatMult(A,y,y).
2274: Level: developer
2276: .seealso: MatMultTranspose(), MatMultAdd(), MatMultTransposeAdd()
2277: @*/
2278: PetscErrorCode MatMultDiagonalBlock(Mat mat,Vec x,Vec y)
2279: {
2288: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2289: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2290: if (x == y) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"x and y must be different vectors");
2291: MatCheckPreallocated(mat,1);
2293: if (!mat->ops->multdiagonalblock) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"This matrix type does not have a multiply defined");
2294: (*mat->ops->multdiagonalblock)(mat,x,y);
2295: PetscObjectStateIncrease((PetscObject)y);
2296: return(0);
2297: }
2299: /* --------------------------------------------------------*/
2300: /*@
2301: MatMult - Computes the matrix-vector product, y = Ax.
2303: Neighbor-wise Collective on Mat
2305: Input Parameters:
2306: + mat - the matrix
2307: - x - the vector to be multiplied
2309: Output Parameters:
2310: . y - the result
2312: Notes:
2313: The vectors x and y cannot be the same. I.e., one cannot
2314: call MatMult(A,y,y).
2316: Level: beginner
2318: .seealso: MatMultTranspose(), MatMultAdd(), MatMultTransposeAdd()
2319: @*/
2320: PetscErrorCode MatMult(Mat mat,Vec x,Vec y)
2321: {
2329: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2330: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2331: if (x == y) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"x and y must be different vectors");
2332: #if !defined(PETSC_HAVE_CONSTRAINTS)
2333: 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);
2334: 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);
2335: 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);
2336: #endif
2337: VecSetErrorIfLocked(y,3);
2338: if (mat->erroriffailure) {VecValidValues(x,2,PETSC_TRUE);}
2339: MatCheckPreallocated(mat,1);
2341: VecLockReadPush(x);
2342: if (!mat->ops->mult) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"This matrix type does not have a multiply defined");
2343: PetscLogEventBegin(MAT_Mult,mat,x,y,0);
2344: (*mat->ops->mult)(mat,x,y);
2345: PetscLogEventEnd(MAT_Mult,mat,x,y,0);
2346: if (mat->erroriffailure) {VecValidValues(y,3,PETSC_FALSE);}
2347: VecLockReadPop(x);
2348: return(0);
2349: }
2351: /*@
2352: MatMultTranspose - Computes matrix transpose times a vector y = A^T * x.
2354: Neighbor-wise Collective on Mat
2356: Input Parameters:
2357: + mat - the matrix
2358: - x - the vector to be multiplied
2360: Output Parameters:
2361: . y - the result
2363: Notes:
2364: The vectors x and y cannot be the same. I.e., one cannot
2365: call MatMultTranspose(A,y,y).
2367: For complex numbers this does NOT compute the Hermitian (complex conjugate) transpose multiple,
2368: use MatMultHermitianTranspose()
2370: Level: beginner
2372: .seealso: MatMult(), MatMultAdd(), MatMultTransposeAdd(), MatMultHermitianTranspose(), MatTranspose()
2373: @*/
2374: PetscErrorCode MatMultTranspose(Mat mat,Vec x,Vec y)
2375: {
2384: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2385: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2386: if (x == y) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"x and y must be different vectors");
2387: #if !defined(PETSC_HAVE_CONSTRAINTS)
2388: 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);
2389: 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);
2390: #endif
2391: if (mat->erroriffailure) {VecValidValues(x,2,PETSC_TRUE);}
2392: MatCheckPreallocated(mat,1);
2394: if (!mat->ops->multtranspose) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"This matrix type does not have a multiply transpose defined");
2395: PetscLogEventBegin(MAT_MultTranspose,mat,x,y,0);
2396: VecLockReadPush(x);
2397: (*mat->ops->multtranspose)(mat,x,y);
2398: VecLockReadPop(x);
2399: PetscLogEventEnd(MAT_MultTranspose,mat,x,y,0);
2400: PetscObjectStateIncrease((PetscObject)y);
2401: if (mat->erroriffailure) {VecValidValues(y,3,PETSC_FALSE);}
2402: return(0);
2403: }
2405: /*@
2406: MatMultHermitianTranspose - Computes matrix Hermitian transpose times a vector.
2408: Neighbor-wise Collective on Mat
2410: Input Parameters:
2411: + mat - the matrix
2412: - x - the vector to be multilplied
2414: Output Parameters:
2415: . y - the result
2417: Notes:
2418: The vectors x and y cannot be the same. I.e., one cannot
2419: call MatMultHermitianTranspose(A,y,y).
2421: Also called the conjugate transpose, complex conjugate transpose, or adjoint.
2423: For real numbers MatMultTranspose() and MatMultHermitianTranspose() are identical.
2425: Level: beginner
2427: .seealso: MatMult(), MatMultAdd(), MatMultHermitianTransposeAdd(), MatMultTranspose()
2428: @*/
2429: PetscErrorCode MatMultHermitianTranspose(Mat mat,Vec x,Vec y)
2430: {
2432: Vec w;
2440: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2441: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2442: if (x == y) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"x and y must be different vectors");
2443: #if !defined(PETSC_HAVE_CONSTRAINTS)
2444: 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);
2445: 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);
2446: #endif
2447: MatCheckPreallocated(mat,1);
2449: PetscLogEventBegin(MAT_MultHermitianTranspose,mat,x,y,0);
2450: if (mat->ops->multhermitiantranspose) {
2451: VecLockReadPush(x);
2452: (*mat->ops->multhermitiantranspose)(mat,x,y);
2453: VecLockReadPop(x);
2454: } else {
2455: VecDuplicate(x,&w);
2456: VecCopy(x,w);
2457: VecConjugate(w);
2458: MatMultTranspose(mat,w,y);
2459: VecDestroy(&w);
2460: VecConjugate(y);
2461: }
2462: PetscLogEventEnd(MAT_MultHermitianTranspose,mat,x,y,0);
2463: PetscObjectStateIncrease((PetscObject)y);
2464: return(0);
2465: }
2467: /*@
2468: MatMultAdd - Computes v3 = v2 + A * v1.
2470: Neighbor-wise Collective on Mat
2472: Input Parameters:
2473: + mat - the matrix
2474: - v1, v2 - the vectors
2476: Output Parameters:
2477: . v3 - the result
2479: Notes:
2480: The vectors v1 and v3 cannot be the same. I.e., one cannot
2481: call MatMultAdd(A,v1,v2,v1).
2483: Level: beginner
2485: .seealso: MatMultTranspose(), MatMult(), MatMultTransposeAdd()
2486: @*/
2487: PetscErrorCode MatMultAdd(Mat mat,Vec v1,Vec v2,Vec v3)
2488: {
2498: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2499: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2500: 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);
2501: /* 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);
2502: 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); */
2503: 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);
2504: 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);
2505: if (v1 == v3) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"v1 and v3 must be different vectors");
2506: MatCheckPreallocated(mat,1);
2508: if (!mat->ops->multadd) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"No MatMultAdd() for matrix type '%s'",((PetscObject)mat)->type_name);
2509: PetscLogEventBegin(MAT_MultAdd,mat,v1,v2,v3);
2510: VecLockReadPush(v1);
2511: (*mat->ops->multadd)(mat,v1,v2,v3);
2512: VecLockReadPop(v1);
2513: PetscLogEventEnd(MAT_MultAdd,mat,v1,v2,v3);
2514: PetscObjectStateIncrease((PetscObject)v3);
2515: return(0);
2516: }
2518: /*@
2519: MatMultTransposeAdd - Computes v3 = v2 + A' * v1.
2521: Neighbor-wise Collective on Mat
2523: Input Parameters:
2524: + mat - the matrix
2525: - v1, v2 - the vectors
2527: Output Parameters:
2528: . v3 - the result
2530: Notes:
2531: The vectors v1 and v3 cannot be the same. I.e., one cannot
2532: call MatMultTransposeAdd(A,v1,v2,v1).
2534: Level: beginner
2536: .seealso: MatMultTranspose(), MatMultAdd(), MatMult()
2537: @*/
2538: PetscErrorCode MatMultTransposeAdd(Mat mat,Vec v1,Vec v2,Vec v3)
2539: {
2549: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2550: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2551: if (!mat->ops->multtransposeadd) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
2552: if (v1 == v3) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"v1 and v3 must be different vectors");
2553: 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);
2554: 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);
2555: 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);
2556: MatCheckPreallocated(mat,1);
2558: PetscLogEventBegin(MAT_MultTransposeAdd,mat,v1,v2,v3);
2559: VecLockReadPush(v1);
2560: (*mat->ops->multtransposeadd)(mat,v1,v2,v3);
2561: VecLockReadPop(v1);
2562: PetscLogEventEnd(MAT_MultTransposeAdd,mat,v1,v2,v3);
2563: PetscObjectStateIncrease((PetscObject)v3);
2564: return(0);
2565: }
2567: /*@
2568: MatMultHermitianTransposeAdd - Computes v3 = v2 + A^H * v1.
2570: Neighbor-wise Collective on Mat
2572: Input Parameters:
2573: + mat - the matrix
2574: - v1, v2 - the vectors
2576: Output Parameters:
2577: . v3 - the result
2579: Notes:
2580: The vectors v1 and v3 cannot be the same. I.e., one cannot
2581: call MatMultHermitianTransposeAdd(A,v1,v2,v1).
2583: Level: beginner
2585: .seealso: MatMultHermitianTranspose(), MatMultTranspose(), MatMultAdd(), MatMult()
2586: @*/
2587: PetscErrorCode MatMultHermitianTransposeAdd(Mat mat,Vec v1,Vec v2,Vec v3)
2588: {
2598: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2599: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2600: if (v1 == v3) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"v1 and v3 must be different vectors");
2601: 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);
2602: 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);
2603: 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);
2604: MatCheckPreallocated(mat,1);
2606: PetscLogEventBegin(MAT_MultHermitianTransposeAdd,mat,v1,v2,v3);
2607: VecLockReadPush(v1);
2608: if (mat->ops->multhermitiantransposeadd) {
2609: (*mat->ops->multhermitiantransposeadd)(mat,v1,v2,v3);
2610: } else {
2611: Vec w,z;
2612: VecDuplicate(v1,&w);
2613: VecCopy(v1,w);
2614: VecConjugate(w);
2615: VecDuplicate(v3,&z);
2616: MatMultTranspose(mat,w,z);
2617: VecDestroy(&w);
2618: VecConjugate(z);
2619: if (v2 != v3) {
2620: VecWAXPY(v3,1.0,v2,z);
2621: } else {
2622: VecAXPY(v3,1.0,z);
2623: }
2624: VecDestroy(&z);
2625: }
2626: VecLockReadPop(v1);
2627: PetscLogEventEnd(MAT_MultHermitianTransposeAdd,mat,v1,v2,v3);
2628: PetscObjectStateIncrease((PetscObject)v3);
2629: return(0);
2630: }
2632: /*@
2633: MatMultConstrained - The inner multiplication routine for a
2634: constrained matrix P^T A P.
2636: Neighbor-wise Collective on Mat
2638: Input Parameters:
2639: + mat - the matrix
2640: - x - the vector to be multilplied
2642: Output Parameters:
2643: . y - the result
2645: Notes:
2646: The vectors x and y cannot be the same. I.e., one cannot
2647: call MatMult(A,y,y).
2649: Level: beginner
2651: .seealso: MatMult(), MatMultTranspose(), MatMultAdd(), MatMultTransposeAdd()
2652: @*/
2653: PetscErrorCode MatMultConstrained(Mat mat,Vec x,Vec y)
2654: {
2661: if (!mat->assembled) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2662: if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2663: if (x == y) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"x and y must be different vectors");
2664: 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);
2665: 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);
2666: 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);
2668: PetscLogEventBegin(MAT_MultConstrained,mat,x,y,0);
2669: VecLockReadPush(x);
2670: (*mat->ops->multconstrained)(mat,x,y);
2671: VecLockReadPop(x);
2672: PetscLogEventEnd(MAT_MultConstrained,mat,x,y,0);
2673: PetscObjectStateIncrease((PetscObject)y);
2674: return(0);
2675: }
2677: /*@
2678: MatMultTransposeConstrained - The inner multiplication routine for a
2679: constrained matrix P^T A^T P.
2681: Neighbor-wise Collective on Mat
2683: Input Parameters:
2684: + mat - the matrix
2685: - x - the vector to be multilplied
2687: Output Parameters:
2688: . y - the result
2690: Notes:
2691: The vectors x and y cannot be the same. I.e., one cannot
2692: call MatMult(A,y,y).
2694: Level: beginner
2696: .seealso: MatMult(), MatMultTranspose(), MatMultAdd(), MatMultTransposeAdd()
2697: @*/
2698: PetscErrorCode MatMultTransposeConstrained(Mat mat,Vec x,Vec y)
2699: {
2706: if (!mat->assembled) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2707: if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2708: if (x == y) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"x and y must be different vectors");
2709: 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);
2710: 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);
2712: PetscLogEventBegin(MAT_MultConstrained,mat,x,y,0);
2713: (*mat->ops->multtransposeconstrained)(mat,x,y);
2714: PetscLogEventEnd(MAT_MultConstrained,mat,x,y,0);
2715: PetscObjectStateIncrease((PetscObject)y);
2716: return(0);
2717: }
2719: /*@C
2720: MatGetFactorType - gets the type of factorization it is
2722: Not Collective
2724: Input Parameters:
2725: . mat - the matrix
2727: Output Parameters:
2728: . t - the type, one of MAT_FACTOR_NONE, MAT_FACTOR_LU, MAT_FACTOR_CHOLESKY, MAT_FACTOR_ILU, MAT_FACTOR_ICC,MAT_FACTOR_ILUDT
2730: Level: intermediate
2732: .seealso: MatFactorType, MatGetFactor(), MatSetFactorType()
2733: @*/
2734: PetscErrorCode MatGetFactorType(Mat mat,MatFactorType *t)
2735: {
2740: *t = mat->factortype;
2741: return(0);
2742: }
2744: /*@C
2745: MatSetFactorType - sets the type of factorization it is
2747: Logically Collective on Mat
2749: Input Parameters:
2750: + mat - the matrix
2751: - t - the type, one of MAT_FACTOR_NONE, MAT_FACTOR_LU, MAT_FACTOR_CHOLESKY, MAT_FACTOR_ILU, MAT_FACTOR_ICC,MAT_FACTOR_ILUDT
2753: Level: intermediate
2755: .seealso: MatFactorType, MatGetFactor(), MatGetFactorType()
2756: @*/
2757: PetscErrorCode MatSetFactorType(Mat mat, MatFactorType t)
2758: {
2762: mat->factortype = t;
2763: return(0);
2764: }
2766: /* ------------------------------------------------------------*/
2767: /*@C
2768: MatGetInfo - Returns information about matrix storage (number of
2769: nonzeros, memory, etc.).
2771: Collective on Mat if MAT_GLOBAL_MAX or MAT_GLOBAL_SUM is used as the flag
2773: Input Parameters:
2774: . mat - the matrix
2776: Output Parameters:
2777: + flag - flag indicating the type of parameters to be returned
2778: (MAT_LOCAL - local matrix, MAT_GLOBAL_MAX - maximum over all processors,
2779: MAT_GLOBAL_SUM - sum over all processors)
2780: - info - matrix information context
2782: Notes:
2783: The MatInfo context contains a variety of matrix data, including
2784: number of nonzeros allocated and used, number of mallocs during
2785: matrix assembly, etc. Additional information for factored matrices
2786: is provided (such as the fill ratio, number of mallocs during
2787: factorization, etc.). Much of this info is printed to PETSC_STDOUT
2788: when using the runtime options
2789: $ -info -mat_view ::ascii_info
2791: Example for C/C++ Users:
2792: See the file ${PETSC_DIR}/include/petscmat.h for a complete list of
2793: data within the MatInfo context. For example,
2794: .vb
2795: MatInfo info;
2796: Mat A;
2797: double mal, nz_a, nz_u;
2799: MatGetInfo(A,MAT_LOCAL,&info);
2800: mal = info.mallocs;
2801: nz_a = info.nz_allocated;
2802: .ve
2804: Example for Fortran Users:
2805: Fortran users should declare info as a double precision
2806: array of dimension MAT_INFO_SIZE, and then extract the parameters
2807: of interest. See the file ${PETSC_DIR}/include/petsc/finclude/petscmat.h
2808: a complete list of parameter names.
2809: .vb
2810: double precision info(MAT_INFO_SIZE)
2811: double precision mal, nz_a
2812: Mat A
2813: integer ierr
2815: call MatGetInfo(A,MAT_LOCAL,info,ierr)
2816: mal = info(MAT_INFO_MALLOCS)
2817: nz_a = info(MAT_INFO_NZ_ALLOCATED)
2818: .ve
2820: Level: intermediate
2822: Developer Note: fortran interface is not autogenerated as the f90
2823: interface defintion cannot be generated correctly [due to MatInfo]
2825: .seealso: MatStashGetInfo()
2827: @*/
2828: PetscErrorCode MatGetInfo(Mat mat,MatInfoType flag,MatInfo *info)
2829: {
2836: if (!mat->ops->getinfo) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
2837: MatCheckPreallocated(mat,1);
2838: (*mat->ops->getinfo)(mat,flag,info);
2839: return(0);
2840: }
2842: /*
2843: This is used by external packages where it is not easy to get the info from the actual
2844: matrix factorization.
2845: */
2846: PetscErrorCode MatGetInfo_External(Mat A,MatInfoType flag,MatInfo *info)
2847: {
2851: PetscMemzero(info,sizeof(MatInfo));
2852: return(0);
2853: }
2855: /* ----------------------------------------------------------*/
2857: /*@C
2858: MatLUFactor - Performs in-place LU factorization of matrix.
2860: Collective on Mat
2862: Input Parameters:
2863: + mat - the matrix
2864: . row - row permutation
2865: . col - column permutation
2866: - info - options for factorization, includes
2867: $ fill - expected fill as ratio of original fill.
2868: $ dtcol - pivot tolerance (0 no pivot, 1 full column pivoting)
2869: $ Run with the option -info to determine an optimal value to use
2871: Notes:
2872: Most users should employ the simplified KSP interface for linear solvers
2873: instead of working directly with matrix algebra routines such as this.
2874: See, e.g., KSPCreate().
2876: This changes the state of the matrix to a factored matrix; it cannot be used
2877: for example with MatSetValues() unless one first calls MatSetUnfactored().
2879: Level: developer
2881: .seealso: MatLUFactorSymbolic(), MatLUFactorNumeric(), MatCholeskyFactor(),
2882: MatGetOrdering(), MatSetUnfactored(), MatFactorInfo, MatGetFactor()
2884: Developer Note: fortran interface is not autogenerated as the f90
2885: interface defintion cannot be generated correctly [due to MatFactorInfo]
2887: @*/
2888: PetscErrorCode MatLUFactor(Mat mat,IS row,IS col,const MatFactorInfo *info)
2889: {
2891: MatFactorInfo tinfo;
2899: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2900: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2901: if (!mat->ops->lufactor) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
2902: MatCheckPreallocated(mat,1);
2903: if (!info) {
2904: MatFactorInfoInitialize(&tinfo);
2905: info = &tinfo;
2906: }
2908: PetscLogEventBegin(MAT_LUFactor,mat,row,col,0);
2909: (*mat->ops->lufactor)(mat,row,col,info);
2910: PetscLogEventEnd(MAT_LUFactor,mat,row,col,0);
2911: PetscObjectStateIncrease((PetscObject)mat);
2912: return(0);
2913: }
2915: /*@C
2916: MatILUFactor - Performs in-place ILU factorization of matrix.
2918: Collective on Mat
2920: Input Parameters:
2921: + mat - the matrix
2922: . row - row permutation
2923: . col - column permutation
2924: - info - structure containing
2925: $ levels - number of levels of fill.
2926: $ expected fill - as ratio of original fill.
2927: $ 1 or 0 - indicating force fill on diagonal (improves robustness for matrices
2928: missing diagonal entries)
2930: Notes:
2931: Probably really in-place only when level of fill is zero, otherwise allocates
2932: new space to store factored matrix and deletes previous memory.
2934: Most users should employ the simplified KSP interface for linear solvers
2935: instead of working directly with matrix algebra routines such as this.
2936: See, e.g., KSPCreate().
2938: Level: developer
2940: .seealso: MatILUFactorSymbolic(), MatLUFactorNumeric(), MatCholeskyFactor(), MatFactorInfo
2942: Developer Note: fortran interface is not autogenerated as the f90
2943: interface defintion cannot be generated correctly [due to MatFactorInfo]
2945: @*/
2946: PetscErrorCode MatILUFactor(Mat mat,IS row,IS col,const MatFactorInfo *info)
2947: {
2956: if (mat->rmap->N != mat->cmap->N) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONG,"matrix must be square");
2957: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2958: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2959: if (!mat->ops->ilufactor) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
2960: MatCheckPreallocated(mat,1);
2962: PetscLogEventBegin(MAT_ILUFactor,mat,row,col,0);
2963: (*mat->ops->ilufactor)(mat,row,col,info);
2964: PetscLogEventEnd(MAT_ILUFactor,mat,row,col,0);
2965: PetscObjectStateIncrease((PetscObject)mat);
2966: return(0);
2967: }
2969: /*@C
2970: MatLUFactorSymbolic - Performs symbolic LU factorization of matrix.
2971: Call this routine before calling MatLUFactorNumeric().
2973: Collective on Mat
2975: Input Parameters:
2976: + fact - the factor matrix obtained with MatGetFactor()
2977: . mat - the matrix
2978: . row, col - row and column permutations
2979: - info - options for factorization, includes
2980: $ fill - expected fill as ratio of original fill.
2981: $ dtcol - pivot tolerance (0 no pivot, 1 full column pivoting)
2982: $ Run with the option -info to determine an optimal value to use
2985: Notes:
2986: See Users-Manual: ch_mat for additional information about choosing the fill factor for better efficiency.
2988: Most users should employ the simplified KSP interface for linear solvers
2989: instead of working directly with matrix algebra routines such as this.
2990: See, e.g., KSPCreate().
2992: Level: developer
2994: .seealso: MatLUFactor(), MatLUFactorNumeric(), MatCholeskyFactor(), MatFactorInfo, MatFactorInfoInitialize()
2996: Developer Note: fortran interface is not autogenerated as the f90
2997: interface defintion cannot be generated correctly [due to MatFactorInfo]
2999: @*/
3000: PetscErrorCode MatLUFactorSymbolic(Mat fact,Mat mat,IS row,IS col,const MatFactorInfo *info)
3001: {
3003: MatFactorInfo tinfo;
3012: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
3013: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
3014: if (!(fact)->ops->lufactorsymbolic) {
3015: MatSolverType spackage;
3016: MatFactorGetSolverType(fact,&spackage);
3017: SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Matrix type %s symbolic LU using solver package %s",((PetscObject)mat)->type_name,spackage);
3018: }
3019: MatCheckPreallocated(mat,2);
3020: if (!info) {
3021: MatFactorInfoInitialize(&tinfo);
3022: info = &tinfo;
3023: }
3025: PetscLogEventBegin(MAT_LUFactorSymbolic,mat,row,col,0);
3026: (fact->ops->lufactorsymbolic)(fact,mat,row,col,info);
3027: PetscLogEventEnd(MAT_LUFactorSymbolic,mat,row,col,0);
3028: PetscObjectStateIncrease((PetscObject)fact);
3029: return(0);
3030: }
3032: /*@C
3033: MatLUFactorNumeric - Performs numeric LU factorization of a matrix.
3034: Call this routine after first calling MatLUFactorSymbolic().
3036: Collective on Mat
3038: Input Parameters:
3039: + fact - the factor matrix obtained with MatGetFactor()
3040: . mat - the matrix
3041: - info - options for factorization
3043: Notes:
3044: See MatLUFactor() for in-place factorization. See
3045: MatCholeskyFactorNumeric() for the symmetric, positive definite case.
3047: Most users should employ the simplified KSP interface for linear solvers
3048: instead of working directly with matrix algebra routines such as this.
3049: See, e.g., KSPCreate().
3051: Level: developer
3053: .seealso: MatLUFactorSymbolic(), MatLUFactor(), MatCholeskyFactor()
3055: Developer Note: fortran interface is not autogenerated as the f90
3056: interface defintion cannot be generated correctly [due to MatFactorInfo]
3058: @*/
3059: PetscErrorCode MatLUFactorNumeric(Mat fact,Mat mat,const MatFactorInfo *info)
3060: {
3061: MatFactorInfo tinfo;
3069: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
3070: 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);
3072: if (!(fact)->ops->lufactornumeric) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s numeric LU",((PetscObject)mat)->type_name);
3073: MatCheckPreallocated(mat,2);
3074: if (!info) {
3075: MatFactorInfoInitialize(&tinfo);
3076: info = &tinfo;
3077: }
3079: PetscLogEventBegin(MAT_LUFactorNumeric,mat,fact,0,0);
3080: (fact->ops->lufactornumeric)(fact,mat,info);
3081: PetscLogEventEnd(MAT_LUFactorNumeric,mat,fact,0,0);
3082: MatViewFromOptions(fact,NULL,"-mat_factor_view");
3083: PetscObjectStateIncrease((PetscObject)fact);
3084: return(0);
3085: }
3087: /*@C
3088: MatCholeskyFactor - Performs in-place Cholesky factorization of a
3089: symmetric matrix.
3091: Collective on Mat
3093: Input Parameters:
3094: + mat - the matrix
3095: . perm - row and column permutations
3096: - f - expected fill as ratio of original fill
3098: Notes:
3099: See MatLUFactor() for the nonsymmetric case. See also
3100: MatCholeskyFactorSymbolic(), and MatCholeskyFactorNumeric().
3102: Most users should employ the simplified KSP interface for linear solvers
3103: instead of working directly with matrix algebra routines such as this.
3104: See, e.g., KSPCreate().
3106: Level: developer
3108: .seealso: MatLUFactor(), MatCholeskyFactorSymbolic(), MatCholeskyFactorNumeric()
3109: MatGetOrdering()
3111: Developer Note: fortran interface is not autogenerated as the f90
3112: interface defintion cannot be generated correctly [due to MatFactorInfo]
3114: @*/
3115: PetscErrorCode MatCholeskyFactor(Mat mat,IS perm,const MatFactorInfo *info)
3116: {
3118: MatFactorInfo tinfo;
3125: if (mat->rmap->N != mat->cmap->N) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONG,"Matrix must be square");
3126: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
3127: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
3128: 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);
3129: MatCheckPreallocated(mat,1);
3130: if (!info) {
3131: MatFactorInfoInitialize(&tinfo);
3132: info = &tinfo;
3133: }
3135: PetscLogEventBegin(MAT_CholeskyFactor,mat,perm,0,0);
3136: (*mat->ops->choleskyfactor)(mat,perm,info);
3137: PetscLogEventEnd(MAT_CholeskyFactor,mat,perm,0,0);
3138: PetscObjectStateIncrease((PetscObject)mat);
3139: return(0);
3140: }
3142: /*@C
3143: MatCholeskyFactorSymbolic - Performs symbolic Cholesky factorization
3144: of a symmetric matrix.
3146: Collective on Mat
3148: Input Parameters:
3149: + fact - the factor matrix obtained with MatGetFactor()
3150: . mat - the matrix
3151: . perm - row and column permutations
3152: - info - options for factorization, includes
3153: $ fill - expected fill as ratio of original fill.
3154: $ dtcol - pivot tolerance (0 no pivot, 1 full column pivoting)
3155: $ Run with the option -info to determine an optimal value to use
3157: Notes:
3158: See MatLUFactorSymbolic() for the nonsymmetric case. See also
3159: MatCholeskyFactor() and MatCholeskyFactorNumeric().
3161: Most users should employ the simplified KSP interface for linear solvers
3162: instead of working directly with matrix algebra routines such as this.
3163: See, e.g., KSPCreate().
3165: Level: developer
3167: .seealso: MatLUFactorSymbolic(), MatCholeskyFactor(), MatCholeskyFactorNumeric()
3168: MatGetOrdering()
3170: Developer Note: fortran interface is not autogenerated as the f90
3171: interface defintion cannot be generated correctly [due to MatFactorInfo]
3173: @*/
3174: PetscErrorCode MatCholeskyFactorSymbolic(Mat fact,Mat mat,IS perm,const MatFactorInfo *info)
3175: {
3177: MatFactorInfo tinfo;
3185: if (mat->rmap->N != mat->cmap->N) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONG,"Matrix must be square");
3186: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
3187: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
3188: if (!(fact)->ops->choleskyfactorsymbolic) {
3189: MatSolverType spackage;
3190: MatFactorGetSolverType(fact,&spackage);
3191: SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s symbolic factor Cholesky using solver package %s",((PetscObject)mat)->type_name,spackage);
3192: }
3193: MatCheckPreallocated(mat,2);
3194: if (!info) {
3195: MatFactorInfoInitialize(&tinfo);
3196: info = &tinfo;
3197: }
3199: PetscLogEventBegin(MAT_CholeskyFactorSymbolic,mat,perm,0,0);
3200: (fact->ops->choleskyfactorsymbolic)(fact,mat,perm,info);
3201: PetscLogEventEnd(MAT_CholeskyFactorSymbolic,mat,perm,0,0);
3202: PetscObjectStateIncrease((PetscObject)fact);
3203: return(0);
3204: }
3206: /*@C
3207: MatCholeskyFactorNumeric - Performs numeric Cholesky factorization
3208: of a symmetric matrix. Call this routine after first calling
3209: MatCholeskyFactorSymbolic().
3211: Collective on Mat
3213: Input Parameters:
3214: + fact - the factor matrix obtained with MatGetFactor()
3215: . mat - the initial matrix
3216: . info - options for factorization
3217: - fact - the symbolic factor of mat
3220: Notes:
3221: Most users should employ the simplified KSP interface for linear solvers
3222: instead of working directly with matrix algebra routines such as this.
3223: See, e.g., KSPCreate().
3225: Level: developer
3227: .seealso: MatCholeskyFactorSymbolic(), MatCholeskyFactor(), MatLUFactorNumeric()
3229: Developer Note: fortran interface is not autogenerated as the f90
3230: interface defintion cannot be generated correctly [due to MatFactorInfo]
3232: @*/
3233: PetscErrorCode MatCholeskyFactorNumeric(Mat fact,Mat mat,const MatFactorInfo *info)
3234: {
3235: MatFactorInfo tinfo;
3243: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
3244: if (!(fact)->ops->choleskyfactornumeric) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s numeric factor Cholesky",((PetscObject)mat)->type_name);
3245: 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);
3246: MatCheckPreallocated(mat,2);
3247: if (!info) {
3248: MatFactorInfoInitialize(&tinfo);
3249: info = &tinfo;
3250: }
3252: PetscLogEventBegin(MAT_CholeskyFactorNumeric,mat,fact,0,0);
3253: (fact->ops->choleskyfactornumeric)(fact,mat,info);
3254: PetscLogEventEnd(MAT_CholeskyFactorNumeric,mat,fact,0,0);
3255: MatViewFromOptions(fact,NULL,"-mat_factor_view");
3256: PetscObjectStateIncrease((PetscObject)fact);
3257: return(0);
3258: }
3260: /* ----------------------------------------------------------------*/
3261: /*@
3262: MatSolve - Solves A x = b, given a factored matrix.
3264: Neighbor-wise Collective on Mat
3266: Input Parameters:
3267: + mat - the factored matrix
3268: - b - the right-hand-side vector
3270: Output Parameter:
3271: . x - the result vector
3273: Notes:
3274: The vectors b and x cannot be the same. I.e., one cannot
3275: call MatSolve(A,x,x).
3277: Notes:
3278: Most users should employ the simplified KSP interface for linear solvers
3279: instead of working directly with matrix algebra routines such as this.
3280: See, e.g., KSPCreate().
3282: Level: developer
3284: .seealso: MatSolveAdd(), MatSolveTranspose(), MatSolveTransposeAdd()
3285: @*/
3286: PetscErrorCode MatSolve(Mat mat,Vec b,Vec x)
3287: {
3297: if (x == b) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"x and b must be different vectors");
3298: 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);
3299: 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);
3300: 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);
3301: if (!mat->rmap->N && !mat->cmap->N) return(0);
3302: MatCheckPreallocated(mat,1);
3304: PetscLogEventBegin(MAT_Solve,mat,b,x,0);
3305: if (mat->factorerrortype) {
3306: PetscInfo1(mat,"MatFactorError %D\n",mat->factorerrortype);
3307: VecSetInf(x);
3308: } else {
3309: if (!mat->ops->solve) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
3310: (*mat->ops->solve)(mat,b,x);
3311: }
3312: PetscLogEventEnd(MAT_Solve,mat,b,x,0);
3313: PetscObjectStateIncrease((PetscObject)x);
3314: return(0);
3315: }
3317: static PetscErrorCode MatMatSolve_Basic(Mat A,Mat B,Mat X,PetscBool trans)
3318: {
3320: Vec b,x;
3321: PetscInt m,N,i;
3322: PetscScalar *bb,*xx;
3325: MatDenseGetArrayRead(B,(const PetscScalar**)&bb);
3326: MatDenseGetArray(X,&xx);
3327: MatGetLocalSize(B,&m,NULL); /* number local rows */
3328: MatGetSize(B,NULL,&N); /* total columns in dense matrix */
3329: MatCreateVecs(A,&x,&b);
3330: for (i=0; i<N; i++) {
3331: VecPlaceArray(b,bb + i*m);
3332: VecPlaceArray(x,xx + i*m);
3333: if (trans) {
3334: MatSolveTranspose(A,b,x);
3335: } else {
3336: MatSolve(A,b,x);
3337: }
3338: VecResetArray(x);
3339: VecResetArray(b);
3340: }
3341: VecDestroy(&b);
3342: VecDestroy(&x);
3343: MatDenseRestoreArrayRead(B,(const PetscScalar**)&bb);
3344: MatDenseRestoreArray(X,&xx);
3345: return(0);
3346: }
3348: /*@
3349: MatMatSolve - Solves A X = B, given a factored matrix.
3351: Neighbor-wise Collective on Mat
3353: Input Parameters:
3354: + A - the factored matrix
3355: - B - the right-hand-side matrix MATDENSE (or sparse -- when using MUMPS)
3357: Output Parameter:
3358: . X - the result matrix (dense matrix)
3360: Notes:
3361: If B is a MATDENSE matrix then one can call MatMatSolve(A,B,B);
3362: otherwise, B and X cannot be the same.
3364: Notes:
3365: Most users should usually employ the simplified KSP interface for linear solvers
3366: instead of working directly with matrix algebra routines such as this.
3367: See, e.g., KSPCreate(). However KSP can only solve for one vector (column of X)
3368: at a time.
3370: Level: developer
3372: .seealso: MatMatSolveTranspose(), MatLUFactor(), MatCholeskyFactor()
3373: @*/
3374: PetscErrorCode MatMatSolve(Mat A,Mat B,Mat X)
3375: {
3385: 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);
3386: 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);
3387: if (X->cmap->N != B->cmap->N) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Solution matrix must have same number of columns as rhs matrix");
3388: if (!A->rmap->N && !A->cmap->N) return(0);
3389: if (!A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
3390: MatCheckPreallocated(A,1);
3392: PetscLogEventBegin(MAT_MatSolve,A,B,X,0);
3393: if (!A->ops->matsolve) {
3394: PetscInfo1(A,"Mat type %s using basic MatMatSolve\n",((PetscObject)A)->type_name);
3395: MatMatSolve_Basic(A,B,X,PETSC_FALSE);
3396: } else {
3397: (*A->ops->matsolve)(A,B,X);
3398: }
3399: PetscLogEventEnd(MAT_MatSolve,A,B,X,0);
3400: PetscObjectStateIncrease((PetscObject)X);
3401: return(0);
3402: }
3404: /*@
3405: MatMatSolveTranspose - Solves A^T X = B, given a factored matrix.
3407: Neighbor-wise Collective on Mat
3409: Input Parameters:
3410: + A - the factored matrix
3411: - B - the right-hand-side matrix (dense matrix)
3413: Output Parameter:
3414: . X - the result matrix (dense matrix)
3416: Notes:
3417: The matrices B and X cannot be the same. I.e., one cannot
3418: call MatMatSolveTranspose(A,X,X).
3420: Notes:
3421: Most users should usually employ the simplified KSP interface for linear solvers
3422: instead of working directly with matrix algebra routines such as this.
3423: See, e.g., KSPCreate(). However KSP can only solve for one vector (column of X)
3424: at a time.
3426: When using SuperLU_Dist or MUMPS as a parallel solver, PETSc will use their functionality to solve multiple right hand sides simultaneously.
3428: Level: developer
3430: .seealso: MatMatSolve(), MatLUFactor(), MatCholeskyFactor()
3431: @*/
3432: PetscErrorCode MatMatSolveTranspose(Mat A,Mat B,Mat X)
3433: {
3443: if (X == B) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_IDN,"X and B must be different matrices");
3444: 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);
3445: 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);
3446: 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);
3447: 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");
3448: if (!A->rmap->N && !A->cmap->N) return(0);
3449: if (!A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
3450: MatCheckPreallocated(A,1);
3452: PetscLogEventBegin(MAT_MatSolve,A,B,X,0);
3453: if (!A->ops->matsolvetranspose) {
3454: PetscInfo1(A,"Mat type %s using basic MatMatSolveTranspose\n",((PetscObject)A)->type_name);
3455: MatMatSolve_Basic(A,B,X,PETSC_TRUE);
3456: } else {
3457: (*A->ops->matsolvetranspose)(A,B,X);
3458: }
3459: PetscLogEventEnd(MAT_MatSolve,A,B,X,0);
3460: PetscObjectStateIncrease((PetscObject)X);
3461: return(0);
3462: }
3464: /*@
3465: MatMatTransposeSolve - Solves A X = B^T, given a factored matrix.
3467: Neighbor-wise Collective on Mat
3469: Input Parameters:
3470: + A - the factored matrix
3471: - Bt - the transpose of right-hand-side matrix
3473: Output Parameter:
3474: . X - the result matrix (dense matrix)
3476: Notes:
3477: Most users should usually employ the simplified KSP interface for linear solvers
3478: instead of working directly with matrix algebra routines such as this.
3479: See, e.g., KSPCreate(). However KSP can only solve for one vector (column of X)
3480: at a time.
3482: 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().
3484: Level: developer
3486: .seealso: MatMatSolve(), MatMatSolveTranspose(), MatLUFactor(), MatCholeskyFactor()
3487: @*/
3488: PetscErrorCode MatMatTransposeSolve(Mat A,Mat Bt,Mat X)
3489: {
3500: if (X == Bt) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_IDN,"X and B must be different matrices");
3501: if (A->cmap->N != X->rmap->N) SETERRQ2(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Mat A,Mat X: global dim %D %D",A->cmap->N,X->rmap->N);
3502: if (A->rmap->N != 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);
3503: 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");
3504: if (!A->rmap->N && !A->cmap->N) return(0);
3505: if (!A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
3506: MatCheckPreallocated(A,1);
3508: if (!A->ops->mattransposesolve) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Mat type %s",((PetscObject)A)->type_name);
3509: PetscLogEventBegin(MAT_MatTrSolve,A,Bt,X,0);
3510: (*A->ops->mattransposesolve)(A,Bt,X);
3511: PetscLogEventEnd(MAT_MatTrSolve,A,Bt,X,0);
3512: PetscObjectStateIncrease((PetscObject)X);
3513: return(0);
3514: }
3516: /*@
3517: MatForwardSolve - Solves L x = b, given a factored matrix, A = LU, or
3518: U^T*D^(1/2) x = b, given a factored symmetric matrix, A = U^T*D*U,
3520: Neighbor-wise Collective on Mat
3522: Input Parameters:
3523: + mat - the factored matrix
3524: - b - the right-hand-side vector
3526: Output Parameter:
3527: . x - the result vector
3529: Notes:
3530: MatSolve() should be used for most applications, as it performs
3531: a forward solve followed by a backward solve.
3533: The vectors b and x cannot be the same, i.e., one cannot
3534: call MatForwardSolve(A,x,x).
3536: For matrix in seqsbaij format with block size larger than 1,
3537: the diagonal blocks are not implemented as D = D^(1/2) * D^(1/2) yet.
3538: MatForwardSolve() solves U^T*D y = b, and
3539: MatBackwardSolve() solves U x = y.
3540: Thus they do not provide a symmetric preconditioner.
3542: Most users should employ the simplified KSP interface for linear solvers
3543: instead of working directly with matrix algebra routines such as this.
3544: See, e.g., KSPCreate().
3546: Level: developer
3548: .seealso: MatSolve(), MatBackwardSolve()
3549: @*/
3550: PetscErrorCode MatForwardSolve(Mat mat,Vec b,Vec x)
3551: {
3561: if (x == b) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"x and b must be different vectors");
3562: 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);
3563: 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);
3564: 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);
3565: if (!mat->rmap->N && !mat->cmap->N) return(0);
3566: MatCheckPreallocated(mat,1);
3568: if (!mat->ops->forwardsolve) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
3569: PetscLogEventBegin(MAT_ForwardSolve,mat,b,x,0);
3570: (*mat->ops->forwardsolve)(mat,b,x);
3571: PetscLogEventEnd(MAT_ForwardSolve,mat,b,x,0);
3572: PetscObjectStateIncrease((PetscObject)x);
3573: return(0);
3574: }
3576: /*@
3577: MatBackwardSolve - Solves U x = b, given a factored matrix, A = LU.
3578: D^(1/2) U x = b, given a factored symmetric matrix, A = U^T*D*U,
3580: Neighbor-wise Collective on Mat
3582: Input Parameters:
3583: + mat - the factored matrix
3584: - b - the right-hand-side vector
3586: Output Parameter:
3587: . x - the result vector
3589: Notes:
3590: MatSolve() should be used for most applications, as it performs
3591: a forward solve followed by a backward solve.
3593: The vectors b and x cannot be the same. I.e., one cannot
3594: call MatBackwardSolve(A,x,x).
3596: For matrix in seqsbaij format with block size larger than 1,
3597: the diagonal blocks are not implemented as D = D^(1/2) * D^(1/2) yet.
3598: MatForwardSolve() solves U^T*D y = b, and
3599: MatBackwardSolve() solves U x = y.
3600: Thus they do not provide a symmetric preconditioner.
3602: Most users should employ the simplified KSP interface for linear solvers
3603: instead of working directly with matrix algebra routines such as this.
3604: See, e.g., KSPCreate().
3606: Level: developer
3608: .seealso: MatSolve(), MatForwardSolve()
3609: @*/
3610: PetscErrorCode MatBackwardSolve(Mat mat,Vec b,Vec x)
3611: {
3621: if (x == b) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"x and b must be different vectors");
3622: 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);
3623: 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);
3624: 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);
3625: if (!mat->rmap->N && !mat->cmap->N) return(0);
3626: MatCheckPreallocated(mat,1);
3628: if (!mat->ops->backwardsolve) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
3629: PetscLogEventBegin(MAT_BackwardSolve,mat,b,x,0);
3630: (*mat->ops->backwardsolve)(mat,b,x);
3631: PetscLogEventEnd(MAT_BackwardSolve,mat,b,x,0);
3632: PetscObjectStateIncrease((PetscObject)x);
3633: return(0);
3634: }
3636: /*@
3637: MatSolveAdd - Computes x = y + inv(A)*b, given a factored matrix.
3639: Neighbor-wise Collective on Mat
3641: Input Parameters:
3642: + mat - the factored matrix
3643: . b - the right-hand-side vector
3644: - y - the vector to be added to
3646: Output Parameter:
3647: . x - the result vector
3649: Notes:
3650: The vectors b and x cannot be the same. I.e., one cannot
3651: call MatSolveAdd(A,x,y,x).
3653: Most users should employ the simplified KSP interface for linear solvers
3654: instead of working directly with matrix algebra routines such as this.
3655: See, e.g., KSPCreate().
3657: Level: developer
3659: .seealso: MatSolve(), MatSolveTranspose(), MatSolveTransposeAdd()
3660: @*/
3661: PetscErrorCode MatSolveAdd(Mat mat,Vec b,Vec y,Vec x)
3662: {
3663: PetscScalar one = 1.0;
3664: Vec tmp;
3676: if (x == b) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"x and b must be different vectors");
3677: 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);
3678: 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);
3679: 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);
3680: 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);
3681: 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);
3682: if (!mat->rmap->N && !mat->cmap->N) return(0);
3683: MatCheckPreallocated(mat,1);
3685: PetscLogEventBegin(MAT_SolveAdd,mat,b,x,y);
3686: if (mat->factorerrortype) {
3687: PetscInfo1(mat,"MatFactorError %D\n",mat->factorerrortype);
3688: VecSetInf(x);
3689: } else if (mat->ops->solveadd) {
3690: (*mat->ops->solveadd)(mat,b,y,x);
3691: } else {
3692: /* do the solve then the add manually */
3693: if (x != y) {
3694: MatSolve(mat,b,x);
3695: VecAXPY(x,one,y);
3696: } else {
3697: VecDuplicate(x,&tmp);
3698: PetscLogObjectParent((PetscObject)mat,(PetscObject)tmp);
3699: VecCopy(x,tmp);
3700: MatSolve(mat,b,x);
3701: VecAXPY(x,one,tmp);
3702: VecDestroy(&tmp);
3703: }
3704: }
3705: PetscLogEventEnd(MAT_SolveAdd,mat,b,x,y);
3706: PetscObjectStateIncrease((PetscObject)x);
3707: return(0);
3708: }
3710: /*@
3711: MatSolveTranspose - Solves A' x = b, given a factored matrix.
3713: Neighbor-wise Collective on Mat
3715: Input Parameters:
3716: + mat - the factored matrix
3717: - b - the right-hand-side vector
3719: Output Parameter:
3720: . x - the result vector
3722: Notes:
3723: The vectors b and x cannot be the same. I.e., one cannot
3724: call MatSolveTranspose(A,x,x).
3726: Most users should employ the simplified KSP interface for linear solvers
3727: instead of working directly with matrix algebra routines such as this.
3728: See, e.g., KSPCreate().
3730: Level: developer
3732: .seealso: MatSolve(), MatSolveAdd(), MatSolveTransposeAdd()
3733: @*/
3734: PetscErrorCode MatSolveTranspose(Mat mat,Vec b,Vec x)
3735: {
3745: if (x == b) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"x and b must be different vectors");
3746: 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);
3747: 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);
3748: if (!mat->rmap->N && !mat->cmap->N) return(0);
3749: MatCheckPreallocated(mat,1);
3750: PetscLogEventBegin(MAT_SolveTranspose,mat,b,x,0);
3751: if (mat->factorerrortype) {
3752: PetscInfo1(mat,"MatFactorError %D\n",mat->factorerrortype);
3753: VecSetInf(x);
3754: } else {
3755: if (!mat->ops->solvetranspose) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Matrix type %s",((PetscObject)mat)->type_name);
3756: (*mat->ops->solvetranspose)(mat,b,x);
3757: }
3758: PetscLogEventEnd(MAT_SolveTranspose,mat,b,x,0);
3759: PetscObjectStateIncrease((PetscObject)x);
3760: return(0);
3761: }
3763: /*@
3764: MatSolveTransposeAdd - Computes x = y + inv(Transpose(A)) b, given a
3765: factored matrix.
3767: Neighbor-wise Collective on Mat
3769: Input Parameters:
3770: + mat - the factored matrix
3771: . b - the right-hand-side vector
3772: - y - the vector to be added to
3774: Output Parameter:
3775: . x - the result vector
3777: Notes:
3778: The vectors b and x cannot be the same. I.e., one cannot
3779: call MatSolveTransposeAdd(A,x,y,x).
3781: Most users should employ the simplified KSP interface for linear solvers
3782: instead of working directly with matrix algebra routines such as this.
3783: See, e.g., KSPCreate().
3785: Level: developer
3787: .seealso: MatSolve(), MatSolveAdd(), MatSolveTranspose()
3788: @*/
3789: PetscErrorCode MatSolveTransposeAdd(Mat mat,Vec b,Vec y,Vec x)
3790: {
3791: PetscScalar one = 1.0;
3793: Vec tmp;
3804: if (x == b) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"x and b must be different vectors");
3805: 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);
3806: 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);
3807: 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);
3808: 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);
3809: if (!mat->rmap->N && !mat->cmap->N) return(0);
3810: MatCheckPreallocated(mat,1);
3812: PetscLogEventBegin(MAT_SolveTransposeAdd,mat,b,x,y);
3813: if (mat->factorerrortype) {
3814: PetscInfo1(mat,"MatFactorError %D\n",mat->factorerrortype);
3815: VecSetInf(x);
3816: } else if (mat->ops->solvetransposeadd){
3817: (*mat->ops->solvetransposeadd)(mat,b,y,x);
3818: } else {
3819: /* do the solve then the add manually */
3820: if (x != y) {
3821: MatSolveTranspose(mat,b,x);
3822: VecAXPY(x,one,y);
3823: } else {
3824: VecDuplicate(x,&tmp);
3825: PetscLogObjectParent((PetscObject)mat,(PetscObject)tmp);
3826: VecCopy(x,tmp);
3827: MatSolveTranspose(mat,b,x);
3828: VecAXPY(x,one,tmp);
3829: VecDestroy(&tmp);
3830: }
3831: }
3832: PetscLogEventEnd(MAT_SolveTransposeAdd,mat,b,x,y);
3833: PetscObjectStateIncrease((PetscObject)x);
3834: return(0);
3835: }
3836: /* ----------------------------------------------------------------*/
3838: /*@
3839: MatSOR - Computes relaxation (SOR, Gauss-Seidel) sweeps.
3841: Neighbor-wise Collective on Mat
3843: Input Parameters:
3844: + mat - the matrix
3845: . b - the right hand side
3846: . omega - the relaxation factor
3847: . flag - flag indicating the type of SOR (see below)
3848: . shift - diagonal shift
3849: . its - the number of iterations
3850: - lits - the number of local iterations
3852: Output Parameters:
3853: . x - the solution (can contain an initial guess, use option SOR_ZERO_INITIAL_GUESS to indicate no guess)
3855: SOR Flags:
3856: + SOR_FORWARD_SWEEP - forward SOR
3857: . SOR_BACKWARD_SWEEP - backward SOR
3858: . SOR_SYMMETRIC_SWEEP - SSOR (symmetric SOR)
3859: . SOR_LOCAL_FORWARD_SWEEP - local forward SOR
3860: . SOR_LOCAL_BACKWARD_SWEEP - local forward SOR
3861: . SOR_LOCAL_SYMMETRIC_SWEEP - local SSOR
3862: . SOR_APPLY_UPPER, SOR_APPLY_LOWER - applies
3863: upper/lower triangular part of matrix to
3864: vector (with omega)
3865: - SOR_ZERO_INITIAL_GUESS - zero initial guess
3867: Notes:
3868: SOR_LOCAL_FORWARD_SWEEP, SOR_LOCAL_BACKWARD_SWEEP, and
3869: SOR_LOCAL_SYMMETRIC_SWEEP perform separate independent smoothings
3870: on each processor.
3872: Application programmers will not generally use MatSOR() directly,
3873: but instead will employ the KSP/PC interface.
3875: Notes:
3876: for BAIJ, SBAIJ, and AIJ matrices with Inodes this does a block SOR smoothing, otherwise it does a pointwise smoothing
3878: Notes for Advanced Users:
3879: The flags are implemented as bitwise inclusive or operations.
3880: For example, use (SOR_ZERO_INITIAL_GUESS | SOR_SYMMETRIC_SWEEP)
3881: to specify a zero initial guess for SSOR.
3883: Most users should employ the simplified KSP interface for linear solvers
3884: instead of working directly with matrix algebra routines such as this.
3885: See, e.g., KSPCreate().
3887: Vectors x and b CANNOT be the same
3889: Developer Note: We should add block SOR support for AIJ matrices with block size set to great than one and no inodes
3891: Level: developer
3893: @*/
3894: PetscErrorCode MatSOR(Mat mat,Vec b,PetscReal omega,MatSORType flag,PetscReal shift,PetscInt its,PetscInt lits,Vec x)
3895: {
3905: if (!mat->ops->sor) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
3906: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
3907: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
3908: 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);
3909: 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);
3910: 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);
3911: if (its <= 0) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONG,"Relaxation requires global its %D positive",its);
3912: if (lits <= 0) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONG,"Relaxation requires local its %D positive",lits);
3913: if (b == x) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_IDN,"b and x vector cannot be the same");
3915: MatCheckPreallocated(mat,1);
3916: PetscLogEventBegin(MAT_SOR,mat,b,x,0);
3917: ierr =(*mat->ops->sor)(mat,b,omega,flag,shift,its,lits,x);
3918: PetscLogEventEnd(MAT_SOR,mat,b,x,0);
3919: PetscObjectStateIncrease((PetscObject)x);
3920: return(0);
3921: }
3923: /*
3924: Default matrix copy routine.
3925: */
3926: PetscErrorCode MatCopy_Basic(Mat A,Mat B,MatStructure str)
3927: {
3928: PetscErrorCode ierr;
3929: PetscInt i,rstart = 0,rend = 0,nz;
3930: const PetscInt *cwork;
3931: const PetscScalar *vwork;
3934: if (B->assembled) {
3935: MatZeroEntries(B);
3936: }
3937: if (str == SAME_NONZERO_PATTERN) {
3938: MatGetOwnershipRange(A,&rstart,&rend);
3939: for (i=rstart; i<rend; i++) {
3940: MatGetRow(A,i,&nz,&cwork,&vwork);
3941: MatSetValues(B,1,&i,nz,cwork,vwork,INSERT_VALUES);
3942: MatRestoreRow(A,i,&nz,&cwork,&vwork);
3943: }
3944: } else {
3945: MatAYPX(B,0.0,A,str);
3946: }
3947: MatAssemblyBegin(B,MAT_FINAL_ASSEMBLY);
3948: MatAssemblyEnd(B,MAT_FINAL_ASSEMBLY);
3949: return(0);
3950: }
3952: /*@
3953: MatCopy - Copies a matrix to another matrix.
3955: Collective on Mat
3957: Input Parameters:
3958: + A - the matrix
3959: - str - SAME_NONZERO_PATTERN or DIFFERENT_NONZERO_PATTERN
3961: Output Parameter:
3962: . B - where the copy is put
3964: Notes:
3965: If you use SAME_NONZERO_PATTERN then the two matrices had better have the
3966: same nonzero pattern or the routine will crash.
3968: MatCopy() copies the matrix entries of a matrix to another existing
3969: matrix (after first zeroing the second matrix). A related routine is
3970: MatConvert(), which first creates a new matrix and then copies the data.
3972: Level: intermediate
3974: .seealso: MatConvert(), MatDuplicate()
3976: @*/
3977: PetscErrorCode MatCopy(Mat A,Mat B,MatStructure str)
3978: {
3980: PetscInt i;
3988: MatCheckPreallocated(B,2);
3989: if (!A->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
3990: if (A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
3991: 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);
3992: MatCheckPreallocated(A,1);
3993: if (A == B) return(0);
3995: PetscLogEventBegin(MAT_Copy,A,B,0,0);
3996: if (A->ops->copy) {
3997: (*A->ops->copy)(A,B,str);
3998: } else { /* generic conversion */
3999: MatCopy_Basic(A,B,str);
4000: }
4002: B->stencil.dim = A->stencil.dim;
4003: B->stencil.noc = A->stencil.noc;
4004: for (i=0; i<=A->stencil.dim; i++) {
4005: B->stencil.dims[i] = A->stencil.dims[i];
4006: B->stencil.starts[i] = A->stencil.starts[i];
4007: }
4009: PetscLogEventEnd(MAT_Copy,A,B,0,0);
4010: PetscObjectStateIncrease((PetscObject)B);
4011: return(0);
4012: }
4014: /*@C
4015: MatConvert - Converts a matrix to another matrix, either of the same
4016: or different type.
4018: Collective on Mat
4020: Input Parameters:
4021: + mat - the matrix
4022: . newtype - new matrix type. Use MATSAME to create a new matrix of the
4023: same type as the original matrix.
4024: - reuse - denotes if the destination matrix is to be created or reused.
4025: 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
4026: 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).
4028: Output Parameter:
4029: . M - pointer to place new matrix
4031: Notes:
4032: MatConvert() first creates a new matrix and then copies the data from
4033: the first matrix. A related routine is MatCopy(), which copies the matrix
4034: entries of one matrix to another already existing matrix context.
4036: Cannot be used to convert a sequential matrix to parallel or parallel to sequential,
4037: the MPI communicator of the generated matrix is always the same as the communicator
4038: of the input matrix.
4040: Level: intermediate
4042: .seealso: MatCopy(), MatDuplicate()
4043: @*/
4044: PetscErrorCode MatConvert(Mat mat, MatType newtype,MatReuse reuse,Mat *M)
4045: {
4047: PetscBool sametype,issame,flg,issymmetric,ishermitian;
4048: char convname[256],mtype[256];
4049: Mat B;
4055: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
4056: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
4057: MatCheckPreallocated(mat,1);
4059: PetscOptionsGetString(((PetscObject)mat)->options,((PetscObject)mat)->prefix,"-matconvert_type",mtype,256,&flg);
4060: if (flg) newtype = mtype;
4062: PetscObjectTypeCompare((PetscObject)mat,newtype,&sametype);
4063: PetscStrcmp(newtype,"same",&issame);
4064: if ((reuse == MAT_INPLACE_MATRIX) && (mat != *M)) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"MAT_INPLACE_MATRIX requires same input and output matrix");
4065: 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");
4067: if ((reuse == MAT_INPLACE_MATRIX) && (issame || sametype)) {
4068: PetscInfo3(mat,"Early return for inplace %s %d %d\n",((PetscObject)mat)->type_name,sametype,issame);
4069: return(0);
4070: }
4072: /* Cache Mat options because some converter use MatHeaderReplace */
4073: issymmetric = mat->symmetric;
4074: ishermitian = mat->hermitian;
4076: if ((sametype || issame) && (reuse==MAT_INITIAL_MATRIX) && mat->ops->duplicate) {
4077: PetscInfo3(mat,"Calling duplicate for initial matrix %s %d %d\n",((PetscObject)mat)->type_name,sametype,issame);
4078: (*mat->ops->duplicate)(mat,MAT_COPY_VALUES,M);
4079: } else {
4080: PetscErrorCode (*conv)(Mat, MatType,MatReuse,Mat*)=NULL;
4081: const char *prefix[3] = {"seq","mpi",""};
4082: PetscInt i;
4083: /*
4084: Order of precedence:
4085: 0) See if newtype is a superclass of the current matrix.
4086: 1) See if a specialized converter is known to the current matrix.
4087: 2) See if a specialized converter is known to the desired matrix class.
4088: 3) See if a good general converter is registered for the desired class
4089: (as of 6/27/03 only MATMPIADJ falls into this category).
4090: 4) See if a good general converter is known for the current matrix.
4091: 5) Use a really basic converter.
4092: */
4094: /* 0) See if newtype is a superclass of the current matrix.
4095: i.e mat is mpiaij and newtype is aij */
4096: for (i=0; i<2; i++) {
4097: PetscStrncpy(convname,prefix[i],sizeof(convname));
4098: PetscStrlcat(convname,newtype,sizeof(convname));
4099: PetscStrcmp(convname,((PetscObject)mat)->type_name,&flg);
4100: PetscInfo3(mat,"Check superclass %s %s -> %d\n",convname,((PetscObject)mat)->type_name,flg);
4101: if (flg) {
4102: if (reuse == MAT_INPLACE_MATRIX) {
4103: return(0);
4104: } else if (reuse == MAT_INITIAL_MATRIX && mat->ops->duplicate) {
4105: (*mat->ops->duplicate)(mat,MAT_COPY_VALUES,M);
4106: return(0);
4107: } else if (reuse == MAT_REUSE_MATRIX && mat->ops->copy) {
4108: MatCopy(mat,*M,SAME_NONZERO_PATTERN);
4109: return(0);
4110: }
4111: }
4112: }
4113: /* 1) See if a specialized converter is known to the current matrix and the desired class */
4114: for (i=0; i<3; i++) {
4115: PetscStrncpy(convname,"MatConvert_",sizeof(convname));
4116: PetscStrlcat(convname,((PetscObject)mat)->type_name,sizeof(convname));
4117: PetscStrlcat(convname,"_",sizeof(convname));
4118: PetscStrlcat(convname,prefix[i],sizeof(convname));
4119: PetscStrlcat(convname,issame ? ((PetscObject)mat)->type_name : newtype,sizeof(convname));
4120: PetscStrlcat(convname,"_C",sizeof(convname));
4121: PetscObjectQueryFunction((PetscObject)mat,convname,&conv);
4122: PetscInfo3(mat,"Check specialized (1) %s (%s) -> %d\n",convname,((PetscObject)mat)->type_name,!!conv);
4123: if (conv) goto foundconv;
4124: }
4126: /* 2) See if a specialized converter is known to the desired matrix class. */
4127: MatCreate(PetscObjectComm((PetscObject)mat),&B);
4128: MatSetSizes(B,mat->rmap->n,mat->cmap->n,mat->rmap->N,mat->cmap->N);
4129: MatSetType(B,newtype);
4130: for (i=0; i<3; i++) {
4131: PetscStrncpy(convname,"MatConvert_",sizeof(convname));
4132: PetscStrlcat(convname,((PetscObject)mat)->type_name,sizeof(convname));
4133: PetscStrlcat(convname,"_",sizeof(convname));
4134: PetscStrlcat(convname,prefix[i],sizeof(convname));
4135: PetscStrlcat(convname,newtype,sizeof(convname));
4136: PetscStrlcat(convname,"_C",sizeof(convname));
4137: PetscObjectQueryFunction((PetscObject)B,convname,&conv);
4138: PetscInfo3(mat,"Check specialized (2) %s (%s) -> %d\n",convname,((PetscObject)B)->type_name,!!conv);
4139: if (conv) {
4140: MatDestroy(&B);
4141: goto foundconv;
4142: }
4143: }
4145: /* 3) See if a good general converter is registered for the desired class */
4146: conv = B->ops->convertfrom;
4147: PetscInfo2(mat,"Check convertfrom (%s) -> %d\n",((PetscObject)B)->type_name,!!conv);
4148: MatDestroy(&B);
4149: if (conv) goto foundconv;
4151: /* 4) See if a good general converter is known for the current matrix */
4152: if (mat->ops->convert) {
4153: conv = mat->ops->convert;
4154: }
4155: PetscInfo2(mat,"Check general convert (%s) -> %d\n",((PetscObject)mat)->type_name,!!conv);
4156: if (conv) goto foundconv;
4158: /* 5) Use a really basic converter. */
4159: PetscInfo(mat,"Using MatConvert_Basic\n");
4160: conv = MatConvert_Basic;
4162: foundconv:
4163: PetscLogEventBegin(MAT_Convert,mat,0,0,0);
4164: (*conv)(mat,newtype,reuse,M);
4165: if (mat->rmap->mapping && mat->cmap->mapping && !(*M)->rmap->mapping && !(*M)->cmap->mapping) {
4166: /* the block sizes must be same if the mappings are copied over */
4167: (*M)->rmap->bs = mat->rmap->bs;
4168: (*M)->cmap->bs = mat->cmap->bs;
4169: PetscObjectReference((PetscObject)mat->rmap->mapping);
4170: PetscObjectReference((PetscObject)mat->cmap->mapping);
4171: (*M)->rmap->mapping = mat->rmap->mapping;
4172: (*M)->cmap->mapping = mat->cmap->mapping;
4173: }
4174: (*M)->stencil.dim = mat->stencil.dim;
4175: (*M)->stencil.noc = mat->stencil.noc;
4176: for (i=0; i<=mat->stencil.dim; i++) {
4177: (*M)->stencil.dims[i] = mat->stencil.dims[i];
4178: (*M)->stencil.starts[i] = mat->stencil.starts[i];
4179: }
4180: PetscLogEventEnd(MAT_Convert,mat,0,0,0);
4181: }
4182: PetscObjectStateIncrease((PetscObject)*M);
4184: /* Copy Mat options */
4185: if (issymmetric) {
4186: MatSetOption(*M,MAT_SYMMETRIC,PETSC_TRUE);
4187: }
4188: if (ishermitian) {
4189: MatSetOption(*M,MAT_HERMITIAN,PETSC_TRUE);
4190: }
4191: return(0);
4192: }
4194: /*@C
4195: MatFactorGetSolverType - Returns name of the package providing the factorization routines
4197: Not Collective
4199: Input Parameter:
4200: . mat - the matrix, must be a factored matrix
4202: Output Parameter:
4203: . type - the string name of the package (do not free this string)
4205: Notes:
4206: In Fortran you pass in a empty string and the package name will be copied into it.
4207: (Make sure the string is long enough)
4209: Level: intermediate
4211: .seealso: MatCopy(), MatDuplicate(), MatGetFactorAvailable(), MatGetFactor()
4212: @*/
4213: PetscErrorCode MatFactorGetSolverType(Mat mat, MatSolverType *type)
4214: {
4215: PetscErrorCode ierr, (*conv)(Mat,MatSolverType*);
4220: if (!mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Only for factored matrix");
4221: PetscObjectQueryFunction((PetscObject)mat,"MatFactorGetSolverType_C",&conv);
4222: if (!conv) {
4223: *type = MATSOLVERPETSC;
4224: } else {
4225: (*conv)(mat,type);
4226: }
4227: return(0);
4228: }
4230: typedef struct _MatSolverTypeForSpecifcType* MatSolverTypeForSpecifcType;
4231: struct _MatSolverTypeForSpecifcType {
4232: MatType mtype;
4233: PetscErrorCode (*getfactor[4])(Mat,MatFactorType,Mat*);
4234: MatSolverTypeForSpecifcType next;
4235: };
4237: typedef struct _MatSolverTypeHolder* MatSolverTypeHolder;
4238: struct _MatSolverTypeHolder {
4239: char *name;
4240: MatSolverTypeForSpecifcType handlers;
4241: MatSolverTypeHolder next;
4242: };
4244: static MatSolverTypeHolder MatSolverTypeHolders = NULL;
4246: /*@C
4247: MatSolvePackageRegister - Registers a MatSolverType that works for a particular matrix type
4249: Input Parameters:
4250: + package - name of the package, for example petsc or superlu
4251: . mtype - the matrix type that works with this package
4252: . ftype - the type of factorization supported by the package
4253: - getfactor - routine that will create the factored matrix ready to be used
4255: Level: intermediate
4257: .seealso: MatCopy(), MatDuplicate(), MatGetFactorAvailable()
4258: @*/
4259: PetscErrorCode MatSolverTypeRegister(MatSolverType package,MatType mtype,MatFactorType ftype,PetscErrorCode (*getfactor)(Mat,MatFactorType,Mat*))
4260: {
4261: PetscErrorCode ierr;
4262: MatSolverTypeHolder next = MatSolverTypeHolders,prev = NULL;
4263: PetscBool flg;
4264: MatSolverTypeForSpecifcType inext,iprev = NULL;
4267: MatInitializePackage();
4268: if (!next) {
4269: PetscNew(&MatSolverTypeHolders);
4270: PetscStrallocpy(package,&MatSolverTypeHolders->name);
4271: PetscNew(&MatSolverTypeHolders->handlers);
4272: PetscStrallocpy(mtype,(char **)&MatSolverTypeHolders->handlers->mtype);
4273: MatSolverTypeHolders->handlers->getfactor[(int)ftype-1] = getfactor;
4274: return(0);
4275: }
4276: while (next) {
4277: PetscStrcasecmp(package,next->name,&flg);
4278: if (flg) {
4279: if (!next->handlers) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_PLIB,"MatSolverTypeHolder is missing handlers");
4280: inext = next->handlers;
4281: while (inext) {
4282: PetscStrcasecmp(mtype,inext->mtype,&flg);
4283: if (flg) {
4284: inext->getfactor[(int)ftype-1] = getfactor;
4285: return(0);
4286: }
4287: iprev = inext;
4288: inext = inext->next;
4289: }
4290: PetscNew(&iprev->next);
4291: PetscStrallocpy(mtype,(char **)&iprev->next->mtype);
4292: iprev->next->getfactor[(int)ftype-1] = getfactor;
4293: return(0);
4294: }
4295: prev = next;
4296: next = next->next;
4297: }
4298: PetscNew(&prev->next);
4299: PetscStrallocpy(package,&prev->next->name);
4300: PetscNew(&prev->next->handlers);
4301: PetscStrallocpy(mtype,(char **)&prev->next->handlers->mtype);
4302: prev->next->handlers->getfactor[(int)ftype-1] = getfactor;
4303: return(0);
4304: }
4306: /*@C
4307: MatSolvePackageGet - Get's the function that creates the factor matrix if it exist
4309: Input Parameters:
4310: + package - name of the package, for example petsc or superlu
4311: . ftype - the type of factorization supported by the package
4312: - mtype - the matrix type that works with this package
4314: Output Parameters:
4315: + foundpackage - PETSC_TRUE if the package was registered
4316: . foundmtype - PETSC_TRUE if the package supports the requested mtype
4317: - getfactor - routine that will create the factored matrix ready to be used or NULL if not found
4319: Level: intermediate
4321: .seealso: MatCopy(), MatDuplicate(), MatGetFactorAvailable()
4322: @*/
4323: PetscErrorCode MatSolverTypeGet(MatSolverType package,MatType mtype,MatFactorType ftype,PetscBool *foundpackage,PetscBool *foundmtype,PetscErrorCode (**getfactor)(Mat,MatFactorType,Mat*))
4324: {
4325: PetscErrorCode ierr;
4326: MatSolverTypeHolder next = MatSolverTypeHolders;
4327: PetscBool flg;
4328: MatSolverTypeForSpecifcType inext;
4331: if (foundpackage) *foundpackage = PETSC_FALSE;
4332: if (foundmtype) *foundmtype = PETSC_FALSE;
4333: if (getfactor) *getfactor = NULL;
4335: if (package) {
4336: while (next) {
4337: PetscStrcasecmp(package,next->name,&flg);
4338: if (flg) {
4339: if (foundpackage) *foundpackage = PETSC_TRUE;
4340: inext = next->handlers;
4341: while (inext) {
4342: PetscStrbeginswith(mtype,inext->mtype,&flg);
4343: if (flg) {
4344: if (foundmtype) *foundmtype = PETSC_TRUE;
4345: if (getfactor) *getfactor = inext->getfactor[(int)ftype-1];
4346: return(0);
4347: }
4348: inext = inext->next;
4349: }
4350: }
4351: next = next->next;
4352: }
4353: } else {
4354: while (next) {
4355: inext = next->handlers;
4356: while (inext) {
4357: PetscStrbeginswith(mtype,inext->mtype,&flg);
4358: if (flg && inext->getfactor[(int)ftype-1]) {
4359: if (foundpackage) *foundpackage = PETSC_TRUE;
4360: if (foundmtype) *foundmtype = PETSC_TRUE;
4361: if (getfactor) *getfactor = inext->getfactor[(int)ftype-1];
4362: return(0);
4363: }
4364: inext = inext->next;
4365: }
4366: next = next->next;
4367: }
4368: }
4369: return(0);
4370: }
4372: PetscErrorCode MatSolverTypeDestroy(void)
4373: {
4374: PetscErrorCode ierr;
4375: MatSolverTypeHolder next = MatSolverTypeHolders,prev;
4376: MatSolverTypeForSpecifcType inext,iprev;
4379: while (next) {
4380: PetscFree(next->name);
4381: inext = next->handlers;
4382: while (inext) {
4383: PetscFree(inext->mtype);
4384: iprev = inext;
4385: inext = inext->next;
4386: PetscFree(iprev);
4387: }
4388: prev = next;
4389: next = next->next;
4390: PetscFree(prev);
4391: }
4392: MatSolverTypeHolders = NULL;
4393: return(0);
4394: }
4396: /*@C
4397: MatGetFactor - Returns a matrix suitable to calls to MatXXFactorSymbolic()
4399: Collective on Mat
4401: Input Parameters:
4402: + mat - the matrix
4403: . type - name of solver type, for example, superlu, petsc (to use PETSc's default)
4404: - ftype - factor type, MAT_FACTOR_LU, MAT_FACTOR_CHOLESKY, MAT_FACTOR_ICC, MAT_FACTOR_ILU,
4406: Output Parameters:
4407: . f - the factor matrix used with MatXXFactorSymbolic() calls
4409: Notes:
4410: Some PETSc matrix formats have alternative solvers available that are contained in alternative packages
4411: such as pastix, superlu, mumps etc.
4413: PETSc must have been ./configure to use the external solver, using the option --download-package
4415: Level: intermediate
4417: .seealso: MatCopy(), MatDuplicate(), MatGetFactorAvailable()
4418: @*/
4419: PetscErrorCode MatGetFactor(Mat mat, MatSolverType type,MatFactorType ftype,Mat *f)
4420: {
4421: PetscErrorCode ierr,(*conv)(Mat,MatFactorType,Mat*);
4422: PetscBool foundpackage,foundmtype;
4428: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
4429: MatCheckPreallocated(mat,1);
4431: MatSolverTypeGet(type,((PetscObject)mat)->type_name,ftype,&foundpackage,&foundmtype,&conv);
4432: if (!foundpackage) {
4433: if (type) {
4434: SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_MISSING_FACTOR,"Could not locate solver package %s. Perhaps you must ./configure with --download-%s",type,type);
4435: } else {
4436: SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_MISSING_FACTOR,"Could not locate a solver package. Perhaps you must ./configure with --download-<package>");
4437: }
4438: }
4440: if (!foundmtype) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_MISSING_FACTOR,"MatSolverType %s does not support matrix type %s",type,((PetscObject)mat)->type_name);
4441: 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);
4443: (*conv)(mat,ftype,f);
4444: return(0);
4445: }
4447: /*@C
4448: MatGetFactorAvailable - Returns a a flag if matrix supports particular package and factor type
4450: Not Collective
4452: Input Parameters:
4453: + mat - the matrix
4454: . type - name of solver type, for example, superlu, petsc (to use PETSc's default)
4455: - ftype - factor type, MAT_FACTOR_LU, MAT_FACTOR_CHOLESKY, MAT_FACTOR_ICC, MAT_FACTOR_ILU,
4457: Output Parameter:
4458: . flg - PETSC_TRUE if the factorization is available
4460: Notes:
4461: Some PETSc matrix formats have alternative solvers available that are contained in alternative packages
4462: such as pastix, superlu, mumps etc.
4464: PETSc must have been ./configure to use the external solver, using the option --download-package
4466: Level: intermediate
4468: .seealso: MatCopy(), MatDuplicate(), MatGetFactor()
4469: @*/
4470: PetscErrorCode MatGetFactorAvailable(Mat mat, MatSolverType type,MatFactorType ftype,PetscBool *flg)
4471: {
4472: PetscErrorCode ierr, (*gconv)(Mat,MatFactorType,Mat*);
4478: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
4479: MatCheckPreallocated(mat,1);
4481: *flg = PETSC_FALSE;
4482: MatSolverTypeGet(type,((PetscObject)mat)->type_name,ftype,NULL,NULL,&gconv);
4483: if (gconv) {
4484: *flg = PETSC_TRUE;
4485: }
4486: return(0);
4487: }
4489: #include <petscdmtypes.h>
4491: /*@
4492: MatDuplicate - Duplicates a matrix including the non-zero structure.
4494: Collective on Mat
4496: Input Parameters:
4497: + mat - the matrix
4498: - op - One of MAT_DO_NOT_COPY_VALUES, MAT_COPY_VALUES, or MAT_SHARE_NONZERO_PATTERN.
4499: See the manual page for MatDuplicateOption for an explanation of these options.
4501: Output Parameter:
4502: . M - pointer to place new matrix
4504: Level: intermediate
4506: Notes:
4507: You cannot change the nonzero pattern for the parent or child matrix if you use MAT_SHARE_NONZERO_PATTERN.
4508: 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.
4510: .seealso: MatCopy(), MatConvert(), MatDuplicateOption
4511: @*/
4512: PetscErrorCode MatDuplicate(Mat mat,MatDuplicateOption op,Mat *M)
4513: {
4515: Mat B;
4516: PetscInt i;
4517: DM dm;
4518: void (*viewf)(void);
4524: if (op == MAT_COPY_VALUES && !mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"MAT_COPY_VALUES not allowed for unassembled matrix");
4525: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
4526: MatCheckPreallocated(mat,1);
4528: *M = 0;
4529: if (!mat->ops->duplicate) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Not written for this matrix type");
4530: PetscLogEventBegin(MAT_Convert,mat,0,0,0);
4531: (*mat->ops->duplicate)(mat,op,M);
4532: B = *M;
4534: MatGetOperation(mat,MATOP_VIEW,&viewf);
4535: if (viewf) {
4536: MatSetOperation(B,MATOP_VIEW,viewf);
4537: }
4539: B->stencil.dim = mat->stencil.dim;
4540: B->stencil.noc = mat->stencil.noc;
4541: for (i=0; i<=mat->stencil.dim; i++) {
4542: B->stencil.dims[i] = mat->stencil.dims[i];
4543: B->stencil.starts[i] = mat->stencil.starts[i];
4544: }
4546: B->nooffproczerorows = mat->nooffproczerorows;
4547: B->nooffprocentries = mat->nooffprocentries;
4549: PetscObjectQuery((PetscObject) mat, "__PETSc_dm", (PetscObject*) &dm);
4550: if (dm) {
4551: PetscObjectCompose((PetscObject) B, "__PETSc_dm", (PetscObject) dm);
4552: }
4553: PetscLogEventEnd(MAT_Convert,mat,0,0,0);
4554: PetscObjectStateIncrease((PetscObject)B);
4555: return(0);
4556: }
4558: /*@
4559: MatGetDiagonal - Gets the diagonal of a matrix.
4561: Logically Collective on Mat
4563: Input Parameters:
4564: + mat - the matrix
4565: - v - the vector for storing the diagonal
4567: Output Parameter:
4568: . v - the diagonal of the matrix
4570: Level: intermediate
4572: Note:
4573: Currently only correct in parallel for square matrices.
4575: .seealso: MatGetRow(), MatCreateSubMatrices(), MatCreateSubMatrix(), MatGetRowMaxAbs()
4576: @*/
4577: PetscErrorCode MatGetDiagonal(Mat mat,Vec v)
4578: {
4585: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
4586: if (!mat->ops->getdiagonal) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
4587: MatCheckPreallocated(mat,1);
4589: (*mat->ops->getdiagonal)(mat,v);
4590: PetscObjectStateIncrease((PetscObject)v);
4591: return(0);
4592: }
4594: /*@C
4595: MatGetRowMin - Gets the minimum value (of the real part) of each
4596: row of the matrix
4598: Logically Collective on Mat
4600: Input Parameters:
4601: . mat - the matrix
4603: Output Parameter:
4604: + v - the vector for storing the maximums
4605: - idx - the indices of the column found for each row (optional)
4607: Level: intermediate
4609: Notes:
4610: The result of this call are the same as if one converted the matrix to dense format
4611: and found the minimum value in each row (i.e. the implicit zeros are counted as zeros).
4613: This code is only implemented for a couple of matrix formats.
4615: .seealso: MatGetDiagonal(), MatCreateSubMatrices(), MatCreateSubMatrix(), MatGetRowMaxAbs(),
4616: MatGetRowMax()
4617: @*/
4618: PetscErrorCode MatGetRowMin(Mat mat,Vec v,PetscInt idx[])
4619: {
4626: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
4627: if (!mat->ops->getrowmax) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
4628: MatCheckPreallocated(mat,1);
4630: (*mat->ops->getrowmin)(mat,v,idx);
4631: PetscObjectStateIncrease((PetscObject)v);
4632: return(0);
4633: }
4635: /*@C
4636: MatGetRowMinAbs - Gets the minimum value (in absolute value) of each
4637: row of the matrix
4639: Logically Collective on Mat
4641: Input Parameters:
4642: . mat - the matrix
4644: Output Parameter:
4645: + v - the vector for storing the minimums
4646: - idx - the indices of the column found for each row (or NULL if not needed)
4648: Level: intermediate
4650: Notes:
4651: if a row is completely empty or has only 0.0 values then the idx[] value for that
4652: row is 0 (the first column).
4654: This code is only implemented for a couple of matrix formats.
4656: .seealso: MatGetDiagonal(), MatCreateSubMatrices(), MatCreateSubMatrix(), MatGetRowMax(), MatGetRowMaxAbs(), MatGetRowMin()
4657: @*/
4658: PetscErrorCode MatGetRowMinAbs(Mat mat,Vec v,PetscInt idx[])
4659: {
4666: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
4667: if (!mat->ops->getrowminabs) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
4668: MatCheckPreallocated(mat,1);
4669: if (idx) {PetscArrayzero(idx,mat->rmap->n);}
4671: (*mat->ops->getrowminabs)(mat,v,idx);
4672: PetscObjectStateIncrease((PetscObject)v);
4673: return(0);
4674: }
4676: /*@C
4677: MatGetRowMax - Gets the maximum value (of the real part) of each
4678: row of the matrix
4680: Logically Collective on Mat
4682: Input Parameters:
4683: . mat - the matrix
4685: Output Parameter:
4686: + v - the vector for storing the maximums
4687: - idx - the indices of the column found for each row (optional)
4689: Level: intermediate
4691: Notes:
4692: The result of this call are the same as if one converted the matrix to dense format
4693: and found the minimum value in each row (i.e. the implicit zeros are counted as zeros).
4695: This code is only implemented for a couple of matrix formats.
4697: .seealso: MatGetDiagonal(), MatCreateSubMatrices(), MatCreateSubMatrix(), MatGetRowMaxAbs(), MatGetRowMin()
4698: @*/
4699: PetscErrorCode MatGetRowMax(Mat mat,Vec v,PetscInt idx[])
4700: {
4707: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
4708: if (!mat->ops->getrowmax) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
4709: MatCheckPreallocated(mat,1);
4711: (*mat->ops->getrowmax)(mat,v,idx);
4712: PetscObjectStateIncrease((PetscObject)v);
4713: return(0);
4714: }
4716: /*@C
4717: MatGetRowMaxAbs - Gets the maximum value (in absolute value) of each
4718: row of the matrix
4720: Logically Collective on Mat
4722: Input Parameters:
4723: . mat - the matrix
4725: Output Parameter:
4726: + v - the vector for storing the maximums
4727: - idx - the indices of the column found for each row (or NULL if not needed)
4729: Level: intermediate
4731: Notes:
4732: if a row is completely empty or has only 0.0 values then the idx[] value for that
4733: row is 0 (the first column).
4735: This code is only implemented for a couple of matrix formats.
4737: .seealso: MatGetDiagonal(), MatCreateSubMatrices(), MatCreateSubMatrix(), MatGetRowMax(), MatGetRowMin()
4738: @*/
4739: PetscErrorCode MatGetRowMaxAbs(Mat mat,Vec v,PetscInt idx[])
4740: {
4747: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
4748: if (!mat->ops->getrowmaxabs) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
4749: MatCheckPreallocated(mat,1);
4750: if (idx) {PetscArrayzero(idx,mat->rmap->n);}
4752: (*mat->ops->getrowmaxabs)(mat,v,idx);
4753: PetscObjectStateIncrease((PetscObject)v);
4754: return(0);
4755: }
4757: /*@
4758: MatGetRowSum - Gets the sum of each row of the matrix
4760: Logically or Neighborhood Collective on Mat
4762: Input Parameters:
4763: . mat - the matrix
4765: Output Parameter:
4766: . v - the vector for storing the sum of rows
4768: Level: intermediate
4770: Notes:
4771: This code is slow since it is not currently specialized for different formats
4773: .seealso: MatGetDiagonal(), MatCreateSubMatrices(), MatCreateSubMatrix(), MatGetRowMax(), MatGetRowMin()
4774: @*/
4775: PetscErrorCode MatGetRowSum(Mat mat, Vec v)
4776: {
4777: Vec ones;
4784: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
4785: MatCheckPreallocated(mat,1);
4786: MatCreateVecs(mat,&ones,NULL);
4787: VecSet(ones,1.);
4788: MatMult(mat,ones,v);
4789: VecDestroy(&ones);
4790: return(0);
4791: }
4793: /*@
4794: MatTranspose - Computes an in-place or out-of-place transpose of a matrix.
4796: Collective on Mat
4798: Input Parameter:
4799: + mat - the matrix to transpose
4800: - reuse - either MAT_INITIAL_MATRIX, MAT_REUSE_MATRIX, or MAT_INPLACE_MATRIX
4802: Output Parameters:
4803: . B - the transpose
4805: Notes:
4806: If you use MAT_INPLACE_MATRIX then you must pass in &mat for B
4808: MAT_REUSE_MATRIX causes the B matrix from a previous call to this function with MAT_INITIAL_MATRIX to be used
4810: Consider using MatCreateTranspose() instead if you only need a matrix that behaves like the transpose, but don't need the storage to be changed.
4812: Level: intermediate
4814: .seealso: MatMultTranspose(), MatMultTransposeAdd(), MatIsTranspose(), MatReuse
4815: @*/
4816: PetscErrorCode MatTranspose(Mat mat,MatReuse reuse,Mat *B)
4817: {
4823: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
4824: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
4825: if (!mat->ops->transpose) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
4826: if (reuse == MAT_INPLACE_MATRIX && mat != *B) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"MAT_INPLACE_MATRIX requires last matrix to match first");
4827: if (reuse == MAT_REUSE_MATRIX && mat == *B) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Perhaps you mean MAT_INPLACE_MATRIX");
4828: MatCheckPreallocated(mat,1);
4830: PetscLogEventBegin(MAT_Transpose,mat,0,0,0);
4831: (*mat->ops->transpose)(mat,reuse,B);
4832: PetscLogEventEnd(MAT_Transpose,mat,0,0,0);
4833: if (B) {PetscObjectStateIncrease((PetscObject)*B);}
4834: return(0);
4835: }
4837: /*@
4838: MatIsTranspose - Test whether a matrix is another one's transpose,
4839: or its own, in which case it tests symmetry.
4841: Collective on Mat
4843: Input Parameter:
4844: + A - the matrix to test
4845: - B - the matrix to test against, this can equal the first parameter
4847: Output Parameters:
4848: . flg - the result
4850: Notes:
4851: Only available for SeqAIJ/MPIAIJ matrices. The sequential algorithm
4852: has a running time of the order of the number of nonzeros; the parallel
4853: test involves parallel copies of the block-offdiagonal parts of the matrix.
4855: Level: intermediate
4857: .seealso: MatTranspose(), MatIsSymmetric(), MatIsHermitian()
4858: @*/
4859: PetscErrorCode MatIsTranspose(Mat A,Mat B,PetscReal tol,PetscBool *flg)
4860: {
4861: PetscErrorCode ierr,(*f)(Mat,Mat,PetscReal,PetscBool*),(*g)(Mat,Mat,PetscReal,PetscBool*);
4867: PetscObjectQueryFunction((PetscObject)A,"MatIsTranspose_C",&f);
4868: PetscObjectQueryFunction((PetscObject)B,"MatIsTranspose_C",&g);
4869: *flg = PETSC_FALSE;
4870: if (f && g) {
4871: if (f == g) {
4872: (*f)(A,B,tol,flg);
4873: } else SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_NOTSAMETYPE,"Matrices do not have the same comparator for symmetry test");
4874: } else {
4875: MatType mattype;
4876: if (!f) {
4877: MatGetType(A,&mattype);
4878: } else {
4879: MatGetType(B,&mattype);
4880: }
4881: SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Matrix of type <%s> does not support checking for transpose",mattype);
4882: }
4883: return(0);
4884: }
4886: /*@
4887: MatHermitianTranspose - Computes an in-place or out-of-place transpose of a matrix in complex conjugate.
4889: Collective on Mat
4891: Input Parameter:
4892: + mat - the matrix to transpose and complex conjugate
4893: - reuse - MAT_INITIAL_MATRIX to create a new matrix, MAT_INPLACE_MATRIX to reuse the first argument to store the transpose
4895: Output Parameters:
4896: . B - the Hermitian
4898: Level: intermediate
4900: .seealso: MatTranspose(), MatMultTranspose(), MatMultTransposeAdd(), MatIsTranspose(), MatReuse
4901: @*/
4902: PetscErrorCode MatHermitianTranspose(Mat mat,MatReuse reuse,Mat *B)
4903: {
4907: MatTranspose(mat,reuse,B);
4908: #if defined(PETSC_USE_COMPLEX)
4909: MatConjugate(*B);
4910: #endif
4911: return(0);
4912: }
4914: /*@
4915: MatIsHermitianTranspose - Test whether a matrix is another one's Hermitian transpose,
4917: Collective on Mat
4919: Input Parameter:
4920: + A - the matrix to test
4921: - B - the matrix to test against, this can equal the first parameter
4923: Output Parameters:
4924: . flg - the result
4926: Notes:
4927: Only available for SeqAIJ/MPIAIJ matrices. The sequential algorithm
4928: has a running time of the order of the number of nonzeros; the parallel
4929: test involves parallel copies of the block-offdiagonal parts of the matrix.
4931: Level: intermediate
4933: .seealso: MatTranspose(), MatIsSymmetric(), MatIsHermitian(), MatIsTranspose()
4934: @*/
4935: PetscErrorCode MatIsHermitianTranspose(Mat A,Mat B,PetscReal tol,PetscBool *flg)
4936: {
4937: PetscErrorCode ierr,(*f)(Mat,Mat,PetscReal,PetscBool*),(*g)(Mat,Mat,PetscReal,PetscBool*);
4943: PetscObjectQueryFunction((PetscObject)A,"MatIsHermitianTranspose_C",&f);
4944: PetscObjectQueryFunction((PetscObject)B,"MatIsHermitianTranspose_C",&g);
4945: if (f && g) {
4946: if (f==g) {
4947: (*f)(A,B,tol,flg);
4948: } else SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_NOTSAMETYPE,"Matrices do not have the same comparator for Hermitian test");
4949: }
4950: return(0);
4951: }
4953: /*@
4954: MatPermute - Creates a new matrix with rows and columns permuted from the
4955: original.
4957: Collective on Mat
4959: Input Parameters:
4960: + mat - the matrix to permute
4961: . row - row permutation, each processor supplies only the permutation for its rows
4962: - col - column permutation, each processor supplies only the permutation for its columns
4964: Output Parameters:
4965: . B - the permuted matrix
4967: Level: advanced
4969: Note:
4970: The index sets map from row/col of permuted matrix to row/col of original matrix.
4971: The index sets should be on the same communicator as Mat and have the same local sizes.
4973: .seealso: MatGetOrdering(), ISAllGather()
4975: @*/
4976: PetscErrorCode MatPermute(Mat mat,IS row,IS col,Mat *B)
4977: {
4986: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
4987: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
4988: if (!mat->ops->permute) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"MatPermute not available for Mat type %s",((PetscObject)mat)->type_name);
4989: MatCheckPreallocated(mat,1);
4991: (*mat->ops->permute)(mat,row,col,B);
4992: PetscObjectStateIncrease((PetscObject)*B);
4993: return(0);
4994: }
4996: /*@
4997: MatEqual - Compares two matrices.
4999: Collective on Mat
5001: Input Parameters:
5002: + A - the first matrix
5003: - B - the second matrix
5005: Output Parameter:
5006: . flg - PETSC_TRUE if the matrices are equal; PETSC_FALSE otherwise.
5008: Level: intermediate
5010: @*/
5011: PetscErrorCode MatEqual(Mat A,Mat B,PetscBool *flg)
5012: {
5022: MatCheckPreallocated(B,2);
5023: if (!A->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
5024: if (!B->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
5025: 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);
5026: if (!A->ops->equal) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Mat type %s",((PetscObject)A)->type_name);
5027: if (!B->ops->equal) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Mat type %s",((PetscObject)B)->type_name);
5028: 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);
5029: MatCheckPreallocated(A,1);
5031: (*A->ops->equal)(A,B,flg);
5032: return(0);
5033: }
5035: /*@
5036: MatDiagonalScale - Scales a matrix on the left and right by diagonal
5037: matrices that are stored as vectors. Either of the two scaling
5038: matrices can be NULL.
5040: Collective on Mat
5042: Input Parameters:
5043: + mat - the matrix to be scaled
5044: . l - the left scaling vector (or NULL)
5045: - r - the right scaling vector (or NULL)
5047: Notes:
5048: MatDiagonalScale() computes A = LAR, where
5049: L = a diagonal matrix (stored as a vector), R = a diagonal matrix (stored as a vector)
5050: The L scales the rows of the matrix, the R scales the columns of the matrix.
5052: Level: intermediate
5055: .seealso: MatScale(), MatShift(), MatDiagonalSet()
5056: @*/
5057: PetscErrorCode MatDiagonalScale(Mat mat,Vec l,Vec r)
5058: {
5064: if (!mat->ops->diagonalscale) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
5067: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
5068: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
5069: MatCheckPreallocated(mat,1);
5071: PetscLogEventBegin(MAT_Scale,mat,0,0,0);
5072: (*mat->ops->diagonalscale)(mat,l,r);
5073: PetscLogEventEnd(MAT_Scale,mat,0,0,0);
5074: PetscObjectStateIncrease((PetscObject)mat);
5075: return(0);
5076: }
5078: /*@
5079: MatScale - Scales all elements of a matrix by a given number.
5081: Logically Collective on Mat
5083: Input Parameters:
5084: + mat - the matrix to be scaled
5085: - a - the scaling value
5087: Output Parameter:
5088: . mat - the scaled matrix
5090: Level: intermediate
5092: .seealso: MatDiagonalScale()
5093: @*/
5094: PetscErrorCode MatScale(Mat mat,PetscScalar a)
5095: {
5101: if (a != (PetscScalar)1.0 && !mat->ops->scale) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
5102: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
5103: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
5105: MatCheckPreallocated(mat,1);
5107: PetscLogEventBegin(MAT_Scale,mat,0,0,0);
5108: if (a != (PetscScalar)1.0) {
5109: (*mat->ops->scale)(mat,a);
5110: PetscObjectStateIncrease((PetscObject)mat);
5111: }
5112: PetscLogEventEnd(MAT_Scale,mat,0,0,0);
5113: return(0);
5114: }
5116: /*@
5117: MatNorm - Calculates various norms of a matrix.
5119: Collective on Mat
5121: Input Parameters:
5122: + mat - the matrix
5123: - type - the type of norm, NORM_1, NORM_FROBENIUS, NORM_INFINITY
5125: Output Parameters:
5126: . nrm - the resulting norm
5128: Level: intermediate
5130: @*/
5131: PetscErrorCode MatNorm(Mat mat,NormType type,PetscReal *nrm)
5132: {
5140: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
5141: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
5142: if (!mat->ops->norm) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
5143: MatCheckPreallocated(mat,1);
5145: (*mat->ops->norm)(mat,type,nrm);
5146: return(0);
5147: }
5149: /*
5150: This variable is used to prevent counting of MatAssemblyBegin() that
5151: are called from within a MatAssemblyEnd().
5152: */
5153: static PetscInt MatAssemblyEnd_InUse = 0;
5154: /*@
5155: MatAssemblyBegin - Begins assembling the matrix. This routine should
5156: be called after completing all calls to MatSetValues().
5158: Collective on Mat
5160: Input Parameters:
5161: + mat - the matrix
5162: - type - type of assembly, either MAT_FLUSH_ASSEMBLY or MAT_FINAL_ASSEMBLY
5164: Notes:
5165: MatSetValues() generally caches the values. The matrix is ready to
5166: use only after MatAssemblyBegin() and MatAssemblyEnd() have been called.
5167: Use MAT_FLUSH_ASSEMBLY when switching between ADD_VALUES and INSERT_VALUES
5168: in MatSetValues(); use MAT_FINAL_ASSEMBLY for the final assembly before
5169: using the matrix.
5171: ALL processes that share a matrix MUST call MatAssemblyBegin() and MatAssemblyEnd() the SAME NUMBER of times, and each time with the
5172: 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
5173: a global collective operation requring all processes that share the matrix.
5175: Space for preallocated nonzeros that is not filled by a call to MatSetValues() or a related routine are compressed
5176: out by assembly. If you intend to use that extra space on a subsequent assembly, be sure to insert explicit zeros
5177: before MAT_FINAL_ASSEMBLY so the space is not compressed out.
5179: Level: beginner
5181: .seealso: MatAssemblyEnd(), MatSetValues(), MatAssembled()
5182: @*/
5183: PetscErrorCode MatAssemblyBegin(Mat mat,MatAssemblyType type)
5184: {
5190: MatCheckPreallocated(mat,1);
5191: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix.\nDid you forget to call MatSetUnfactored()?");
5192: if (mat->assembled) {
5193: mat->was_assembled = PETSC_TRUE;
5194: mat->assembled = PETSC_FALSE;
5195: }
5197: if (!MatAssemblyEnd_InUse) {
5198: PetscLogEventBegin(MAT_AssemblyBegin,mat,0,0,0);
5199: if (mat->ops->assemblybegin) {(*mat->ops->assemblybegin)(mat,type);}
5200: PetscLogEventEnd(MAT_AssemblyBegin,mat,0,0,0);
5201: } else if (mat->ops->assemblybegin) {
5202: (*mat->ops->assemblybegin)(mat,type);
5203: }
5204: return(0);
5205: }
5207: /*@
5208: MatAssembled - Indicates if a matrix has been assembled and is ready for
5209: use; for example, in matrix-vector product.
5211: Not Collective
5213: Input Parameter:
5214: . mat - the matrix
5216: Output Parameter:
5217: . assembled - PETSC_TRUE or PETSC_FALSE
5219: Level: advanced
5221: .seealso: MatAssemblyEnd(), MatSetValues(), MatAssemblyBegin()
5222: @*/
5223: PetscErrorCode MatAssembled(Mat mat,PetscBool *assembled)
5224: {
5228: *assembled = mat->assembled;
5229: return(0);
5230: }
5232: /*@
5233: MatAssemblyEnd - Completes assembling the matrix. This routine should
5234: be called after MatAssemblyBegin().
5236: Collective on Mat
5238: Input Parameters:
5239: + mat - the matrix
5240: - type - type of assembly, either MAT_FLUSH_ASSEMBLY or MAT_FINAL_ASSEMBLY
5242: Options Database Keys:
5243: + -mat_view ::ascii_info - Prints info on matrix at conclusion of MatEndAssembly()
5244: . -mat_view ::ascii_info_detail - Prints more detailed info
5245: . -mat_view - Prints matrix in ASCII format
5246: . -mat_view ::ascii_matlab - Prints matrix in Matlab format
5247: . -mat_view draw - PetscDraws nonzero structure of matrix, using MatView() and PetscDrawOpenX().
5248: . -display <name> - Sets display name (default is host)
5249: . -draw_pause <sec> - Sets number of seconds to pause after display
5250: . -mat_view socket - Sends matrix to socket, can be accessed from Matlab (See Users-Manual: Chapter 12 Using MATLAB with PETSc )
5251: . -viewer_socket_machine <machine> - Machine to use for socket
5252: . -viewer_socket_port <port> - Port number to use for socket
5253: - -mat_view binary:filename[:append] - Save matrix to file in binary format
5255: Notes:
5256: MatSetValues() generally caches the values. The matrix is ready to
5257: use only after MatAssemblyBegin() and MatAssemblyEnd() have been called.
5258: Use MAT_FLUSH_ASSEMBLY when switching between ADD_VALUES and INSERT_VALUES
5259: in MatSetValues(); use MAT_FINAL_ASSEMBLY for the final assembly before
5260: using the matrix.
5262: Space for preallocated nonzeros that is not filled by a call to MatSetValues() or a related routine are compressed
5263: out by assembly. If you intend to use that extra space on a subsequent assembly, be sure to insert explicit zeros
5264: before MAT_FINAL_ASSEMBLY so the space is not compressed out.
5266: Level: beginner
5268: .seealso: MatAssemblyBegin(), MatSetValues(), PetscDrawOpenX(), PetscDrawCreate(), MatView(), MatAssembled(), PetscViewerSocketOpen()
5269: @*/
5270: PetscErrorCode MatAssemblyEnd(Mat mat,MatAssemblyType type)
5271: {
5272: PetscErrorCode ierr;
5273: static PetscInt inassm = 0;
5274: PetscBool flg = PETSC_FALSE;
5280: inassm++;
5281: MatAssemblyEnd_InUse++;
5282: if (MatAssemblyEnd_InUse == 1) { /* Do the logging only the first time through */
5283: PetscLogEventBegin(MAT_AssemblyEnd,mat,0,0,0);
5284: if (mat->ops->assemblyend) {
5285: (*mat->ops->assemblyend)(mat,type);
5286: }
5287: PetscLogEventEnd(MAT_AssemblyEnd,mat,0,0,0);
5288: } else if (mat->ops->assemblyend) {
5289: (*mat->ops->assemblyend)(mat,type);
5290: }
5292: /* Flush assembly is not a true assembly */
5293: if (type != MAT_FLUSH_ASSEMBLY) {
5294: mat->num_ass++;
5295: mat->assembled = PETSC_TRUE;
5296: mat->ass_nonzerostate = mat->nonzerostate;
5297: }
5299: mat->insertmode = NOT_SET_VALUES;
5300: MatAssemblyEnd_InUse--;
5301: PetscObjectStateIncrease((PetscObject)mat);
5302: if (!mat->symmetric_eternal) {
5303: mat->symmetric_set = PETSC_FALSE;
5304: mat->hermitian_set = PETSC_FALSE;
5305: mat->structurally_symmetric_set = PETSC_FALSE;
5306: }
5307: if (inassm == 1 && type != MAT_FLUSH_ASSEMBLY) {
5308: MatViewFromOptions(mat,NULL,"-mat_view");
5310: if (mat->checksymmetryonassembly) {
5311: MatIsSymmetric(mat,mat->checksymmetrytol,&flg);
5312: if (flg) {
5313: PetscPrintf(PetscObjectComm((PetscObject)mat),"Matrix is symmetric (tolerance %g)\n",(double)mat->checksymmetrytol);
5314: } else {
5315: PetscPrintf(PetscObjectComm((PetscObject)mat),"Matrix is not symmetric (tolerance %g)\n",(double)mat->checksymmetrytol);
5316: }
5317: }
5318: if (mat->nullsp && mat->checknullspaceonassembly) {
5319: MatNullSpaceTest(mat->nullsp,mat,NULL);
5320: }
5321: }
5322: inassm--;
5323: return(0);
5324: }
5326: /*@
5327: MatSetOption - Sets a parameter option for a matrix. Some options
5328: may be specific to certain storage formats. Some options
5329: determine how values will be inserted (or added). Sorted,
5330: row-oriented input will generally assemble the fastest. The default
5331: is row-oriented.
5333: Logically Collective on Mat for certain operations, such as MAT_SPD, not collective for MAT_ROW_ORIENTED, see MatOption
5335: Input Parameters:
5336: + mat - the matrix
5337: . option - the option, one of those listed below (and possibly others),
5338: - flg - turn the option on (PETSC_TRUE) or off (PETSC_FALSE)
5340: Options Describing Matrix Structure:
5341: + MAT_SPD - symmetric positive definite
5342: . MAT_SYMMETRIC - symmetric in terms of both structure and value
5343: . MAT_HERMITIAN - transpose is the complex conjugation
5344: . MAT_STRUCTURALLY_SYMMETRIC - symmetric nonzero structure
5345: - MAT_SYMMETRY_ETERNAL - if you would like the symmetry/Hermitian flag
5346: you set to be kept with all future use of the matrix
5347: including after MatAssemblyBegin/End() which could
5348: potentially change the symmetry structure, i.e. you
5349: KNOW the matrix will ALWAYS have the property you set.
5352: Options For Use with MatSetValues():
5353: Insert a logically dense subblock, which can be
5354: . MAT_ROW_ORIENTED - row-oriented (default)
5356: Note these options reflect the data you pass in with MatSetValues(); it has
5357: nothing to do with how the data is stored internally in the matrix
5358: data structure.
5360: When (re)assembling a matrix, we can restrict the input for
5361: efficiency/debugging purposes. These options include:
5362: + MAT_NEW_NONZERO_LOCATIONS - additional insertions will be allowed if they generate a new nonzero (slow)
5363: . MAT_NEW_DIAGONALS - new diagonals will be allowed (for block diagonal format only)
5364: . MAT_IGNORE_OFF_PROC_ENTRIES - drops off-processor entries
5365: . MAT_NEW_NONZERO_LOCATION_ERR - generates an error for new matrix entry
5366: . MAT_USE_HASH_TABLE - uses a hash table to speed up matrix assembly
5367: . MAT_NO_OFF_PROC_ENTRIES - you know each process will only set values for its own rows, will generate an error if
5368: any process sets values for another process. This avoids all reductions in the MatAssembly routines and thus improves
5369: performance for very large process counts.
5370: - MAT_SUBSET_OFF_PROC_ENTRIES - you know that the first assembly after setting this flag will set a superset
5371: of the off-process entries required for all subsequent assemblies. This avoids a rendezvous step in the MatAssembly
5372: functions, instead sending only neighbor messages.
5374: Notes:
5375: Except for MAT_UNUSED_NONZERO_LOCATION_ERR and MAT_ROW_ORIENTED all processes that share the matrix must pass the same value in flg!
5377: Some options are relevant only for particular matrix types and
5378: are thus ignored by others. Other options are not supported by
5379: certain matrix types and will generate an error message if set.
5381: If using a Fortran 77 module to compute a matrix, one may need to
5382: use the column-oriented option (or convert to the row-oriented
5383: format).
5385: MAT_NEW_NONZERO_LOCATIONS set to PETSC_FALSE indicates that any add or insertion
5386: that would generate a new entry in the nonzero structure is instead
5387: ignored. Thus, if memory has not alredy been allocated for this particular
5388: data, then the insertion is ignored. For dense matrices, in which
5389: the entire array is allocated, no entries are ever ignored.
5390: Set after the first MatAssemblyEnd(). If this option is set then the MatAssemblyBegin/End() processes has one less global reduction
5392: MAT_NEW_NONZERO_LOCATION_ERR set to PETSC_TRUE indicates that any add or insertion
5393: that would generate a new entry in the nonzero structure instead produces
5394: 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
5396: MAT_NEW_NONZERO_ALLOCATION_ERR set to PETSC_TRUE indicates that any add or insertion
5397: that would generate a new entry that has not been preallocated will
5398: instead produce an error. (Currently supported for AIJ and BAIJ formats
5399: only.) This is a useful flag when debugging matrix memory preallocation.
5400: If this option is set then the MatAssemblyBegin/End() processes has one less global reduction
5402: MAT_IGNORE_OFF_PROC_ENTRIES set to PETSC_TRUE indicates entries destined for
5403: other processors should be dropped, rather than stashed.
5404: This is useful if you know that the "owning" processor is also
5405: always generating the correct matrix entries, so that PETSc need
5406: not transfer duplicate entries generated on another processor.
5408: MAT_USE_HASH_TABLE indicates that a hash table be used to improve the
5409: searches during matrix assembly. When this flag is set, the hash table
5410: is created during the first Matrix Assembly. This hash table is
5411: used the next time through, during MatSetVaules()/MatSetVaulesBlocked()
5412: to improve the searching of indices. MAT_NEW_NONZERO_LOCATIONS flag
5413: should be used with MAT_USE_HASH_TABLE flag. This option is currently
5414: supported by MATMPIBAIJ format only.
5416: MAT_KEEP_NONZERO_PATTERN indicates when MatZeroRows() is called the zeroed entries
5417: are kept in the nonzero structure
5419: MAT_IGNORE_ZERO_ENTRIES - for AIJ/IS matrices this will stop zero values from creating
5420: a zero location in the matrix
5422: MAT_USE_INODES - indicates using inode version of the code - works with AIJ matrix types
5424: MAT_NO_OFF_PROC_ZERO_ROWS - you know each process will only zero its own rows. This avoids all reductions in the
5425: zero row routines and thus improves performance for very large process counts.
5427: MAT_IGNORE_LOWER_TRIANGULAR - For SBAIJ matrices will ignore any insertions you make in the lower triangular
5428: part of the matrix (since they should match the upper triangular part).
5430: MAT_SORTED_FULL - each process provides exactly its local rows; all column indices for a given row are passed in a
5431: single call to MatSetValues(), preallocation is perfect, row oriented, INSERT_VALUES is used. Common
5432: with finite difference schemes with non-periodic boundary conditions.
5433: Notes:
5434: Can only be called after MatSetSizes() and MatSetType() have been set.
5436: Level: intermediate
5438: .seealso: MatOption, Mat
5440: @*/
5441: PetscErrorCode MatSetOption(Mat mat,MatOption op,PetscBool flg)
5442: {
5448: if (op > 0) {
5451: }
5453: 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);
5454: 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()");
5456: switch (op) {
5457: case MAT_NO_OFF_PROC_ENTRIES:
5458: mat->nooffprocentries = flg;
5459: return(0);
5460: break;
5461: case MAT_SUBSET_OFF_PROC_ENTRIES:
5462: mat->assembly_subset = flg;
5463: if (!mat->assembly_subset) { /* See the same logic in VecAssembly wrt VEC_SUBSET_OFF_PROC_ENTRIES */
5464: #if !defined(PETSC_HAVE_MPIUNI)
5465: MatStashScatterDestroy_BTS(&mat->stash);
5466: #endif
5467: mat->stash.first_assembly_done = PETSC_FALSE;
5468: }
5469: return(0);
5470: case MAT_NO_OFF_PROC_ZERO_ROWS:
5471: mat->nooffproczerorows = flg;
5472: return(0);
5473: break;
5474: case MAT_SPD:
5475: mat->spd_set = PETSC_TRUE;
5476: mat->spd = flg;
5477: if (flg) {
5478: mat->symmetric = PETSC_TRUE;
5479: mat->structurally_symmetric = PETSC_TRUE;
5480: mat->symmetric_set = PETSC_TRUE;
5481: mat->structurally_symmetric_set = PETSC_TRUE;
5482: }
5483: break;
5484: case MAT_SYMMETRIC:
5485: mat->symmetric = flg;
5486: if (flg) mat->structurally_symmetric = PETSC_TRUE;
5487: mat->symmetric_set = PETSC_TRUE;
5488: mat->structurally_symmetric_set = flg;
5489: #if !defined(PETSC_USE_COMPLEX)
5490: mat->hermitian = flg;
5491: mat->hermitian_set = PETSC_TRUE;
5492: #endif
5493: break;
5494: case MAT_HERMITIAN:
5495: mat->hermitian = flg;
5496: if (flg) mat->structurally_symmetric = PETSC_TRUE;
5497: mat->hermitian_set = PETSC_TRUE;
5498: mat->structurally_symmetric_set = flg;
5499: #if !defined(PETSC_USE_COMPLEX)
5500: mat->symmetric = flg;
5501: mat->symmetric_set = PETSC_TRUE;
5502: #endif
5503: break;
5504: case MAT_STRUCTURALLY_SYMMETRIC:
5505: mat->structurally_symmetric = flg;
5506: mat->structurally_symmetric_set = PETSC_TRUE;
5507: break;
5508: case MAT_SYMMETRY_ETERNAL:
5509: mat->symmetric_eternal = flg;
5510: break;
5511: case MAT_STRUCTURE_ONLY:
5512: mat->structure_only = flg;
5513: break;
5514: case MAT_SORTED_FULL:
5515: mat->sortedfull = flg;
5516: break;
5517: default:
5518: break;
5519: }
5520: if (mat->ops->setoption) {
5521: (*mat->ops->setoption)(mat,op,flg);
5522: }
5523: return(0);
5524: }
5526: /*@
5527: MatGetOption - Gets a parameter option that has been set for a matrix.
5529: Logically Collective on Mat for certain operations, such as MAT_SPD, not collective for MAT_ROW_ORIENTED, see MatOption
5531: Input Parameters:
5532: + mat - the matrix
5533: - option - the option, this only responds to certain options, check the code for which ones
5535: Output Parameter:
5536: . flg - turn the option on (PETSC_TRUE) or off (PETSC_FALSE)
5538: Notes:
5539: Can only be called after MatSetSizes() and MatSetType() have been set.
5541: Level: intermediate
5543: .seealso: MatOption, MatSetOption()
5545: @*/
5546: PetscErrorCode MatGetOption(Mat mat,MatOption op,PetscBool *flg)
5547: {
5552: 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);
5553: 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()");
5555: switch (op) {
5556: case MAT_NO_OFF_PROC_ENTRIES:
5557: *flg = mat->nooffprocentries;
5558: break;
5559: case MAT_NO_OFF_PROC_ZERO_ROWS:
5560: *flg = mat->nooffproczerorows;
5561: break;
5562: case MAT_SYMMETRIC:
5563: *flg = mat->symmetric;
5564: break;
5565: case MAT_HERMITIAN:
5566: *flg = mat->hermitian;
5567: break;
5568: case MAT_STRUCTURALLY_SYMMETRIC:
5569: *flg = mat->structurally_symmetric;
5570: break;
5571: case MAT_SYMMETRY_ETERNAL:
5572: *flg = mat->symmetric_eternal;
5573: break;
5574: case MAT_SPD:
5575: *flg = mat->spd;
5576: break;
5577: default:
5578: break;
5579: }
5580: return(0);
5581: }
5583: /*@
5584: MatZeroEntries - Zeros all entries of a matrix. For sparse matrices
5585: this routine retains the old nonzero structure.
5587: Logically Collective on Mat
5589: Input Parameters:
5590: . mat - the matrix
5592: Level: intermediate
5594: Notes:
5595: 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.
5596: See the Performance chapter of the users manual for information on preallocating matrices.
5598: .seealso: MatZeroRows()
5599: @*/
5600: PetscErrorCode MatZeroEntries(Mat mat)
5601: {
5607: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
5608: 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");
5609: if (!mat->ops->zeroentries) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
5610: MatCheckPreallocated(mat,1);
5612: PetscLogEventBegin(MAT_ZeroEntries,mat,0,0,0);
5613: (*mat->ops->zeroentries)(mat);
5614: PetscLogEventEnd(MAT_ZeroEntries,mat,0,0,0);
5615: PetscObjectStateIncrease((PetscObject)mat);
5616: return(0);
5617: }
5619: /*@
5620: MatZeroRowsColumns - Zeros all entries (except possibly the main diagonal)
5621: of a set of rows and columns of a matrix.
5623: Collective on Mat
5625: Input Parameters:
5626: + mat - the matrix
5627: . numRows - the number of rows to remove
5628: . rows - the global row indices
5629: . diag - value put in all diagonals of eliminated rows (0.0 will even eliminate diagonal entry)
5630: . x - optional vector of solutions for zeroed rows (other entries in vector are not used)
5631: - b - optional vector of right hand side, that will be adjusted by provided solution
5633: Notes:
5634: This does not change the nonzero structure of the matrix, it merely zeros those entries in the matrix.
5636: The user can set a value in the diagonal entry (or for the AIJ and
5637: row formats can optionally remove the main diagonal entry from the
5638: nonzero structure as well, by passing 0.0 as the final argument).
5640: For the parallel case, all processes that share the matrix (i.e.,
5641: those in the communicator used for matrix creation) MUST call this
5642: routine, regardless of whether any rows being zeroed are owned by
5643: them.
5645: Each processor can indicate any rows in the entire matrix to be zeroed (i.e. each process does NOT have to
5646: list only rows local to itself).
5648: The option MAT_NO_OFF_PROC_ZERO_ROWS does not apply to this routine.
5650: Level: intermediate
5652: .seealso: MatZeroRowsIS(), MatZeroRows(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
5653: MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
5654: @*/
5655: PetscErrorCode MatZeroRowsColumns(Mat mat,PetscInt numRows,const PetscInt rows[],PetscScalar diag,Vec x,Vec b)
5656: {
5663: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
5664: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
5665: if (!mat->ops->zerorowscolumns) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
5666: MatCheckPreallocated(mat,1);
5668: (*mat->ops->zerorowscolumns)(mat,numRows,rows,diag,x,b);
5669: MatViewFromOptions(mat,NULL,"-mat_view");
5670: PetscObjectStateIncrease((PetscObject)mat);
5671: return(0);
5672: }
5674: /*@
5675: MatZeroRowsColumnsIS - Zeros all entries (except possibly the main diagonal)
5676: of a set of rows and columns of a matrix.
5678: Collective on Mat
5680: Input Parameters:
5681: + mat - the matrix
5682: . is - the rows to zero
5683: . diag - value put in all diagonals of eliminated rows (0.0 will even eliminate diagonal entry)
5684: . x - optional vector of solutions for zeroed rows (other entries in vector are not used)
5685: - b - optional vector of right hand side, that will be adjusted by provided solution
5687: Notes:
5688: This does not change the nonzero structure of the matrix, it merely zeros those entries in the matrix.
5690: The user can set a value in the diagonal entry (or for the AIJ and
5691: row formats can optionally remove the main diagonal entry from the
5692: nonzero structure as well, by passing 0.0 as the final argument).
5694: For the parallel case, all processes that share the matrix (i.e.,
5695: those in the communicator used for matrix creation) MUST call this
5696: routine, regardless of whether any rows being zeroed are owned by
5697: them.
5699: Each processor can indicate any rows in the entire matrix to be zeroed (i.e. each process does NOT have to
5700: list only rows local to itself).
5702: The option MAT_NO_OFF_PROC_ZERO_ROWS does not apply to this routine.
5704: Level: intermediate
5706: .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
5707: MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRows(), MatZeroRowsColumnsStencil()
5708: @*/
5709: PetscErrorCode MatZeroRowsColumnsIS(Mat mat,IS is,PetscScalar diag,Vec x,Vec b)
5710: {
5712: PetscInt numRows;
5713: const PetscInt *rows;
5720: ISGetLocalSize(is,&numRows);
5721: ISGetIndices(is,&rows);
5722: MatZeroRowsColumns(mat,numRows,rows,diag,x,b);
5723: ISRestoreIndices(is,&rows);
5724: return(0);
5725: }
5727: /*@
5728: MatZeroRows - Zeros all entries (except possibly the main diagonal)
5729: of a set of rows of a matrix.
5731: Collective on Mat
5733: Input Parameters:
5734: + mat - the matrix
5735: . numRows - the number of rows to remove
5736: . rows - the global row indices
5737: . diag - value put in all diagonals of eliminated rows (0.0 will even eliminate diagonal entry)
5738: . x - optional vector of solutions for zeroed rows (other entries in vector are not used)
5739: - b - optional vector of right hand side, that will be adjusted by provided solution
5741: Notes:
5742: For the AIJ and BAIJ matrix formats this removes the old nonzero structure,
5743: but does not release memory. For the dense and block diagonal
5744: formats this does not alter the nonzero structure.
5746: If the option MatSetOption(mat,MAT_KEEP_NONZERO_PATTERN,PETSC_TRUE) the nonzero structure
5747: of the matrix is not changed (even for AIJ and BAIJ matrices) the values are
5748: merely zeroed.
5750: The user can set a value in the diagonal entry (or for the AIJ and
5751: row formats can optionally remove the main diagonal entry from the
5752: nonzero structure as well, by passing 0.0 as the final argument).
5754: For the parallel case, all processes that share the matrix (i.e.,
5755: those in the communicator used for matrix creation) MUST call this
5756: routine, regardless of whether any rows being zeroed are owned by
5757: them.
5759: Each processor can indicate any rows in the entire matrix to be zeroed (i.e. each process does NOT have to
5760: list only rows local to itself).
5762: You can call MatSetOption(mat,MAT_NO_OFF_PROC_ZERO_ROWS,PETSC_TRUE) if each process indicates only rows it
5763: owns that are to be zeroed. This saves a global synchronization in the implementation.
5765: Level: intermediate
5767: .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
5768: MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
5769: @*/
5770: PetscErrorCode MatZeroRows(Mat mat,PetscInt numRows,const PetscInt rows[],PetscScalar diag,Vec x,Vec b)
5771: {
5778: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
5779: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
5780: if (!mat->ops->zerorows) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
5781: MatCheckPreallocated(mat,1);
5783: (*mat->ops->zerorows)(mat,numRows,rows,diag,x,b);
5784: MatViewFromOptions(mat,NULL,"-mat_view");
5785: PetscObjectStateIncrease((PetscObject)mat);
5786: return(0);
5787: }
5789: /*@
5790: MatZeroRowsIS - Zeros all entries (except possibly the main diagonal)
5791: of a set of rows of a matrix.
5793: Collective on Mat
5795: Input Parameters:
5796: + mat - the matrix
5797: . is - index set of rows to remove
5798: . diag - value put in all diagonals of eliminated rows
5799: . x - optional vector of solutions for zeroed rows (other entries in vector are not used)
5800: - b - optional vector of right hand side, that will be adjusted by provided solution
5802: Notes:
5803: For the AIJ and BAIJ matrix formats this removes the old nonzero structure,
5804: but does not release memory. For the dense and block diagonal
5805: formats this does not alter the nonzero structure.
5807: If the option MatSetOption(mat,MAT_KEEP_NONZERO_PATTERN,PETSC_TRUE) the nonzero structure
5808: of the matrix is not changed (even for AIJ and BAIJ matrices) the values are
5809: merely zeroed.
5811: The user can set a value in the diagonal entry (or for the AIJ and
5812: row formats can optionally remove the main diagonal entry from the
5813: nonzero structure as well, by passing 0.0 as the final argument).
5815: For the parallel case, all processes that share the matrix (i.e.,
5816: those in the communicator used for matrix creation) MUST call this
5817: routine, regardless of whether any rows being zeroed are owned by
5818: them.
5820: Each processor can indicate any rows in the entire matrix to be zeroed (i.e. each process does NOT have to
5821: list only rows local to itself).
5823: You can call MatSetOption(mat,MAT_NO_OFF_PROC_ZERO_ROWS,PETSC_TRUE) if each process indicates only rows it
5824: owns that are to be zeroed. This saves a global synchronization in the implementation.
5826: Level: intermediate
5828: .seealso: MatZeroRows(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
5829: MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
5830: @*/
5831: PetscErrorCode MatZeroRowsIS(Mat mat,IS is,PetscScalar diag,Vec x,Vec b)
5832: {
5833: PetscInt numRows;
5834: const PetscInt *rows;
5841: ISGetLocalSize(is,&numRows);
5842: ISGetIndices(is,&rows);
5843: MatZeroRows(mat,numRows,rows,diag,x,b);
5844: ISRestoreIndices(is,&rows);
5845: return(0);
5846: }
5848: /*@
5849: MatZeroRowsStencil - Zeros all entries (except possibly the main diagonal)
5850: of a set of rows of a matrix. These rows must be local to the process.
5852: Collective on Mat
5854: Input Parameters:
5855: + mat - the matrix
5856: . numRows - the number of rows to remove
5857: . rows - the grid coordinates (and component number when dof > 1) for matrix rows
5858: . diag - value put in all diagonals of eliminated rows (0.0 will even eliminate diagonal entry)
5859: . x - optional vector of solutions for zeroed rows (other entries in vector are not used)
5860: - b - optional vector of right hand side, that will be adjusted by provided solution
5862: Notes:
5863: For the AIJ and BAIJ matrix formats this removes the old nonzero structure,
5864: but does not release memory. For the dense and block diagonal
5865: formats this does not alter the nonzero structure.
5867: If the option MatSetOption(mat,MAT_KEEP_NONZERO_PATTERN,PETSC_TRUE) the nonzero structure
5868: of the matrix is not changed (even for AIJ and BAIJ matrices) the values are
5869: merely zeroed.
5871: The user can set a value in the diagonal entry (or for the AIJ and
5872: row formats can optionally remove the main diagonal entry from the
5873: nonzero structure as well, by passing 0.0 as the final argument).
5875: For the parallel case, all processes that share the matrix (i.e.,
5876: those in the communicator used for matrix creation) MUST call this
5877: routine, regardless of whether any rows being zeroed are owned by
5878: them.
5880: Each processor can indicate any rows in the entire matrix to be zeroed (i.e. each process does NOT have to
5881: list only rows local to itself).
5883: The grid coordinates are across the entire grid, not just the local portion
5885: In Fortran idxm and idxn should be declared as
5886: $ MatStencil idxm(4,m)
5887: and the values inserted using
5888: $ idxm(MatStencil_i,1) = i
5889: $ idxm(MatStencil_j,1) = j
5890: $ idxm(MatStencil_k,1) = k
5891: $ idxm(MatStencil_c,1) = c
5892: etc
5894: For periodic boundary conditions use negative indices for values to the left (below 0; that are to be
5895: obtained by wrapping values from right edge). For values to the right of the last entry using that index plus one
5896: etc to obtain values that obtained by wrapping the values from the left edge. This does not work for anything but the
5897: DM_BOUNDARY_PERIODIC boundary type.
5899: 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
5900: a single value per point) you can skip filling those indices.
5902: Level: intermediate
5904: .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsl(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
5905: MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
5906: @*/
5907: PetscErrorCode MatZeroRowsStencil(Mat mat,PetscInt numRows,const MatStencil rows[],PetscScalar diag,Vec x,Vec b)
5908: {
5909: PetscInt dim = mat->stencil.dim;
5910: PetscInt sdim = dim - (1 - (PetscInt) mat->stencil.noc);
5911: PetscInt *dims = mat->stencil.dims+1;
5912: PetscInt *starts = mat->stencil.starts;
5913: PetscInt *dxm = (PetscInt*) rows;
5914: PetscInt *jdxm, i, j, tmp, numNewRows = 0;
5922: PetscMalloc1(numRows, &jdxm);
5923: for (i = 0; i < numRows; ++i) {
5924: /* Skip unused dimensions (they are ordered k, j, i, c) */
5925: for (j = 0; j < 3-sdim; ++j) dxm++;
5926: /* Local index in X dir */
5927: tmp = *dxm++ - starts[0];
5928: /* Loop over remaining dimensions */
5929: for (j = 0; j < dim-1; ++j) {
5930: /* If nonlocal, set index to be negative */
5931: if ((*dxm++ - starts[j+1]) < 0 || tmp < 0) tmp = PETSC_MIN_INT;
5932: /* Update local index */
5933: else tmp = tmp*dims[j] + *(dxm-1) - starts[j+1];
5934: }
5935: /* Skip component slot if necessary */
5936: if (mat->stencil.noc) dxm++;
5937: /* Local row number */
5938: if (tmp >= 0) {
5939: jdxm[numNewRows++] = tmp;
5940: }
5941: }
5942: MatZeroRowsLocal(mat,numNewRows,jdxm,diag,x,b);
5943: PetscFree(jdxm);
5944: return(0);
5945: }
5947: /*@
5948: MatZeroRowsColumnsStencil - Zeros all row and column entries (except possibly the main diagonal)
5949: of a set of rows and columns of a matrix.
5951: Collective on Mat
5953: Input Parameters:
5954: + mat - the matrix
5955: . numRows - the number of rows/columns to remove
5956: . rows - the grid coordinates (and component number when dof > 1) for matrix rows
5957: . diag - value put in all diagonals of eliminated rows (0.0 will even eliminate diagonal entry)
5958: . x - optional vector of solutions for zeroed rows (other entries in vector are not used)
5959: - b - optional vector of right hand side, that will be adjusted by provided solution
5961: Notes:
5962: For the AIJ and BAIJ matrix formats this removes the old nonzero structure,
5963: but does not release memory. For the dense and block diagonal
5964: formats this does not alter the nonzero structure.
5966: If the option MatSetOption(mat,MAT_KEEP_NONZERO_PATTERN,PETSC_TRUE) the nonzero structure
5967: of the matrix is not changed (even for AIJ and BAIJ matrices) the values are
5968: merely zeroed.
5970: The user can set a value in the diagonal entry (or for the AIJ and
5971: row formats can optionally remove the main diagonal entry from the
5972: nonzero structure as well, by passing 0.0 as the final argument).
5974: For the parallel case, all processes that share the matrix (i.e.,
5975: those in the communicator used for matrix creation) MUST call this
5976: routine, regardless of whether any rows being zeroed are owned by
5977: them.
5979: Each processor can indicate any rows in the entire matrix to be zeroed (i.e. each process does NOT have to
5980: list only rows local to itself, but the row/column numbers are given in local numbering).
5982: The grid coordinates are across the entire grid, not just the local portion
5984: In Fortran idxm and idxn should be declared as
5985: $ MatStencil idxm(4,m)
5986: and the values inserted using
5987: $ idxm(MatStencil_i,1) = i
5988: $ idxm(MatStencil_j,1) = j
5989: $ idxm(MatStencil_k,1) = k
5990: $ idxm(MatStencil_c,1) = c
5991: etc
5993: For periodic boundary conditions use negative indices for values to the left (below 0; that are to be
5994: obtained by wrapping values from right edge). For values to the right of the last entry using that index plus one
5995: etc to obtain values that obtained by wrapping the values from the left edge. This does not work for anything but the
5996: DM_BOUNDARY_PERIODIC boundary type.
5998: 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
5999: a single value per point) you can skip filling those indices.
6001: Level: intermediate
6003: .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
6004: MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRows()
6005: @*/
6006: PetscErrorCode MatZeroRowsColumnsStencil(Mat mat,PetscInt numRows,const MatStencil rows[],PetscScalar diag,Vec x,Vec b)
6007: {
6008: PetscInt dim = mat->stencil.dim;
6009: PetscInt sdim = dim - (1 - (PetscInt) mat->stencil.noc);
6010: PetscInt *dims = mat->stencil.dims+1;
6011: PetscInt *starts = mat->stencil.starts;
6012: PetscInt *dxm = (PetscInt*) rows;
6013: PetscInt *jdxm, i, j, tmp, numNewRows = 0;
6021: PetscMalloc1(numRows, &jdxm);
6022: for (i = 0; i < numRows; ++i) {
6023: /* Skip unused dimensions (they are ordered k, j, i, c) */
6024: for (j = 0; j < 3-sdim; ++j) dxm++;
6025: /* Local index in X dir */
6026: tmp = *dxm++ - starts[0];
6027: /* Loop over remaining dimensions */
6028: for (j = 0; j < dim-1; ++j) {
6029: /* If nonlocal, set index to be negative */
6030: if ((*dxm++ - starts[j+1]) < 0 || tmp < 0) tmp = PETSC_MIN_INT;
6031: /* Update local index */
6032: else tmp = tmp*dims[j] + *(dxm-1) - starts[j+1];
6033: }
6034: /* Skip component slot if necessary */
6035: if (mat->stencil.noc) dxm++;
6036: /* Local row number */
6037: if (tmp >= 0) {
6038: jdxm[numNewRows++] = tmp;
6039: }
6040: }
6041: MatZeroRowsColumnsLocal(mat,numNewRows,jdxm,diag,x,b);
6042: PetscFree(jdxm);
6043: return(0);
6044: }
6046: /*@C
6047: MatZeroRowsLocal - Zeros all entries (except possibly the main diagonal)
6048: of a set of rows of a matrix; using local numbering of rows.
6050: Collective on Mat
6052: Input Parameters:
6053: + mat - the matrix
6054: . numRows - the number of rows to remove
6055: . rows - the global row indices
6056: . diag - value put in all diagonals of eliminated rows
6057: . x - optional vector of solutions for zeroed rows (other entries in vector are not used)
6058: - b - optional vector of right hand side, that will be adjusted by provided solution
6060: Notes:
6061: Before calling MatZeroRowsLocal(), the user must first set the
6062: local-to-global mapping by calling MatSetLocalToGlobalMapping().
6064: For the AIJ matrix formats this removes the old nonzero structure,
6065: but does not release memory. For the dense and block diagonal
6066: formats this does not alter the nonzero structure.
6068: If the option MatSetOption(mat,MAT_KEEP_NONZERO_PATTERN,PETSC_TRUE) the nonzero structure
6069: of the matrix is not changed (even for AIJ and BAIJ matrices) the values are
6070: merely zeroed.
6072: The user can set a value in the diagonal entry (or for the AIJ and
6073: row formats can optionally remove the main diagonal entry from the
6074: nonzero structure as well, by passing 0.0 as the final argument).
6076: You can call MatSetOption(mat,MAT_NO_OFF_PROC_ZERO_ROWS,PETSC_TRUE) if each process indicates only rows it
6077: owns that are to be zeroed. This saves a global synchronization in the implementation.
6079: Level: intermediate
6081: .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRows(), MatSetOption(),
6082: MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
6083: @*/
6084: PetscErrorCode MatZeroRowsLocal(Mat mat,PetscInt numRows,const PetscInt rows[],PetscScalar diag,Vec x,Vec b)
6085: {
6092: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6093: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6094: MatCheckPreallocated(mat,1);
6096: if (mat->ops->zerorowslocal) {
6097: (*mat->ops->zerorowslocal)(mat,numRows,rows,diag,x,b);
6098: } else {
6099: IS is, newis;
6100: const PetscInt *newRows;
6102: if (!mat->rmap->mapping) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Need to provide local to global mapping to matrix first");
6103: ISCreateGeneral(PETSC_COMM_SELF,numRows,rows,PETSC_COPY_VALUES,&is);
6104: ISLocalToGlobalMappingApplyIS(mat->rmap->mapping,is,&newis);
6105: ISGetIndices(newis,&newRows);
6106: (*mat->ops->zerorows)(mat,numRows,newRows,diag,x,b);
6107: ISRestoreIndices(newis,&newRows);
6108: ISDestroy(&newis);
6109: ISDestroy(&is);
6110: }
6111: PetscObjectStateIncrease((PetscObject)mat);
6112: return(0);
6113: }
6115: /*@
6116: MatZeroRowsLocalIS - Zeros all entries (except possibly the main diagonal)
6117: of a set of rows of a matrix; using local numbering of rows.
6119: Collective on Mat
6121: Input Parameters:
6122: + mat - the matrix
6123: . is - index set of rows to remove
6124: . diag - value put in all diagonals of eliminated rows
6125: . x - optional vector of solutions for zeroed rows (other entries in vector are not used)
6126: - b - optional vector of right hand side, that will be adjusted by provided solution
6128: Notes:
6129: Before calling MatZeroRowsLocalIS(), the user must first set the
6130: local-to-global mapping by calling MatSetLocalToGlobalMapping().
6132: For the AIJ matrix formats this removes the old nonzero structure,
6133: but does not release memory. For the dense and block diagonal
6134: formats this does not alter the nonzero structure.
6136: If the option MatSetOption(mat,MAT_KEEP_NONZERO_PATTERN,PETSC_TRUE) the nonzero structure
6137: of the matrix is not changed (even for AIJ and BAIJ matrices) the values are
6138: merely zeroed.
6140: The user can set a value in the diagonal entry (or for the AIJ and
6141: row formats can optionally remove the main diagonal entry from the
6142: nonzero structure as well, by passing 0.0 as the final argument).
6144: You can call MatSetOption(mat,MAT_NO_OFF_PROC_ZERO_ROWS,PETSC_TRUE) if each process indicates only rows it
6145: owns that are to be zeroed. This saves a global synchronization in the implementation.
6147: Level: intermediate
6149: .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRows(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
6150: MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
6151: @*/
6152: PetscErrorCode MatZeroRowsLocalIS(Mat mat,IS is,PetscScalar diag,Vec x,Vec b)
6153: {
6155: PetscInt numRows;
6156: const PetscInt *rows;
6162: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6163: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6164: MatCheckPreallocated(mat,1);
6166: ISGetLocalSize(is,&numRows);
6167: ISGetIndices(is,&rows);
6168: MatZeroRowsLocal(mat,numRows,rows,diag,x,b);
6169: ISRestoreIndices(is,&rows);
6170: return(0);
6171: }
6173: /*@
6174: MatZeroRowsColumnsLocal - Zeros all entries (except possibly the main diagonal)
6175: of a set of rows and columns of a matrix; using local numbering of rows.
6177: Collective on Mat
6179: Input Parameters:
6180: + mat - the matrix
6181: . numRows - the number of rows to remove
6182: . rows - the global row indices
6183: . diag - value put in all diagonals of eliminated rows
6184: . x - optional vector of solutions for zeroed rows (other entries in vector are not used)
6185: - b - optional vector of right hand side, that will be adjusted by provided solution
6187: Notes:
6188: Before calling MatZeroRowsColumnsLocal(), the user must first set the
6189: local-to-global mapping by calling MatSetLocalToGlobalMapping().
6191: The user can set a value in the diagonal entry (or for the AIJ and
6192: row formats can optionally remove the main diagonal entry from the
6193: nonzero structure as well, by passing 0.0 as the final argument).
6195: Level: intermediate
6197: .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
6198: MatZeroRows(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
6199: @*/
6200: PetscErrorCode MatZeroRowsColumnsLocal(Mat mat,PetscInt numRows,const PetscInt rows[],PetscScalar diag,Vec x,Vec b)
6201: {
6203: IS is, newis;
6204: const PetscInt *newRows;
6210: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6211: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6212: MatCheckPreallocated(mat,1);
6214: if (!mat->cmap->mapping) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Need to provide local to global mapping to matrix first");
6215: ISCreateGeneral(PETSC_COMM_SELF,numRows,rows,PETSC_COPY_VALUES,&is);
6216: ISLocalToGlobalMappingApplyIS(mat->cmap->mapping,is,&newis);
6217: ISGetIndices(newis,&newRows);
6218: (*mat->ops->zerorowscolumns)(mat,numRows,newRows,diag,x,b);
6219: ISRestoreIndices(newis,&newRows);
6220: ISDestroy(&newis);
6221: ISDestroy(&is);
6222: PetscObjectStateIncrease((PetscObject)mat);
6223: return(0);
6224: }
6226: /*@
6227: MatZeroRowsColumnsLocalIS - Zeros all entries (except possibly the main diagonal)
6228: of a set of rows and columns of a matrix; using local numbering of rows.
6230: Collective on Mat
6232: Input Parameters:
6233: + mat - the matrix
6234: . is - index set of rows to remove
6235: . diag - value put in all diagonals of eliminated rows
6236: . x - optional vector of solutions for zeroed rows (other entries in vector are not used)
6237: - b - optional vector of right hand side, that will be adjusted by provided solution
6239: Notes:
6240: Before calling MatZeroRowsColumnsLocalIS(), the user must first set the
6241: local-to-global mapping by calling MatSetLocalToGlobalMapping().
6243: The user can set a value in the diagonal entry (or for the AIJ and
6244: row formats can optionally remove the main diagonal entry from the
6245: nonzero structure as well, by passing 0.0 as the final argument).
6247: Level: intermediate
6249: .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
6250: MatZeroRowsColumnsLocal(), MatZeroRows(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
6251: @*/
6252: PetscErrorCode MatZeroRowsColumnsLocalIS(Mat mat,IS is,PetscScalar diag,Vec x,Vec b)
6253: {
6255: PetscInt numRows;
6256: const PetscInt *rows;
6262: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6263: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6264: MatCheckPreallocated(mat,1);
6266: ISGetLocalSize(is,&numRows);
6267: ISGetIndices(is,&rows);
6268: MatZeroRowsColumnsLocal(mat,numRows,rows,diag,x,b);
6269: ISRestoreIndices(is,&rows);
6270: return(0);
6271: }
6273: /*@C
6274: MatGetSize - Returns the numbers of rows and columns in a matrix.
6276: Not Collective
6278: Input Parameter:
6279: . mat - the matrix
6281: Output Parameters:
6282: + m - the number of global rows
6283: - n - the number of global columns
6285: Note: both output parameters can be NULL on input.
6287: Level: beginner
6289: .seealso: MatGetLocalSize()
6290: @*/
6291: PetscErrorCode MatGetSize(Mat mat,PetscInt *m,PetscInt *n)
6292: {
6295: if (m) *m = mat->rmap->N;
6296: if (n) *n = mat->cmap->N;
6297: return(0);
6298: }
6300: /*@C
6301: MatGetLocalSize - Returns the number of rows and columns in a matrix
6302: stored locally. This information may be implementation dependent, so
6303: use with care.
6305: Not Collective
6307: Input Parameters:
6308: . mat - the matrix
6310: Output Parameters:
6311: + m - the number of local rows
6312: - n - the number of local columns
6314: Note: both output parameters can be NULL on input.
6316: Level: beginner
6318: .seealso: MatGetSize()
6319: @*/
6320: PetscErrorCode MatGetLocalSize(Mat mat,PetscInt *m,PetscInt *n)
6321: {
6326: if (m) *m = mat->rmap->n;
6327: if (n) *n = mat->cmap->n;
6328: return(0);
6329: }
6331: /*@C
6332: MatGetOwnershipRangeColumn - Returns the range of matrix columns associated with rows of a vector one multiplies by that owned by
6333: this processor. (The columns of the "diagonal block")
6335: Not Collective, unless matrix has not been allocated, then collective on Mat
6337: Input Parameters:
6338: . mat - the matrix
6340: Output Parameters:
6341: + m - the global index of the first local column
6342: - n - one more than the global index of the last local column
6344: Notes:
6345: both output parameters can be NULL on input.
6347: Level: developer
6349: .seealso: MatGetOwnershipRange(), MatGetOwnershipRanges(), MatGetOwnershipRangesColumn()
6351: @*/
6352: PetscErrorCode MatGetOwnershipRangeColumn(Mat mat,PetscInt *m,PetscInt *n)
6353: {
6359: MatCheckPreallocated(mat,1);
6360: if (m) *m = mat->cmap->rstart;
6361: if (n) *n = mat->cmap->rend;
6362: return(0);
6363: }
6365: /*@C
6366: MatGetOwnershipRange - Returns the range of matrix rows owned by
6367: this processor, assuming that the matrix is laid out with the first
6368: n1 rows on the first processor, the next n2 rows on the second, etc.
6369: For certain parallel layouts this range may not be well defined.
6371: Not Collective
6373: Input Parameters:
6374: . mat - the matrix
6376: Output Parameters:
6377: + m - the global index of the first local row
6378: - n - one more than the global index of the last local row
6380: Note: Both output parameters can be NULL on input.
6381: $ This function requires that the matrix be preallocated. If you have not preallocated, consider using
6382: $ PetscSplitOwnership(MPI_Comm comm, PetscInt *n, PetscInt *N)
6383: $ and then MPI_Scan() to calculate prefix sums of the local sizes.
6385: Level: beginner
6387: .seealso: MatGetOwnershipRanges(), MatGetOwnershipRangeColumn(), MatGetOwnershipRangesColumn(), PetscSplitOwnership(), PetscSplitOwnershipBlock()
6389: @*/
6390: PetscErrorCode MatGetOwnershipRange(Mat mat,PetscInt *m,PetscInt *n)
6391: {
6397: MatCheckPreallocated(mat,1);
6398: if (m) *m = mat->rmap->rstart;
6399: if (n) *n = mat->rmap->rend;
6400: return(0);
6401: }
6403: /*@C
6404: MatGetOwnershipRanges - Returns the range of matrix rows owned by
6405: each process
6407: Not Collective, unless matrix has not been allocated, then collective on Mat
6409: Input Parameters:
6410: . mat - the matrix
6412: Output Parameters:
6413: . ranges - start of each processors portion plus one more than the total length at the end
6415: Level: beginner
6417: .seealso: MatGetOwnershipRange(), MatGetOwnershipRangeColumn(), MatGetOwnershipRangesColumn()
6419: @*/
6420: PetscErrorCode MatGetOwnershipRanges(Mat mat,const PetscInt **ranges)
6421: {
6427: MatCheckPreallocated(mat,1);
6428: PetscLayoutGetRanges(mat->rmap,ranges);
6429: return(0);
6430: }
6432: /*@C
6433: MatGetOwnershipRangesColumn - Returns the range of matrix columns associated with rows of a vector one multiplies by that owned by
6434: this processor. (The columns of the "diagonal blocks" for each process)
6436: Not Collective, unless matrix has not been allocated, then collective on Mat
6438: Input Parameters:
6439: . mat - the matrix
6441: Output Parameters:
6442: . ranges - start of each processors portion plus one more then the total length at the end
6444: Level: beginner
6446: .seealso: MatGetOwnershipRange(), MatGetOwnershipRangeColumn(), MatGetOwnershipRanges()
6448: @*/
6449: PetscErrorCode MatGetOwnershipRangesColumn(Mat mat,const PetscInt **ranges)
6450: {
6456: MatCheckPreallocated(mat,1);
6457: PetscLayoutGetRanges(mat->cmap,ranges);
6458: return(0);
6459: }
6461: /*@C
6462: MatGetOwnershipIS - Get row and column ownership as index sets
6464: Not Collective
6466: Input Arguments:
6467: . A - matrix of type Elemental
6469: Output Arguments:
6470: + rows - rows in which this process owns elements
6471: - cols - columns in which this process owns elements
6473: Level: intermediate
6475: .seealso: MatGetOwnershipRange(), MatGetOwnershipRangeColumn(), MatSetValues(), MATELEMENTAL
6476: @*/
6477: PetscErrorCode MatGetOwnershipIS(Mat A,IS *rows,IS *cols)
6478: {
6479: PetscErrorCode ierr,(*f)(Mat,IS*,IS*);
6482: MatCheckPreallocated(A,1);
6483: PetscObjectQueryFunction((PetscObject)A,"MatGetOwnershipIS_C",&f);
6484: if (f) {
6485: (*f)(A,rows,cols);
6486: } else { /* Create a standard row-based partition, each process is responsible for ALL columns in their row block */
6487: if (rows) {ISCreateStride(PETSC_COMM_SELF,A->rmap->n,A->rmap->rstart,1,rows);}
6488: if (cols) {ISCreateStride(PETSC_COMM_SELF,A->cmap->N,0,1,cols);}
6489: }
6490: return(0);
6491: }
6493: /*@C
6494: MatILUFactorSymbolic - Performs symbolic ILU factorization of a matrix.
6495: Uses levels of fill only, not drop tolerance. Use MatLUFactorNumeric()
6496: to complete the factorization.
6498: Collective on Mat
6500: Input Parameters:
6501: + mat - the matrix
6502: . row - row permutation
6503: . column - column permutation
6504: - info - structure containing
6505: $ levels - number of levels of fill.
6506: $ expected fill - as ratio of original fill.
6507: $ 1 or 0 - indicating force fill on diagonal (improves robustness for matrices
6508: missing diagonal entries)
6510: Output Parameters:
6511: . fact - new matrix that has been symbolically factored
6513: Notes:
6514: See Users-Manual: ch_mat for additional information about choosing the fill factor for better efficiency.
6516: Most users should employ the simplified KSP interface for linear solvers
6517: instead of working directly with matrix algebra routines such as this.
6518: See, e.g., KSPCreate().
6520: Level: developer
6522: .seealso: MatLUFactorSymbolic(), MatLUFactorNumeric(), MatCholeskyFactor()
6523: MatGetOrdering(), MatFactorInfo
6525: Note: this uses the definition of level of fill as in Y. Saad, 2003
6527: Developer Note: fortran interface is not autogenerated as the f90
6528: interface defintion cannot be generated correctly [due to MatFactorInfo]
6530: References:
6531: Y. Saad, Iterative methods for sparse linear systems Philadelphia: Society for Industrial and Applied Mathematics, 2003
6532: @*/
6533: PetscErrorCode MatILUFactorSymbolic(Mat fact,Mat mat,IS row,IS col,const MatFactorInfo *info)
6534: {
6544: if (info->levels < 0) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_OUTOFRANGE,"Levels of fill negative %D",(PetscInt)info->levels);
6545: if (info->fill < 1.0) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_OUTOFRANGE,"Expected fill less than 1.0 %g",(double)info->fill);
6546: if (!(fact)->ops->ilufactorsymbolic) {
6547: MatSolverType spackage;
6548: MatFactorGetSolverType(fact,&spackage);
6549: SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Matrix type %s symbolic ILU using solver package %s",((PetscObject)mat)->type_name,spackage);
6550: }
6551: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6552: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6553: MatCheckPreallocated(mat,2);
6555: PetscLogEventBegin(MAT_ILUFactorSymbolic,mat,row,col,0);
6556: (fact->ops->ilufactorsymbolic)(fact,mat,row,col,info);
6557: PetscLogEventEnd(MAT_ILUFactorSymbolic,mat,row,col,0);
6558: return(0);
6559: }
6561: /*@C
6562: MatICCFactorSymbolic - Performs symbolic incomplete
6563: Cholesky factorization for a symmetric matrix. Use
6564: MatCholeskyFactorNumeric() to complete the factorization.
6566: Collective on Mat
6568: Input Parameters:
6569: + mat - the matrix
6570: . perm - row and column permutation
6571: - info - structure containing
6572: $ levels - number of levels of fill.
6573: $ expected fill - as ratio of original fill.
6575: Output Parameter:
6576: . fact - the factored matrix
6578: Notes:
6579: Most users should employ the KSP interface for linear solvers
6580: instead of working directly with matrix algebra routines such as this.
6581: See, e.g., KSPCreate().
6583: Level: developer
6585: .seealso: MatCholeskyFactorNumeric(), MatCholeskyFactor(), MatFactorInfo
6587: Note: this uses the definition of level of fill as in Y. Saad, 2003
6589: Developer Note: fortran interface is not autogenerated as the f90
6590: interface defintion cannot be generated correctly [due to MatFactorInfo]
6592: References:
6593: Y. Saad, Iterative methods for sparse linear systems Philadelphia: Society for Industrial and Applied Mathematics, 2003
6594: @*/
6595: PetscErrorCode MatICCFactorSymbolic(Mat fact,Mat mat,IS perm,const MatFactorInfo *info)
6596: {
6605: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6606: if (info->levels < 0) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_OUTOFRANGE,"Levels negative %D",(PetscInt) info->levels);
6607: if (info->fill < 1.0) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_OUTOFRANGE,"Expected fill less than 1.0 %g",(double)info->fill);
6608: if (!(fact)->ops->iccfactorsymbolic) {
6609: MatSolverType spackage;
6610: MatFactorGetSolverType(fact,&spackage);
6611: SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Matrix type %s symbolic ICC using solver package %s",((PetscObject)mat)->type_name,spackage);
6612: }
6613: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6614: MatCheckPreallocated(mat,2);
6616: PetscLogEventBegin(MAT_ICCFactorSymbolic,mat,perm,0,0);
6617: (fact->ops->iccfactorsymbolic)(fact,mat,perm,info);
6618: PetscLogEventEnd(MAT_ICCFactorSymbolic,mat,perm,0,0);
6619: return(0);
6620: }
6622: /*@C
6623: MatCreateSubMatrices - Extracts several submatrices from a matrix. If submat
6624: points to an array of valid matrices, they may be reused to store the new
6625: submatrices.
6627: Collective on Mat
6629: Input Parameters:
6630: + mat - the matrix
6631: . n - the number of submatrixes to be extracted (on this processor, may be zero)
6632: . irow, icol - index sets of rows and columns to extract
6633: - scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
6635: Output Parameter:
6636: . submat - the array of submatrices
6638: Notes:
6639: MatCreateSubMatrices() can extract ONLY sequential submatrices
6640: (from both sequential and parallel matrices). Use MatCreateSubMatrix()
6641: to extract a parallel submatrix.
6643: Some matrix types place restrictions on the row and column
6644: indices, such as that they be sorted or that they be equal to each other.
6646: The index sets may not have duplicate entries.
6648: When extracting submatrices from a parallel matrix, each processor can
6649: form a different submatrix by setting the rows and columns of its
6650: individual index sets according to the local submatrix desired.
6652: When finished using the submatrices, the user should destroy
6653: them with MatDestroySubMatrices().
6655: MAT_REUSE_MATRIX can only be used when the nonzero structure of the
6656: original matrix has not changed from that last call to MatCreateSubMatrices().
6658: This routine creates the matrices in submat; you should NOT create them before
6659: calling it. It also allocates the array of matrix pointers submat.
6661: For BAIJ matrices the index sets must respect the block structure, that is if they
6662: request one row/column in a block, they must request all rows/columns that are in
6663: that block. For example, if the block size is 2 you cannot request just row 0 and
6664: column 0.
6666: Fortran Note:
6667: The Fortran interface is slightly different from that given below; it
6668: requires one to pass in as submat a Mat (integer) array of size at least n+1.
6670: Level: advanced
6673: .seealso: MatDestroySubMatrices(), MatCreateSubMatrix(), MatGetRow(), MatGetDiagonal(), MatReuse
6674: @*/
6675: PetscErrorCode MatCreateSubMatrices(Mat mat,PetscInt n,const IS irow[],const IS icol[],MatReuse scall,Mat *submat[])
6676: {
6678: PetscInt i;
6679: PetscBool eq;
6684: if (n) {
6689: }
6691: if (n && scall == MAT_REUSE_MATRIX) {
6694: }
6695: if (!mat->ops->createsubmatrices) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
6696: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6697: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6698: MatCheckPreallocated(mat,1);
6700: PetscLogEventBegin(MAT_CreateSubMats,mat,0,0,0);
6701: (*mat->ops->createsubmatrices)(mat,n,irow,icol,scall,submat);
6702: PetscLogEventEnd(MAT_CreateSubMats,mat,0,0,0);
6703: for (i=0; i<n; i++) {
6704: (*submat)[i]->factortype = MAT_FACTOR_NONE; /* in case in place factorization was previously done on submatrix */
6705: ISEqualUnsorted(irow[i],icol[i],&eq);
6706: if (eq) {
6707: MatPropagateSymmetryOptions(mat,(*submat)[i]);
6708: }
6709: }
6710: return(0);
6711: }
6713: /*@C
6714: MatCreateSubMatricesMPI - Extracts MPI submatrices across a sub communicator of mat (by pairs of IS that may live on subcomms).
6716: Collective on Mat
6718: Input Parameters:
6719: + mat - the matrix
6720: . n - the number of submatrixes to be extracted
6721: . irow, icol - index sets of rows and columns to extract
6722: - scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
6724: Output Parameter:
6725: . submat - the array of submatrices
6727: Level: advanced
6730: .seealso: MatCreateSubMatrices(), MatCreateSubMatrix(), MatGetRow(), MatGetDiagonal(), MatReuse
6731: @*/
6732: PetscErrorCode MatCreateSubMatricesMPI(Mat mat,PetscInt n,const IS irow[],const IS icol[],MatReuse scall,Mat *submat[])
6733: {
6735: PetscInt i;
6736: PetscBool eq;
6741: if (n) {
6746: }
6748: if (n && scall == MAT_REUSE_MATRIX) {
6751: }
6752: if (!mat->ops->createsubmatricesmpi) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
6753: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6754: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6755: MatCheckPreallocated(mat,1);
6757: PetscLogEventBegin(MAT_CreateSubMats,mat,0,0,0);
6758: (*mat->ops->createsubmatricesmpi)(mat,n,irow,icol,scall,submat);
6759: PetscLogEventEnd(MAT_CreateSubMats,mat,0,0,0);
6760: for (i=0; i<n; i++) {
6761: ISEqualUnsorted(irow[i],icol[i],&eq);
6762: if (eq) {
6763: MatPropagateSymmetryOptions(mat,(*submat)[i]);
6764: }
6765: }
6766: return(0);
6767: }
6769: /*@C
6770: MatDestroyMatrices - Destroys an array of matrices.
6772: Collective on Mat
6774: Input Parameters:
6775: + n - the number of local matrices
6776: - mat - the matrices (note that this is a pointer to the array of matrices)
6778: Level: advanced
6780: Notes:
6781: Frees not only the matrices, but also the array that contains the matrices
6782: In Fortran will not free the array.
6784: .seealso: MatCreateSubMatrices() MatDestroySubMatrices()
6785: @*/
6786: PetscErrorCode MatDestroyMatrices(PetscInt n,Mat *mat[])
6787: {
6789: PetscInt i;
6792: if (!*mat) return(0);
6793: if (n < 0) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Trying to destroy negative number of matrices %D",n);
6796: for (i=0; i<n; i++) {
6797: MatDestroy(&(*mat)[i]);
6798: }
6800: /* memory is allocated even if n = 0 */
6801: PetscFree(*mat);
6802: return(0);
6803: }
6805: /*@C
6806: MatDestroySubMatrices - Destroys a set of matrices obtained with MatCreateSubMatrices().
6808: Collective on Mat
6810: Input Parameters:
6811: + n - the number of local matrices
6812: - mat - the matrices (note that this is a pointer to the array of matrices, just to match the calling
6813: sequence of MatCreateSubMatrices())
6815: Level: advanced
6817: Notes:
6818: Frees not only the matrices, but also the array that contains the matrices
6819: In Fortran will not free the array.
6821: .seealso: MatCreateSubMatrices()
6822: @*/
6823: PetscErrorCode MatDestroySubMatrices(PetscInt n,Mat *mat[])
6824: {
6826: Mat mat0;
6829: if (!*mat) return(0);
6830: /* mat[] is an array of length n+1, see MatCreateSubMatrices_xxx() */
6831: if (n < 0) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Trying to destroy negative number of matrices %D",n);
6834: mat0 = (*mat)[0];
6835: if (mat0 && mat0->ops->destroysubmatrices) {
6836: (mat0->ops->destroysubmatrices)(n,mat);
6837: } else {
6838: MatDestroyMatrices(n,mat);
6839: }
6840: return(0);
6841: }
6843: /*@C
6844: MatGetSeqNonzeroStructure - Extracts the sequential nonzero structure from a matrix.
6846: Collective on Mat
6848: Input Parameters:
6849: . mat - the matrix
6851: Output Parameter:
6852: . matstruct - the sequential matrix with the nonzero structure of mat
6854: Level: intermediate
6856: .seealso: MatDestroySeqNonzeroStructure(), MatCreateSubMatrices(), MatDestroyMatrices()
6857: @*/
6858: PetscErrorCode MatGetSeqNonzeroStructure(Mat mat,Mat *matstruct)
6859: {
6867: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6868: MatCheckPreallocated(mat,1);
6870: if (!mat->ops->getseqnonzerostructure) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Not for matrix type %s\n",((PetscObject)mat)->type_name);
6871: PetscLogEventBegin(MAT_GetSeqNonzeroStructure,mat,0,0,0);
6872: (*mat->ops->getseqnonzerostructure)(mat,matstruct);
6873: PetscLogEventEnd(MAT_GetSeqNonzeroStructure,mat,0,0,0);
6874: return(0);
6875: }
6877: /*@C
6878: MatDestroySeqNonzeroStructure - Destroys matrix obtained with MatGetSeqNonzeroStructure().
6880: Collective on Mat
6882: Input Parameters:
6883: . mat - the matrix (note that this is a pointer to the array of matrices, just to match the calling
6884: sequence of MatGetSequentialNonzeroStructure())
6886: Level: advanced
6888: Notes:
6889: Frees not only the matrices, but also the array that contains the matrices
6891: .seealso: MatGetSeqNonzeroStructure()
6892: @*/
6893: PetscErrorCode MatDestroySeqNonzeroStructure(Mat *mat)
6894: {
6899: MatDestroy(mat);
6900: return(0);
6901: }
6903: /*@
6904: MatIncreaseOverlap - Given a set of submatrices indicated by index sets,
6905: replaces the index sets by larger ones that represent submatrices with
6906: additional overlap.
6908: Collective on Mat
6910: Input Parameters:
6911: + mat - the matrix
6912: . n - the number of index sets
6913: . is - the array of index sets (these index sets will changed during the call)
6914: - ov - the additional overlap requested
6916: Options Database:
6917: . -mat_increase_overlap_scalable - use a scalable algorithm to compute the overlap (supported by MPIAIJ matrix)
6919: Level: developer
6922: .seealso: MatCreateSubMatrices()
6923: @*/
6924: PetscErrorCode MatIncreaseOverlap(Mat mat,PetscInt n,IS is[],PetscInt ov)
6925: {
6931: if (n < 0) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Must have one or more domains, you have %D",n);
6932: if (n) {
6935: }
6936: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6937: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6938: MatCheckPreallocated(mat,1);
6940: if (!ov) return(0);
6941: if (!mat->ops->increaseoverlap) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
6942: PetscLogEventBegin(MAT_IncreaseOverlap,mat,0,0,0);
6943: (*mat->ops->increaseoverlap)(mat,n,is,ov);
6944: PetscLogEventEnd(MAT_IncreaseOverlap,mat,0,0,0);
6945: return(0);
6946: }
6949: PetscErrorCode MatIncreaseOverlapSplit_Single(Mat,IS*,PetscInt);
6951: /*@
6952: MatIncreaseOverlapSplit - Given a set of submatrices indicated by index sets across
6953: a sub communicator, replaces the index sets by larger ones that represent submatrices with
6954: additional overlap.
6956: Collective on Mat
6958: Input Parameters:
6959: + mat - the matrix
6960: . n - the number of index sets
6961: . is - the array of index sets (these index sets will changed during the call)
6962: - ov - the additional overlap requested
6964: Options Database:
6965: . -mat_increase_overlap_scalable - use a scalable algorithm to compute the overlap (supported by MPIAIJ matrix)
6967: Level: developer
6970: .seealso: MatCreateSubMatrices()
6971: @*/
6972: PetscErrorCode MatIncreaseOverlapSplit(Mat mat,PetscInt n,IS is[],PetscInt ov)
6973: {
6974: PetscInt i;
6980: if (n < 0) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Must have one or more domains, you have %D",n);
6981: if (n) {
6984: }
6985: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6986: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6987: MatCheckPreallocated(mat,1);
6988: if (!ov) return(0);
6989: PetscLogEventBegin(MAT_IncreaseOverlap,mat,0,0,0);
6990: for(i=0; i<n; i++){
6991: MatIncreaseOverlapSplit_Single(mat,&is[i],ov);
6992: }
6993: PetscLogEventEnd(MAT_IncreaseOverlap,mat,0,0,0);
6994: return(0);
6995: }
7000: /*@
7001: MatGetBlockSize - Returns the matrix block size.
7003: Not Collective
7005: Input Parameter:
7006: . mat - the matrix
7008: Output Parameter:
7009: . bs - block size
7011: Notes:
7012: Block row formats are MATSEQBAIJ, MATMPIBAIJ, MATSEQSBAIJ, MATMPISBAIJ. These formats ALWAYS have square block storage in the matrix.
7014: If the block size has not been set yet this routine returns 1.
7016: Level: intermediate
7018: .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSizes()
7019: @*/
7020: PetscErrorCode MatGetBlockSize(Mat mat,PetscInt *bs)
7021: {
7025: *bs = PetscAbs(mat->rmap->bs);
7026: return(0);
7027: }
7029: /*@
7030: MatGetBlockSizes - Returns the matrix block row and column sizes.
7032: Not Collective
7034: Input Parameter:
7035: . mat - the matrix
7037: Output Parameter:
7038: + rbs - row block size
7039: - cbs - column block size
7041: Notes:
7042: Block row formats are MATSEQBAIJ, MATMPIBAIJ, MATSEQSBAIJ, MATMPISBAIJ. These formats ALWAYS have square block storage in the matrix.
7043: If you pass a different block size for the columns than the rows, the row block size determines the square block storage.
7045: If a block size has not been set yet this routine returns 1.
7047: Level: intermediate
7049: .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSize(), MatSetBlockSize(), MatSetBlockSizes()
7050: @*/
7051: PetscErrorCode MatGetBlockSizes(Mat mat,PetscInt *rbs, PetscInt *cbs)
7052: {
7057: if (rbs) *rbs = PetscAbs(mat->rmap->bs);
7058: if (cbs) *cbs = PetscAbs(mat->cmap->bs);
7059: return(0);
7060: }
7062: /*@
7063: MatSetBlockSize - Sets the matrix block size.
7065: Logically Collective on Mat
7067: Input Parameters:
7068: + mat - the matrix
7069: - bs - block size
7071: Notes:
7072: Block row formats are MATSEQBAIJ, MATMPIBAIJ, MATSEQSBAIJ, MATMPISBAIJ. These formats ALWAYS have square block storage in the matrix.
7073: This must be called before MatSetUp() or MatXXXSetPreallocation() (or will default to 1) and the block size cannot be changed later.
7075: For MATMPIAIJ and MATSEQAIJ matrix formats, this function can be called at a later stage, provided that the specified block size
7076: is compatible with the matrix local sizes.
7078: Level: intermediate
7080: .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSize(), MatSetBlockSizes(), MatGetBlockSizes()
7081: @*/
7082: PetscErrorCode MatSetBlockSize(Mat mat,PetscInt bs)
7083: {
7089: MatSetBlockSizes(mat,bs,bs);
7090: return(0);
7091: }
7093: /*@
7094: MatSetVariableBlockSizes - Sets a diagonal blocks of the matrix that need not be of the same size
7096: Logically Collective on Mat
7098: Input Parameters:
7099: + mat - the matrix
7100: . nblocks - the number of blocks on this process
7101: - bsizes - the block sizes
7103: Notes:
7104: Currently used by PCVPBJACOBI for SeqAIJ matrices
7106: Level: intermediate
7108: .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSize(), MatSetBlockSizes(), MatGetBlockSizes(), MatGetVariableBlockSizes()
7109: @*/
7110: PetscErrorCode MatSetVariableBlockSizes(Mat mat,PetscInt nblocks,PetscInt *bsizes)
7111: {
7113: PetscInt i,ncnt = 0, nlocal;
7117: if (nblocks < 0) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Number of local blocks must be great than or equal to zero");
7118: MatGetLocalSize(mat,&nlocal,NULL);
7119: for (i=0; i<nblocks; i++) ncnt += bsizes[i];
7120: 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);
7121: PetscFree(mat->bsizes);
7122: mat->nblocks = nblocks;
7123: PetscMalloc1(nblocks,&mat->bsizes);
7124: PetscArraycpy(mat->bsizes,bsizes,nblocks);
7125: return(0);
7126: }
7128: /*@C
7129: MatGetVariableBlockSizes - Gets a diagonal blocks of the matrix that need not be of the same size
7131: Logically Collective on Mat
7133: Input Parameters:
7134: . mat - the matrix
7136: Output Parameters:
7137: + nblocks - the number of blocks on this process
7138: - bsizes - the block sizes
7140: Notes: Currently not supported from Fortran
7142: Level: intermediate
7144: .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSize(), MatSetBlockSizes(), MatGetBlockSizes(), MatSetVariableBlockSizes()
7145: @*/
7146: PetscErrorCode MatGetVariableBlockSizes(Mat mat,PetscInt *nblocks,const PetscInt **bsizes)
7147: {
7150: *nblocks = mat->nblocks;
7151: *bsizes = mat->bsizes;
7152: return(0);
7153: }
7155: /*@
7156: MatSetBlockSizes - Sets the matrix block row and column sizes.
7158: Logically Collective on Mat
7160: Input Parameters:
7161: + mat - the matrix
7162: . rbs - row block size
7163: - cbs - column block size
7165: Notes:
7166: Block row formats are MATSEQBAIJ, MATMPIBAIJ, MATSEQSBAIJ, MATMPISBAIJ. These formats ALWAYS have square block storage in the matrix.
7167: If you pass a different block size for the columns than the rows, the row block size determines the square block storage.
7168: This must be called before MatSetUp() or MatXXXSetPreallocation() (or will default to 1) and the block size cannot be changed later.
7170: For MATMPIAIJ and MATSEQAIJ matrix formats, this function can be called at a later stage, provided that the specified block sizes
7171: are compatible with the matrix local sizes.
7173: The row and column block size determine the blocksize of the "row" and "column" vectors returned by MatCreateVecs().
7175: Level: intermediate
7177: .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSize(), MatSetBlockSize(), MatGetBlockSizes()
7178: @*/
7179: PetscErrorCode MatSetBlockSizes(Mat mat,PetscInt rbs,PetscInt cbs)
7180: {
7187: if (mat->ops->setblocksizes) {
7188: (*mat->ops->setblocksizes)(mat,rbs,cbs);
7189: }
7190: if (mat->rmap->refcnt) {
7191: ISLocalToGlobalMapping l2g = NULL;
7192: PetscLayout nmap = NULL;
7194: PetscLayoutDuplicate(mat->rmap,&nmap);
7195: if (mat->rmap->mapping) {
7196: ISLocalToGlobalMappingDuplicate(mat->rmap->mapping,&l2g);
7197: }
7198: PetscLayoutDestroy(&mat->rmap);
7199: mat->rmap = nmap;
7200: mat->rmap->mapping = l2g;
7201: }
7202: if (mat->cmap->refcnt) {
7203: ISLocalToGlobalMapping l2g = NULL;
7204: PetscLayout nmap = NULL;
7206: PetscLayoutDuplicate(mat->cmap,&nmap);
7207: if (mat->cmap->mapping) {
7208: ISLocalToGlobalMappingDuplicate(mat->cmap->mapping,&l2g);
7209: }
7210: PetscLayoutDestroy(&mat->cmap);
7211: mat->cmap = nmap;
7212: mat->cmap->mapping = l2g;
7213: }
7214: PetscLayoutSetBlockSize(mat->rmap,rbs);
7215: PetscLayoutSetBlockSize(mat->cmap,cbs);
7216: return(0);
7217: }
7219: /*@
7220: MatSetBlockSizesFromMats - Sets the matrix block row and column sizes to match a pair of matrices
7222: Logically Collective on Mat
7224: Input Parameters:
7225: + mat - the matrix
7226: . fromRow - matrix from which to copy row block size
7227: - fromCol - matrix from which to copy column block size (can be same as fromRow)
7229: Level: developer
7231: .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSize(), MatSetBlockSizes()
7232: @*/
7233: PetscErrorCode MatSetBlockSizesFromMats(Mat mat,Mat fromRow,Mat fromCol)
7234: {
7241: if (fromRow->rmap->bs > 0) {PetscLayoutSetBlockSize(mat->rmap,fromRow->rmap->bs);}
7242: if (fromCol->cmap->bs > 0) {PetscLayoutSetBlockSize(mat->cmap,fromCol->cmap->bs);}
7243: return(0);
7244: }
7246: /*@
7247: MatResidual - Default routine to calculate the residual.
7249: Collective on Mat
7251: Input Parameters:
7252: + mat - the matrix
7253: . b - the right-hand-side
7254: - x - the approximate solution
7256: Output Parameter:
7257: . r - location to store the residual
7259: Level: developer
7261: .seealso: PCMGSetResidual()
7262: @*/
7263: PetscErrorCode MatResidual(Mat mat,Vec b,Vec x,Vec r)
7264: {
7273: MatCheckPreallocated(mat,1);
7274: PetscLogEventBegin(MAT_Residual,mat,0,0,0);
7275: if (!mat->ops->residual) {
7276: MatMult(mat,x,r);
7277: VecAYPX(r,-1.0,b);
7278: } else {
7279: (*mat->ops->residual)(mat,b,x,r);
7280: }
7281: PetscLogEventEnd(MAT_Residual,mat,0,0,0);
7282: return(0);
7283: }
7285: /*@C
7286: MatGetRowIJ - Returns the compressed row storage i and j indices for sequential matrices.
7288: Collective on Mat
7290: Input Parameters:
7291: + mat - the matrix
7292: . shift - 0 or 1 indicating we want the indices starting at 0 or 1
7293: . symmetric - PETSC_TRUE or PETSC_FALSE indicating the matrix data structure should be symmetrized
7294: - inodecompressed - PETSC_TRUE or PETSC_FALSE indicating if the nonzero structure of the
7295: inodes or the nonzero elements is wanted. For BAIJ matrices the compressed version is
7296: always used.
7298: Output Parameters:
7299: + n - number of rows in the (possibly compressed) matrix
7300: . ia - the row pointers; that is ia[0] = 0, ia[row] = ia[row-1] + number of elements in that row of the matrix
7301: . ja - the column indices
7302: - done - indicates if the routine actually worked and returned appropriate ia[] and ja[] arrays; callers
7303: are responsible for handling the case when done == PETSC_FALSE and ia and ja are not set
7305: Level: developer
7307: Notes:
7308: You CANNOT change any of the ia[] or ja[] values.
7310: Use MatRestoreRowIJ() when you are finished accessing the ia[] and ja[] values.
7312: Fortran Notes:
7313: In Fortran use
7314: $
7315: $ PetscInt ia(1), ja(1)
7316: $ PetscOffset iia, jja
7317: $ call MatGetRowIJ(mat,shift,symmetric,inodecompressed,n,ia,iia,ja,jja,done,ierr)
7318: $ ! Access the ith and jth entries via ia(iia + i) and ja(jja + j)
7320: or
7321: $
7322: $ PetscInt, pointer :: ia(:),ja(:)
7323: $ call MatGetRowIJF90(mat,shift,symmetric,inodecompressed,n,ia,ja,done,ierr)
7324: $ ! Access the ith and jth entries via ia(i) and ja(j)
7326: .seealso: MatGetColumnIJ(), MatRestoreRowIJ(), MatSeqAIJGetArray()
7327: @*/
7328: PetscErrorCode MatGetRowIJ(Mat mat,PetscInt shift,PetscBool symmetric,PetscBool inodecompressed,PetscInt *n,const PetscInt *ia[],const PetscInt *ja[],PetscBool *done)
7329: {
7339: MatCheckPreallocated(mat,1);
7340: if (!mat->ops->getrowij) *done = PETSC_FALSE;
7341: else {
7342: *done = PETSC_TRUE;
7343: PetscLogEventBegin(MAT_GetRowIJ,mat,0,0,0);
7344: (*mat->ops->getrowij)(mat,shift,symmetric,inodecompressed,n,ia,ja,done);
7345: PetscLogEventEnd(MAT_GetRowIJ,mat,0,0,0);
7346: }
7347: return(0);
7348: }
7350: /*@C
7351: MatGetColumnIJ - Returns the compressed column storage i and j indices for sequential matrices.
7353: Collective on Mat
7355: Input Parameters:
7356: + mat - the matrix
7357: . shift - 1 or zero indicating we want the indices starting at 0 or 1
7358: . symmetric - PETSC_TRUE or PETSC_FALSE indicating the matrix data structure should be
7359: symmetrized
7360: . inodecompressed - PETSC_TRUE or PETSC_FALSE indicating if the nonzero structure of the
7361: inodes or the nonzero elements is wanted. For BAIJ matrices the compressed version is
7362: always used.
7363: . n - number of columns in the (possibly compressed) matrix
7364: . ia - the column pointers; that is ia[0] = 0, ia[col] = i[col-1] + number of elements in that col of the matrix
7365: - ja - the row indices
7367: Output Parameters:
7368: . done - PETSC_TRUE or PETSC_FALSE, indicating whether the values have been returned
7370: Level: developer
7372: .seealso: MatGetRowIJ(), MatRestoreColumnIJ()
7373: @*/
7374: PetscErrorCode MatGetColumnIJ(Mat mat,PetscInt shift,PetscBool symmetric,PetscBool inodecompressed,PetscInt *n,const PetscInt *ia[],const PetscInt *ja[],PetscBool *done)
7375: {
7385: MatCheckPreallocated(mat,1);
7386: if (!mat->ops->getcolumnij) *done = PETSC_FALSE;
7387: else {
7388: *done = PETSC_TRUE;
7389: (*mat->ops->getcolumnij)(mat,shift,symmetric,inodecompressed,n,ia,ja,done);
7390: }
7391: return(0);
7392: }
7394: /*@C
7395: MatRestoreRowIJ - Call after you are completed with the ia,ja indices obtained with
7396: MatGetRowIJ().
7398: Collective on Mat
7400: Input Parameters:
7401: + mat - the matrix
7402: . shift - 1 or zero indicating we want the indices starting at 0 or 1
7403: . symmetric - PETSC_TRUE or PETSC_FALSE indicating the matrix data structure should be
7404: symmetrized
7405: . inodecompressed - PETSC_TRUE or PETSC_FALSE indicating if the nonzero structure of the
7406: inodes or the nonzero elements is wanted. For BAIJ matrices the compressed version is
7407: always used.
7408: . n - size of (possibly compressed) matrix
7409: . ia - the row pointers
7410: - ja - the column indices
7412: Output Parameters:
7413: . done - PETSC_TRUE or PETSC_FALSE indicated that the values have been returned
7415: Note:
7416: This routine zeros out n, ia, and ja. This is to prevent accidental
7417: us of the array after it has been restored. If you pass NULL, it will
7418: not zero the pointers. Use of ia or ja after MatRestoreRowIJ() is invalid.
7420: Level: developer
7422: .seealso: MatGetRowIJ(), MatRestoreColumnIJ()
7423: @*/
7424: PetscErrorCode MatRestoreRowIJ(Mat mat,PetscInt shift,PetscBool symmetric,PetscBool inodecompressed,PetscInt *n,const PetscInt *ia[],const PetscInt *ja[],PetscBool *done)
7425: {
7434: MatCheckPreallocated(mat,1);
7436: if (!mat->ops->restorerowij) *done = PETSC_FALSE;
7437: else {
7438: *done = PETSC_TRUE;
7439: (*mat->ops->restorerowij)(mat,shift,symmetric,inodecompressed,n,ia,ja,done);
7440: if (n) *n = 0;
7441: if (ia) *ia = NULL;
7442: if (ja) *ja = NULL;
7443: }
7444: return(0);
7445: }
7447: /*@C
7448: MatRestoreColumnIJ - Call after you are completed with the ia,ja indices obtained with
7449: MatGetColumnIJ().
7451: Collective on Mat
7453: Input Parameters:
7454: + mat - the matrix
7455: . shift - 1 or zero indicating we want the indices starting at 0 or 1
7456: - symmetric - PETSC_TRUE or PETSC_FALSE indicating the matrix data structure should be
7457: symmetrized
7458: - inodecompressed - PETSC_TRUE or PETSC_FALSE indicating if the nonzero structure of the
7459: inodes or the nonzero elements is wanted. For BAIJ matrices the compressed version is
7460: always used.
7462: Output Parameters:
7463: + n - size of (possibly compressed) matrix
7464: . ia - the column pointers
7465: . ja - the row indices
7466: - done - PETSC_TRUE or PETSC_FALSE indicated that the values have been returned
7468: Level: developer
7470: .seealso: MatGetColumnIJ(), MatRestoreRowIJ()
7471: @*/
7472: PetscErrorCode MatRestoreColumnIJ(Mat mat,PetscInt shift,PetscBool symmetric,PetscBool inodecompressed,PetscInt *n,const PetscInt *ia[],const PetscInt *ja[],PetscBool *done)
7473: {
7482: MatCheckPreallocated(mat,1);
7484: if (!mat->ops->restorecolumnij) *done = PETSC_FALSE;
7485: else {
7486: *done = PETSC_TRUE;
7487: (*mat->ops->restorecolumnij)(mat,shift,symmetric,inodecompressed,n,ia,ja,done);
7488: if (n) *n = 0;
7489: if (ia) *ia = NULL;
7490: if (ja) *ja = NULL;
7491: }
7492: return(0);
7493: }
7495: /*@C
7496: MatColoringPatch -Used inside matrix coloring routines that
7497: use MatGetRowIJ() and/or MatGetColumnIJ().
7499: Collective on Mat
7501: Input Parameters:
7502: + mat - the matrix
7503: . ncolors - max color value
7504: . n - number of entries in colorarray
7505: - colorarray - array indicating color for each column
7507: Output Parameters:
7508: . iscoloring - coloring generated using colorarray information
7510: Level: developer
7512: .seealso: MatGetRowIJ(), MatGetColumnIJ()
7514: @*/
7515: PetscErrorCode MatColoringPatch(Mat mat,PetscInt ncolors,PetscInt n,ISColoringValue colorarray[],ISColoring *iscoloring)
7516: {
7524: MatCheckPreallocated(mat,1);
7526: if (!mat->ops->coloringpatch) {
7527: ISColoringCreate(PetscObjectComm((PetscObject)mat),ncolors,n,colorarray,PETSC_OWN_POINTER,iscoloring);
7528: } else {
7529: (*mat->ops->coloringpatch)(mat,ncolors,n,colorarray,iscoloring);
7530: }
7531: return(0);
7532: }
7535: /*@
7536: MatSetUnfactored - Resets a factored matrix to be treated as unfactored.
7538: Logically Collective on Mat
7540: Input Parameter:
7541: . mat - the factored matrix to be reset
7543: Notes:
7544: This routine should be used only with factored matrices formed by in-place
7545: factorization via ILU(0) (or by in-place LU factorization for the MATSEQDENSE
7546: format). This option can save memory, for example, when solving nonlinear
7547: systems with a matrix-free Newton-Krylov method and a matrix-based, in-place
7548: ILU(0) preconditioner.
7550: Note that one can specify in-place ILU(0) factorization by calling
7551: .vb
7552: PCType(pc,PCILU);
7553: PCFactorSeUseInPlace(pc);
7554: .ve
7555: or by using the options -pc_type ilu -pc_factor_in_place
7557: In-place factorization ILU(0) can also be used as a local
7558: solver for the blocks within the block Jacobi or additive Schwarz
7559: methods (runtime option: -sub_pc_factor_in_place). See Users-Manual: ch_pc
7560: for details on setting local solver options.
7562: Most users should employ the simplified KSP interface for linear solvers
7563: instead of working directly with matrix algebra routines such as this.
7564: See, e.g., KSPCreate().
7566: Level: developer
7568: .seealso: PCFactorSetUseInPlace(), PCFactorGetUseInPlace()
7570: @*/
7571: PetscErrorCode MatSetUnfactored(Mat mat)
7572: {
7578: MatCheckPreallocated(mat,1);
7579: mat->factortype = MAT_FACTOR_NONE;
7580: if (!mat->ops->setunfactored) return(0);
7581: (*mat->ops->setunfactored)(mat);
7582: return(0);
7583: }
7585: /*MC
7586: MatDenseGetArrayF90 - Accesses a matrix array from Fortran90.
7588: Synopsis:
7589: MatDenseGetArrayF90(Mat x,{Scalar, pointer :: xx_v(:,:)},integer ierr)
7591: Not collective
7593: Input Parameter:
7594: . x - matrix
7596: Output Parameters:
7597: + xx_v - the Fortran90 pointer to the array
7598: - ierr - error code
7600: Example of Usage:
7601: .vb
7602: PetscScalar, pointer xx_v(:,:)
7603: ....
7604: call MatDenseGetArrayF90(x,xx_v,ierr)
7605: a = xx_v(3)
7606: call MatDenseRestoreArrayF90(x,xx_v,ierr)
7607: .ve
7609: Level: advanced
7611: .seealso: MatDenseRestoreArrayF90(), MatDenseGetArray(), MatDenseRestoreArray(), MatSeqAIJGetArrayF90()
7613: M*/
7615: /*MC
7616: MatDenseRestoreArrayF90 - Restores a matrix array that has been
7617: accessed with MatDenseGetArrayF90().
7619: Synopsis:
7620: MatDenseRestoreArrayF90(Mat x,{Scalar, pointer :: xx_v(:,:)},integer ierr)
7622: Not collective
7624: Input Parameters:
7625: + x - matrix
7626: - xx_v - the Fortran90 pointer to the array
7628: Output Parameter:
7629: . ierr - error code
7631: Example of Usage:
7632: .vb
7633: PetscScalar, pointer xx_v(:,:)
7634: ....
7635: call MatDenseGetArrayF90(x,xx_v,ierr)
7636: a = xx_v(3)
7637: call MatDenseRestoreArrayF90(x,xx_v,ierr)
7638: .ve
7640: Level: advanced
7642: .seealso: MatDenseGetArrayF90(), MatDenseGetArray(), MatDenseRestoreArray(), MatSeqAIJRestoreArrayF90()
7644: M*/
7647: /*MC
7648: MatSeqAIJGetArrayF90 - Accesses a matrix array from Fortran90.
7650: Synopsis:
7651: MatSeqAIJGetArrayF90(Mat x,{Scalar, pointer :: xx_v(:)},integer ierr)
7653: Not collective
7655: Input Parameter:
7656: . x - matrix
7658: Output Parameters:
7659: + xx_v - the Fortran90 pointer to the array
7660: - ierr - error code
7662: Example of Usage:
7663: .vb
7664: PetscScalar, pointer xx_v(:)
7665: ....
7666: call MatSeqAIJGetArrayF90(x,xx_v,ierr)
7667: a = xx_v(3)
7668: call MatSeqAIJRestoreArrayF90(x,xx_v,ierr)
7669: .ve
7671: Level: advanced
7673: .seealso: MatSeqAIJRestoreArrayF90(), MatSeqAIJGetArray(), MatSeqAIJRestoreArray(), MatDenseGetArrayF90()
7675: M*/
7677: /*MC
7678: MatSeqAIJRestoreArrayF90 - Restores a matrix array that has been
7679: accessed with MatSeqAIJGetArrayF90().
7681: Synopsis:
7682: MatSeqAIJRestoreArrayF90(Mat x,{Scalar, pointer :: xx_v(:)},integer ierr)
7684: Not collective
7686: Input Parameters:
7687: + x - matrix
7688: - xx_v - the Fortran90 pointer to the array
7690: Output Parameter:
7691: . ierr - error code
7693: Example of Usage:
7694: .vb
7695: PetscScalar, pointer xx_v(:)
7696: ....
7697: call MatSeqAIJGetArrayF90(x,xx_v,ierr)
7698: a = xx_v(3)
7699: call MatSeqAIJRestoreArrayF90(x,xx_v,ierr)
7700: .ve
7702: Level: advanced
7704: .seealso: MatSeqAIJGetArrayF90(), MatSeqAIJGetArray(), MatSeqAIJRestoreArray(), MatDenseRestoreArrayF90()
7706: M*/
7709: /*@
7710: MatCreateSubMatrix - Gets a single submatrix on the same number of processors
7711: as the original matrix.
7713: Collective on Mat
7715: Input Parameters:
7716: + mat - the original matrix
7717: . isrow - parallel IS containing the rows this processor should obtain
7718: . 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.
7719: - cll - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
7721: Output Parameter:
7722: . newmat - the new submatrix, of the same type as the old
7724: Level: advanced
7726: Notes:
7727: The submatrix will be able to be multiplied with vectors using the same layout as iscol.
7729: Some matrix types place restrictions on the row and column indices, such
7730: as that they be sorted or that they be equal to each other.
7732: The index sets may not have duplicate entries.
7734: The first time this is called you should use a cll of MAT_INITIAL_MATRIX,
7735: the MatCreateSubMatrix() routine will create the newmat for you. Any additional calls
7736: to this routine with a mat of the same nonzero structure and with a call of MAT_REUSE_MATRIX
7737: will reuse the matrix generated the first time. You should call MatDestroy() on newmat when
7738: you are finished using it.
7740: The communicator of the newly obtained matrix is ALWAYS the same as the communicator of
7741: the input matrix.
7743: If iscol is NULL then all columns are obtained (not supported in Fortran).
7745: Example usage:
7746: Consider the following 8x8 matrix with 34 non-zero values, that is
7747: assembled across 3 processors. Let's assume that proc0 owns 3 rows,
7748: proc1 owns 3 rows, proc2 owns 2 rows. This division can be shown
7749: as follows:
7751: .vb
7752: 1 2 0 | 0 3 0 | 0 4
7753: Proc0 0 5 6 | 7 0 0 | 8 0
7754: 9 0 10 | 11 0 0 | 12 0
7755: -------------------------------------
7756: 13 0 14 | 15 16 17 | 0 0
7757: Proc1 0 18 0 | 19 20 21 | 0 0
7758: 0 0 0 | 22 23 0 | 24 0
7759: -------------------------------------
7760: Proc2 25 26 27 | 0 0 28 | 29 0
7761: 30 0 0 | 31 32 33 | 0 34
7762: .ve
7764: Suppose isrow = [0 1 | 4 | 6 7] and iscol = [1 2 | 3 4 5 | 6]. The resulting submatrix is
7766: .vb
7767: 2 0 | 0 3 0 | 0
7768: Proc0 5 6 | 7 0 0 | 8
7769: -------------------------------
7770: Proc1 18 0 | 19 20 21 | 0
7771: -------------------------------
7772: Proc2 26 27 | 0 0 28 | 29
7773: 0 0 | 31 32 33 | 0
7774: .ve
7777: .seealso: MatCreateSubMatrices(), MatCreateSubMatricesMPI(), MatCreateSubMatrixVirtual(), MatSubMatrixVirtualUpdate()
7778: @*/
7779: PetscErrorCode MatCreateSubMatrix(Mat mat,IS isrow,IS iscol,MatReuse cll,Mat *newmat)
7780: {
7782: PetscMPIInt size;
7783: Mat *local;
7784: IS iscoltmp;
7785: PetscBool flg;
7794: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
7795: if (cll == MAT_IGNORE_MATRIX) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Cannot use MAT_IGNORE_MATRIX");
7797: MatCheckPreallocated(mat,1);
7798: MPI_Comm_size(PetscObjectComm((PetscObject)mat),&size);
7800: if (!iscol || isrow == iscol) {
7801: PetscBool stride;
7802: PetscMPIInt grabentirematrix = 0,grab;
7803: PetscObjectTypeCompare((PetscObject)isrow,ISSTRIDE,&stride);
7804: if (stride) {
7805: PetscInt first,step,n,rstart,rend;
7806: ISStrideGetInfo(isrow,&first,&step);
7807: if (step == 1) {
7808: MatGetOwnershipRange(mat,&rstart,&rend);
7809: if (rstart == first) {
7810: ISGetLocalSize(isrow,&n);
7811: if (n == rend-rstart) {
7812: grabentirematrix = 1;
7813: }
7814: }
7815: }
7816: }
7817: MPIU_Allreduce(&grabentirematrix,&grab,1,MPI_INT,MPI_MIN,PetscObjectComm((PetscObject)mat));
7818: if (grab) {
7819: PetscInfo(mat,"Getting entire matrix as submatrix\n");
7820: if (cll == MAT_INITIAL_MATRIX) {
7821: *newmat = mat;
7822: PetscObjectReference((PetscObject)mat);
7823: }
7824: return(0);
7825: }
7826: }
7828: if (!iscol) {
7829: ISCreateStride(PetscObjectComm((PetscObject)mat),mat->cmap->n,mat->cmap->rstart,1,&iscoltmp);
7830: } else {
7831: iscoltmp = iscol;
7832: }
7834: /* if original matrix is on just one processor then use submatrix generated */
7835: if (mat->ops->createsubmatrices && !mat->ops->createsubmatrix && size == 1 && cll == MAT_REUSE_MATRIX) {
7836: MatCreateSubMatrices(mat,1,&isrow,&iscoltmp,MAT_REUSE_MATRIX,&newmat);
7837: goto setproperties;
7838: } else if (mat->ops->createsubmatrices && !mat->ops->createsubmatrix && size == 1) {
7839: MatCreateSubMatrices(mat,1,&isrow,&iscoltmp,MAT_INITIAL_MATRIX,&local);
7840: *newmat = *local;
7841: PetscFree(local);
7842: goto setproperties;
7843: } else if (!mat->ops->createsubmatrix) {
7844: /* Create a new matrix type that implements the operation using the full matrix */
7845: PetscLogEventBegin(MAT_CreateSubMat,mat,0,0,0);
7846: switch (cll) {
7847: case MAT_INITIAL_MATRIX:
7848: MatCreateSubMatrixVirtual(mat,isrow,iscoltmp,newmat);
7849: break;
7850: case MAT_REUSE_MATRIX:
7851: MatSubMatrixVirtualUpdate(*newmat,mat,isrow,iscoltmp);
7852: break;
7853: default: SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_OUTOFRANGE,"Invalid MatReuse, must be either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX");
7854: }
7855: PetscLogEventEnd(MAT_CreateSubMat,mat,0,0,0);
7856: goto setproperties;
7857: }
7859: if (!mat->ops->createsubmatrix) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
7860: PetscLogEventBegin(MAT_CreateSubMat,mat,0,0,0);
7861: (*mat->ops->createsubmatrix)(mat,isrow,iscoltmp,cll,newmat);
7862: PetscLogEventEnd(MAT_CreateSubMat,mat,0,0,0);
7864: setproperties:
7865: ISEqualUnsorted(isrow,iscoltmp,&flg);
7866: if (flg) {
7867: MatPropagateSymmetryOptions(mat,*newmat);
7868: }
7869: if (!iscol) {ISDestroy(&iscoltmp);}
7870: if (*newmat && cll == MAT_INITIAL_MATRIX) {PetscObjectStateIncrease((PetscObject)*newmat);}
7871: return(0);
7872: }
7874: /*@
7875: MatPropagateSymmetryOptions - Propagates symmetry options set on a matrix to another matrix
7877: Not Collective
7879: Input Parameters:
7880: + A - the matrix we wish to propagate options from
7881: - B - the matrix we wish to propagate options to
7883: Level: beginner
7885: Notes: Propagates the options associated to MAT_SYMMETRY_ETERNAL, MAT_STRUCTURALLY_SYMMETRIC, MAT_HERMITIAN, MAT_SPD and MAT_SYMMETRIC
7887: .seealso: MatSetOption()
7888: @*/
7889: PetscErrorCode MatPropagateSymmetryOptions(Mat A, Mat B)
7890: {
7896: if (A->symmetric_eternal) { /* symmetric_eternal does not have a corresponding *set flag */
7897: MatSetOption(B,MAT_SYMMETRY_ETERNAL,A->symmetric_eternal);
7898: }
7899: if (A->structurally_symmetric_set) {
7900: MatSetOption(B,MAT_STRUCTURALLY_SYMMETRIC,A->structurally_symmetric);
7901: }
7902: if (A->hermitian_set) {
7903: MatSetOption(B,MAT_HERMITIAN,A->hermitian);
7904: }
7905: if (A->spd_set) {
7906: MatSetOption(B,MAT_SPD,A->spd);
7907: }
7908: if (A->symmetric_set) {
7909: MatSetOption(B,MAT_SYMMETRIC,A->symmetric);
7910: }
7911: return(0);
7912: }
7914: /*@
7915: MatStashSetInitialSize - sets the sizes of the matrix stash, that is
7916: used during the assembly process to store values that belong to
7917: other processors.
7919: Not Collective
7921: Input Parameters:
7922: + mat - the matrix
7923: . size - the initial size of the stash.
7924: - bsize - the initial size of the block-stash(if used).
7926: Options Database Keys:
7927: + -matstash_initial_size <size> or <size0,size1,...sizep-1>
7928: - -matstash_block_initial_size <bsize> or <bsize0,bsize1,...bsizep-1>
7930: Level: intermediate
7932: Notes:
7933: The block-stash is used for values set with MatSetValuesBlocked() while
7934: the stash is used for values set with MatSetValues()
7936: Run with the option -info and look for output of the form
7937: MatAssemblyBegin_MPIXXX:Stash has MM entries, uses nn mallocs.
7938: to determine the appropriate value, MM, to use for size and
7939: MatAssemblyBegin_MPIXXX:Block-Stash has BMM entries, uses nn mallocs.
7940: to determine the value, BMM to use for bsize
7943: .seealso: MatAssemblyBegin(), MatAssemblyEnd(), Mat, MatStashGetInfo()
7945: @*/
7946: PetscErrorCode MatStashSetInitialSize(Mat mat,PetscInt size, PetscInt bsize)
7947: {
7953: MatStashSetInitialSize_Private(&mat->stash,size);
7954: MatStashSetInitialSize_Private(&mat->bstash,bsize);
7955: return(0);
7956: }
7958: /*@
7959: MatInterpolateAdd - w = y + A*x or A'*x depending on the shape of
7960: the matrix
7962: Neighbor-wise Collective on Mat
7964: Input Parameters:
7965: + mat - the matrix
7966: . x,y - the vectors
7967: - w - where the result is stored
7969: Level: intermediate
7971: Notes:
7972: w may be the same vector as y.
7974: This allows one to use either the restriction or interpolation (its transpose)
7975: matrix to do the interpolation
7977: .seealso: MatMultAdd(), MatMultTransposeAdd(), MatRestrict()
7979: @*/
7980: PetscErrorCode MatInterpolateAdd(Mat A,Vec x,Vec y,Vec w)
7981: {
7983: PetscInt M,N,Ny;
7991: MatCheckPreallocated(A,1);
7992: MatGetSize(A,&M,&N);
7993: VecGetSize(y,&Ny);
7994: if (M == Ny) {
7995: MatMultAdd(A,x,y,w);
7996: } else {
7997: MatMultTransposeAdd(A,x,y,w);
7998: }
7999: return(0);
8000: }
8002: /*@
8003: MatInterpolate - y = A*x or A'*x depending on the shape of
8004: the matrix
8006: Neighbor-wise Collective on Mat
8008: Input Parameters:
8009: + mat - the matrix
8010: - x,y - the vectors
8012: Level: intermediate
8014: Notes:
8015: This allows one to use either the restriction or interpolation (its transpose)
8016: matrix to do the interpolation
8018: .seealso: MatMultAdd(), MatMultTransposeAdd(), MatRestrict()
8020: @*/
8021: PetscErrorCode MatInterpolate(Mat A,Vec x,Vec y)
8022: {
8024: PetscInt M,N,Ny;
8031: MatCheckPreallocated(A,1);
8032: MatGetSize(A,&M,&N);
8033: VecGetSize(y,&Ny);
8034: if (M == Ny) {
8035: MatMult(A,x,y);
8036: } else {
8037: MatMultTranspose(A,x,y);
8038: }
8039: return(0);
8040: }
8042: /*@
8043: MatRestrict - y = A*x or A'*x
8045: Neighbor-wise Collective on Mat
8047: Input Parameters:
8048: + mat - the matrix
8049: - x,y - the vectors
8051: Level: intermediate
8053: Notes:
8054: This allows one to use either the restriction or interpolation (its transpose)
8055: matrix to do the restriction
8057: .seealso: MatMultAdd(), MatMultTransposeAdd(), MatInterpolate()
8059: @*/
8060: PetscErrorCode MatRestrict(Mat A,Vec x,Vec y)
8061: {
8063: PetscInt M,N,Ny;
8070: MatCheckPreallocated(A,1);
8072: MatGetSize(A,&M,&N);
8073: VecGetSize(y,&Ny);
8074: if (M == Ny) {
8075: MatMult(A,x,y);
8076: } else {
8077: MatMultTranspose(A,x,y);
8078: }
8079: return(0);
8080: }
8082: /*@
8083: MatGetNullSpace - retrieves the null space of a matrix.
8085: Logically Collective on Mat
8087: Input Parameters:
8088: + mat - the matrix
8089: - nullsp - the null space object
8091: Level: developer
8093: .seealso: MatCreate(), MatNullSpaceCreate(), MatSetNearNullSpace(), MatSetNullSpace()
8094: @*/
8095: PetscErrorCode MatGetNullSpace(Mat mat, MatNullSpace *nullsp)
8096: {
8100: *nullsp = (mat->symmetric_set && mat->symmetric && !mat->nullsp) ? mat->transnullsp : mat->nullsp;
8101: return(0);
8102: }
8104: /*@
8105: MatSetNullSpace - attaches a null space to a matrix.
8107: Logically Collective on Mat
8109: Input Parameters:
8110: + mat - the matrix
8111: - nullsp - the null space object
8113: Level: advanced
8115: Notes:
8116: This null space is used by the linear solvers. Overwrites any previous null space that may have been attached
8118: For inconsistent singular systems (linear systems where the right hand side is not in the range of the operator) you also likely should
8119: call MatSetTransposeNullSpace(). This allows the linear system to be solved in a least squares sense.
8121: You can remove the null space by calling this routine with an nullsp of NULL
8124: The fundamental theorem of linear algebra (Gilbert Strang, Introduction to Applied Mathematics, page 72) states that
8125: 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).
8126: 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
8127: 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
8128: 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).
8130: Krylov solvers can produce the minimal norm solution to the least squares problem by utilizing MatNullSpaceRemove().
8132: 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
8133: routine also automatically calls MatSetTransposeNullSpace().
8135: .seealso: MatCreate(), MatNullSpaceCreate(), MatSetNearNullSpace(), MatGetNullSpace(), MatSetTransposeNullSpace(), MatGetTransposeNullSpace(), MatNullSpaceRemove()
8136: @*/
8137: PetscErrorCode MatSetNullSpace(Mat mat,MatNullSpace nullsp)
8138: {
8144: if (nullsp) {PetscObjectReference((PetscObject)nullsp);}
8145: MatNullSpaceDestroy(&mat->nullsp);
8146: mat->nullsp = nullsp;
8147: if (mat->symmetric_set && mat->symmetric) {
8148: MatSetTransposeNullSpace(mat,nullsp);
8149: }
8150: return(0);
8151: }
8153: /*@
8154: MatGetTransposeNullSpace - retrieves the null space of the transpose of a matrix.
8156: Logically Collective on Mat
8158: Input Parameters:
8159: + mat - the matrix
8160: - nullsp - the null space object
8162: Level: developer
8164: .seealso: MatCreate(), MatNullSpaceCreate(), MatSetNearNullSpace(), MatSetTransposeNullSpace(), MatSetNullSpace(), MatGetNullSpace()
8165: @*/
8166: PetscErrorCode MatGetTransposeNullSpace(Mat mat, MatNullSpace *nullsp)
8167: {
8172: *nullsp = (mat->symmetric_set && mat->symmetric && !mat->transnullsp) ? mat->nullsp : mat->transnullsp;
8173: return(0);
8174: }
8176: /*@
8177: MatSetTransposeNullSpace - attaches a null space to a matrix.
8179: Logically Collective on Mat
8181: Input Parameters:
8182: + mat - the matrix
8183: - nullsp - the null space object
8185: Level: advanced
8187: Notes:
8188: 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.
8189: You must also call MatSetNullSpace()
8192: The fundamental theorem of linear algebra (Gilbert Strang, Introduction to Applied Mathematics, page 72) states that
8193: 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).
8194: 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
8195: 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
8196: 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).
8198: Krylov solvers can produce the minimal norm solution to the least squares problem by utilizing MatNullSpaceRemove().
8200: .seealso: MatCreate(), MatNullSpaceCreate(), MatSetNearNullSpace(), MatGetNullSpace(), MatSetNullSpace(), MatGetTransposeNullSpace(), MatNullSpaceRemove()
8201: @*/
8202: PetscErrorCode MatSetTransposeNullSpace(Mat mat,MatNullSpace nullsp)
8203: {
8209: if (nullsp) {PetscObjectReference((PetscObject)nullsp);}
8210: MatNullSpaceDestroy(&mat->transnullsp);
8211: mat->transnullsp = nullsp;
8212: return(0);
8213: }
8215: /*@
8216: MatSetNearNullSpace - attaches a null space to a matrix, which is often the null space (rigid body modes) of the operator without boundary conditions
8217: This null space will be used to provide near null space vectors to a multigrid preconditioner built from this matrix.
8219: Logically Collective on Mat
8221: Input Parameters:
8222: + mat - the matrix
8223: - nullsp - the null space object
8225: Level: advanced
8227: Notes:
8228: Overwrites any previous near null space that may have been attached
8230: You can remove the null space by calling this routine with an nullsp of NULL
8232: .seealso: MatCreate(), MatNullSpaceCreate(), MatSetNullSpace(), MatNullSpaceCreateRigidBody(), MatGetNearNullSpace()
8233: @*/
8234: PetscErrorCode MatSetNearNullSpace(Mat mat,MatNullSpace nullsp)
8235: {
8242: MatCheckPreallocated(mat,1);
8243: if (nullsp) {PetscObjectReference((PetscObject)nullsp);}
8244: MatNullSpaceDestroy(&mat->nearnullsp);
8245: mat->nearnullsp = nullsp;
8246: return(0);
8247: }
8249: /*@
8250: MatGetNearNullSpace -Get null space attached with MatSetNearNullSpace()
8252: Not Collective
8254: Input Parameters:
8255: . mat - the matrix
8257: Output Parameters:
8258: . nullsp - the null space object, NULL if not set
8260: Level: developer
8262: .seealso: MatSetNearNullSpace(), MatGetNullSpace(), MatNullSpaceCreate()
8263: @*/
8264: PetscErrorCode MatGetNearNullSpace(Mat mat,MatNullSpace *nullsp)
8265: {
8270: MatCheckPreallocated(mat,1);
8271: *nullsp = mat->nearnullsp;
8272: return(0);
8273: }
8275: /*@C
8276: MatICCFactor - Performs in-place incomplete Cholesky factorization of matrix.
8278: Collective on Mat
8280: Input Parameters:
8281: + mat - the matrix
8282: . row - row/column permutation
8283: . fill - expected fill factor >= 1.0
8284: - level - level of fill, for ICC(k)
8286: Notes:
8287: Probably really in-place only when level of fill is zero, otherwise allocates
8288: new space to store factored matrix and deletes previous memory.
8290: Most users should employ the simplified KSP interface for linear solvers
8291: instead of working directly with matrix algebra routines such as this.
8292: See, e.g., KSPCreate().
8294: Level: developer
8297: .seealso: MatICCFactorSymbolic(), MatLUFactorNumeric(), MatCholeskyFactor()
8299: Developer Note: fortran interface is not autogenerated as the f90
8300: interface defintion cannot be generated correctly [due to MatFactorInfo]
8302: @*/
8303: PetscErrorCode MatICCFactor(Mat mat,IS row,const MatFactorInfo *info)
8304: {
8312: if (mat->rmap->N != mat->cmap->N) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONG,"matrix must be square");
8313: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
8314: if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
8315: if (!mat->ops->iccfactor) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
8316: MatCheckPreallocated(mat,1);
8317: (*mat->ops->iccfactor)(mat,row,info);
8318: PetscObjectStateIncrease((PetscObject)mat);
8319: return(0);
8320: }
8322: /*@
8323: MatDiagonalScaleLocal - Scales columns of a matrix given the scaling values including the
8324: ghosted ones.
8326: Not Collective
8328: Input Parameters:
8329: + mat - the matrix
8330: - diag = the diagonal values, including ghost ones
8332: Level: developer
8334: Notes:
8335: Works only for MPIAIJ and MPIBAIJ matrices
8337: .seealso: MatDiagonalScale()
8338: @*/
8339: PetscErrorCode MatDiagonalScaleLocal(Mat mat,Vec diag)
8340: {
8342: PetscMPIInt size;
8349: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Matrix must be already assembled");
8350: PetscLogEventBegin(MAT_Scale,mat,0,0,0);
8351: MPI_Comm_size(PetscObjectComm((PetscObject)mat),&size);
8352: if (size == 1) {
8353: PetscInt n,m;
8354: VecGetSize(diag,&n);
8355: MatGetSize(mat,0,&m);
8356: if (m == n) {
8357: MatDiagonalScale(mat,0,diag);
8358: } else SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"Only supported for sequential matrices when no ghost points/periodic conditions");
8359: } else {
8360: PetscUseMethod(mat,"MatDiagonalScaleLocal_C",(Mat,Vec),(mat,diag));
8361: }
8362: PetscLogEventEnd(MAT_Scale,mat,0,0,0);
8363: PetscObjectStateIncrease((PetscObject)mat);
8364: return(0);
8365: }
8367: /*@
8368: MatGetInertia - Gets the inertia from a factored matrix
8370: Collective on Mat
8372: Input Parameter:
8373: . mat - the matrix
8375: Output Parameters:
8376: + nneg - number of negative eigenvalues
8377: . nzero - number of zero eigenvalues
8378: - npos - number of positive eigenvalues
8380: Level: advanced
8382: Notes:
8383: Matrix must have been factored by MatCholeskyFactor()
8386: @*/
8387: PetscErrorCode MatGetInertia(Mat mat,PetscInt *nneg,PetscInt *nzero,PetscInt *npos)
8388: {
8394: if (!mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
8395: if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Numeric factor mat is not assembled");
8396: if (!mat->ops->getinertia) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
8397: (*mat->ops->getinertia)(mat,nneg,nzero,npos);
8398: return(0);
8399: }
8401: /* ----------------------------------------------------------------*/
8402: /*@C
8403: MatSolves - Solves A x = b, given a factored matrix, for a collection of vectors
8405: Neighbor-wise Collective on Mats
8407: Input Parameters:
8408: + mat - the factored matrix
8409: - b - the right-hand-side vectors
8411: Output Parameter:
8412: . x - the result vectors
8414: Notes:
8415: The vectors b and x cannot be the same. I.e., one cannot
8416: call MatSolves(A,x,x).
8418: Notes:
8419: Most users should employ the simplified KSP interface for linear solvers
8420: instead of working directly with matrix algebra routines such as this.
8421: See, e.g., KSPCreate().
8423: Level: developer
8425: .seealso: MatSolveAdd(), MatSolveTranspose(), MatSolveTransposeAdd(), MatSolve()
8426: @*/
8427: PetscErrorCode MatSolves(Mat mat,Vecs b,Vecs x)
8428: {
8434: if (x == b) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"x and b must be different vectors");
8435: if (!mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
8436: if (!mat->rmap->N && !mat->cmap->N) return(0);
8438: if (!mat->ops->solves) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
8439: MatCheckPreallocated(mat,1);
8440: PetscLogEventBegin(MAT_Solves,mat,0,0,0);
8441: (*mat->ops->solves)(mat,b,x);
8442: PetscLogEventEnd(MAT_Solves,mat,0,0,0);
8443: return(0);
8444: }
8446: /*@
8447: MatIsSymmetric - Test whether a matrix is symmetric
8449: Collective on Mat
8451: Input Parameter:
8452: + A - the matrix to test
8453: - tol - difference between value and its transpose less than this amount counts as equal (use 0.0 for exact transpose)
8455: Output Parameters:
8456: . flg - the result
8458: Notes:
8459: For real numbers MatIsSymmetric() and MatIsHermitian() return identical results
8461: Level: intermediate
8463: .seealso: MatTranspose(), MatIsTranspose(), MatIsHermitian(), MatIsStructurallySymmetric(), MatSetOption(), MatIsSymmetricKnown()
8464: @*/
8465: PetscErrorCode MatIsSymmetric(Mat A,PetscReal tol,PetscBool *flg)
8466: {
8473: if (!A->symmetric_set) {
8474: if (!A->ops->issymmetric) {
8475: MatType mattype;
8476: MatGetType(A,&mattype);
8477: SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Matrix of type <%s> does not support checking for symmetric",mattype);
8478: }
8479: (*A->ops->issymmetric)(A,tol,flg);
8480: if (!tol) {
8481: MatSetOption(A,MAT_SYMMETRIC,*flg);
8482: }
8483: } else if (A->symmetric) {
8484: *flg = PETSC_TRUE;
8485: } else if (!tol) {
8486: *flg = PETSC_FALSE;
8487: } else {
8488: if (!A->ops->issymmetric) {
8489: MatType mattype;
8490: MatGetType(A,&mattype);
8491: SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Matrix of type <%s> does not support checking for symmetric",mattype);
8492: }
8493: (*A->ops->issymmetric)(A,tol,flg);
8494: }
8495: return(0);
8496: }
8498: /*@
8499: MatIsHermitian - Test whether a matrix is Hermitian
8501: Collective on Mat
8503: Input Parameter:
8504: + A - the matrix to test
8505: - tol - difference between value and its transpose less than this amount counts as equal (use 0.0 for exact Hermitian)
8507: Output Parameters:
8508: . flg - the result
8510: Level: intermediate
8512: .seealso: MatTranspose(), MatIsTranspose(), MatIsHermitian(), MatIsStructurallySymmetric(), MatSetOption(),
8513: MatIsSymmetricKnown(), MatIsSymmetric()
8514: @*/
8515: PetscErrorCode MatIsHermitian(Mat A,PetscReal tol,PetscBool *flg)
8516: {
8523: if (!A->hermitian_set) {
8524: if (!A->ops->ishermitian) {
8525: MatType mattype;
8526: MatGetType(A,&mattype);
8527: SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Matrix of type <%s> does not support checking for hermitian",mattype);
8528: }
8529: (*A->ops->ishermitian)(A,tol,flg);
8530: if (!tol) {
8531: MatSetOption(A,MAT_HERMITIAN,*flg);
8532: }
8533: } else if (A->hermitian) {
8534: *flg = PETSC_TRUE;
8535: } else if (!tol) {
8536: *flg = PETSC_FALSE;
8537: } else {
8538: if (!A->ops->ishermitian) {
8539: MatType mattype;
8540: MatGetType(A,&mattype);
8541: SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Matrix of type <%s> does not support checking for hermitian",mattype);
8542: }
8543: (*A->ops->ishermitian)(A,tol,flg);
8544: }
8545: return(0);
8546: }
8548: /*@
8549: MatIsSymmetricKnown - Checks the flag on the matrix to see if it is symmetric.
8551: Not Collective
8553: Input Parameter:
8554: . A - the matrix to check
8556: Output Parameters:
8557: + set - if the symmetric flag is set (this tells you if the next flag is valid)
8558: - flg - the result
8560: Level: advanced
8562: Note: Does not check the matrix values directly, so this may return unknown (set = PETSC_FALSE). Use MatIsSymmetric()
8563: if you want it explicitly checked
8565: .seealso: MatTranspose(), MatIsTranspose(), MatIsHermitian(), MatIsStructurallySymmetric(), MatSetOption(), MatIsSymmetric()
8566: @*/
8567: PetscErrorCode MatIsSymmetricKnown(Mat A,PetscBool *set,PetscBool *flg)
8568: {
8573: if (A->symmetric_set) {
8574: *set = PETSC_TRUE;
8575: *flg = A->symmetric;
8576: } else {
8577: *set = PETSC_FALSE;
8578: }
8579: return(0);
8580: }
8582: /*@
8583: MatIsHermitianKnown - Checks the flag on the matrix to see if it is hermitian.
8585: Not Collective
8587: Input Parameter:
8588: . A - the matrix to check
8590: Output Parameters:
8591: + set - if the hermitian flag is set (this tells you if the next flag is valid)
8592: - flg - the result
8594: Level: advanced
8596: Note: Does not check the matrix values directly, so this may return unknown (set = PETSC_FALSE). Use MatIsHermitian()
8597: if you want it explicitly checked
8599: .seealso: MatTranspose(), MatIsTranspose(), MatIsHermitian(), MatIsStructurallySymmetric(), MatSetOption(), MatIsSymmetric()
8600: @*/
8601: PetscErrorCode MatIsHermitianKnown(Mat A,PetscBool *set,PetscBool *flg)
8602: {
8607: if (A->hermitian_set) {
8608: *set = PETSC_TRUE;
8609: *flg = A->hermitian;
8610: } else {
8611: *set = PETSC_FALSE;
8612: }
8613: return(0);
8614: }
8616: /*@
8617: MatIsStructurallySymmetric - Test whether a matrix is structurally symmetric
8619: Collective on Mat
8621: Input Parameter:
8622: . A - the matrix to test
8624: Output Parameters:
8625: . flg - the result
8627: Level: intermediate
8629: .seealso: MatTranspose(), MatIsTranspose(), MatIsHermitian(), MatIsSymmetric(), MatSetOption()
8630: @*/
8631: PetscErrorCode MatIsStructurallySymmetric(Mat A,PetscBool *flg)
8632: {
8638: if (!A->structurally_symmetric_set) {
8639: if (!A->ops->isstructurallysymmetric) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Matrix does not support checking for structural symmetric");
8640: (*A->ops->isstructurallysymmetric)(A,flg);
8641: MatSetOption(A,MAT_STRUCTURALLY_SYMMETRIC,*flg);
8642: } else *flg = A->structurally_symmetric;
8643: return(0);
8644: }
8646: /*@
8647: MatStashGetInfo - Gets how many values are currently in the matrix stash, i.e. need
8648: to be communicated to other processors during the MatAssemblyBegin/End() process
8650: Not collective
8652: Input Parameter:
8653: . vec - the vector
8655: Output Parameters:
8656: + nstash - the size of the stash
8657: . reallocs - the number of additional mallocs incurred.
8658: . bnstash - the size of the block stash
8659: - breallocs - the number of additional mallocs incurred.in the block stash
8661: Level: advanced
8663: .seealso: MatAssemblyBegin(), MatAssemblyEnd(), Mat, MatStashSetInitialSize()
8665: @*/
8666: PetscErrorCode MatStashGetInfo(Mat mat,PetscInt *nstash,PetscInt *reallocs,PetscInt *bnstash,PetscInt *breallocs)
8667: {
8671: MatStashGetInfo_Private(&mat->stash,nstash,reallocs);
8672: MatStashGetInfo_Private(&mat->bstash,bnstash,breallocs);
8673: return(0);
8674: }
8676: /*@C
8677: MatCreateVecs - Get vector(s) compatible with the matrix, i.e. with the same
8678: parallel layout
8680: Collective on Mat
8682: Input Parameter:
8683: . mat - the matrix
8685: Output Parameter:
8686: + right - (optional) vector that the matrix can be multiplied against
8687: - left - (optional) vector that the matrix vector product can be stored in
8689: Notes:
8690: 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().
8692: Notes:
8693: These are new vectors which are not owned by the Mat, they should be destroyed in VecDestroy() when no longer needed
8695: Level: advanced
8697: .seealso: MatCreate(), VecDestroy()
8698: @*/
8699: PetscErrorCode MatCreateVecs(Mat mat,Vec *right,Vec *left)
8700: {
8706: if (mat->ops->getvecs) {
8707: (*mat->ops->getvecs)(mat,right,left);
8708: } else {
8709: PetscInt rbs,cbs;
8710: MatGetBlockSizes(mat,&rbs,&cbs);
8711: if (right) {
8712: if (mat->cmap->n < 0) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"PetscLayout for columns not yet setup");
8713: VecCreate(PetscObjectComm((PetscObject)mat),right);
8714: VecSetSizes(*right,mat->cmap->n,PETSC_DETERMINE);
8715: VecSetBlockSize(*right,cbs);
8716: VecSetType(*right,mat->defaultvectype);
8717: PetscLayoutReference(mat->cmap,&(*right)->map);
8718: }
8719: if (left) {
8720: if (mat->rmap->n < 0) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"PetscLayout for rows not yet setup");
8721: VecCreate(PetscObjectComm((PetscObject)mat),left);
8722: VecSetSizes(*left,mat->rmap->n,PETSC_DETERMINE);
8723: VecSetBlockSize(*left,rbs);
8724: VecSetType(*left,mat->defaultvectype);
8725: PetscLayoutReference(mat->rmap,&(*left)->map);
8726: }
8727: }
8728: return(0);
8729: }
8731: /*@C
8732: MatFactorInfoInitialize - Initializes a MatFactorInfo data structure
8733: with default values.
8735: Not Collective
8737: Input Parameters:
8738: . info - the MatFactorInfo data structure
8741: Notes:
8742: The solvers are generally used through the KSP and PC objects, for example
8743: PCLU, PCILU, PCCHOLESKY, PCICC
8745: Level: developer
8747: .seealso: MatFactorInfo
8749: Developer Note: fortran interface is not autogenerated as the f90
8750: interface defintion cannot be generated correctly [due to MatFactorInfo]
8752: @*/
8754: PetscErrorCode MatFactorInfoInitialize(MatFactorInfo *info)
8755: {
8759: PetscMemzero(info,sizeof(MatFactorInfo));
8760: return(0);
8761: }
8763: /*@
8764: MatFactorSetSchurIS - Set indices corresponding to the Schur complement you wish to have computed
8766: Collective on Mat
8768: Input Parameters:
8769: + mat - the factored matrix
8770: - is - the index set defining the Schur indices (0-based)
8772: Notes:
8773: Call MatFactorSolveSchurComplement() or MatFactorSolveSchurComplementTranspose() after this call to solve a Schur complement system.
8775: You can call MatFactorGetSchurComplement() or MatFactorCreateSchurComplement() after this call.
8777: Level: developer
8779: .seealso: MatGetFactor(), MatFactorGetSchurComplement(), MatFactorRestoreSchurComplement(), MatFactorCreateSchurComplement(), MatFactorSolveSchurComplement(),
8780: MatFactorSolveSchurComplementTranspose(), MatFactorSolveSchurComplement()
8782: @*/
8783: PetscErrorCode MatFactorSetSchurIS(Mat mat,IS is)
8784: {
8785: PetscErrorCode ierr,(*f)(Mat,IS);
8793: if (!mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Only for factored matrix");
8794: PetscObjectQueryFunction((PetscObject)mat,"MatFactorSetSchurIS_C",&f);
8795: 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");
8796: MatDestroy(&mat->schur);
8797: (*f)(mat,is);
8798: if (!mat->schur) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_PLIB,"Schur complement has not been created");
8799: return(0);
8800: }
8802: /*@
8803: MatFactorCreateSchurComplement - Create a Schur complement matrix object using Schur data computed during the factorization step
8805: Logically Collective on Mat
8807: Input Parameters:
8808: + F - the factored matrix obtained by calling MatGetFactor() from PETSc-MUMPS interface
8809: . S - location where to return the Schur complement, can be NULL
8810: - status - the status of the Schur complement matrix, can be NULL
8812: Notes:
8813: You must call MatFactorSetSchurIS() before calling this routine.
8815: The routine provides a copy of the Schur matrix stored within the solver data structures.
8816: The caller must destroy the object when it is no longer needed.
8817: If MatFactorInvertSchurComplement() has been called, the routine gets back the inverse.
8819: 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)
8821: Developer Notes:
8822: The reason this routine exists is because the representation of the Schur complement within the factor matrix may be different than a standard PETSc
8823: matrix representation and we normally do not want to use the time or memory to make a copy as a regular PETSc matrix.
8825: See MatCreateSchurComplement() or MatGetSchurComplement() for ways to create virtual or approximate Schur complements.
8827: Level: advanced
8829: References:
8831: .seealso: MatGetFactor(), MatFactorSetSchurIS(), MatFactorGetSchurComplement(), MatFactorSchurStatus
8832: @*/
8833: PetscErrorCode MatFactorCreateSchurComplement(Mat F,Mat* S,MatFactorSchurStatus* status)
8834: {
8841: if (S) {
8842: PetscErrorCode (*f)(Mat,Mat*);
8844: PetscObjectQueryFunction((PetscObject)F,"MatFactorCreateSchurComplement_C",&f);
8845: if (f) {
8846: (*f)(F,S);
8847: } else {
8848: MatDuplicate(F->schur,MAT_COPY_VALUES,S);
8849: }
8850: }
8851: if (status) *status = F->schur_status;
8852: return(0);
8853: }
8855: /*@
8856: MatFactorGetSchurComplement - Gets access to a Schur complement matrix using the current Schur data within a factored matrix
8858: Logically Collective on Mat
8860: Input Parameters:
8861: + F - the factored matrix obtained by calling MatGetFactor()
8862: . *S - location where to return the Schur complement, can be NULL
8863: - status - the status of the Schur complement matrix, can be NULL
8865: Notes:
8866: You must call MatFactorSetSchurIS() before calling this routine.
8868: Schur complement mode is currently implemented for sequential matrices.
8869: The routine returns a the Schur Complement stored within the data strutures of the solver.
8870: If MatFactorInvertSchurComplement() has previously been called, the returned matrix is actually the inverse of the Schur complement.
8871: The returned matrix should not be destroyed; the caller should call MatFactorRestoreSchurComplement() when the object is no longer needed.
8873: Use MatFactorCreateSchurComplement() to create a copy of the Schur complement matrix that is within a factored matrix
8875: See MatCreateSchurComplement() or MatGetSchurComplement() for ways to create virtual or approximate Schur complements.
8877: Level: advanced
8879: References:
8881: .seealso: MatGetFactor(), MatFactorSetSchurIS(), MatFactorRestoreSchurComplement(), MatFactorCreateSchurComplement(), MatFactorSchurStatus
8882: @*/
8883: PetscErrorCode MatFactorGetSchurComplement(Mat F,Mat* S,MatFactorSchurStatus* status)
8884: {
8889: if (S) *S = F->schur;
8890: if (status) *status = F->schur_status;
8891: return(0);
8892: }
8894: /*@
8895: MatFactorRestoreSchurComplement - Restore the Schur complement matrix object obtained from a call to MatFactorGetSchurComplement
8897: Logically Collective on Mat
8899: Input Parameters:
8900: + F - the factored matrix obtained by calling MatGetFactor()
8901: . *S - location where the Schur complement is stored
8902: - status - the status of the Schur complement matrix (see MatFactorSchurStatus)
8904: Notes:
8906: Level: advanced
8908: References:
8910: .seealso: MatGetFactor(), MatFactorSetSchurIS(), MatFactorRestoreSchurComplement(), MatFactorCreateSchurComplement(), MatFactorSchurStatus
8911: @*/
8912: PetscErrorCode MatFactorRestoreSchurComplement(Mat F,Mat* S,MatFactorSchurStatus status)
8913: {
8918: if (S) {
8920: *S = NULL;
8921: }
8922: F->schur_status = status;
8923: MatFactorUpdateSchurStatus_Private(F);
8924: return(0);
8925: }
8927: /*@
8928: MatFactorSolveSchurComplementTranspose - Solve the transpose of the Schur complement system computed during the factorization step
8930: Logically Collective on Mat
8932: Input Parameters:
8933: + F - the factored matrix obtained by calling MatGetFactor()
8934: . rhs - location where the right hand side of the Schur complement system is stored
8935: - sol - location where the solution of the Schur complement system has to be returned
8937: Notes:
8938: The sizes of the vectors should match the size of the Schur complement
8940: Must be called after MatFactorSetSchurIS()
8942: Level: advanced
8944: References:
8946: .seealso: MatGetFactor(), MatFactorSetSchurIS(), MatFactorSolveSchurComplement()
8947: @*/
8948: PetscErrorCode MatFactorSolveSchurComplementTranspose(Mat F, Vec rhs, Vec sol)
8949: {
8961: MatFactorFactorizeSchurComplement(F);
8962: switch (F->schur_status) {
8963: case MAT_FACTOR_SCHUR_FACTORED:
8964: MatSolveTranspose(F->schur,rhs,sol);
8965: break;
8966: case MAT_FACTOR_SCHUR_INVERTED:
8967: MatMultTranspose(F->schur,rhs,sol);
8968: break;
8969: default:
8970: SETERRQ1(PetscObjectComm((PetscObject)F),PETSC_ERR_SUP,"Unhandled MatFactorSchurStatus %D",F->schur_status);
8971: break;
8972: }
8973: return(0);
8974: }
8976: /*@
8977: MatFactorSolveSchurComplement - Solve the Schur complement system computed during the factorization step
8979: Logically Collective on Mat
8981: Input Parameters:
8982: + F - the factored matrix obtained by calling MatGetFactor()
8983: . rhs - location where the right hand side of the Schur complement system is stored
8984: - sol - location where the solution of the Schur complement system has to be returned
8986: Notes:
8987: The sizes of the vectors should match the size of the Schur complement
8989: Must be called after MatFactorSetSchurIS()
8991: Level: advanced
8993: References:
8995: .seealso: MatGetFactor(), MatFactorSetSchurIS(), MatFactorSolveSchurComplementTranspose()
8996: @*/
8997: PetscErrorCode MatFactorSolveSchurComplement(Mat F, Vec rhs, Vec sol)
8998: {
9010: MatFactorFactorizeSchurComplement(F);
9011: switch (F->schur_status) {
9012: case MAT_FACTOR_SCHUR_FACTORED:
9013: MatSolve(F->schur,rhs,sol);
9014: break;
9015: case MAT_FACTOR_SCHUR_INVERTED:
9016: MatMult(F->schur,rhs,sol);
9017: break;
9018: default:
9019: SETERRQ1(PetscObjectComm((PetscObject)F),PETSC_ERR_SUP,"Unhandled MatFactorSchurStatus %D",F->schur_status);
9020: break;
9021: }
9022: return(0);
9023: }
9025: /*@
9026: MatFactorInvertSchurComplement - Invert the Schur complement matrix computed during the factorization step
9028: Logically Collective on Mat
9030: Input Parameters:
9031: . F - the factored matrix obtained by calling MatGetFactor()
9033: Notes:
9034: Must be called after MatFactorSetSchurIS().
9036: Call MatFactorGetSchurComplement() or MatFactorCreateSchurComplement() AFTER this call to actually compute the inverse and get access to it.
9038: Level: advanced
9040: References:
9042: .seealso: MatGetFactor(), MatFactorSetSchurIS(), MatFactorGetSchurComplement(), MatFactorCreateSchurComplement()
9043: @*/
9044: PetscErrorCode MatFactorInvertSchurComplement(Mat F)
9045: {
9051: if (F->schur_status == MAT_FACTOR_SCHUR_INVERTED) return(0);
9052: MatFactorFactorizeSchurComplement(F);
9053: MatFactorInvertSchurComplement_Private(F);
9054: F->schur_status = MAT_FACTOR_SCHUR_INVERTED;
9055: return(0);
9056: }
9058: /*@
9059: MatFactorFactorizeSchurComplement - Factorize the Schur complement matrix computed during the factorization step
9061: Logically Collective on Mat
9063: Input Parameters:
9064: . F - the factored matrix obtained by calling MatGetFactor()
9066: Notes:
9067: Must be called after MatFactorSetSchurIS().
9069: Level: advanced
9071: References:
9073: .seealso: MatGetFactor(), MatFactorSetSchurIS(), MatFactorInvertSchurComplement()
9074: @*/
9075: PetscErrorCode MatFactorFactorizeSchurComplement(Mat F)
9076: {
9082: if (F->schur_status == MAT_FACTOR_SCHUR_INVERTED || F->schur_status == MAT_FACTOR_SCHUR_FACTORED) return(0);
9083: MatFactorFactorizeSchurComplement_Private(F);
9084: F->schur_status = MAT_FACTOR_SCHUR_FACTORED;
9085: return(0);
9086: }
9088: PetscErrorCode MatPtAP_Basic(Mat A,Mat P,MatReuse scall,PetscReal fill,Mat *C)
9089: {
9090: Mat AP;
9094: PetscInfo2(A,"Mat types %s and %s using basic PtAP\n",((PetscObject)A)->type_name,((PetscObject)P)->type_name);
9095: MatMatMult(A,P,MAT_INITIAL_MATRIX,PETSC_DEFAULT,&AP);
9096: MatTransposeMatMult(P,AP,scall,fill,C);
9097: MatDestroy(&AP);
9098: return(0);
9099: }
9101: /*@
9102: MatPtAP - Creates the matrix product C = P^T * A * P
9104: Neighbor-wise Collective on Mat
9106: Input Parameters:
9107: + A - the matrix
9108: . P - the projection matrix
9109: . scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
9110: - fill - expected fill as ratio of nnz(C)/(nnz(A) + nnz(P)), use PETSC_DEFAULT if you do not have a good estimate
9111: if the result is a dense matrix this is irrelevent
9113: Output Parameters:
9114: . C - the product matrix
9116: Notes:
9117: C will be created and must be destroyed by the user with MatDestroy().
9119: For matrix types without special implementation the function fallbacks to MatMatMult() followed by MatTransposeMatMult().
9121: Level: intermediate
9123: .seealso: MatPtAPSymbolic(), MatPtAPNumeric(), MatMatMult(), MatRARt()
9124: @*/
9125: PetscErrorCode MatPtAP(Mat A,Mat P,MatReuse scall,PetscReal fill,Mat *C)
9126: {
9128: PetscErrorCode (*fA)(Mat,Mat,MatReuse,PetscReal,Mat*);
9129: PetscErrorCode (*fP)(Mat,Mat,MatReuse,PetscReal,Mat*);
9130: PetscErrorCode (*ptap)(Mat,Mat,MatReuse,PetscReal,Mat*)=NULL;
9131: PetscBool sametype;
9136: MatCheckPreallocated(A,1);
9137: if (scall == MAT_INPLACE_MATRIX) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Inplace product not supported");
9138: if (!A->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
9139: if (A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
9142: MatCheckPreallocated(P,2);
9143: if (!P->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
9144: if (P->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
9146: 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);
9147: 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);
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: if (scall == MAT_REUSE_MATRIX) {
9155: PetscLogEventBegin(MAT_PtAP,A,P,0,0);
9156: PetscLogEventBegin(MAT_PtAPNumeric,A,P,0,0);
9157: if ((*C)->ops->ptapnumeric) {
9158: (*(*C)->ops->ptapnumeric)(A,P,*C);
9159: } else {
9160: MatPtAP_Basic(A,P,scall,fill,C);
9161: }
9162: PetscLogEventEnd(MAT_PtAPNumeric,A,P,0,0);
9163: PetscLogEventEnd(MAT_PtAP,A,P,0,0);
9164: return(0);
9165: }
9167: if (fill == PETSC_DEFAULT || fill == PETSC_DECIDE) fill = 2.0;
9168: if (fill < 1.0) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Expected fill=%g must be >= 1.0",(double)fill);
9170: fA = A->ops->ptap;
9171: fP = P->ops->ptap;
9172: PetscStrcmp(((PetscObject)A)->type_name,((PetscObject)P)->type_name,&sametype);
9173: if (fP == fA && sametype) {
9174: ptap = fA;
9175: } else {
9176: /* dispatch based on the type of A and P from their PetscObject's PetscFunctionLists. */
9177: char ptapname[256];
9178: PetscStrncpy(ptapname,"MatPtAP_",sizeof(ptapname));
9179: PetscStrlcat(ptapname,((PetscObject)A)->type_name,sizeof(ptapname));
9180: PetscStrlcat(ptapname,"_",sizeof(ptapname));
9181: PetscStrlcat(ptapname,((PetscObject)P)->type_name,sizeof(ptapname));
9182: PetscStrlcat(ptapname,"_C",sizeof(ptapname)); /* e.g., ptapname = "MatPtAP_seqdense_seqaij_C" */
9183: PetscObjectQueryFunction((PetscObject)P,ptapname,&ptap);
9184: }
9186: if (!ptap) ptap = MatPtAP_Basic;
9187: PetscLogEventBegin(MAT_PtAP,A,P,0,0);
9188: (*ptap)(A,P,scall,fill,C);
9189: PetscLogEventEnd(MAT_PtAP,A,P,0,0);
9190: if (A->symmetric_set && A->symmetric) {
9191: MatSetOption(*C,MAT_SYMMETRIC,PETSC_TRUE);
9192: }
9193: return(0);
9194: }
9196: /*@
9197: MatPtAPNumeric - Computes the matrix product C = P^T * A * P
9199: Neighbor-wise Collective on Mat
9201: Input Parameters:
9202: + A - the matrix
9203: - P - the projection matrix
9205: Output Parameters:
9206: . C - the product matrix
9208: Notes:
9209: C must have been created by calling MatPtAPSymbolic and must be destroyed by
9210: the user using MatDeatroy().
9212: This routine is currently only implemented for pairs of AIJ matrices and classes
9213: which inherit from AIJ. C will be of type MATAIJ.
9215: Level: intermediate
9217: .seealso: MatPtAP(), MatPtAPSymbolic(), MatMatMultNumeric()
9218: @*/
9219: PetscErrorCode MatPtAPNumeric(Mat A,Mat P,Mat C)
9220: {
9226: if (!A->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
9227: if (A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
9230: MatCheckPreallocated(P,2);
9231: if (!P->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
9232: if (P->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
9235: MatCheckPreallocated(C,3);
9236: if (C->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
9237: 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);
9238: 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);
9239: 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);
9240: 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);
9241: MatCheckPreallocated(A,1);
9243: if (!C->ops->ptapnumeric) SETERRQ(PetscObjectComm((PetscObject)C),PETSC_ERR_ARG_WRONGSTATE,"MatPtAPNumeric implementation is missing. You should call MatPtAPSymbolic first");
9244: PetscLogEventBegin(MAT_PtAPNumeric,A,P,0,0);
9245: (*C->ops->ptapnumeric)(A,P,C);
9246: PetscLogEventEnd(MAT_PtAPNumeric,A,P,0,0);
9247: return(0);
9248: }
9250: /*@
9251: MatPtAPSymbolic - Creates the (i,j) structure of the matrix product C = P^T * A * P
9253: Neighbor-wise Collective on Mat
9255: Input Parameters:
9256: + A - the matrix
9257: - P - the projection matrix
9259: Output Parameters:
9260: . C - the (i,j) structure of the product matrix
9262: Notes:
9263: C will be created and must be destroyed by the user with MatDestroy().
9265: This routine is currently only implemented for pairs of SeqAIJ matrices and classes
9266: which inherit from SeqAIJ. C will be of type MATSEQAIJ. The product is computed using
9267: this (i,j) structure by calling MatPtAPNumeric().
9269: Level: intermediate
9271: .seealso: MatPtAP(), MatPtAPNumeric(), MatMatMultSymbolic()
9272: @*/
9273: PetscErrorCode MatPtAPSymbolic(Mat A,Mat P,PetscReal fill,Mat *C)
9274: {
9280: if (!A->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
9281: if (A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
9282: if (fill <1.0) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Expected fill=%g must be >= 1.0",(double)fill);
9285: MatCheckPreallocated(P,2);
9286: if (!P->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
9287: if (P->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
9290: 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);
9291: 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);
9292: MatCheckPreallocated(A,1);
9294: if (!A->ops->ptapsymbolic) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"MatType %s",((PetscObject)A)->type_name);
9295: PetscLogEventBegin(MAT_PtAPSymbolic,A,P,0,0);
9296: (*A->ops->ptapsymbolic)(A,P,fill,C);
9297: PetscLogEventEnd(MAT_PtAPSymbolic,A,P,0,0);
9299: /* MatSetBlockSize(*C,A->rmap->bs); NO! this is not always true -ma */
9300: return(0);
9301: }
9303: /*@
9304: MatRARt - Creates the matrix product C = R * A * R^T
9306: Neighbor-wise Collective on Mat
9308: Input Parameters:
9309: + A - the matrix
9310: . R - the projection matrix
9311: . scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
9312: - fill - expected fill as ratio of nnz(C)/nnz(A), use PETSC_DEFAULT if you do not have a good estimate
9313: if the result is a dense matrix this is irrelevent
9315: Output Parameters:
9316: . C - the product matrix
9318: Notes: