Actual source code: matrix.c

petsc-3.13.0 2020-03-29
Report Typos and Errors
  1: /*
  2:    This is where the abstract matrix operations are defined
  3: */

  5:  #include <petsc/private/matimpl.h>
  6:  #include <petsc/private/isimpl.h>
  7:  #include <petsc/private/vecimpl.h>

  9: /* Logging support */
 10: PetscClassId MAT_CLASSID;
 11: PetscClassId MAT_COLORING_CLASSID;
 12: PetscClassId MAT_FDCOLORING_CLASSID;
 13: PetscClassId MAT_TRANSPOSECOLORING_CLASSID;

 15: PetscLogEvent MAT_Mult, MAT_Mults, MAT_MultConstrained, MAT_MultAdd, MAT_MultTranspose;
 16: PetscLogEvent MAT_MultTransposeConstrained, MAT_MultTransposeAdd, MAT_Solve, MAT_Solves, MAT_SolveAdd, MAT_SolveTranspose, MAT_MatSolve,MAT_MatTrSolve;
 17: PetscLogEvent MAT_SolveTransposeAdd, MAT_SOR, MAT_ForwardSolve, MAT_BackwardSolve, MAT_LUFactor, MAT_LUFactorSymbolic;
 18: PetscLogEvent MAT_LUFactorNumeric, MAT_CholeskyFactor, MAT_CholeskyFactorSymbolic, MAT_CholeskyFactorNumeric, MAT_ILUFactor;
 19: PetscLogEvent MAT_ILUFactorSymbolic, MAT_ICCFactorSymbolic, MAT_Copy, MAT_Convert, MAT_Scale, MAT_AssemblyBegin;
 20: PetscLogEvent MAT_AssemblyEnd, MAT_SetValues, MAT_GetValues, MAT_GetRow, MAT_GetRowIJ, MAT_CreateSubMats, MAT_GetOrdering, MAT_RedundantMat, MAT_GetSeqNonzeroStructure;
 21: PetscLogEvent MAT_IncreaseOverlap, MAT_Partitioning, MAT_PartitioningND, MAT_Coarsen, MAT_ZeroEntries, MAT_Load, MAT_View, MAT_AXPY, MAT_FDColoringCreate;
 22: PetscLogEvent MAT_FDColoringSetUp, MAT_FDColoringApply,MAT_Transpose,MAT_FDColoringFunction, MAT_CreateSubMat;
 23: PetscLogEvent MAT_TransposeColoringCreate;
 24: PetscLogEvent MAT_MatMult, MAT_MatMultSymbolic, MAT_MatMultNumeric;
 25: PetscLogEvent MAT_PtAP, MAT_PtAPSymbolic, MAT_PtAPNumeric,MAT_RARt, MAT_RARtSymbolic, MAT_RARtNumeric;
 26: PetscLogEvent MAT_MatTransposeMult, MAT_MatTransposeMultSymbolic, MAT_MatTransposeMultNumeric;
 27: PetscLogEvent MAT_TransposeMatMult, MAT_TransposeMatMultSymbolic, MAT_TransposeMatMultNumeric;
 28: PetscLogEvent MAT_MatMatMult, MAT_MatMatMultSymbolic, MAT_MatMatMultNumeric;
 29: PetscLogEvent MAT_MultHermitianTranspose,MAT_MultHermitianTransposeAdd;
 30: PetscLogEvent MAT_Getsymtranspose, MAT_Getsymtransreduced, MAT_GetBrowsOfAcols;
 31: PetscLogEvent MAT_GetBrowsOfAocols, MAT_Getlocalmat, MAT_Getlocalmatcondensed, MAT_Seqstompi, MAT_Seqstompinum, MAT_Seqstompisym;
 32: PetscLogEvent MAT_Applypapt, MAT_Applypapt_numeric, MAT_Applypapt_symbolic, MAT_GetSequentialNonzeroStructure;
 33: PetscLogEvent MAT_GetMultiProcBlock;
 34: PetscLogEvent MAT_CUSPARSECopyToGPU, MAT_SetValuesBatch;
 35: PetscLogEvent MAT_ViennaCLCopyToGPU;
 36: PetscLogEvent MAT_DenseCopyToGPU, MAT_DenseCopyFromGPU;
 37: PetscLogEvent MAT_Merge,MAT_Residual,MAT_SetRandom;
 38: PetscLogEvent MAT_FactorFactS,MAT_FactorInvS;
 39: PetscLogEvent MATCOLORING_Apply,MATCOLORING_Comm,MATCOLORING_Local,MATCOLORING_ISCreate,MATCOLORING_SetUp,MATCOLORING_Weights;

 41: const char *const MatFactorTypes[] = {"NONE","LU","CHOLESKY","ILU","ICC","ILUDT","MatFactorType","MAT_FACTOR_",0};

 43: /*@
 44:    MatSetRandom - Sets all components of a matrix to random numbers. For sparse matrices that have been preallocated but not been assembled it randomly selects appropriate locations,
 45:                   for sparse matrices that already have locations it fills the locations with random numbers

 47:    Logically Collective on Mat

 49:    Input Parameters:
 50: +  x  - the matrix
 51: -  rctx - the random number context, formed by PetscRandomCreate(), or NULL and
 52:           it will create one internally.

 54:    Output Parameter:
 55: .  x  - the matrix

 57:    Example of Usage:
 58: .vb
 59:      PetscRandomCreate(PETSC_COMM_WORLD,&rctx);
 60:      MatSetRandom(x,rctx);
 61:      PetscRandomDestroy(rctx);
 62: .ve

 64:    Level: intermediate


 67: .seealso: MatZeroEntries(), MatSetValues(), PetscRandomCreate(), PetscRandomDestroy()
 68: @*/
 69: PetscErrorCode MatSetRandom(Mat x,PetscRandom rctx)
 70: {
 72:   PetscRandom    randObj = NULL;


 79:   if (!x->ops->setrandom) SETERRQ1(PetscObjectComm((PetscObject)x),PETSC_ERR_SUP,"Mat type %s",((PetscObject)x)->type_name);

 81:   if (!rctx) {
 82:     MPI_Comm comm;
 83:     PetscObjectGetComm((PetscObject)x,&comm);
 84:     PetscRandomCreate(comm,&randObj);
 85:     PetscRandomSetFromOptions(randObj);
 86:     rctx = randObj;
 87:   }

 89:   PetscLogEventBegin(MAT_SetRandom,x,rctx,0,0);
 90:   (*x->ops->setrandom)(x,rctx);
 91:   PetscLogEventEnd(MAT_SetRandom,x,rctx,0,0);

 93:   MatAssemblyBegin(x, MAT_FINAL_ASSEMBLY);
 94:   MatAssemblyEnd(x, MAT_FINAL_ASSEMBLY);
 95:   PetscRandomDestroy(&randObj);
 96:   return(0);
 97: }

 99: /*@
100:    MatFactorGetErrorZeroPivot - returns the pivot value that was determined to be zero and the row it occurred in

102:    Logically Collective on Mat

104:    Input Parameters:
105: .  mat - the factored matrix

107:    Output Parameter:
108: +  pivot - the pivot value computed
109: -  row - the row that the zero pivot occurred. Note that this row must be interpreted carefully due to row reorderings and which processes
110:          the share the matrix

112:    Level: advanced

114:    Notes:
115:     This routine does not work for factorizations done with external packages.
116:    This routine should only be called if MatGetFactorError() returns a value of MAT_FACTOR_NUMERIC_ZEROPIVOT

118:    This can be called on non-factored matrices that come from, for example, matrices used in SOR.

120: .seealso: MatZeroEntries(), MatFactor(), MatGetFactor(), MatFactorSymbolic(), MatFactorClearError(), MatFactorGetErrorZeroPivot()
121: @*/
122: PetscErrorCode MatFactorGetErrorZeroPivot(Mat mat,PetscReal *pivot,PetscInt *row)
123: {
126:   *pivot = mat->factorerror_zeropivot_value;
127:   *row   = mat->factorerror_zeropivot_row;
128:   return(0);
129: }

131: /*@
132:    MatFactorGetError - gets the error code from a factorization

134:    Logically Collective on Mat

136:    Input Parameters:
137: .  mat - the factored matrix

139:    Output Parameter:
140: .  err  - the error code

142:    Level: advanced

144:    Notes:
145:     This can be called on non-factored matrices that come from, for example, matrices used in SOR.

147: .seealso: MatZeroEntries(), MatFactor(), MatGetFactor(), MatFactorSymbolic(), MatFactorClearError(), MatFactorGetErrorZeroPivot()
148: @*/
149: PetscErrorCode MatFactorGetError(Mat mat,MatFactorError *err)
150: {
153:   *err = mat->factorerrortype;
154:   return(0);
155: }

157: /*@
158:    MatFactorClearError - clears the error code in a factorization

160:    Logically Collective on Mat

162:    Input Parameter:
163: .  mat - the factored matrix

165:    Level: developer

167:    Notes:
168:     This can be called on non-factored matrices that come from, for example, matrices used in SOR.

170: .seealso: MatZeroEntries(), MatFactor(), MatGetFactor(), MatFactorSymbolic(), MatFactorGetError(), MatFactorGetErrorZeroPivot()
171: @*/
172: PetscErrorCode MatFactorClearError(Mat mat)
173: {
176:   mat->factorerrortype             = MAT_FACTOR_NOERROR;
177:   mat->factorerror_zeropivot_value = 0.0;
178:   mat->factorerror_zeropivot_row   = 0;
179:   return(0);
180: }

182: PETSC_INTERN PetscErrorCode MatFindNonzeroRowsOrCols_Basic(Mat mat,PetscBool cols,PetscReal tol,IS *nonzero)
183: {
184:   PetscErrorCode    ierr;
185:   Vec               r,l;
186:   const PetscScalar *al;
187:   PetscInt          i,nz,gnz,N,n;

190:   MatCreateVecs(mat,&r,&l);
191:   if (!cols) { /* nonzero rows */
192:     MatGetSize(mat,&N,NULL);
193:     MatGetLocalSize(mat,&n,NULL);
194:     VecSet(l,0.0);
195:     VecSetRandom(r,NULL);
196:     MatMult(mat,r,l);
197:     VecGetArrayRead(l,&al);
198:   } else { /* nonzero columns */
199:     MatGetSize(mat,NULL,&N);
200:     MatGetLocalSize(mat,NULL,&n);
201:     VecSet(r,0.0);
202:     VecSetRandom(l,NULL);
203:     MatMultTranspose(mat,l,r);
204:     VecGetArrayRead(r,&al);
205:   }
206:   if (tol <= 0.0) { for (i=0,nz=0;i<n;i++) if (al[i] != 0.0) nz++; }
207:   else { for (i=0,nz=0;i<n;i++) if (PetscAbsScalar(al[i]) > tol) nz++; }
208:   MPIU_Allreduce(&nz,&gnz,1,MPIU_INT,MPI_SUM,PetscObjectComm((PetscObject)mat));
209:   if (gnz != N) {
210:     PetscInt *nzr;
211:     PetscMalloc1(nz,&nzr);
212:     if (nz) {
213:       if (tol < 0) { for (i=0,nz=0;i<n;i++) if (al[i] != 0.0) nzr[nz++] = i; }
214:       else { for (i=0,nz=0;i<n;i++) if (PetscAbsScalar(al[i]) > tol) nzr[nz++] = i; }
215:     }
216:     ISCreateGeneral(PetscObjectComm((PetscObject)mat),nz,nzr,PETSC_OWN_POINTER,nonzero);
217:   } else *nonzero = NULL;
218:   if (!cols) { /* nonzero rows */
219:     VecRestoreArrayRead(l,&al);
220:   } else {
221:     VecRestoreArrayRead(r,&al);
222:   }
223:   VecDestroy(&l);
224:   VecDestroy(&r);
225:   return(0);
226: }

228: /*@
229:       MatFindNonzeroRows - Locate all rows that are not completely zero in the matrix

231:   Input Parameter:
232: .    A  - the matrix

234:   Output Parameter:
235: .    keptrows - the rows that are not completely zero

237:   Notes:
238:     keptrows is set to NULL if all rows are nonzero.

240:   Level: intermediate

242:  @*/
243: PetscErrorCode MatFindNonzeroRows(Mat mat,IS *keptrows)
244: {

251:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
252:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
253:   if (!mat->ops->findnonzerorows) {
254:     MatFindNonzeroRowsOrCols_Basic(mat,PETSC_FALSE,0.0,keptrows);
255:   } else {
256:     (*mat->ops->findnonzerorows)(mat,keptrows);
257:   }
258:   return(0);
259: }

261: /*@
262:       MatFindZeroRows - Locate all rows that are completely zero in the matrix

264:   Input Parameter:
265: .    A  - the matrix

267:   Output Parameter:
268: .    zerorows - the rows that are completely zero

270:   Notes:
271:     zerorows is set to NULL if no rows are zero.

273:   Level: intermediate

275:  @*/
276: PetscErrorCode MatFindZeroRows(Mat mat,IS *zerorows)
277: {
279:   IS keptrows;
280:   PetscInt m, n;


285:   MatFindNonzeroRows(mat, &keptrows);
286:   /* MatFindNonzeroRows sets keptrows to NULL if there are no zero rows.
287:      In keeping with this convention, we set zerorows to NULL if there are no zero
288:      rows. */
289:   if (keptrows == NULL) {
290:     *zerorows = NULL;
291:   } else {
292:     MatGetOwnershipRange(mat,&m,&n);
293:     ISComplement(keptrows,m,n,zerorows);
294:     ISDestroy(&keptrows);
295:   }
296:   return(0);
297: }

299: /*@
300:    MatGetDiagonalBlock - Returns the part of the matrix associated with the on-process coupling

302:    Not Collective

304:    Input Parameters:
305: .   A - the matrix

307:    Output Parameters:
308: .   a - the diagonal part (which is a SEQUENTIAL matrix)

310:    Notes:
311:     see the manual page for MatCreateAIJ() for more information on the "diagonal part" of the matrix.
312:           Use caution, as the reference count on the returned matrix is not incremented and it is used as
313:           part of the containing MPI Mat's normal operation.

315:    Level: advanced

317: @*/
318: PetscErrorCode MatGetDiagonalBlock(Mat A,Mat *a)
319: {

326:   if (A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
327:   if (!A->ops->getdiagonalblock) {
328:     PetscMPIInt size;
329:     MPI_Comm_size(PetscObjectComm((PetscObject)A),&size);
330:     if (size == 1) {
331:       *a = A;
332:       return(0);
333:     } else SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Not coded for matrix type %s",((PetscObject)A)->type_name);
334:   }
335:   (*A->ops->getdiagonalblock)(A,a);
336:   return(0);
337: }

339: /*@
340:    MatGetTrace - Gets the trace of a matrix. The sum of the diagonal entries.

342:    Collective on Mat

344:    Input Parameters:
345: .  mat - the matrix

347:    Output Parameter:
348: .   trace - the sum of the diagonal entries

350:    Level: advanced

352: @*/
353: PetscErrorCode MatGetTrace(Mat mat,PetscScalar *trace)
354: {
356:   Vec            diag;

359:   MatCreateVecs(mat,&diag,NULL);
360:   MatGetDiagonal(mat,diag);
361:   VecSum(diag,trace);
362:   VecDestroy(&diag);
363:   return(0);
364: }

366: /*@
367:    MatRealPart - Zeros out the imaginary part of the matrix

369:    Logically Collective on Mat

371:    Input Parameters:
372: .  mat - the matrix

374:    Level: advanced


377: .seealso: MatImaginaryPart()
378: @*/
379: PetscErrorCode MatRealPart(Mat mat)
380: {

386:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
387:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
388:   if (!mat->ops->realpart) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
389:   MatCheckPreallocated(mat,1);
390:   (*mat->ops->realpart)(mat);
391:   return(0);
392: }

394: /*@C
395:    MatGetGhosts - Get the global index of all ghost nodes defined by the sparse matrix

397:    Collective on Mat

399:    Input Parameter:
400: .  mat - the matrix

402:    Output Parameters:
403: +   nghosts - number of ghosts (note for BAIJ matrices there is one ghost for each block)
404: -   ghosts - the global indices of the ghost points

406:    Notes:
407:     the nghosts and ghosts are suitable to pass into VecCreateGhost()

409:    Level: advanced

411: @*/
412: PetscErrorCode MatGetGhosts(Mat mat,PetscInt *nghosts,const PetscInt *ghosts[])
413: {

419:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
420:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
421:   if (!mat->ops->getghosts) {
422:     if (nghosts) *nghosts = 0;
423:     if (ghosts) *ghosts = 0;
424:   } else {
425:     (*mat->ops->getghosts)(mat,nghosts,ghosts);
426:   }
427:   return(0);
428: }


431: /*@
432:    MatImaginaryPart - Moves the imaginary part of the matrix to the real part and zeros the imaginary part

434:    Logically Collective on Mat

436:    Input Parameters:
437: .  mat - the matrix

439:    Level: advanced


442: .seealso: MatRealPart()
443: @*/
444: PetscErrorCode MatImaginaryPart(Mat mat)
445: {

451:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
452:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
453:   if (!mat->ops->imaginarypart) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
454:   MatCheckPreallocated(mat,1);
455:   (*mat->ops->imaginarypart)(mat);
456:   return(0);
457: }

459: /*@
460:    MatMissingDiagonal - Determine if sparse matrix is missing a diagonal entry (or block entry for BAIJ matrices)

462:    Not Collective

464:    Input Parameter:
465: .  mat - the matrix

467:    Output Parameters:
468: +  missing - is any diagonal missing
469: -  dd - first diagonal entry that is missing (optional) on this process

471:    Level: advanced


474: .seealso: MatRealPart()
475: @*/
476: PetscErrorCode MatMissingDiagonal(Mat mat,PetscBool *missing,PetscInt *dd)
477: {

484:   if (!mat->assembled) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix %s",((PetscObject)mat)->type_name);
485:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
486:   if (!mat->ops->missingdiagonal) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
487:   (*mat->ops->missingdiagonal)(mat,missing,dd);
488:   return(0);
489: }

491: /*@C
492:    MatGetRow - Gets a row of a matrix.  You MUST call MatRestoreRow()
493:    for each row that you get to ensure that your application does
494:    not bleed memory.

496:    Not Collective

498:    Input Parameters:
499: +  mat - the matrix
500: -  row - the row to get

502:    Output Parameters:
503: +  ncols -  if not NULL, the number of nonzeros in the row
504: .  cols - if not NULL, the column numbers
505: -  vals - if not NULL, the values

507:    Notes:
508:    This routine is provided for people who need to have direct access
509:    to the structure of a matrix.  We hope that we provide enough
510:    high-level matrix routines that few users will need it.

512:    MatGetRow() always returns 0-based column indices, regardless of
513:    whether the internal representation is 0-based (default) or 1-based.

515:    For better efficiency, set cols and/or vals to NULL if you do
516:    not wish to extract these quantities.

518:    The user can only examine the values extracted with MatGetRow();
519:    the values cannot be altered.  To change the matrix entries, one
520:    must use MatSetValues().

522:    You can only have one call to MatGetRow() outstanding for a particular
523:    matrix at a time, per processor. MatGetRow() can only obtain rows
524:    associated with the given processor, it cannot get rows from the
525:    other processors; for that we suggest using MatCreateSubMatrices(), then
526:    MatGetRow() on the submatrix. The row index passed to MatGetRow()
527:    is in the global number of rows.

529:    Fortran Notes:
530:    The calling sequence from Fortran is
531: .vb
532:    MatGetRow(matrix,row,ncols,cols,values,ierr)
533:          Mat     matrix (input)
534:          integer row    (input)
535:          integer ncols  (output)
536:          integer cols(maxcols) (output)
537:          double precision (or double complex) values(maxcols) output
538: .ve
539:    where maxcols >= maximum nonzeros in any row of the matrix.


542:    Caution:
543:    Do not try to change the contents of the output arrays (cols and vals).
544:    In some cases, this may corrupt the matrix.

546:    Level: advanced

548: .seealso: MatRestoreRow(), MatSetValues(), MatGetValues(), MatCreateSubMatrices(), MatGetDiagonal()
549: @*/
550: PetscErrorCode MatGetRow(Mat mat,PetscInt row,PetscInt *ncols,const PetscInt *cols[],const PetscScalar *vals[])
551: {
553:   PetscInt       incols;

558:   if (!mat->assembled) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
559:   if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
560:   if (!mat->ops->getrow) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
561:   MatCheckPreallocated(mat,1);
562:   PetscLogEventBegin(MAT_GetRow,mat,0,0,0);
563:   (*mat->ops->getrow)(mat,row,&incols,(PetscInt**)cols,(PetscScalar**)vals);
564:   if (ncols) *ncols = incols;
565:   PetscLogEventEnd(MAT_GetRow,mat,0,0,0);
566:   return(0);
567: }

569: /*@
570:    MatConjugate - replaces the matrix values with their complex conjugates

572:    Logically Collective on Mat

574:    Input Parameters:
575: .  mat - the matrix

577:    Level: advanced

579: .seealso:  VecConjugate()
580: @*/
581: PetscErrorCode MatConjugate(Mat mat)
582: {
583: #if defined(PETSC_USE_COMPLEX)

588:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
589:   if (!mat->ops->conjugate) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Not provided for matrix type %s, send email to petsc-maint@mcs.anl.gov",((PetscObject)mat)->type_name);
590:   (*mat->ops->conjugate)(mat);
591: #else
593: #endif
594:   return(0);
595: }

597: /*@C
598:    MatRestoreRow - Frees any temporary space allocated by MatGetRow().

600:    Not Collective

602:    Input Parameters:
603: +  mat - the matrix
604: .  row - the row to get
605: .  ncols, cols - the number of nonzeros and their columns
606: -  vals - if nonzero the column values

608:    Notes:
609:    This routine should be called after you have finished examining the entries.

611:    This routine zeros out ncols, cols, and vals. This is to prevent accidental
612:    us of the array after it has been restored. If you pass NULL, it will
613:    not zero the pointers.  Use of cols or vals after MatRestoreRow is invalid.

615:    Fortran Notes:
616:    The calling sequence from Fortran is
617: .vb
618:    MatRestoreRow(matrix,row,ncols,cols,values,ierr)
619:       Mat     matrix (input)
620:       integer row    (input)
621:       integer ncols  (output)
622:       integer cols(maxcols) (output)
623:       double precision (or double complex) values(maxcols) output
624: .ve
625:    Where maxcols >= maximum nonzeros in any row of the matrix.

627:    In Fortran MatRestoreRow() MUST be called after MatGetRow()
628:    before another call to MatGetRow() can be made.

630:    Level: advanced

632: .seealso:  MatGetRow()
633: @*/
634: PetscErrorCode MatRestoreRow(Mat mat,PetscInt row,PetscInt *ncols,const PetscInt *cols[],const PetscScalar *vals[])
635: {

641:   if (!mat->assembled) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
642:   if (!mat->ops->restorerow) return(0);
643:   (*mat->ops->restorerow)(mat,row,ncols,(PetscInt **)cols,(PetscScalar **)vals);
644:   if (ncols) *ncols = 0;
645:   if (cols)  *cols = NULL;
646:   if (vals)  *vals = NULL;
647:   return(0);
648: }

650: /*@
651:    MatGetRowUpperTriangular - Sets a flag to enable calls to MatGetRow() for matrix in MATSBAIJ format.
652:    You should call MatRestoreRowUpperTriangular() after calling MatGetRow/MatRestoreRow() to disable the flag.

654:    Not Collective

656:    Input Parameters:
657: .  mat - the matrix

659:    Notes:
660:    The flag is to ensure that users are aware of MatGetRow() only provides the upper triangular part of the row for the matrices in MATSBAIJ format.

662:    Level: advanced

664: .seealso: MatRestoreRowUpperTriangular()
665: @*/
666: PetscErrorCode MatGetRowUpperTriangular(Mat mat)
667: {

673:   if (!mat->assembled) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
674:   if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
675:   MatCheckPreallocated(mat,1);
676:   if (!mat->ops->getrowuppertriangular) return(0);
677:   (*mat->ops->getrowuppertriangular)(mat);
678:   return(0);
679: }

681: /*@
682:    MatRestoreRowUpperTriangular - Disable calls to MatGetRow() for matrix in MATSBAIJ format.

684:    Not Collective

686:    Input Parameters:
687: .  mat - the matrix

689:    Notes:
690:    This routine should be called after you have finished MatGetRow/MatRestoreRow().


693:    Level: advanced

695: .seealso:  MatGetRowUpperTriangular()
696: @*/
697: PetscErrorCode MatRestoreRowUpperTriangular(Mat mat)
698: {

704:   if (!mat->assembled) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
705:   if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
706:   MatCheckPreallocated(mat,1);
707:   if (!mat->ops->restorerowuppertriangular) return(0);
708:   (*mat->ops->restorerowuppertriangular)(mat);
709:   return(0);
710: }

712: /*@C
713:    MatSetOptionsPrefix - Sets the prefix used for searching for all
714:    Mat options in the database.

716:    Logically Collective on Mat

718:    Input Parameter:
719: +  A - the Mat context
720: -  prefix - the prefix to prepend to all option names

722:    Notes:
723:    A hyphen (-) must NOT be given at the beginning of the prefix name.
724:    The first character of all runtime options is AUTOMATICALLY the hyphen.

726:    Level: advanced

728: .seealso: MatSetFromOptions()
729: @*/
730: PetscErrorCode MatSetOptionsPrefix(Mat A,const char prefix[])
731: {

736:   PetscObjectSetOptionsPrefix((PetscObject)A,prefix);
737:   return(0);
738: }

740: /*@C
741:    MatAppendOptionsPrefix - Appends to the prefix used for searching for all
742:    Mat options in the database.

744:    Logically Collective on Mat

746:    Input Parameters:
747: +  A - the Mat context
748: -  prefix - the prefix to prepend to all option names

750:    Notes:
751:    A hyphen (-) must NOT be given at the beginning of the prefix name.
752:    The first character of all runtime options is AUTOMATICALLY the hyphen.

754:    Level: advanced

756: .seealso: MatGetOptionsPrefix()
757: @*/
758: PetscErrorCode MatAppendOptionsPrefix(Mat A,const char prefix[])
759: {

764:   PetscObjectAppendOptionsPrefix((PetscObject)A,prefix);
765:   return(0);
766: }

768: /*@C
769:    MatGetOptionsPrefix - Gets the prefix used for searching for all
770:    Mat options in the database.

772:    Not Collective

774:    Input Parameter:
775: .  A - the Mat context

777:    Output Parameter:
778: .  prefix - pointer to the prefix string used

780:    Notes:
781:     On the fortran side, the user should pass in a string 'prefix' of
782:    sufficient length to hold the prefix.

784:    Level: advanced

786: .seealso: MatAppendOptionsPrefix()
787: @*/
788: PetscErrorCode MatGetOptionsPrefix(Mat A,const char *prefix[])
789: {

794:   PetscObjectGetOptionsPrefix((PetscObject)A,prefix);
795:   return(0);
796: }

798: /*@
799:    MatResetPreallocation - Reset mat to use the original nonzero pattern provided by users.

801:    Collective on Mat

803:    Input Parameters:
804: .  A - the Mat context

806:    Notes:
807:    The allocated memory will be shrunk after calling MatAssembly with MAT_FINAL_ASSEMBLY. Users can reset the preallocation to access the original memory.
808:    Currently support MPIAIJ and SEQAIJ.

810:    Level: beginner

812: .seealso: MatSeqAIJSetPreallocation(), MatMPIAIJSetPreallocation(), MatXAIJSetPreallocation()
813: @*/
814: PetscErrorCode MatResetPreallocation(Mat A)
815: {

821:   PetscUseMethod(A,"MatResetPreallocation_C",(Mat),(A));
822:   return(0);
823: }


826: /*@
827:    MatSetUp - Sets up the internal matrix data structures for later use.

829:    Collective on Mat

831:    Input Parameters:
832: .  A - the Mat context

834:    Notes:
835:    If the user has not set preallocation for this matrix then a default preallocation that is likely to be inefficient is used.

837:    If a suitable preallocation routine is used, this function does not need to be called.

839:    See the Performance chapter of the PETSc users manual for how to preallocate matrices

841:    Level: beginner

843: .seealso: MatCreate(), MatDestroy()
844: @*/
845: PetscErrorCode MatSetUp(Mat A)
846: {
847:   PetscMPIInt    size;

852:   if (!((PetscObject)A)->type_name) {
853:     MPI_Comm_size(PetscObjectComm((PetscObject)A), &size);
854:     if (size == 1) {
855:       MatSetType(A, MATSEQAIJ);
856:     } else {
857:       MatSetType(A, MATMPIAIJ);
858:     }
859:   }
860:   if (!A->preallocated && A->ops->setup) {
861:     PetscInfo(A,"Warning not preallocating matrix storage\n");
862:     (*A->ops->setup)(A);
863:   }
864:   PetscLayoutSetUp(A->rmap);
865:   PetscLayoutSetUp(A->cmap);
866:   A->preallocated = PETSC_TRUE;
867:   return(0);
868: }

870: #if defined(PETSC_HAVE_SAWS)
871:  #include <petscviewersaws.h>
872: #endif

874: /*@C
875:    MatViewFromOptions - View from Options

877:    Collective on Mat

879:    Input Parameters:
880: +  A - the Mat context
881: .  obj - Optional object
882: -  name - command line option

884:    Level: intermediate
885: .seealso:  Mat, MatView, PetscObjectViewFromOptions(), MatCreate()
886: @*/
887: PetscErrorCode  MatViewFromOptions(Mat A,PetscObject obj,const char name[])
888: {

893:   PetscObjectViewFromOptions((PetscObject)A,obj,name);
894:   return(0);
895: }

897: /*@C
898:    MatView - Visualizes a matrix object.

900:    Collective on Mat

902:    Input Parameters:
903: +  mat - the matrix
904: -  viewer - visualization context

906:   Notes:
907:   The available visualization contexts include
908: +    PETSC_VIEWER_STDOUT_SELF - for sequential matrices
909: .    PETSC_VIEWER_STDOUT_WORLD - for parallel matrices created on PETSC_COMM_WORLD
910: .    PETSC_VIEWER_STDOUT_(comm) - for matrices created on MPI communicator comm
911: -     PETSC_VIEWER_DRAW_WORLD - graphical display of nonzero structure

913:    The user can open alternative visualization contexts with
914: +    PetscViewerASCIIOpen() - Outputs matrix to a specified file
915: .    PetscViewerBinaryOpen() - Outputs matrix in binary to a
916:          specified file; corresponding input uses MatLoad()
917: .    PetscViewerDrawOpen() - Outputs nonzero matrix structure to
918:          an X window display
919: -    PetscViewerSocketOpen() - Outputs matrix to Socket viewer.
920:          Currently only the sequential dense and AIJ
921:          matrix types support the Socket viewer.

923:    The user can call PetscViewerPushFormat() to specify the output
924:    format of ASCII printed objects (when using PETSC_VIEWER_STDOUT_SELF,
925:    PETSC_VIEWER_STDOUT_WORLD and PetscViewerASCIIOpen).  Available formats include
926: +    PETSC_VIEWER_DEFAULT - default, prints matrix contents
927: .    PETSC_VIEWER_ASCII_MATLAB - prints matrix contents in Matlab format
928: .    PETSC_VIEWER_ASCII_DENSE - prints entire matrix including zeros
929: .    PETSC_VIEWER_ASCII_COMMON - prints matrix contents, using a sparse
930:          format common among all matrix types
931: .    PETSC_VIEWER_ASCII_IMPL - prints matrix contents, using an implementation-specific
932:          format (which is in many cases the same as the default)
933: .    PETSC_VIEWER_ASCII_INFO - prints basic information about the matrix
934:          size and structure (not the matrix entries)
935: -    PETSC_VIEWER_ASCII_INFO_DETAIL - prints more detailed information about
936:          the matrix structure

938:    Options Database Keys:
939: +  -mat_view ::ascii_info - Prints info on matrix at conclusion of MatAssemblyEnd()
940: .  -mat_view ::ascii_info_detail - Prints more detailed info
941: .  -mat_view - Prints matrix in ASCII format
942: .  -mat_view ::ascii_matlab - Prints matrix in Matlab format
943: .  -mat_view draw - PetscDraws nonzero structure of matrix, using MatView() and PetscDrawOpenX().
944: .  -display <name> - Sets display name (default is host)
945: .  -draw_pause <sec> - Sets number of seconds to pause after display
946: .  -mat_view socket - Sends matrix to socket, can be accessed from Matlab (see Users-Manual: Chapter 12 Using MATLAB with PETSc for details)
947: .  -viewer_socket_machine <machine> -
948: .  -viewer_socket_port <port> -
949: .  -mat_view binary - save matrix to file in binary format
950: -  -viewer_binary_filename <name> -
951:    Level: beginner

953:    Notes:
954:     The ASCII viewers are only recommended for small matrices on at most a moderate number of processes,
955:     the program will seemingly hang and take hours for larger matrices, for larger matrices one should use the binary format.

957:     See the manual page for MatLoad() for the exact format of the binary file when the binary
958:       viewer is used.

960:       See share/petsc/matlab/PetscBinaryRead.m for a Matlab code that can read in the binary file when the binary
961:       viewer is used.

963:       One can use '-mat_view draw -draw_pause -1' to pause the graphical display of matrix nonzero structure,
964:       and then use the following mouse functions.
965: + left mouse: zoom in
966: . middle mouse: zoom out
967: - right mouse: continue with the simulation

969: .seealso: PetscViewerPushFormat(), PetscViewerASCIIOpen(), PetscViewerDrawOpen(),
970:           PetscViewerSocketOpen(), PetscViewerBinaryOpen(), MatLoad()
971: @*/
972: PetscErrorCode MatView(Mat mat,PetscViewer viewer)
973: {
974:   PetscErrorCode    ierr;
975:   PetscInt          rows,cols,rbs,cbs;
976:   PetscBool         isascii,isstring,issaws;
977:   PetscViewerFormat format;
978:   PetscMPIInt       size;

983:   if (!viewer) {PetscViewerASCIIGetStdout(PetscObjectComm((PetscObject)mat),&viewer);}
986:   MatCheckPreallocated(mat,1);

988:   PetscViewerGetFormat(viewer,&format);
989:   MPI_Comm_size(PetscObjectComm((PetscObject)mat),&size);
990:   if (size == 1 && format == PETSC_VIEWER_LOAD_BALANCE) return(0);

992:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERSTRING,&isstring);
993:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERASCII,&isascii);
994:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERSAWS,&issaws);
995:   if ((!isascii || (format != PETSC_VIEWER_ASCII_INFO || format == PETSC_VIEWER_ASCII_INFO_DETAIL)) && mat->factortype) {
996:     SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"No viewers for factored matrix except ASCII info or info_detail");
997:   }

999:   PetscLogEventBegin(MAT_View,mat,viewer,0,0);
1000:   if (isascii) {
1001:     if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ORDER,"Must call MatAssemblyBegin/End() before viewing matrix");
1002:     PetscObjectPrintClassNamePrefixType((PetscObject)mat,viewer);
1003:     if (format == PETSC_VIEWER_ASCII_INFO || format == PETSC_VIEWER_ASCII_INFO_DETAIL) {
1004:       MatNullSpace nullsp,transnullsp;

1006:       PetscViewerASCIIPushTab(viewer);
1007:       MatGetSize(mat,&rows,&cols);
1008:       MatGetBlockSizes(mat,&rbs,&cbs);
1009:       if (rbs != 1 || cbs != 1) {
1010:         if (rbs != cbs) {PetscViewerASCIIPrintf(viewer,"rows=%D, cols=%D, rbs=%D, cbs=%D\n",rows,cols,rbs,cbs);}
1011:         else            {PetscViewerASCIIPrintf(viewer,"rows=%D, cols=%D, bs=%D\n",rows,cols,rbs);}
1012:       } else {
1013:         PetscViewerASCIIPrintf(viewer,"rows=%D, cols=%D\n",rows,cols);
1014:       }
1015:       if (mat->factortype) {
1016:         MatSolverType solver;
1017:         MatFactorGetSolverType(mat,&solver);
1018:         PetscViewerASCIIPrintf(viewer,"package used to perform factorization: %s\n",solver);
1019:       }
1020:       if (mat->ops->getinfo) {
1021:         MatInfo info;
1022:         MatGetInfo(mat,MAT_GLOBAL_SUM,&info);
1023:         PetscViewerASCIIPrintf(viewer,"total: nonzeros=%.f, allocated nonzeros=%.f\n",info.nz_used,info.nz_allocated);
1024:         PetscViewerASCIIPrintf(viewer,"total number of mallocs used during MatSetValues calls=%D\n",(PetscInt)info.mallocs);
1025:       }
1026:       MatGetNullSpace(mat,&nullsp);
1027:       MatGetTransposeNullSpace(mat,&transnullsp);
1028:       if (nullsp) {PetscViewerASCIIPrintf(viewer,"  has attached null space\n");}
1029:       if (transnullsp && transnullsp != nullsp) {PetscViewerASCIIPrintf(viewer,"  has attached transposed null space\n");}
1030:       MatGetNearNullSpace(mat,&nullsp);
1031:       if (nullsp) {PetscViewerASCIIPrintf(viewer,"  has attached near null space\n");}
1032:     }
1033:   } else if (issaws) {
1034: #if defined(PETSC_HAVE_SAWS)
1035:     PetscMPIInt rank;

1037:     PetscObjectName((PetscObject)mat);
1038:     MPI_Comm_rank(PETSC_COMM_WORLD,&rank);
1039:     if (!((PetscObject)mat)->amsmem && !rank) {
1040:       PetscObjectViewSAWs((PetscObject)mat,viewer);
1041:     }
1042: #endif
1043:   } else if (isstring) {
1044:     const char *type;
1045:     MatGetType(mat,&type);
1046:     PetscViewerStringSPrintf(viewer," MatType: %-7.7s",type);
1047:     if (mat->ops->view) {(*mat->ops->view)(mat,viewer);}
1048:   }
1049:   if ((format == PETSC_VIEWER_NATIVE || format == PETSC_VIEWER_LOAD_BALANCE) && mat->ops->viewnative) {
1050:     PetscViewerASCIIPushTab(viewer);
1051:     (*mat->ops->viewnative)(mat,viewer);
1052:     PetscViewerASCIIPopTab(viewer);
1053:   } else if (mat->ops->view) {
1054:     PetscViewerASCIIPushTab(viewer);
1055:     (*mat->ops->view)(mat,viewer);
1056:     PetscViewerASCIIPopTab(viewer);
1057:   }
1058:   if (isascii) {
1059:     PetscViewerGetFormat(viewer,&format);
1060:     if (format == PETSC_VIEWER_ASCII_INFO || format == PETSC_VIEWER_ASCII_INFO_DETAIL) {
1061:       PetscViewerASCIIPopTab(viewer);
1062:     }
1063:   }
1064:   PetscLogEventEnd(MAT_View,mat,viewer,0,0);
1065:   return(0);
1066: }

1068: #if defined(PETSC_USE_DEBUG)
1069: #include <../src/sys/totalview/tv_data_display.h>
1070: PETSC_UNUSED static int TV_display_type(const struct _p_Mat *mat)
1071: {
1072:   TV_add_row("Local rows", "int", &mat->rmap->n);
1073:   TV_add_row("Local columns", "int", &mat->cmap->n);
1074:   TV_add_row("Global rows", "int", &mat->rmap->N);
1075:   TV_add_row("Global columns", "int", &mat->cmap->N);
1076:   TV_add_row("Typename", TV_ascii_string_type, ((PetscObject)mat)->type_name);
1077:   return TV_format_OK;
1078: }
1079: #endif

1081: /*@C
1082:    MatLoad - Loads a matrix that has been stored in binary/HDF5 format
1083:    with MatView().  The matrix format is determined from the options database.
1084:    Generates a parallel MPI matrix if the communicator has more than one
1085:    processor.  The default matrix type is AIJ.

1087:    Collective on PetscViewer

1089:    Input Parameters:
1090: +  mat - the newly loaded matrix, this needs to have been created with MatCreate()
1091:             or some related function before a call to MatLoad()
1092: -  viewer - binary/HDF5 file viewer

1094:    Options Database Keys:
1095:    Used with block matrix formats (MATSEQBAIJ,  ...) to specify
1096:    block size
1097: .    -matload_block_size <bs>

1099:    Level: beginner

1101:    Notes:
1102:    If the Mat type has not yet been given then MATAIJ is used, call MatSetFromOptions() on the
1103:    Mat before calling this routine if you wish to set it from the options database.

1105:    MatLoad() automatically loads into the options database any options
1106:    given in the file filename.info where filename is the name of the file
1107:    that was passed to the PetscViewerBinaryOpen(). The options in the info
1108:    file will be ignored if you use the -viewer_binary_skip_info option.

1110:    If the type or size of mat is not set before a call to MatLoad, PETSc
1111:    sets the default matrix type AIJ and sets the local and global sizes.
1112:    If type and/or size is already set, then the same are used.

1114:    In parallel, each processor can load a subset of rows (or the
1115:    entire matrix).  This routine is especially useful when a large
1116:    matrix is stored on disk and only part of it is desired on each
1117:    processor.  For example, a parallel solver may access only some of
1118:    the rows from each processor.  The algorithm used here reads
1119:    relatively small blocks of data rather than reading the entire
1120:    matrix and then subsetting it.

1122:    Viewer's PetscViewerType must be either PETSCVIEWERBINARY or PETSCVIEWERHDF5.
1123:    Such viewer can be created using PetscViewerBinaryOpen()/PetscViewerHDF5Open(),
1124:    or the sequence like
1125: $    PetscViewer v;
1126: $    PetscViewerCreate(PETSC_COMM_WORLD,&v);
1127: $    PetscViewerSetType(v,PETSCVIEWERBINARY);
1128: $    PetscViewerSetFromOptions(v);
1129: $    PetscViewerFileSetMode(v,FILE_MODE_READ);
1130: $    PetscViewerFileSetName(v,"datafile");
1131:    The optional PetscViewerSetFromOptions() call allows to override PetscViewerSetType() using option
1132: $ -viewer_type {binary,hdf5}

1134:    See the example src/ksp/ksp/tutorials/ex27.c with the first approach,
1135:    and src/mat/tutorials/ex10.c with the second approach.

1137:    Notes about the PETSc binary format:
1138:    In case of PETSCVIEWERBINARY, a native PETSc binary format is used. Each of the blocks
1139:    is read onto rank 0 and then shipped to its destination rank, one after another.
1140:    Multiple objects, both matrices and vectors, can be stored within the same file.
1141:    Their PetscObject name is ignored; they are loaded in the order of their storage.

1143:    Most users should not need to know the details of the binary storage
1144:    format, since MatLoad() and MatView() completely hide these details.
1145:    But for anyone who's interested, the standard binary matrix storage
1146:    format is

1148: $    PetscInt    MAT_FILE_CLASSID
1149: $    PetscInt    number of rows
1150: $    PetscInt    number of columns
1151: $    PetscInt    total number of nonzeros
1152: $    PetscInt    *number nonzeros in each row
1153: $    PetscInt    *column indices of all nonzeros (starting index is zero)
1154: $    PetscScalar *values of all nonzeros

1156:    PETSc automatically does the byte swapping for
1157: machines that store the bytes reversed, e.g.  DEC alpha, freebsd,
1158: linux, Windows and the paragon; thus if you write your own binary
1159: read/write routines you have to swap the bytes; see PetscBinaryRead()
1160: and PetscBinaryWrite() to see how this may be done.

1162:    Notes about the HDF5 (MATLAB MAT-File Version 7.3) format:
1163:    In case of PETSCVIEWERHDF5, a parallel HDF5 reader is used.
1164:    Each processor's chunk is loaded independently by its owning rank.
1165:    Multiple objects, both matrices and vectors, can be stored within the same file.
1166:    They are looked up by their PetscObject name.

1168:    As the MATLAB MAT-File Version 7.3 format is also a HDF5 flavor, we decided to use
1169:    by default the same structure and naming of the AIJ arrays and column count
1170:    within the HDF5 file. This means that a MAT file saved with -v7.3 flag, e.g.
1171: $    save example.mat A b -v7.3
1172:    can be directly read by this routine (see Reference 1 for details).
1173:    Note that depending on your MATLAB version, this format might be a default,
1174:    otherwise you can set it as default in Preferences.

1176:    Unless -nocompression flag is used to save the file in MATLAB,
1177:    PETSc must be configured with ZLIB package.

1179:    See also examples src/mat/tutorials/ex10.c and src/ksp/ksp/tutorials/ex27.c

1181:    Current HDF5 (MAT-File) limitations:
1182:    This reader currently supports only real MATSEQAIJ, MATMPIAIJ, MATSEQDENSE and MATMPIDENSE matrices.

1184:    Corresponding MatView() is not yet implemented.

1186:    The loaded matrix is actually a transpose of the original one in MATLAB,
1187:    unless you push PETSC_VIEWER_HDF5_MAT format (see examples above).
1188:    With this format, matrix is automatically transposed by PETSc,
1189:    unless the matrix is marked as SPD or symmetric
1190:    (see MatSetOption(), MAT_SPD, MAT_SYMMETRIC).

1192:    References:
1193: 1. MATLAB(R) Documentation, manual page of save(), https://www.mathworks.com/help/matlab/ref/save.html#btox10b-1-version

1195: .seealso: PetscViewerBinaryOpen(), PetscViewerSetType(), MatView(), VecLoad()

1197:  @*/
1198: PetscErrorCode MatLoad(Mat mat,PetscViewer viewer)
1199: {
1201:   PetscBool      flg;


1207:   if (!((PetscObject)mat)->type_name) {
1208:     MatSetType(mat,MATAIJ);
1209:   }

1211:   flg  = PETSC_FALSE;
1212:   PetscOptionsGetBool(((PetscObject)mat)->options,((PetscObject)mat)->prefix,"-matload_symmetric",&flg,NULL);
1213:   if (flg) {
1214:     MatSetOption(mat,MAT_SYMMETRIC,PETSC_TRUE);
1215:     MatSetOption(mat,MAT_SYMMETRY_ETERNAL,PETSC_TRUE);
1216:   }
1217:   flg  = PETSC_FALSE;
1218:   PetscOptionsGetBool(((PetscObject)mat)->options,((PetscObject)mat)->prefix,"-matload_spd",&flg,NULL);
1219:   if (flg) {
1220:     MatSetOption(mat,MAT_SPD,PETSC_TRUE);
1221:   }

1223:   if (!mat->ops->load) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"MatLoad is not supported for type %s",((PetscObject)mat)->type_name);
1224:   PetscLogEventBegin(MAT_Load,mat,viewer,0,0);
1225:   (*mat->ops->load)(mat,viewer);
1226:   PetscLogEventEnd(MAT_Load,mat,viewer,0,0);
1227:   return(0);
1228: }

1230: static PetscErrorCode MatDestroy_Redundant(Mat_Redundant **redundant)
1231: {
1233:   Mat_Redundant  *redund = *redundant;
1234:   PetscInt       i;

1237:   if (redund){
1238:     if (redund->matseq) { /* via MatCreateSubMatrices()  */
1239:       ISDestroy(&redund->isrow);
1240:       ISDestroy(&redund->iscol);
1241:       MatDestroySubMatrices(1,&redund->matseq);
1242:     } else {
1243:       PetscFree2(redund->send_rank,redund->recv_rank);
1244:       PetscFree(redund->sbuf_j);
1245:       PetscFree(redund->sbuf_a);
1246:       for (i=0; i<redund->nrecvs; i++) {
1247:         PetscFree(redund->rbuf_j[i]);
1248:         PetscFree(redund->rbuf_a[i]);
1249:       }
1250:       PetscFree4(redund->sbuf_nz,redund->rbuf_nz,redund->rbuf_j,redund->rbuf_a);
1251:     }

1253:     if (redund->subcomm) {
1254:       PetscCommDestroy(&redund->subcomm);
1255:     }
1256:     PetscFree(redund);
1257:   }
1258:   return(0);
1259: }

1261: /*@
1262:    MatDestroy - Frees space taken by a matrix.

1264:    Collective on Mat

1266:    Input Parameter:
1267: .  A - the matrix

1269:    Level: beginner

1271: @*/
1272: PetscErrorCode MatDestroy(Mat *A)
1273: {

1277:   if (!*A) return(0);
1279:   if (--((PetscObject)(*A))->refct > 0) {*A = NULL; return(0);}

1281:   /* if memory was published with SAWs then destroy it */
1282:   PetscObjectSAWsViewOff((PetscObject)*A);
1283:   if ((*A)->ops->destroy) {
1284:     (*(*A)->ops->destroy)(*A);
1285:   }

1287:   PetscFree((*A)->defaultvectype);
1288:   PetscFree((*A)->bsizes);
1289:   PetscFree((*A)->solvertype);
1290:   MatDestroy_Redundant(&(*A)->redundant);
1291:   if ((*A)->product) {
1292:     Mat_Product  *product = (*A)->product;
1293:     MatDestroy(&product->Dwork);
1294:     PetscFree(product);
1295:   }

1297:   MatNullSpaceDestroy(&(*A)->nullsp);
1298:   MatNullSpaceDestroy(&(*A)->transnullsp);
1299:   MatNullSpaceDestroy(&(*A)->nearnullsp);
1300:   MatDestroy(&(*A)->schur);
1301:   PetscLayoutDestroy(&(*A)->rmap);
1302:   PetscLayoutDestroy(&(*A)->cmap);
1303:   PetscHeaderDestroy(A);
1304:   return(0);
1305: }

1307: /*@C
1308:    MatSetValues - Inserts or adds a block of values into a matrix.
1309:    These values may be cached, so MatAssemblyBegin() and MatAssemblyEnd()
1310:    MUST be called after all calls to MatSetValues() have been completed.

1312:    Not Collective

1314:    Input Parameters:
1315: +  mat - the matrix
1316: .  v - a logically two-dimensional array of values
1317: .  m, idxm - the number of rows and their global indices
1318: .  n, idxn - the number of columns and their global indices
1319: -  addv - either ADD_VALUES or INSERT_VALUES, where
1320:    ADD_VALUES adds values to any existing entries, and
1321:    INSERT_VALUES replaces existing entries with new values

1323:    Notes:
1324:    If you create the matrix yourself (that is not with a call to DMCreateMatrix()) then you MUST call MatXXXXSetPreallocation() or
1325:       MatSetUp() before using this routine

1327:    By default the values, v, are row-oriented. See MatSetOption() for other options.

1329:    Calls to MatSetValues() with the INSERT_VALUES and ADD_VALUES
1330:    options cannot be mixed without intervening calls to the assembly
1331:    routines.

1333:    MatSetValues() uses 0-based row and column numbers in Fortran
1334:    as well as in C.

1336:    Negative indices may be passed in idxm and idxn, these rows and columns are
1337:    simply ignored. This allows easily inserting element stiffness matrices
1338:    with homogeneous Dirchlet boundary conditions that you don't want represented
1339:    in the matrix.

1341:    Efficiency Alert:
1342:    The routine MatSetValuesBlocked() may offer much better efficiency
1343:    for users of block sparse formats (MATSEQBAIJ and MATMPIBAIJ).

1345:    Level: beginner

1347:    Developer Notes:
1348:     This is labeled with C so does not automatically generate Fortran stubs and interfaces
1349:                     because it requires multiple Fortran interfaces depending on which arguments are scalar or arrays.

1351: .seealso: MatSetOption(), MatAssemblyBegin(), MatAssemblyEnd(), MatSetValuesBlocked(), MatSetValuesLocal(),
1352:           InsertMode, INSERT_VALUES, ADD_VALUES
1353: @*/
1354: PetscErrorCode MatSetValues(Mat mat,PetscInt m,const PetscInt idxm[],PetscInt n,const PetscInt idxn[],const PetscScalar v[],InsertMode addv)
1355: {
1357: #if defined(PETSC_USE_DEBUG)
1358:   PetscInt       i,j;
1359: #endif

1364:   if (!m || !n) return(0); /* no values to insert */
1367:   MatCheckPreallocated(mat,1);

1369:   if (mat->insertmode == NOT_SET_VALUES) {
1370:     mat->insertmode = addv;
1371:   }
1372: #if defined(PETSC_USE_DEBUG)
1373:   else if (mat->insertmode != addv) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Cannot mix add values and insert values");
1374:   if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
1375:   if (!mat->ops->setvalues) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);

1377:   for (i=0; i<m; i++) {
1378:     for (j=0; j<n; j++) {
1379:       if (mat->erroriffailure && PetscIsInfOrNanScalar(v[i*n+j]))
1380: #if defined(PETSC_USE_COMPLEX)
1381:         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]);
1382: #else
1383:         SETERRQ3(PETSC_COMM_SELF,PETSC_ERR_FP,"Inserting %g at matrix entry (%D,%D)",(double)v[i*n+j],idxm[i],idxn[j]);
1384: #endif
1385:     }
1386:   }
1387: #endif

1389:   if (mat->assembled) {
1390:     mat->was_assembled = PETSC_TRUE;
1391:     mat->assembled     = PETSC_FALSE;
1392:   }
1393:   PetscLogEventBegin(MAT_SetValues,mat,0,0,0);
1394:   (*mat->ops->setvalues)(mat,m,idxm,n,idxn,v,addv);
1395:   PetscLogEventEnd(MAT_SetValues,mat,0,0,0);
1396:   return(0);
1397: }


1400: /*@
1401:    MatSetValuesRowLocal - Inserts a row (block row for BAIJ matrices) of nonzero
1402:         values into a matrix

1404:    Not Collective

1406:    Input Parameters:
1407: +  mat - the matrix
1408: .  row - the (block) row to set
1409: -  v - a logically two-dimensional array of values

1411:    Notes:
1412:    By the values, v, are column-oriented (for the block version) and sorted

1414:    All the nonzeros in the row must be provided

1416:    The matrix must have previously had its column indices set

1418:    The row must belong to this process

1420:    Level: intermediate

1422: .seealso: MatSetOption(), MatAssemblyBegin(), MatAssemblyEnd(), MatSetValuesBlocked(), MatSetValuesLocal(),
1423:           InsertMode, INSERT_VALUES, ADD_VALUES, MatSetValues(), MatSetValuesRow(), MatSetLocalToGlobalMapping()
1424: @*/
1425: PetscErrorCode MatSetValuesRowLocal(Mat mat,PetscInt row,const PetscScalar v[])
1426: {
1428:   PetscInt       globalrow;

1434:   ISLocalToGlobalMappingApply(mat->rmap->mapping,1,&row,&globalrow);
1435:   MatSetValuesRow(mat,globalrow,v);
1436:   return(0);
1437: }

1439: /*@
1440:    MatSetValuesRow - Inserts a row (block row for BAIJ matrices) of nonzero
1441:         values into a matrix

1443:    Not Collective

1445:    Input Parameters:
1446: +  mat - the matrix
1447: .  row - the (block) row to set
1448: -  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

1450:    Notes:
1451:    The values, v, are column-oriented for the block version.

1453:    All the nonzeros in the row must be provided

1455:    THE MATRIX MUST HAVE PREVIOUSLY HAD ITS COLUMN INDICES SET. IT IS RARE THAT THIS ROUTINE IS USED, usually MatSetValues() is used.

1457:    The row must belong to this process

1459:    Level: advanced

1461: .seealso: MatSetOption(), MatAssemblyBegin(), MatAssemblyEnd(), MatSetValuesBlocked(), MatSetValuesLocal(),
1462:           InsertMode, INSERT_VALUES, ADD_VALUES, MatSetValues()
1463: @*/
1464: PetscErrorCode MatSetValuesRow(Mat mat,PetscInt row,const PetscScalar v[])
1465: {

1471:   MatCheckPreallocated(mat,1);
1473: #if defined(PETSC_USE_DEBUG)
1474:   if (mat->insertmode == ADD_VALUES) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Cannot mix add and insert values");
1475:   if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
1476: #endif
1477:   mat->insertmode = INSERT_VALUES;

1479:   if (mat->assembled) {
1480:     mat->was_assembled = PETSC_TRUE;
1481:     mat->assembled     = PETSC_FALSE;
1482:   }
1483:   PetscLogEventBegin(MAT_SetValues,mat,0,0,0);
1484:   if (!mat->ops->setvaluesrow) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
1485:   (*mat->ops->setvaluesrow)(mat,row,v);
1486:   PetscLogEventEnd(MAT_SetValues,mat,0,0,0);
1487:   return(0);
1488: }

1490: /*@
1491:    MatSetValuesStencil - Inserts or adds a block of values into a matrix.
1492:      Using structured grid indexing

1494:    Not Collective

1496:    Input Parameters:
1497: +  mat - the matrix
1498: .  m - number of rows being entered
1499: .  idxm - grid coordinates (and component number when dof > 1) for matrix rows being entered
1500: .  n - number of columns being entered
1501: .  idxn - grid coordinates (and component number when dof > 1) for matrix columns being entered
1502: .  v - a logically two-dimensional array of values
1503: -  addv - either ADD_VALUES or INSERT_VALUES, where
1504:    ADD_VALUES adds values to any existing entries, and
1505:    INSERT_VALUES replaces existing entries with new values

1507:    Notes:
1508:    By default the values, v, are row-oriented.  See MatSetOption() for other options.

1510:    Calls to MatSetValuesStencil() with the INSERT_VALUES and ADD_VALUES
1511:    options cannot be mixed without intervening calls to the assembly
1512:    routines.

1514:    The grid coordinates are across the entire grid, not just the local portion

1516:    MatSetValuesStencil() uses 0-based row and column numbers in Fortran
1517:    as well as in C.

1519:    For setting/accessing vector values via array coordinates you can use the DMDAVecGetArray() routine

1521:    In order to use this routine you must either obtain the matrix with DMCreateMatrix()
1522:    or call MatSetLocalToGlobalMapping() and MatSetStencil() first.

1524:    The columns and rows in the stencil passed in MUST be contained within the
1525:    ghost region of the given process as set with DMDACreateXXX() or MatSetStencil(). For example,
1526:    if you create a DMDA with an overlap of one grid level and on a particular process its first
1527:    local nonghost x logical coordinate is 6 (so its first ghost x logical coordinate is 5) the
1528:    first i index you can use in your column and row indices in MatSetStencil() is 5.

1530:    In Fortran idxm and idxn should be declared as
1531: $     MatStencil idxm(4,m),idxn(4,n)
1532:    and the values inserted using
1533: $    idxm(MatStencil_i,1) = i
1534: $    idxm(MatStencil_j,1) = j
1535: $    idxm(MatStencil_k,1) = k
1536: $    idxm(MatStencil_c,1) = c
1537:    etc

1539:    For periodic boundary conditions use negative indices for values to the left (below 0; that are to be
1540:    obtained by wrapping values from right edge). For values to the right of the last entry using that index plus one
1541:    etc to obtain values that obtained by wrapping the values from the left edge. This does not work for anything but the
1542:    DM_BOUNDARY_PERIODIC boundary type.

1544:    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
1545:    a single value per point) you can skip filling those indices.

1547:    Inspired by the structured grid interface to the HYPRE package
1548:    (https://computation.llnl.gov/projects/hypre-scalable-linear-solvers-multigrid-methods)

1550:    Efficiency Alert:
1551:    The routine MatSetValuesBlockedStencil() may offer much better efficiency
1552:    for users of block sparse formats (MATSEQBAIJ and MATMPIBAIJ).

1554:    Level: beginner

1556: .seealso: MatSetOption(), MatAssemblyBegin(), MatAssemblyEnd(), MatSetValuesBlocked(), MatSetValuesLocal()
1557:           MatSetValues(), MatSetValuesBlockedStencil(), MatSetStencil(), DMCreateMatrix(), DMDAVecGetArray(), MatStencil
1558: @*/
1559: PetscErrorCode MatSetValuesStencil(Mat mat,PetscInt m,const MatStencil idxm[],PetscInt n,const MatStencil idxn[],const PetscScalar v[],InsertMode addv)
1560: {
1562:   PetscInt       buf[8192],*bufm=0,*bufn=0,*jdxm,*jdxn;
1563:   PetscInt       j,i,dim = mat->stencil.dim,*dims = mat->stencil.dims+1,tmp;
1564:   PetscInt       *starts = mat->stencil.starts,*dxm = (PetscInt*)idxm,*dxn = (PetscInt*)idxn,sdim = dim - (1 - (PetscInt)mat->stencil.noc);

1567:   if (!m || !n) return(0); /* no values to insert */

1573:   if ((m+n) <= (PetscInt)(sizeof(buf)/sizeof(PetscInt))) {
1574:     jdxm = buf; jdxn = buf+m;
1575:   } else {
1576:     PetscMalloc2(m,&bufm,n,&bufn);
1577:     jdxm = bufm; jdxn = bufn;
1578:   }
1579:   for (i=0; i<m; i++) {
1580:     for (j=0; j<3-sdim; j++) dxm++;
1581:     tmp = *dxm++ - starts[0];
1582:     for (j=0; j<dim-1; j++) {
1583:       if ((*dxm++ - starts[j+1]) < 0 || tmp < 0) tmp = -1;
1584:       else                                       tmp = tmp*dims[j] + *(dxm-1) - starts[j+1];
1585:     }
1586:     if (mat->stencil.noc) dxm++;
1587:     jdxm[i] = tmp;
1588:   }
1589:   for (i=0; i<n; i++) {
1590:     for (j=0; j<3-sdim; j++) dxn++;
1591:     tmp = *dxn++ - starts[0];
1592:     for (j=0; j<dim-1; j++) {
1593:       if ((*dxn++ - starts[j+1]) < 0 || tmp < 0) tmp = -1;
1594:       else                                       tmp = tmp*dims[j] + *(dxn-1) - starts[j+1];
1595:     }
1596:     if (mat->stencil.noc) dxn++;
1597:     jdxn[i] = tmp;
1598:   }
1599:   MatSetValuesLocal(mat,m,jdxm,n,jdxn,v,addv);
1600:   PetscFree2(bufm,bufn);
1601:   return(0);
1602: }

1604: /*@
1605:    MatSetValuesBlockedStencil - Inserts or adds a block of values into a matrix.
1606:      Using structured grid indexing

1608:    Not Collective

1610:    Input Parameters:
1611: +  mat - the matrix
1612: .  m - number of rows being entered
1613: .  idxm - grid coordinates for matrix rows being entered
1614: .  n - number of columns being entered
1615: .  idxn - grid coordinates for matrix columns being entered
1616: .  v - a logically two-dimensional array of values
1617: -  addv - either ADD_VALUES or INSERT_VALUES, where
1618:    ADD_VALUES adds values to any existing entries, and
1619:    INSERT_VALUES replaces existing entries with new values

1621:    Notes:
1622:    By default the values, v, are row-oriented and unsorted.
1623:    See MatSetOption() for other options.

1625:    Calls to MatSetValuesBlockedStencil() with the INSERT_VALUES and ADD_VALUES
1626:    options cannot be mixed without intervening calls to the assembly
1627:    routines.

1629:    The grid coordinates are across the entire grid, not just the local portion

1631:    MatSetValuesBlockedStencil() uses 0-based row and column numbers in Fortran
1632:    as well as in C.

1634:    For setting/accessing vector values via array coordinates you can use the DMDAVecGetArray() routine

1636:    In order to use this routine you must either obtain the matrix with DMCreateMatrix()
1637:    or call MatSetBlockSize(), MatSetLocalToGlobalMapping() and MatSetStencil() first.

1639:    The columns and rows in the stencil passed in MUST be contained within the
1640:    ghost region of the given process as set with DMDACreateXXX() or MatSetStencil(). For example,
1641:    if you create a DMDA with an overlap of one grid level and on a particular process its first
1642:    local nonghost x logical coordinate is 6 (so its first ghost x logical coordinate is 5) the
1643:    first i index you can use in your column and row indices in MatSetStencil() is 5.

1645:    In Fortran idxm and idxn should be declared as
1646: $     MatStencil idxm(4,m),idxn(4,n)
1647:    and the values inserted using
1648: $    idxm(MatStencil_i,1) = i
1649: $    idxm(MatStencil_j,1) = j
1650: $    idxm(MatStencil_k,1) = k
1651:    etc

1653:    Negative indices may be passed in idxm and idxn, these rows and columns are
1654:    simply ignored. This allows easily inserting element stiffness matrices
1655:    with homogeneous Dirchlet boundary conditions that you don't want represented
1656:    in the matrix.

1658:    Inspired by the structured grid interface to the HYPRE package
1659:    (https://computation.llnl.gov/projects/hypre-scalable-linear-solvers-multigrid-methods)

1661:    Level: beginner

1663: .seealso: MatSetOption(), MatAssemblyBegin(), MatAssemblyEnd(), MatSetValuesBlocked(), MatSetValuesLocal()
1664:           MatSetValues(), MatSetValuesStencil(), MatSetStencil(), DMCreateMatrix(), DMDAVecGetArray(), MatStencil,
1665:           MatSetBlockSize(), MatSetLocalToGlobalMapping()
1666: @*/
1667: PetscErrorCode MatSetValuesBlockedStencil(Mat mat,PetscInt m,const MatStencil idxm[],PetscInt n,const MatStencil idxn[],const PetscScalar v[],InsertMode addv)
1668: {
1670:   PetscInt       buf[8192],*bufm=0,*bufn=0,*jdxm,*jdxn;
1671:   PetscInt       j,i,dim = mat->stencil.dim,*dims = mat->stencil.dims+1,tmp;
1672:   PetscInt       *starts = mat->stencil.starts,*dxm = (PetscInt*)idxm,*dxn = (PetscInt*)idxn,sdim = dim - (1 - (PetscInt)mat->stencil.noc);

1675:   if (!m || !n) return(0); /* no values to insert */

1682:   if ((m+n) <= (PetscInt)(sizeof(buf)/sizeof(PetscInt))) {
1683:     jdxm = buf; jdxn = buf+m;
1684:   } else {
1685:     PetscMalloc2(m,&bufm,n,&bufn);
1686:     jdxm = bufm; jdxn = bufn;
1687:   }
1688:   for (i=0; i<m; i++) {
1689:     for (j=0; j<3-sdim; j++) dxm++;
1690:     tmp = *dxm++ - starts[0];
1691:     for (j=0; j<sdim-1; j++) {
1692:       if ((*dxm++ - starts[j+1]) < 0 || tmp < 0) tmp = -1;
1693:       else                                       tmp = tmp*dims[j] + *(dxm-1) - starts[j+1];
1694:     }
1695:     dxm++;
1696:     jdxm[i] = tmp;
1697:   }
1698:   for (i=0; i<n; i++) {
1699:     for (j=0; j<3-sdim; j++) dxn++;
1700:     tmp = *dxn++ - starts[0];
1701:     for (j=0; j<sdim-1; j++) {
1702:       if ((*dxn++ - starts[j+1]) < 0 || tmp < 0) tmp = -1;
1703:       else                                       tmp = tmp*dims[j] + *(dxn-1) - starts[j+1];
1704:     }
1705:     dxn++;
1706:     jdxn[i] = tmp;
1707:   }
1708:   MatSetValuesBlockedLocal(mat,m,jdxm,n,jdxn,v,addv);
1709:   PetscFree2(bufm,bufn);
1710:   return(0);
1711: }

1713: /*@
1714:    MatSetStencil - Sets the grid information for setting values into a matrix via
1715:         MatSetValuesStencil()

1717:    Not Collective

1719:    Input Parameters:
1720: +  mat - the matrix
1721: .  dim - dimension of the grid 1, 2, or 3
1722: .  dims - number of grid points in x, y, and z direction, including ghost points on your processor
1723: .  starts - starting point of ghost nodes on your processor in x, y, and z direction
1724: -  dof - number of degrees of freedom per node


1727:    Inspired by the structured grid interface to the HYPRE package
1728:    (www.llnl.gov/CASC/hyper)

1730:    For matrices generated with DMCreateMatrix() this routine is automatically called and so not needed by the
1731:    user.

1733:    Level: beginner

1735: .seealso: MatSetOption(), MatAssemblyBegin(), MatAssemblyEnd(), MatSetValuesBlocked(), MatSetValuesLocal()
1736:           MatSetValues(), MatSetValuesBlockedStencil(), MatSetValuesStencil()
1737: @*/
1738: PetscErrorCode MatSetStencil(Mat mat,PetscInt dim,const PetscInt dims[],const PetscInt starts[],PetscInt dof)
1739: {
1740:   PetscInt i;


1747:   mat->stencil.dim = dim + (dof > 1);
1748:   for (i=0; i<dim; i++) {
1749:     mat->stencil.dims[i]   = dims[dim-i-1];      /* copy the values in backwards */
1750:     mat->stencil.starts[i] = starts[dim-i-1];
1751:   }
1752:   mat->stencil.dims[dim]   = dof;
1753:   mat->stencil.starts[dim] = 0;
1754:   mat->stencil.noc         = (PetscBool)(dof == 1);
1755:   return(0);
1756: }

1758: /*@C
1759:    MatSetValuesBlocked - Inserts or adds a block of values into a matrix.

1761:    Not Collective

1763:    Input Parameters:
1764: +  mat - the matrix
1765: .  v - a logically two-dimensional array of values
1766: .  m, idxm - the number of block rows and their global block indices
1767: .  n, idxn - the number of block columns and their global block indices
1768: -  addv - either ADD_VALUES or INSERT_VALUES, where
1769:    ADD_VALUES adds values to any existing entries, and
1770:    INSERT_VALUES replaces existing entries with new values

1772:    Notes:
1773:    If you create the matrix yourself (that is not with a call to DMCreateMatrix()) then you MUST call
1774:    MatXXXXSetPreallocation() or MatSetUp() before using this routine.

1776:    The m and n count the NUMBER of blocks in the row direction and column direction,
1777:    NOT the total number of rows/columns; for example, if the block size is 2 and
1778:    you are passing in values for rows 2,3,4,5  then m would be 2 (not 4).
1779:    The values in idxm would be 1 2; that is the first index for each block divided by
1780:    the block size.

1782:    Note that you must call MatSetBlockSize() when constructing this matrix (before
1783:    preallocating it).

1785:    By default the values, v, are row-oriented, so the layout of
1786:    v is the same as for MatSetValues(). See MatSetOption() for other options.

1788:    Calls to MatSetValuesBlocked() with the INSERT_VALUES and ADD_VALUES
1789:    options cannot be mixed without intervening calls to the assembly
1790:    routines.

1792:    MatSetValuesBlocked() uses 0-based row and column numbers in Fortran
1793:    as well as in C.

1795:    Negative indices may be passed in idxm and idxn, these rows and columns are
1796:    simply ignored. This allows easily inserting element stiffness matrices
1797:    with homogeneous Dirchlet boundary conditions that you don't want represented
1798:    in the matrix.

1800:    Each time an entry is set within a sparse matrix via MatSetValues(),
1801:    internal searching must be done to determine where to place the
1802:    data in the matrix storage space.  By instead inserting blocks of
1803:    entries via MatSetValuesBlocked(), the overhead of matrix assembly is
1804:    reduced.

1806:    Example:
1807: $   Suppose m=n=2 and block size(bs) = 2 The array is
1808: $
1809: $   1  2  | 3  4
1810: $   5  6  | 7  8
1811: $   - - - | - - -
1812: $   9  10 | 11 12
1813: $   13 14 | 15 16
1814: $
1815: $   v[] should be passed in like
1816: $   v[] = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]
1817: $
1818: $  If you are not using row oriented storage of v (that is you called MatSetOption(mat,MAT_ROW_ORIENTED,PETSC_FALSE)) then
1819: $   v[] = [1,5,9,13,2,6,10,14,3,7,11,15,4,8,12,16]

1821:    Level: intermediate

1823: .seealso: MatSetBlockSize(), MatSetOption(), MatAssemblyBegin(), MatAssemblyEnd(), MatSetValues(), MatSetValuesBlockedLocal()
1824: @*/
1825: PetscErrorCode MatSetValuesBlocked(Mat mat,PetscInt m,const PetscInt idxm[],PetscInt n,const PetscInt idxn[],const PetscScalar v[],InsertMode addv)
1826: {

1832:   if (!m || !n) return(0); /* no values to insert */
1836:   MatCheckPreallocated(mat,1);
1837:   if (mat->insertmode == NOT_SET_VALUES) {
1838:     mat->insertmode = addv;
1839:   }
1840: #if defined(PETSC_USE_DEBUG)
1841:   else if (mat->insertmode != addv) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Cannot mix add values and insert values");
1842:   if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
1843:   if (!mat->ops->setvaluesblocked && !mat->ops->setvalues) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
1844: #endif

1846:   if (mat->assembled) {
1847:     mat->was_assembled = PETSC_TRUE;
1848:     mat->assembled     = PETSC_FALSE;
1849:   }
1850:   PetscLogEventBegin(MAT_SetValues,mat,0,0,0);
1851:   if (mat->ops->setvaluesblocked) {
1852:     (*mat->ops->setvaluesblocked)(mat,m,idxm,n,idxn,v,addv);
1853:   } else {
1854:     PetscInt buf[8192],*bufr=0,*bufc=0,*iidxm,*iidxn;
1855:     PetscInt i,j,bs,cbs;
1856:     MatGetBlockSizes(mat,&bs,&cbs);
1857:     if (m*bs+n*cbs <= (PetscInt)(sizeof(buf)/sizeof(PetscInt))) {
1858:       iidxm = buf; iidxn = buf + m*bs;
1859:     } else {
1860:       PetscMalloc2(m*bs,&bufr,n*cbs,&bufc);
1861:       iidxm = bufr; iidxn = bufc;
1862:     }
1863:     for (i=0; i<m; i++) {
1864:       for (j=0; j<bs; j++) {
1865:         iidxm[i*bs+j] = bs*idxm[i] + j;
1866:       }
1867:     }
1868:     for (i=0; i<n; i++) {
1869:       for (j=0; j<cbs; j++) {
1870:         iidxn[i*cbs+j] = cbs*idxn[i] + j;
1871:       }
1872:     }
1873:     MatSetValues(mat,m*bs,iidxm,n*cbs,iidxn,v,addv);
1874:     PetscFree2(bufr,bufc);
1875:   }
1876:   PetscLogEventEnd(MAT_SetValues,mat,0,0,0);
1877:   return(0);
1878: }

1880: /*@C
1881:    MatGetValues - Gets a block of values from a matrix.

1883:    Not Collective; currently only returns a local block

1885:    Input Parameters:
1886: +  mat - the matrix
1887: .  v - a logically two-dimensional array for storing the values
1888: .  m, idxm - the number of rows and their global indices
1889: -  n, idxn - the number of columns and their global indices

1891:    Notes:
1892:    The user must allocate space (m*n PetscScalars) for the values, v.
1893:    The values, v, are then returned in a row-oriented format,
1894:    analogous to that used by default in MatSetValues().

1896:    MatGetValues() uses 0-based row and column numbers in
1897:    Fortran as well as in C.

1899:    MatGetValues() requires that the matrix has been assembled
1900:    with MatAssemblyBegin()/MatAssemblyEnd().  Thus, calls to
1901:    MatSetValues() and MatGetValues() CANNOT be made in succession
1902:    without intermediate matrix assembly.

1904:    Negative row or column indices will be ignored and those locations in v[] will be
1905:    left unchanged.

1907:    Level: advanced

1909: .seealso: MatGetRow(), MatCreateSubMatrices(), MatSetValues()
1910: @*/
1911: PetscErrorCode MatGetValues(Mat mat,PetscInt m,const PetscInt idxm[],PetscInt n,const PetscInt idxn[],PetscScalar v[])
1912: {

1918:   if (!m || !n) return(0);
1922:   if (!mat->assembled) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
1923:   if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
1924:   if (!mat->ops->getvalues) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
1925:   MatCheckPreallocated(mat,1);

1927:   PetscLogEventBegin(MAT_GetValues,mat,0,0,0);
1928:   (*mat->ops->getvalues)(mat,m,idxm,n,idxn,v);
1929:   PetscLogEventEnd(MAT_GetValues,mat,0,0,0);
1930:   return(0);
1931: }

1933: /*@C
1934:    MatGetValuesLocal - retrieves values into certain locations of a matrix,
1935:    using a local numbering of the nodes.

1937:    Not Collective

1939:    Input Parameters:
1940: +  mat - the matrix
1941: .  nrow, irow - number of rows and their local indices
1942: -  ncol, icol - number of columns and their local indices

1944:    Output Parameter:
1945: .  y -  a logically two-dimensional array of values

1947:    Notes:
1948:    If you create the matrix yourself (that is not with a call to DMCreateMatrix()) then you MUST call MatSetLocalToGlobalMapping() before using this routine

1950:    Level: advanced

1952:    Developer Notes:
1953:     This is labelled with C so does not automatically generate Fortran stubs and interfaces
1954:                     because it requires multiple Fortran interfaces depending on which arguments are scalar or arrays.

1956: .seealso:  MatAssemblyBegin(), MatAssemblyEnd(), MatSetValues(), MatSetLocalToGlobalMapping(),
1957:            MatSetValuesLocal()
1958: @*/
1959: PetscErrorCode MatGetValuesLocal(Mat mat,PetscInt nrow,const PetscInt irow[],PetscInt ncol,const PetscInt icol[],PetscScalar y[])
1960: {

1966:   MatCheckPreallocated(mat,1);
1967:   if (!nrow || !ncol) return(0); /* no values to retrieve */
1970: #if defined(PETSC_USE_DEBUG)
1971:   if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
1972:   if (!mat->ops->getvalueslocal && !mat->ops->getvalues) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
1973: #endif
1974:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
1975:   PetscLogEventBegin(MAT_GetValues,mat,0,0,0);
1976:   if (mat->ops->getvalueslocal) {
1977:     (*mat->ops->getvalueslocal)(mat,nrow,irow,ncol,icol,y);
1978:   } else {
1979:     PetscInt buf[8192],*bufr=0,*bufc=0,*irowm,*icolm;
1980:     if ((nrow+ncol) <= (PetscInt)(sizeof(buf)/sizeof(PetscInt))) {
1981:       irowm = buf; icolm = buf+nrow;
1982:     } else {
1983:       PetscMalloc2(nrow,&bufr,ncol,&bufc);
1984:       irowm = bufr; icolm = bufc;
1985:     }
1986:     if (!mat->rmap->mapping) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"MatGetValuesLocal() cannot proceed without local-to-global row mapping (See MatSetLocalToGlobalMapping()).");
1987:     if (!mat->cmap->mapping) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"MatGetValuesLocal() cannot proceed without local-to-global column mapping (See MatSetLocalToGlobalMapping()).");
1988:     ISLocalToGlobalMappingApply(mat->rmap->mapping,nrow,irow,irowm);
1989:     ISLocalToGlobalMappingApply(mat->cmap->mapping,ncol,icol,icolm);
1990:     MatGetValues(mat,nrow,irowm,ncol,icolm,y);
1991:     PetscFree2(bufr,bufc);
1992:   }
1993:   PetscLogEventEnd(MAT_GetValues,mat,0,0,0);
1994:   return(0);
1995: }

1997: /*@
1998:   MatSetValuesBatch - Adds (ADD_VALUES) many blocks of values into a matrix at once. The blocks must all be square and
1999:   the same size. Currently, this can only be called once and creates the given matrix.

2001:   Not Collective

2003:   Input Parameters:
2004: + mat - the matrix
2005: . nb - the number of blocks
2006: . bs - the number of rows (and columns) in each block
2007: . rows - a concatenation of the rows for each block
2008: - v - a concatenation of logically two-dimensional arrays of values

2010:   Notes:
2011:   In the future, we will extend this routine to handle rectangular blocks, and to allow multiple calls for a given matrix.

2013:   Level: advanced

2015: .seealso: MatSetOption(), MatAssemblyBegin(), MatAssemblyEnd(), MatSetValuesBlocked(), MatSetValuesLocal(),
2016:           InsertMode, INSERT_VALUES, ADD_VALUES, MatSetValues()
2017: @*/
2018: PetscErrorCode MatSetValuesBatch(Mat mat, PetscInt nb, PetscInt bs, PetscInt rows[], const PetscScalar v[])
2019: {

2027: #if defined(PETSC_USE_DEBUG)
2028:   if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2029: #endif

2031:   PetscLogEventBegin(MAT_SetValuesBatch,mat,0,0,0);
2032:   if (mat->ops->setvaluesbatch) {
2033:     (*mat->ops->setvaluesbatch)(mat,nb,bs,rows,v);
2034:   } else {
2035:     PetscInt b;
2036:     for (b = 0; b < nb; ++b) {
2037:       MatSetValues(mat, bs, &rows[b*bs], bs, &rows[b*bs], &v[b*bs*bs], ADD_VALUES);
2038:     }
2039:   }
2040:   PetscLogEventEnd(MAT_SetValuesBatch,mat,0,0,0);
2041:   return(0);
2042: }

2044: /*@
2045:    MatSetLocalToGlobalMapping - Sets a local-to-global numbering for use by
2046:    the routine MatSetValuesLocal() to allow users to insert matrix entries
2047:    using a local (per-processor) numbering.

2049:    Not Collective

2051:    Input Parameters:
2052: +  x - the matrix
2053: .  rmapping - row mapping created with ISLocalToGlobalMappingCreate()   or ISLocalToGlobalMappingCreateIS()
2054: - cmapping - column mapping

2056:    Level: intermediate


2059: .seealso:  MatAssemblyBegin(), MatAssemblyEnd(), MatSetValues(), MatSetValuesLocal()
2060: @*/
2061: PetscErrorCode MatSetLocalToGlobalMapping(Mat x,ISLocalToGlobalMapping rmapping,ISLocalToGlobalMapping cmapping)
2062: {


2071:   if (x->ops->setlocaltoglobalmapping) {
2072:     (*x->ops->setlocaltoglobalmapping)(x,rmapping,cmapping);
2073:   } else {
2074:     PetscLayoutSetISLocalToGlobalMapping(x->rmap,rmapping);
2075:     PetscLayoutSetISLocalToGlobalMapping(x->cmap,cmapping);
2076:   }
2077:   return(0);
2078: }


2081: /*@
2082:    MatGetLocalToGlobalMapping - Gets the local-to-global numbering set by MatSetLocalToGlobalMapping()

2084:    Not Collective

2086:    Input Parameters:
2087: .  A - the matrix

2089:    Output Parameters:
2090: + rmapping - row mapping
2091: - cmapping - column mapping

2093:    Level: advanced


2096: .seealso:  MatSetValuesLocal()
2097: @*/
2098: PetscErrorCode MatGetLocalToGlobalMapping(Mat A,ISLocalToGlobalMapping *rmapping,ISLocalToGlobalMapping *cmapping)
2099: {
2105:   if (rmapping) *rmapping = A->rmap->mapping;
2106:   if (cmapping) *cmapping = A->cmap->mapping;
2107:   return(0);
2108: }

2110: /*@
2111:    MatGetLayouts - Gets the PetscLayout objects for rows and columns

2113:    Not Collective

2115:    Input Parameters:
2116: .  A - the matrix

2118:    Output Parameters:
2119: + rmap - row layout
2120: - cmap - column layout

2122:    Level: advanced

2124: .seealso:  MatCreateVecs(), MatGetLocalToGlobalMapping()
2125: @*/
2126: PetscErrorCode MatGetLayouts(Mat A,PetscLayout *rmap,PetscLayout *cmap)
2127: {
2133:   if (rmap) *rmap = A->rmap;
2134:   if (cmap) *cmap = A->cmap;
2135:   return(0);
2136: }

2138: /*@C
2139:    MatSetValuesLocal - Inserts or adds values into certain locations of a matrix,
2140:    using a local numbering of the nodes.

2142:    Not Collective

2144:    Input Parameters:
2145: +  mat - the matrix
2146: .  nrow, irow - number of rows and their local indices
2147: .  ncol, icol - number of columns and their local indices
2148: .  y -  a logically two-dimensional array of values
2149: -  addv - either INSERT_VALUES or ADD_VALUES, where
2150:    ADD_VALUES adds values to any existing entries, and
2151:    INSERT_VALUES replaces existing entries with new values

2153:    Notes:
2154:    If you create the matrix yourself (that is not with a call to DMCreateMatrix()) then you MUST call MatXXXXSetPreallocation() or
2155:       MatSetUp() before using this routine

2157:    If you create the matrix yourself (that is not with a call to DMCreateMatrix()) then you MUST call MatSetLocalToGlobalMapping() before using this routine

2159:    Calls to MatSetValuesLocal() with the INSERT_VALUES and ADD_VALUES
2160:    options cannot be mixed without intervening calls to the assembly
2161:    routines.

2163:    These values may be cached, so MatAssemblyBegin() and MatAssemblyEnd()
2164:    MUST be called after all calls to MatSetValuesLocal() have been completed.

2166:    Level: intermediate

2168:    Developer Notes:
2169:     This is labeled with C so does not automatically generate Fortran stubs and interfaces
2170:                     because it requires multiple Fortran interfaces depending on which arguments are scalar or arrays.

2172: .seealso:  MatAssemblyBegin(), MatAssemblyEnd(), MatSetValues(), MatSetLocalToGlobalMapping(),
2173:            MatSetValueLocal(), MatGetValuesLocal()
2174: @*/
2175: PetscErrorCode MatSetValuesLocal(Mat mat,PetscInt nrow,const PetscInt irow[],PetscInt ncol,const PetscInt icol[],const PetscScalar y[],InsertMode addv)
2176: {

2182:   MatCheckPreallocated(mat,1);
2183:   if (!nrow || !ncol) return(0); /* no values to insert */
2186:   if (mat->insertmode == NOT_SET_VALUES) {
2187:     mat->insertmode = addv;
2188:   }
2189: #if defined(PETSC_USE_DEBUG)
2190:   else if (mat->insertmode != addv) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Cannot mix add values and insert values");
2191:   if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2192:   if (!mat->ops->setvalueslocal && !mat->ops->setvalues) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
2193: #endif

2195:   if (mat->assembled) {
2196:     mat->was_assembled = PETSC_TRUE;
2197:     mat->assembled     = PETSC_FALSE;
2198:   }
2199:   PetscLogEventBegin(MAT_SetValues,mat,0,0,0);
2200:   if (mat->ops->setvalueslocal) {
2201:     (*mat->ops->setvalueslocal)(mat,nrow,irow,ncol,icol,y,addv);
2202:   } else {
2203:     PetscInt buf[8192],*bufr=0,*bufc=0,*irowm,*icolm;
2204:     if ((nrow+ncol) <= (PetscInt)(sizeof(buf)/sizeof(PetscInt))) {
2205:       irowm = buf; icolm = buf+nrow;
2206:     } else {
2207:       PetscMalloc2(nrow,&bufr,ncol,&bufc);
2208:       irowm = bufr; icolm = bufc;
2209:     }
2210:     if (!mat->rmap->mapping) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"MatSetValuesLocal() cannot proceed without local-to-global row mapping (See MatSetLocalToGlobalMapping()).");
2211:     if (!mat->cmap->mapping) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"MatSetValuesLocal() cannot proceed without local-to-global column mapping (See MatSetLocalToGlobalMapping()).");
2212:     ISLocalToGlobalMappingApply(mat->rmap->mapping,nrow,irow,irowm);
2213:     ISLocalToGlobalMappingApply(mat->cmap->mapping,ncol,icol,icolm);
2214:     MatSetValues(mat,nrow,irowm,ncol,icolm,y,addv);
2215:     PetscFree2(bufr,bufc);
2216:   }
2217:   PetscLogEventEnd(MAT_SetValues,mat,0,0,0);
2218:   return(0);
2219: }

2221: /*@C
2222:    MatSetValuesBlockedLocal - Inserts or adds values into certain locations of a matrix,
2223:    using a local ordering of the nodes a block at a time.

2225:    Not Collective

2227:    Input Parameters:
2228: +  x - the matrix
2229: .  nrow, irow - number of rows and their local indices
2230: .  ncol, icol - number of columns and their local indices
2231: .  y -  a logically two-dimensional array of values
2232: -  addv - either INSERT_VALUES or ADD_VALUES, where
2233:    ADD_VALUES adds values to any existing entries, and
2234:    INSERT_VALUES replaces existing entries with new values

2236:    Notes:
2237:    If you create the matrix yourself (that is not with a call to DMCreateMatrix()) then you MUST call MatXXXXSetPreallocation() or
2238:       MatSetUp() before using this routine

2240:    If you create the matrix yourself (that is not with a call to DMCreateMatrix()) then you MUST call MatSetBlockSize() and MatSetLocalToGlobalMapping()
2241:       before using this routineBefore calling MatSetValuesLocal(), the user must first set the

2243:    Calls to MatSetValuesBlockedLocal() with the INSERT_VALUES and ADD_VALUES
2244:    options cannot be mixed without intervening calls to the assembly
2245:    routines.

2247:    These values may be cached, so MatAssemblyBegin() and MatAssemblyEnd()
2248:    MUST be called after all calls to MatSetValuesBlockedLocal() have been completed.

2250:    Level: intermediate

2252:    Developer Notes:
2253:     This is labeled with C so does not automatically generate Fortran stubs and interfaces
2254:                     because it requires multiple Fortran interfaces depending on which arguments are scalar or arrays.

2256: .seealso:  MatSetBlockSize(), MatSetLocalToGlobalMapping(), MatAssemblyBegin(), MatAssemblyEnd(),
2257:            MatSetValuesLocal(),  MatSetValuesBlocked()
2258: @*/
2259: PetscErrorCode MatSetValuesBlockedLocal(Mat mat,PetscInt nrow,const PetscInt irow[],PetscInt ncol,const PetscInt icol[],const PetscScalar y[],InsertMode addv)
2260: {

2266:   MatCheckPreallocated(mat,1);
2267:   if (!nrow || !ncol) return(0); /* no values to insert */
2271:   if (mat->insertmode == NOT_SET_VALUES) {
2272:     mat->insertmode = addv;
2273:   }
2274: #if defined(PETSC_USE_DEBUG)
2275:   else if (mat->insertmode != addv) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Cannot mix add values and insert values");
2276:   if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2277:   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);
2278: #endif

2280:   if (mat->assembled) {
2281:     mat->was_assembled = PETSC_TRUE;
2282:     mat->assembled     = PETSC_FALSE;
2283:   }
2284: #if defined(PETSC_USE_DEBUG)
2285:   /* Condition on the mapping existing, because MatSetValuesBlockedLocal_IS does not require it to be set. */
2286:   if (mat->rmap->mapping) {
2287:     PetscInt irbs, rbs;
2288:     MatGetBlockSizes(mat, &rbs, NULL);
2289:     ISLocalToGlobalMappingGetBlockSize(mat->rmap->mapping,&irbs);
2290:     if (rbs != irbs) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Different row block sizes! mat %D, row l2g map %D",rbs,irbs);
2291:   }
2292:   if (mat->cmap->mapping) {
2293:     PetscInt icbs, cbs;
2294:     MatGetBlockSizes(mat,NULL,&cbs);
2295:     ISLocalToGlobalMappingGetBlockSize(mat->cmap->mapping,&icbs);
2296:     if (cbs != icbs) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Different col block sizes! mat %D, col l2g map %D",cbs,icbs);
2297:   }
2298: #endif
2299:   PetscLogEventBegin(MAT_SetValues,mat,0,0,0);
2300:   if (mat->ops->setvaluesblockedlocal) {
2301:     (*mat->ops->setvaluesblockedlocal)(mat,nrow,irow,ncol,icol,y,addv);
2302:   } else {
2303:     PetscInt buf[8192],*bufr=0,*bufc=0,*irowm,*icolm;
2304:     if ((nrow+ncol) <= (PetscInt)(sizeof(buf)/sizeof(PetscInt))) {
2305:       irowm = buf; icolm = buf + nrow;
2306:     } else {
2307:       PetscMalloc2(nrow,&bufr,ncol,&bufc);
2308:       irowm = bufr; icolm = bufc;
2309:     }
2310:     ISLocalToGlobalMappingApplyBlock(mat->rmap->mapping,nrow,irow,irowm);
2311:     ISLocalToGlobalMappingApplyBlock(mat->cmap->mapping,ncol,icol,icolm);
2312:     MatSetValuesBlocked(mat,nrow,irowm,ncol,icolm,y,addv);
2313:     PetscFree2(bufr,bufc);
2314:   }
2315:   PetscLogEventEnd(MAT_SetValues,mat,0,0,0);
2316:   return(0);
2317: }

2319: /*@
2320:    MatMultDiagonalBlock - Computes the matrix-vector product, y = Dx. Where D is defined by the inode or block structure of the diagonal

2322:    Collective on Mat

2324:    Input Parameters:
2325: +  mat - the matrix
2326: -  x   - the vector to be multiplied

2328:    Output Parameters:
2329: .  y - the result

2331:    Notes:
2332:    The vectors x and y cannot be the same.  I.e., one cannot
2333:    call MatMult(A,y,y).

2335:    Level: developer

2337: .seealso: MatMultTranspose(), MatMultAdd(), MatMultTransposeAdd()
2338: @*/
2339: PetscErrorCode MatMultDiagonalBlock(Mat mat,Vec x,Vec y)
2340: {


2349:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2350:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2351:   if (x == y) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"x and y must be different vectors");
2352:   MatCheckPreallocated(mat,1);

2354:   if (!mat->ops->multdiagonalblock) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Matrix type %s does not have a multiply defined",((PetscObject)mat)->type_name);
2355:   (*mat->ops->multdiagonalblock)(mat,x,y);
2356:   PetscObjectStateIncrease((PetscObject)y);
2357:   return(0);
2358: }

2360: /* --------------------------------------------------------*/
2361: /*@
2362:    MatMult - Computes the matrix-vector product, y = Ax.

2364:    Neighbor-wise Collective on Mat

2366:    Input Parameters:
2367: +  mat - the matrix
2368: -  x   - the vector to be multiplied

2370:    Output Parameters:
2371: .  y - the result

2373:    Notes:
2374:    The vectors x and y cannot be the same.  I.e., one cannot
2375:    call MatMult(A,y,y).

2377:    Level: beginner

2379: .seealso: MatMultTranspose(), MatMultAdd(), MatMultTransposeAdd()
2380: @*/
2381: PetscErrorCode MatMult(Mat mat,Vec x,Vec y)
2382: {

2390:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2391:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2392:   if (x == y) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"x and y must be different vectors");
2393: #if !defined(PETSC_HAVE_CONSTRAINTS)
2394:   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);
2395:   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);
2396:   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);
2397: #endif
2398:   VecSetErrorIfLocked(y,3);
2399:   if (mat->erroriffailure) {VecValidValues(x,2,PETSC_TRUE);}
2400:   MatCheckPreallocated(mat,1);

2402:   VecLockReadPush(x);
2403:   if (!mat->ops->mult) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Matrix type %s does not have a multiply defined",((PetscObject)mat)->type_name);
2404:   PetscLogEventBegin(MAT_Mult,mat,x,y,0);
2405:   (*mat->ops->mult)(mat,x,y);
2406:   PetscLogEventEnd(MAT_Mult,mat,x,y,0);
2407:   if (mat->erroriffailure) {VecValidValues(y,3,PETSC_FALSE);}
2408:   VecLockReadPop(x);
2409:   return(0);
2410: }

2412: /*@
2413:    MatMultTranspose - Computes matrix transpose times a vector y = A^T * x.

2415:    Neighbor-wise Collective on Mat

2417:    Input Parameters:
2418: +  mat - the matrix
2419: -  x   - the vector to be multiplied

2421:    Output Parameters:
2422: .  y - the result

2424:    Notes:
2425:    The vectors x and y cannot be the same.  I.e., one cannot
2426:    call MatMultTranspose(A,y,y).

2428:    For complex numbers this does NOT compute the Hermitian (complex conjugate) transpose multiple,
2429:    use MatMultHermitianTranspose()

2431:    Level: beginner

2433: .seealso: MatMult(), MatMultAdd(), MatMultTransposeAdd(), MatMultHermitianTranspose(), MatTranspose()
2434: @*/
2435: PetscErrorCode MatMultTranspose(Mat mat,Vec x,Vec y)
2436: {


2445:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2446:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2447:   if (x == y) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"x and y must be different vectors");
2448: #if !defined(PETSC_HAVE_CONSTRAINTS)
2449:   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);
2450:   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);
2451: #endif
2452:   if (mat->erroriffailure) {VecValidValues(x,2,PETSC_TRUE);}
2453:   MatCheckPreallocated(mat,1);

2455:   if (!mat->ops->multtranspose) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Matrix type %s does not have a multiply transpose defined",((PetscObject)mat)->type_name);
2456:   PetscLogEventBegin(MAT_MultTranspose,mat,x,y,0);
2457:   VecLockReadPush(x);
2458:   (*mat->ops->multtranspose)(mat,x,y);
2459:   VecLockReadPop(x);
2460:   PetscLogEventEnd(MAT_MultTranspose,mat,x,y,0);
2461:   PetscObjectStateIncrease((PetscObject)y);
2462:   if (mat->erroriffailure) {VecValidValues(y,3,PETSC_FALSE);}
2463:   return(0);
2464: }

2466: /*@
2467:    MatMultHermitianTranspose - Computes matrix Hermitian transpose times a vector.

2469:    Neighbor-wise Collective on Mat

2471:    Input Parameters:
2472: +  mat - the matrix
2473: -  x   - the vector to be multilplied

2475:    Output Parameters:
2476: .  y - the result

2478:    Notes:
2479:    The vectors x and y cannot be the same.  I.e., one cannot
2480:    call MatMultHermitianTranspose(A,y,y).

2482:    Also called the conjugate transpose, complex conjugate transpose, or adjoint.

2484:    For real numbers MatMultTranspose() and MatMultHermitianTranspose() are identical.

2486:    Level: beginner

2488: .seealso: MatMult(), MatMultAdd(), MatMultHermitianTransposeAdd(), MatMultTranspose()
2489: @*/
2490: PetscErrorCode MatMultHermitianTranspose(Mat mat,Vec x,Vec y)
2491: {
2493:   Vec            w;


2501:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2502:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2503:   if (x == y) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"x and y must be different vectors");
2504: #if !defined(PETSC_HAVE_CONSTRAINTS)
2505:   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);
2506:   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);
2507: #endif
2508:   MatCheckPreallocated(mat,1);

2510:   PetscLogEventBegin(MAT_MultHermitianTranspose,mat,x,y,0);
2511:   if (mat->ops->multhermitiantranspose) {
2512:     VecLockReadPush(x);
2513:     (*mat->ops->multhermitiantranspose)(mat,x,y);
2514:     VecLockReadPop(x);
2515:   } else {
2516:     VecDuplicate(x,&w);
2517:     VecCopy(x,w);
2518:     VecConjugate(w);
2519:     MatMultTranspose(mat,w,y);
2520:     VecDestroy(&w);
2521:     VecConjugate(y);
2522:   }
2523:   PetscLogEventEnd(MAT_MultHermitianTranspose,mat,x,y,0);
2524:   PetscObjectStateIncrease((PetscObject)y);
2525:   return(0);
2526: }

2528: /*@
2529:     MatMultAdd -  Computes v3 = v2 + A * v1.

2531:     Neighbor-wise Collective on Mat

2533:     Input Parameters:
2534: +   mat - the matrix
2535: -   v1, v2 - the vectors

2537:     Output Parameters:
2538: .   v3 - the result

2540:     Notes:
2541:     The vectors v1 and v3 cannot be the same.  I.e., one cannot
2542:     call MatMultAdd(A,v1,v2,v1).

2544:     Level: beginner

2546: .seealso: MatMultTranspose(), MatMult(), MatMultTransposeAdd()
2547: @*/
2548: PetscErrorCode MatMultAdd(Mat mat,Vec v1,Vec v2,Vec v3)
2549: {


2559:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2560:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2561:   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);
2562:   /* 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);
2563:      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); */
2564:   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);
2565:   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);
2566:   if (v1 == v3) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"v1 and v3 must be different vectors");
2567:   MatCheckPreallocated(mat,1);

2569:   if (!mat->ops->multadd) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"No MatMultAdd() for matrix type %s",((PetscObject)mat)->type_name);
2570:   PetscLogEventBegin(MAT_MultAdd,mat,v1,v2,v3);
2571:   VecLockReadPush(v1);
2572:   (*mat->ops->multadd)(mat,v1,v2,v3);
2573:   VecLockReadPop(v1);
2574:   PetscLogEventEnd(MAT_MultAdd,mat,v1,v2,v3);
2575:   PetscObjectStateIncrease((PetscObject)v3);
2576:   return(0);
2577: }

2579: /*@
2580:    MatMultTransposeAdd - Computes v3 = v2 + A' * v1.

2582:    Neighbor-wise Collective on Mat

2584:    Input Parameters:
2585: +  mat - the matrix
2586: -  v1, v2 - the vectors

2588:    Output Parameters:
2589: .  v3 - the result

2591:    Notes:
2592:    The vectors v1 and v3 cannot be the same.  I.e., one cannot
2593:    call MatMultTransposeAdd(A,v1,v2,v1).

2595:    Level: beginner

2597: .seealso: MatMultTranspose(), MatMultAdd(), MatMult()
2598: @*/
2599: PetscErrorCode MatMultTransposeAdd(Mat mat,Vec v1,Vec v2,Vec v3)
2600: {


2610:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2611:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2612:   if (!mat->ops->multtransposeadd) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
2613:   if (v1 == v3) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"v1 and v3 must be different vectors");
2614:   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);
2615:   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);
2616:   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);
2617:   MatCheckPreallocated(mat,1);

2619:   PetscLogEventBegin(MAT_MultTransposeAdd,mat,v1,v2,v3);
2620:   VecLockReadPush(v1);
2621:   (*mat->ops->multtransposeadd)(mat,v1,v2,v3);
2622:   VecLockReadPop(v1);
2623:   PetscLogEventEnd(MAT_MultTransposeAdd,mat,v1,v2,v3);
2624:   PetscObjectStateIncrease((PetscObject)v3);
2625:   return(0);
2626: }

2628: /*@
2629:    MatMultHermitianTransposeAdd - Computes v3 = v2 + A^H * v1.

2631:    Neighbor-wise Collective on Mat

2633:    Input Parameters:
2634: +  mat - the matrix
2635: -  v1, v2 - the vectors

2637:    Output Parameters:
2638: .  v3 - the result

2640:    Notes:
2641:    The vectors v1 and v3 cannot be the same.  I.e., one cannot
2642:    call MatMultHermitianTransposeAdd(A,v1,v2,v1).

2644:    Level: beginner

2646: .seealso: MatMultHermitianTranspose(), MatMultTranspose(), MatMultAdd(), MatMult()
2647: @*/
2648: PetscErrorCode MatMultHermitianTransposeAdd(Mat mat,Vec v1,Vec v2,Vec v3)
2649: {


2659:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2660:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2661:   if (v1 == v3) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"v1 and v3 must be different vectors");
2662:   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);
2663:   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);
2664:   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);
2665:   MatCheckPreallocated(mat,1);

2667:   PetscLogEventBegin(MAT_MultHermitianTransposeAdd,mat,v1,v2,v3);
2668:   VecLockReadPush(v1);
2669:   if (mat->ops->multhermitiantransposeadd) {
2670:     (*mat->ops->multhermitiantransposeadd)(mat,v1,v2,v3);
2671:   } else {
2672:     Vec w,z;
2673:     VecDuplicate(v1,&w);
2674:     VecCopy(v1,w);
2675:     VecConjugate(w);
2676:     VecDuplicate(v3,&z);
2677:     MatMultTranspose(mat,w,z);
2678:     VecDestroy(&w);
2679:     VecConjugate(z);
2680:     if (v2 != v3) {
2681:       VecWAXPY(v3,1.0,v2,z);
2682:     } else {
2683:       VecAXPY(v3,1.0,z);
2684:     }
2685:     VecDestroy(&z);
2686:   }
2687:   VecLockReadPop(v1);
2688:   PetscLogEventEnd(MAT_MultHermitianTransposeAdd,mat,v1,v2,v3);
2689:   PetscObjectStateIncrease((PetscObject)v3);
2690:   return(0);
2691: }

2693: /*@
2694:    MatMultConstrained - The inner multiplication routine for a
2695:    constrained matrix P^T A P.

2697:    Neighbor-wise Collective on Mat

2699:    Input Parameters:
2700: +  mat - the matrix
2701: -  x   - the vector to be multilplied

2703:    Output Parameters:
2704: .  y - the result

2706:    Notes:
2707:    The vectors x and y cannot be the same.  I.e., one cannot
2708:    call MatMult(A,y,y).

2710:    Level: beginner

2712: .seealso: MatMult(), MatMultTranspose(), MatMultAdd(), MatMultTransposeAdd()
2713: @*/
2714: PetscErrorCode MatMultConstrained(Mat mat,Vec x,Vec y)
2715: {

2722:   if (!mat->assembled) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2723:   if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2724:   if (x == y) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"x and y must be different vectors");
2725:   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);
2726:   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);
2727:   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);

2729:   PetscLogEventBegin(MAT_MultConstrained,mat,x,y,0);
2730:   VecLockReadPush(x);
2731:   (*mat->ops->multconstrained)(mat,x,y);
2732:   VecLockReadPop(x);
2733:   PetscLogEventEnd(MAT_MultConstrained,mat,x,y,0);
2734:   PetscObjectStateIncrease((PetscObject)y);
2735:   return(0);
2736: }

2738: /*@
2739:    MatMultTransposeConstrained - The inner multiplication routine for a
2740:    constrained matrix P^T A^T P.

2742:    Neighbor-wise Collective on Mat

2744:    Input Parameters:
2745: +  mat - the matrix
2746: -  x   - the vector to be multilplied

2748:    Output Parameters:
2749: .  y - the result

2751:    Notes:
2752:    The vectors x and y cannot be the same.  I.e., one cannot
2753:    call MatMult(A,y,y).

2755:    Level: beginner

2757: .seealso: MatMult(), MatMultTranspose(), MatMultAdd(), MatMultTransposeAdd()
2758: @*/
2759: PetscErrorCode MatMultTransposeConstrained(Mat mat,Vec x,Vec y)
2760: {

2767:   if (!mat->assembled) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2768:   if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2769:   if (x == y) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"x and y must be different vectors");
2770:   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);
2771:   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);

2773:   PetscLogEventBegin(MAT_MultConstrained,mat,x,y,0);
2774:   (*mat->ops->multtransposeconstrained)(mat,x,y);
2775:   PetscLogEventEnd(MAT_MultConstrained,mat,x,y,0);
2776:   PetscObjectStateIncrease((PetscObject)y);
2777:   return(0);
2778: }

2780: /*@C
2781:    MatGetFactorType - gets the type of factorization it is

2783:    Not Collective

2785:    Input Parameters:
2786: .  mat - the matrix

2788:    Output Parameters:
2789: .  t - the type, one of MAT_FACTOR_NONE, MAT_FACTOR_LU, MAT_FACTOR_CHOLESKY, MAT_FACTOR_ILU, MAT_FACTOR_ICC,MAT_FACTOR_ILUDT

2791:    Level: intermediate

2793: .seealso: MatFactorType, MatGetFactor(), MatSetFactorType()
2794: @*/
2795: PetscErrorCode MatGetFactorType(Mat mat,MatFactorType *t)
2796: {
2801:   *t = mat->factortype;
2802:   return(0);
2803: }

2805: /*@C
2806:    MatSetFactorType - sets the type of factorization it is

2808:    Logically Collective on Mat

2810:    Input Parameters:
2811: +  mat - the matrix
2812: -  t - the type, one of MAT_FACTOR_NONE, MAT_FACTOR_LU, MAT_FACTOR_CHOLESKY, MAT_FACTOR_ILU, MAT_FACTOR_ICC,MAT_FACTOR_ILUDT

2814:    Level: intermediate

2816: .seealso: MatFactorType, MatGetFactor(), MatGetFactorType()
2817: @*/
2818: PetscErrorCode MatSetFactorType(Mat mat, MatFactorType t)
2819: {
2823:   mat->factortype = t;
2824:   return(0);
2825: }

2827: /* ------------------------------------------------------------*/
2828: /*@C
2829:    MatGetInfo - Returns information about matrix storage (number of
2830:    nonzeros, memory, etc.).

2832:    Collective on Mat if MAT_GLOBAL_MAX or MAT_GLOBAL_SUM is used as the flag

2834:    Input Parameters:
2835: .  mat - the matrix

2837:    Output Parameters:
2838: +  flag - flag indicating the type of parameters to be returned
2839:    (MAT_LOCAL - local matrix, MAT_GLOBAL_MAX - maximum over all processors,
2840:    MAT_GLOBAL_SUM - sum over all processors)
2841: -  info - matrix information context

2843:    Notes:
2844:    The MatInfo context contains a variety of matrix data, including
2845:    number of nonzeros allocated and used, number of mallocs during
2846:    matrix assembly, etc.  Additional information for factored matrices
2847:    is provided (such as the fill ratio, number of mallocs during
2848:    factorization, etc.).  Much of this info is printed to PETSC_STDOUT
2849:    when using the runtime options
2850: $       -info -mat_view ::ascii_info

2852:    Example for C/C++ Users:
2853:    See the file ${PETSC_DIR}/include/petscmat.h for a complete list of
2854:    data within the MatInfo context.  For example,
2855: .vb
2856:       MatInfo info;
2857:       Mat     A;
2858:       double  mal, nz_a, nz_u;

2860:       MatGetInfo(A,MAT_LOCAL,&info);
2861:       mal  = info.mallocs;
2862:       nz_a = info.nz_allocated;
2863: .ve

2865:    Example for Fortran Users:
2866:    Fortran users should declare info as a double precision
2867:    array of dimension MAT_INFO_SIZE, and then extract the parameters
2868:    of interest.  See the file ${PETSC_DIR}/include/petsc/finclude/petscmat.h
2869:    a complete list of parameter names.
2870: .vb
2871:       double  precision info(MAT_INFO_SIZE)
2872:       double  precision mal, nz_a
2873:       Mat     A
2874:       integer ierr

2876:       call MatGetInfo(A,MAT_LOCAL,info,ierr)
2877:       mal = info(MAT_INFO_MALLOCS)
2878:       nz_a = info(MAT_INFO_NZ_ALLOCATED)
2879: .ve

2881:     Level: intermediate

2883:     Developer Note: fortran interface is not autogenerated as the f90
2884:     interface defintion cannot be generated correctly [due to MatInfo]

2886: .seealso: MatStashGetInfo()

2888: @*/
2889: PetscErrorCode MatGetInfo(Mat mat,MatInfoType flag,MatInfo *info)
2890: {

2897:   if (!mat->ops->getinfo) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
2898:   MatCheckPreallocated(mat,1);
2899:   (*mat->ops->getinfo)(mat,flag,info);
2900:   return(0);
2901: }

2903: /*
2904:    This is used by external packages where it is not easy to get the info from the actual
2905:    matrix factorization.
2906: */
2907: PetscErrorCode MatGetInfo_External(Mat A,MatInfoType flag,MatInfo *info)
2908: {

2912:   PetscMemzero(info,sizeof(MatInfo));
2913:   return(0);
2914: }

2916: /* ----------------------------------------------------------*/

2918: /*@C
2919:    MatLUFactor - Performs in-place LU factorization of matrix.

2921:    Collective on Mat

2923:    Input Parameters:
2924: +  mat - the matrix
2925: .  row - row permutation
2926: .  col - column permutation
2927: -  info - options for factorization, includes
2928: $          fill - expected fill as ratio of original fill.
2929: $          dtcol - pivot tolerance (0 no pivot, 1 full column pivoting)
2930: $                   Run with the option -info to determine an optimal value to use

2932:    Notes:
2933:    Most users should employ the simplified KSP interface for linear solvers
2934:    instead of working directly with matrix algebra routines such as this.
2935:    See, e.g., KSPCreate().

2937:    This changes the state of the matrix to a factored matrix; it cannot be used
2938:    for example with MatSetValues() unless one first calls MatSetUnfactored().

2940:    Level: developer

2942: .seealso: MatLUFactorSymbolic(), MatLUFactorNumeric(), MatCholeskyFactor(),
2943:           MatGetOrdering(), MatSetUnfactored(), MatFactorInfo, MatGetFactor()

2945:     Developer Note: fortran interface is not autogenerated as the f90
2946:     interface defintion cannot be generated correctly [due to MatFactorInfo]

2948: @*/
2949: PetscErrorCode MatLUFactor(Mat mat,IS row,IS col,const MatFactorInfo *info)
2950: {
2952:   MatFactorInfo  tinfo;

2960:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2961:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2962:   if (!mat->ops->lufactor) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
2963:   MatCheckPreallocated(mat,1);
2964:   if (!info) {
2965:     MatFactorInfoInitialize(&tinfo);
2966:     info = &tinfo;
2967:   }

2969:   PetscLogEventBegin(MAT_LUFactor,mat,row,col,0);
2970:   (*mat->ops->lufactor)(mat,row,col,info);
2971:   PetscLogEventEnd(MAT_LUFactor,mat,row,col,0);
2972:   PetscObjectStateIncrease((PetscObject)mat);
2973:   return(0);
2974: }

2976: /*@C
2977:    MatILUFactor - Performs in-place ILU factorization of matrix.

2979:    Collective on Mat

2981:    Input Parameters:
2982: +  mat - the matrix
2983: .  row - row permutation
2984: .  col - column permutation
2985: -  info - structure containing
2986: $      levels - number of levels of fill.
2987: $      expected fill - as ratio of original fill.
2988: $      1 or 0 - indicating force fill on diagonal (improves robustness for matrices
2989:                 missing diagonal entries)

2991:    Notes:
2992:    Probably really in-place only when level of fill is zero, otherwise allocates
2993:    new space to store factored matrix and deletes previous memory.

2995:    Most users should employ the simplified KSP interface for linear solvers
2996:    instead of working directly with matrix algebra routines such as this.
2997:    See, e.g., KSPCreate().

2999:    Level: developer

3001: .seealso: MatILUFactorSymbolic(), MatLUFactorNumeric(), MatCholeskyFactor(), MatFactorInfo

3003:     Developer Note: fortran interface is not autogenerated as the f90
3004:     interface defintion cannot be generated correctly [due to MatFactorInfo]

3006: @*/
3007: PetscErrorCode MatILUFactor(Mat mat,IS row,IS col,const MatFactorInfo *info)
3008: {

3017:   if (mat->rmap->N != mat->cmap->N) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONG,"matrix must be square");
3018:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
3019:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
3020:   if (!mat->ops->ilufactor) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
3021:   MatCheckPreallocated(mat,1);

3023:   PetscLogEventBegin(MAT_ILUFactor,mat,row,col,0);
3024:   (*mat->ops->ilufactor)(mat,row,col,info);
3025:   PetscLogEventEnd(MAT_ILUFactor,mat,row,col,0);
3026:   PetscObjectStateIncrease((PetscObject)mat);
3027:   return(0);
3028: }

3030: /*@C
3031:    MatLUFactorSymbolic - Performs symbolic LU factorization of matrix.
3032:    Call this routine before calling MatLUFactorNumeric().

3034:    Collective on Mat

3036:    Input Parameters:
3037: +  fact - the factor matrix obtained with MatGetFactor()
3038: .  mat - the matrix
3039: .  row, col - row and column permutations
3040: -  info - options for factorization, includes
3041: $          fill - expected fill as ratio of original fill.
3042: $          dtcol - pivot tolerance (0 no pivot, 1 full column pivoting)
3043: $                   Run with the option -info to determine an optimal value to use


3046:    Notes:
3047:     See Users-Manual: ch_mat for additional information about choosing the fill factor for better efficiency.

3049:    Most users should employ the simplified KSP interface for linear solvers
3050:    instead of working directly with matrix algebra routines such as this.
3051:    See, e.g., KSPCreate().

3053:    Level: developer

3055: .seealso: MatLUFactor(), MatLUFactorNumeric(), MatCholeskyFactor(), MatFactorInfo, MatFactorInfoInitialize()

3057:     Developer Note: fortran interface is not autogenerated as the f90
3058:     interface defintion cannot be generated correctly [due to MatFactorInfo]

3060: @*/
3061: PetscErrorCode MatLUFactorSymbolic(Mat fact,Mat mat,IS row,IS col,const MatFactorInfo *info)
3062: {
3064:   MatFactorInfo  tinfo;

3073:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
3074:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
3075:   if (!(fact)->ops->lufactorsymbolic) {
3076:     MatSolverType spackage;
3077:     MatFactorGetSolverType(fact,&spackage);
3078:     SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Matrix type %s symbolic LU using solver package %s",((PetscObject)mat)->type_name,spackage);
3079:   }
3080:   MatCheckPreallocated(mat,2);
3081:   if (!info) {
3082:     MatFactorInfoInitialize(&tinfo);
3083:     info = &tinfo;
3084:   }

3086:   PetscLogEventBegin(MAT_LUFactorSymbolic,mat,row,col,0);
3087:   (fact->ops->lufactorsymbolic)(fact,mat,row,col,info);
3088:   PetscLogEventEnd(MAT_LUFactorSymbolic,mat,row,col,0);
3089:   PetscObjectStateIncrease((PetscObject)fact);
3090:   return(0);
3091: }

3093: /*@C
3094:    MatLUFactorNumeric - Performs numeric LU factorization of a matrix.
3095:    Call this routine after first calling MatLUFactorSymbolic().

3097:    Collective on Mat

3099:    Input Parameters:
3100: +  fact - the factor matrix obtained with MatGetFactor()
3101: .  mat - the matrix
3102: -  info - options for factorization

3104:    Notes:
3105:    See MatLUFactor() for in-place factorization.  See
3106:    MatCholeskyFactorNumeric() for the symmetric, positive definite case.

3108:    Most users should employ the simplified KSP interface for linear solvers
3109:    instead of working directly with matrix algebra routines such as this.
3110:    See, e.g., KSPCreate().

3112:    Level: developer

3114: .seealso: MatLUFactorSymbolic(), MatLUFactor(), MatCholeskyFactor()

3116:     Developer Note: fortran interface is not autogenerated as the f90
3117:     interface defintion cannot be generated correctly [due to MatFactorInfo]

3119: @*/
3120: PetscErrorCode MatLUFactorNumeric(Mat fact,Mat mat,const MatFactorInfo *info)
3121: {
3122:   MatFactorInfo  tinfo;

3130:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
3131:   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);

3133:   if (!(fact)->ops->lufactornumeric) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s numeric LU",((PetscObject)mat)->type_name);
3134:   MatCheckPreallocated(mat,2);
3135:   if (!info) {
3136:     MatFactorInfoInitialize(&tinfo);
3137:     info = &tinfo;
3138:   }

3140:   PetscLogEventBegin(MAT_LUFactorNumeric,mat,fact,0,0);
3141:   (fact->ops->lufactornumeric)(fact,mat,info);
3142:   PetscLogEventEnd(MAT_LUFactorNumeric,mat,fact,0,0);
3143:   MatViewFromOptions(fact,NULL,"-mat_factor_view");
3144:   PetscObjectStateIncrease((PetscObject)fact);
3145:   return(0);
3146: }

3148: /*@C
3149:    MatCholeskyFactor - Performs in-place Cholesky factorization of a
3150:    symmetric matrix.

3152:    Collective on Mat

3154:    Input Parameters:
3155: +  mat - the matrix
3156: .  perm - row and column permutations
3157: -  f - expected fill as ratio of original fill

3159:    Notes:
3160:    See MatLUFactor() for the nonsymmetric case.  See also
3161:    MatCholeskyFactorSymbolic(), and MatCholeskyFactorNumeric().

3163:    Most users should employ the simplified KSP interface for linear solvers
3164:    instead of working directly with matrix algebra routines such as this.
3165:    See, e.g., KSPCreate().

3167:    Level: developer

3169: .seealso: MatLUFactor(), MatCholeskyFactorSymbolic(), MatCholeskyFactorNumeric()
3170:           MatGetOrdering()

3172:     Developer Note: fortran interface is not autogenerated as the f90
3173:     interface defintion cannot be generated correctly [due to MatFactorInfo]

3175: @*/
3176: PetscErrorCode MatCholeskyFactor(Mat mat,IS perm,const MatFactorInfo *info)
3177: {
3179:   MatFactorInfo  tinfo;

3186:   if (mat->rmap->N != mat->cmap->N) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONG,"Matrix must be square");
3187:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
3188:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
3189:   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);
3190:   MatCheckPreallocated(mat,1);
3191:   if (!info) {
3192:     MatFactorInfoInitialize(&tinfo);
3193:     info = &tinfo;
3194:   }

3196:   PetscLogEventBegin(MAT_CholeskyFactor,mat,perm,0,0);
3197:   (*mat->ops->choleskyfactor)(mat,perm,info);
3198:   PetscLogEventEnd(MAT_CholeskyFactor,mat,perm,0,0);
3199:   PetscObjectStateIncrease((PetscObject)mat);
3200:   return(0);
3201: }

3203: /*@C
3204:    MatCholeskyFactorSymbolic - Performs symbolic Cholesky factorization
3205:    of a symmetric matrix.

3207:    Collective on Mat

3209:    Input Parameters:
3210: +  fact - the factor matrix obtained with MatGetFactor()
3211: .  mat - the matrix
3212: .  perm - row and column permutations
3213: -  info - options for factorization, includes
3214: $          fill - expected fill as ratio of original fill.
3215: $          dtcol - pivot tolerance (0 no pivot, 1 full column pivoting)
3216: $                   Run with the option -info to determine an optimal value to use

3218:    Notes:
3219:    See MatLUFactorSymbolic() for the nonsymmetric case.  See also
3220:    MatCholeskyFactor() and MatCholeskyFactorNumeric().

3222:    Most users should employ the simplified KSP interface for linear solvers
3223:    instead of working directly with matrix algebra routines such as this.
3224:    See, e.g., KSPCreate().

3226:    Level: developer

3228: .seealso: MatLUFactorSymbolic(), MatCholeskyFactor(), MatCholeskyFactorNumeric()
3229:           MatGetOrdering()

3231:     Developer Note: fortran interface is not autogenerated as the f90
3232:     interface defintion cannot be generated correctly [due to MatFactorInfo]

3234: @*/
3235: PetscErrorCode MatCholeskyFactorSymbolic(Mat fact,Mat mat,IS perm,const MatFactorInfo *info)
3236: {
3238:   MatFactorInfo  tinfo;

3246:   if (mat->rmap->N != mat->cmap->N) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONG,"Matrix must be square");
3247:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
3248:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
3249:   if (!(fact)->ops->choleskyfactorsymbolic) {
3250:     MatSolverType spackage;
3251:     MatFactorGetSolverType(fact,&spackage);
3252:     SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s symbolic factor Cholesky using solver package %s",((PetscObject)mat)->type_name,spackage);
3253:   }
3254:   MatCheckPreallocated(mat,2);
3255:   if (!info) {
3256:     MatFactorInfoInitialize(&tinfo);
3257:     info = &tinfo;
3258:   }

3260:   PetscLogEventBegin(MAT_CholeskyFactorSymbolic,mat,perm,0,0);
3261:   (fact->ops->choleskyfactorsymbolic)(fact,mat,perm,info);
3262:   PetscLogEventEnd(MAT_CholeskyFactorSymbolic,mat,perm,0,0);
3263:   PetscObjectStateIncrease((PetscObject)fact);
3264:   return(0);
3265: }

3267: /*@C
3268:    MatCholeskyFactorNumeric - Performs numeric Cholesky factorization
3269:    of a symmetric matrix. Call this routine after first calling
3270:    MatCholeskyFactorSymbolic().

3272:    Collective on Mat

3274:    Input Parameters:
3275: +  fact - the factor matrix obtained with MatGetFactor()
3276: .  mat - the initial matrix
3277: .  info - options for factorization
3278: -  fact - the symbolic factor of mat


3281:    Notes:
3282:    Most users should employ the simplified KSP interface for linear solvers
3283:    instead of working directly with matrix algebra routines such as this.
3284:    See, e.g., KSPCreate().

3286:    Level: developer

3288: .seealso: MatCholeskyFactorSymbolic(), MatCholeskyFactor(), MatLUFactorNumeric()

3290:     Developer Note: fortran interface is not autogenerated as the f90
3291:     interface defintion cannot be generated correctly [due to MatFactorInfo]

3293: @*/
3294: PetscErrorCode MatCholeskyFactorNumeric(Mat fact,Mat mat,const MatFactorInfo *info)
3295: {
3296:   MatFactorInfo  tinfo;

3304:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
3305:   if (!(fact)->ops->choleskyfactornumeric) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s numeric factor Cholesky",((PetscObject)mat)->type_name);
3306:   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);
3307:   MatCheckPreallocated(mat,2);
3308:   if (!info) {
3309:     MatFactorInfoInitialize(&tinfo);
3310:     info = &tinfo;
3311:   }

3313:   PetscLogEventBegin(MAT_CholeskyFactorNumeric,mat,fact,0,0);
3314:   (fact->ops->choleskyfactornumeric)(fact,mat,info);
3315:   PetscLogEventEnd(MAT_CholeskyFactorNumeric,mat,fact,0,0);
3316:   MatViewFromOptions(fact,NULL,"-mat_factor_view");
3317:   PetscObjectStateIncrease((PetscObject)fact);
3318:   return(0);
3319: }

3321: /* ----------------------------------------------------------------*/
3322: /*@
3323:    MatSolve - Solves A x = b, given a factored matrix.

3325:    Neighbor-wise Collective on Mat

3327:    Input Parameters:
3328: +  mat - the factored matrix
3329: -  b - the right-hand-side vector

3331:    Output Parameter:
3332: .  x - the result vector

3334:    Notes:
3335:    The vectors b and x cannot be the same.  I.e., one cannot
3336:    call MatSolve(A,x,x).

3338:    Notes:
3339:    Most users should employ the simplified KSP interface for linear solvers
3340:    instead of working directly with matrix algebra routines such as this.
3341:    See, e.g., KSPCreate().

3343:    Level: developer

3345: .seealso: MatSolveAdd(), MatSolveTranspose(), MatSolveTransposeAdd()
3346: @*/
3347: PetscErrorCode MatSolve(Mat mat,Vec b,Vec x)
3348: {

3358:   if (x == b) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"x and b must be different vectors");
3359:   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);
3360:   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);
3361:   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);
3362:   if (!mat->rmap->N && !mat->cmap->N) return(0);
3363:   MatCheckPreallocated(mat,1);

3365:   PetscLogEventBegin(MAT_Solve,mat,b,x,0);
3366:   if (mat->factorerrortype) {
3367:     PetscInfo1(mat,"MatFactorError %D\n",mat->factorerrortype);
3368:     VecSetInf(x);
3369:   } else {
3370:     if (!mat->ops->solve) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
3371:     (*mat->ops->solve)(mat,b,x);
3372:   }
3373:   PetscLogEventEnd(MAT_Solve,mat,b,x,0);
3374:   PetscObjectStateIncrease((PetscObject)x);
3375:   return(0);
3376: }

3378: static PetscErrorCode MatMatSolve_Basic(Mat A,Mat B,Mat X,PetscBool trans)
3379: {
3381:   Vec            b,x;
3382:   PetscInt       m,N,i;
3383:   PetscScalar    *bb,*xx;

3386:   MatDenseGetArrayRead(B,(const PetscScalar**)&bb);
3387:   MatDenseGetArray(X,&xx);
3388:   MatGetLocalSize(B,&m,NULL);  /* number local rows */
3389:   MatGetSize(B,NULL,&N);       /* total columns in dense matrix */
3390:   MatCreateVecs(A,&x,&b);
3391:   for (i=0; i<N; i++) {
3392:     VecPlaceArray(b,bb + i*m);
3393:     VecPlaceArray(x,xx + i*m);
3394:     if (trans) {
3395:       MatSolveTranspose(A,b,x);
3396:     } else {
3397:       MatSolve(A,b,x);
3398:     }
3399:     VecResetArray(x);
3400:     VecResetArray(b);
3401:   }
3402:   VecDestroy(&b);
3403:   VecDestroy(&x);
3404:   MatDenseRestoreArrayRead(B,(const PetscScalar**)&bb);
3405:   MatDenseRestoreArray(X,&xx);
3406:   return(0);
3407: }

3409: /*@
3410:    MatMatSolve - Solves A X = B, given a factored matrix.

3412:    Neighbor-wise Collective on Mat

3414:    Input Parameters:
3415: +  A - the factored matrix
3416: -  B - the right-hand-side matrix MATDENSE (or sparse -- when using MUMPS)

3418:    Output Parameter:
3419: .  X - the result matrix (dense matrix)

3421:    Notes:
3422:    If B is a MATDENSE matrix then one can call MatMatSolve(A,B,B);
3423:    otherwise, B and X cannot be the same.

3425:    Notes:
3426:    Most users should usually employ the simplified KSP interface for linear solvers
3427:    instead of working directly with matrix algebra routines such as this.
3428:    See, e.g., KSPCreate(). However KSP can only solve for one vector (column of X)
3429:    at a time.

3431:    Level: developer

3433: .seealso: MatMatSolveTranspose(), MatLUFactor(), MatCholeskyFactor()
3434: @*/
3435: PetscErrorCode MatMatSolve(Mat A,Mat B,Mat X)
3436: {

3446:   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);
3447:   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);
3448:   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");
3449:   if (!A->rmap->N && !A->cmap->N) return(0);
3450:   if (!A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
3451:   MatCheckPreallocated(A,1);

3453:   PetscLogEventBegin(MAT_MatSolve,A,B,X,0);
3454:   if (!A->ops->matsolve) {
3455:     PetscInfo1(A,"Mat type %s using basic MatMatSolve\n",((PetscObject)A)->type_name);
3456:     MatMatSolve_Basic(A,B,X,PETSC_FALSE);
3457:   } else {
3458:     (*A->ops->matsolve)(A,B,X);
3459:   }
3460:   PetscLogEventEnd(MAT_MatSolve,A,B,X,0);
3461:   PetscObjectStateIncrease((PetscObject)X);
3462:   return(0);
3463: }

3465: /*@
3466:    MatMatSolveTranspose - Solves A^T X = B, given a factored matrix.

3468:    Neighbor-wise Collective on Mat

3470:    Input Parameters:
3471: +  A - the factored matrix
3472: -  B - the right-hand-side matrix  (dense matrix)

3474:    Output Parameter:
3475: .  X - the result matrix (dense matrix)

3477:    Notes:
3478:    The matrices B and X cannot be the same.  I.e., one cannot
3479:    call MatMatSolveTranspose(A,X,X).

3481:    Notes:
3482:    Most users should usually employ the simplified KSP interface for linear solvers
3483:    instead of working directly with matrix algebra routines such as this.
3484:    See, e.g., KSPCreate(). However KSP can only solve for one vector (column of X)
3485:    at a time.

3487:    When using SuperLU_Dist or MUMPS as a parallel solver, PETSc will use their functionality to solve multiple right hand sides simultaneously.

3489:    Level: developer

3491: .seealso: MatMatSolve(), MatLUFactor(), MatCholeskyFactor()
3492: @*/
3493: PetscErrorCode MatMatSolveTranspose(Mat A,Mat B,Mat X)
3494: {

3504:   if (X == B) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_IDN,"X and B must be different matrices");
3505:   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);
3506:   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);
3507:   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);
3508:   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");
3509:   if (!A->rmap->N && !A->cmap->N) return(0);
3510:   if (!A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
3511:   MatCheckPreallocated(A,1);

3513:   PetscLogEventBegin(MAT_MatSolve,A,B,X,0);
3514:   if (!A->ops->matsolvetranspose) {
3515:     PetscInfo1(A,"Mat type %s using basic MatMatSolveTranspose\n",((PetscObject)A)->type_name);
3516:     MatMatSolve_Basic(A,B,X,PETSC_TRUE);
3517:   } else {
3518:     (*A->ops->matsolvetranspose)(A,B,X);
3519:   }
3520:   PetscLogEventEnd(MAT_MatSolve,A,B,X,0);
3521:   PetscObjectStateIncrease((PetscObject)X);
3522:   return(0);
3523: }

3525: /*@
3526:    MatMatTransposeSolve - Solves A X = B^T, given a factored matrix.

3528:    Neighbor-wise Collective on Mat

3530:    Input Parameters:
3531: +  A - the factored matrix
3532: -  Bt - the transpose of right-hand-side matrix

3534:    Output Parameter:
3535: .  X - the result matrix (dense matrix)

3537:    Notes:
3538:    Most users should usually employ the simplified KSP interface for linear solvers
3539:    instead of working directly with matrix algebra routines such as this.
3540:    See, e.g., KSPCreate(). However KSP can only solve for one vector (column of X)
3541:    at a time.

3543:    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().

3545:    Level: developer

3547: .seealso: MatMatSolve(), MatMatSolveTranspose(), MatLUFactor(), MatCholeskyFactor()
3548: @*/
3549: PetscErrorCode MatMatTransposeSolve(Mat A,Mat Bt,Mat X)
3550: {


3561:   if (X == Bt) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_IDN,"X and B must be different matrices");
3562:   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);
3563:   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);
3564:   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");
3565:   if (!A->rmap->N && !A->cmap->N) return(0);
3566:   if (!A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
3567:   MatCheckPreallocated(A,1);

3569:   if (!A->ops->mattransposesolve) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Mat type %s",((PetscObject)A)->type_name);
3570:   PetscLogEventBegin(MAT_MatTrSolve,A,Bt,X,0);
3571:   (*A->ops->mattransposesolve)(A,Bt,X);
3572:   PetscLogEventEnd(MAT_MatTrSolve,A,Bt,X,0);
3573:   PetscObjectStateIncrease((PetscObject)X);
3574:   return(0);
3575: }

3577: /*@
3578:    MatForwardSolve - Solves L x = b, given a factored matrix, A = LU, or
3579:                             U^T*D^(1/2) x = b, given a factored symmetric matrix, A = U^T*D*U,

3581:    Neighbor-wise Collective on Mat

3583:    Input Parameters:
3584: +  mat - the factored matrix
3585: -  b - the right-hand-side vector

3587:    Output Parameter:
3588: .  x - the result vector

3590:    Notes:
3591:    MatSolve() should be used for most applications, as it performs
3592:    a forward solve followed by a backward solve.

3594:    The vectors b and x cannot be the same,  i.e., one cannot
3595:    call MatForwardSolve(A,x,x).

3597:    For matrix in seqsbaij format with block size larger than 1,
3598:    the diagonal blocks are not implemented as D = D^(1/2) * D^(1/2) yet.
3599:    MatForwardSolve() solves U^T*D y = b, and
3600:    MatBackwardSolve() solves U x = y.
3601:    Thus they do not provide a symmetric preconditioner.

3603:    Most users should employ the simplified KSP interface for linear solvers
3604:    instead of working directly with matrix algebra routines such as this.
3605:    See, e.g., KSPCreate().

3607:    Level: developer

3609: .seealso: MatSolve(), MatBackwardSolve()
3610: @*/
3611: PetscErrorCode MatForwardSolve(Mat mat,Vec b,Vec x)
3612: {

3622:   if (x == b) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"x and b must be different vectors");
3623:   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);
3624:   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);
3625:   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);
3626:   if (!mat->rmap->N && !mat->cmap->N) return(0);
3627:   MatCheckPreallocated(mat,1);

3629:   if (!mat->ops->forwardsolve) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
3630:   PetscLogEventBegin(MAT_ForwardSolve,mat,b,x,0);
3631:   (*mat->ops->forwardsolve)(mat,b,x);
3632:   PetscLogEventEnd(MAT_ForwardSolve,mat,b,x,0);
3633:   PetscObjectStateIncrease((PetscObject)x);
3634:   return(0);
3635: }

3637: /*@
3638:    MatBackwardSolve - Solves U x = b, given a factored matrix, A = LU.
3639:                              D^(1/2) U x = b, given a factored symmetric matrix, A = U^T*D*U,

3641:    Neighbor-wise Collective on Mat

3643:    Input Parameters:
3644: +  mat - the factored matrix
3645: -  b - the right-hand-side vector

3647:    Output Parameter:
3648: .  x - the result vector

3650:    Notes:
3651:    MatSolve() should be used for most applications, as it performs
3652:    a forward solve followed by a backward solve.

3654:    The vectors b and x cannot be the same.  I.e., one cannot
3655:    call MatBackwardSolve(A,x,x).

3657:    For matrix in seqsbaij format with block size larger than 1,
3658:    the diagonal blocks are not implemented as D = D^(1/2) * D^(1/2) yet.
3659:    MatForwardSolve() solves U^T*D y = b, and
3660:    MatBackwardSolve() solves U x = y.
3661:    Thus they do not provide a symmetric preconditioner.

3663:    Most users should employ the simplified KSP interface for linear solvers
3664:    instead of working directly with matrix algebra routines such as this.
3665:    See, e.g., KSPCreate().

3667:    Level: developer

3669: .seealso: MatSolve(), MatForwardSolve()
3670: @*/
3671: PetscErrorCode MatBackwardSolve(Mat mat,Vec b,Vec x)
3672: {

3682:   if (x == b) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"x and b must be different vectors");
3683:   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);
3684:   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);
3685:   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);
3686:   if (!mat->rmap->N && !mat->cmap->N) return(0);
3687:   MatCheckPreallocated(mat,1);

3689:   if (!mat->ops->backwardsolve) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
3690:   PetscLogEventBegin(MAT_BackwardSolve,mat,b,x,0);
3691:   (*mat->ops->backwardsolve)(mat,b,x);
3692:   PetscLogEventEnd(MAT_BackwardSolve,mat,b,x,0);
3693:   PetscObjectStateIncrease((PetscObject)x);
3694:   return(0);
3695: }

3697: /*@
3698:    MatSolveAdd - Computes x = y + inv(A)*b, given a factored matrix.

3700:    Neighbor-wise Collective on Mat

3702:    Input Parameters:
3703: +  mat - the factored matrix
3704: .  b - the right-hand-side vector
3705: -  y - the vector to be added to

3707:    Output Parameter:
3708: .  x - the result vector

3710:    Notes:
3711:    The vectors b and x cannot be the same.  I.e., one cannot
3712:    call MatSolveAdd(A,x,y,x).

3714:    Most users should employ the simplified KSP interface for linear solvers
3715:    instead of working directly with matrix algebra routines such as this.
3716:    See, e.g., KSPCreate().

3718:    Level: developer

3720: .seealso: MatSolve(), MatSolveTranspose(), MatSolveTransposeAdd()
3721: @*/
3722: PetscErrorCode MatSolveAdd(Mat mat,Vec b,Vec y,Vec x)
3723: {
3724:   PetscScalar    one = 1.0;
3725:   Vec            tmp;

3737:   if (x == b) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"x and b must be different vectors");
3738:   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);
3739:   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);
3740:   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);
3741:   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);
3742:   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);
3743:   if (!mat->rmap->N && !mat->cmap->N) return(0);
3744:    MatCheckPreallocated(mat,1);

3746:   PetscLogEventBegin(MAT_SolveAdd,mat,b,x,y);
3747:   if (mat->factorerrortype) {
3748:     PetscInfo1(mat,"MatFactorError %D\n",mat->factorerrortype);
3749:     VecSetInf(x);
3750:   } else if (mat->ops->solveadd) {
3751:     (*mat->ops->solveadd)(mat,b,y,x);
3752:   } else {
3753:     /* do the solve then the add manually */
3754:     if (x != y) {
3755:       MatSolve(mat,b,x);
3756:       VecAXPY(x,one,y);
3757:     } else {
3758:       VecDuplicate(x,&tmp);
3759:       PetscLogObjectParent((PetscObject)mat,(PetscObject)tmp);
3760:       VecCopy(x,tmp);
3761:       MatSolve(mat,b,x);
3762:       VecAXPY(x,one,tmp);
3763:       VecDestroy(&tmp);
3764:     }
3765:   }
3766:   PetscLogEventEnd(MAT_SolveAdd,mat,b,x,y);
3767:   PetscObjectStateIncrease((PetscObject)x);
3768:   return(0);
3769: }

3771: /*@
3772:    MatSolveTranspose - Solves A' x = b, given a factored matrix.

3774:    Neighbor-wise Collective on Mat

3776:    Input Parameters:
3777: +  mat - the factored matrix
3778: -  b - the right-hand-side vector

3780:    Output Parameter:
3781: .  x - the result vector

3783:    Notes:
3784:    The vectors b and x cannot be the same.  I.e., one cannot
3785:    call MatSolveTranspose(A,x,x).

3787:    Most users should employ the simplified KSP interface for linear solvers
3788:    instead of working directly with matrix algebra routines such as this.
3789:    See, e.g., KSPCreate().

3791:    Level: developer

3793: .seealso: MatSolve(), MatSolveAdd(), MatSolveTransposeAdd()
3794: @*/
3795: PetscErrorCode MatSolveTranspose(Mat mat,Vec b,Vec x)
3796: {

3806:   if (x == b) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"x and b must be different vectors");
3807:   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);
3808:   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);
3809:   if (!mat->rmap->N && !mat->cmap->N) return(0);
3810:   MatCheckPreallocated(mat,1);
3811:   PetscLogEventBegin(MAT_SolveTranspose,mat,b,x,0);
3812:   if (mat->factorerrortype) {
3813:     PetscInfo1(mat,"MatFactorError %D\n",mat->factorerrortype);
3814:     VecSetInf(x);
3815:   } else {
3816:     if (!mat->ops->solvetranspose) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Matrix type %s",((PetscObject)mat)->type_name);
3817:     (*mat->ops->solvetranspose)(mat,b,x);
3818:   }
3819:   PetscLogEventEnd(MAT_SolveTranspose,mat,b,x,0);
3820:   PetscObjectStateIncrease((PetscObject)x);
3821:   return(0);
3822: }

3824: /*@
3825:    MatSolveTransposeAdd - Computes x = y + inv(Transpose(A)) b, given a
3826:                       factored matrix.

3828:    Neighbor-wise Collective on Mat

3830:    Input Parameters:
3831: +  mat - the factored matrix
3832: .  b - the right-hand-side vector
3833: -  y - the vector to be added to

3835:    Output Parameter:
3836: .  x - the result vector

3838:    Notes:
3839:    The vectors b and x cannot be the same.  I.e., one cannot
3840:    call MatSolveTransposeAdd(A,x,y,x).

3842:    Most users should employ the simplified KSP interface for linear solvers
3843:    instead of working directly with matrix algebra routines such as this.
3844:    See, e.g., KSPCreate().

3846:    Level: developer

3848: .seealso: MatSolve(), MatSolveAdd(), MatSolveTranspose()
3849: @*/
3850: PetscErrorCode MatSolveTransposeAdd(Mat mat,Vec b,Vec y,Vec x)
3851: {
3852:   PetscScalar    one = 1.0;
3854:   Vec            tmp;

3865:   if (x == b) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"x and b must be different vectors");
3866:   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);
3867:   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);
3868:   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);
3869:   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);
3870:   if (!mat->rmap->N && !mat->cmap->N) return(0);
3871:    MatCheckPreallocated(mat,1);

3873:   PetscLogEventBegin(MAT_SolveTransposeAdd,mat,b,x,y);
3874:   if (mat->factorerrortype) {
3875:     PetscInfo1(mat,"MatFactorError %D\n",mat->factorerrortype);
3876:     VecSetInf(x);
3877:   } else if (mat->ops->solvetransposeadd){
3878:     (*mat->ops->solvetransposeadd)(mat,b,y,x);
3879:   } else {
3880:     /* do the solve then the add manually */
3881:     if (x != y) {
3882:       MatSolveTranspose(mat,b,x);
3883:       VecAXPY(x,one,y);
3884:     } else {
3885:       VecDuplicate(x,&tmp);
3886:       PetscLogObjectParent((PetscObject)mat,(PetscObject)tmp);
3887:       VecCopy(x,tmp);
3888:       MatSolveTranspose(mat,b,x);
3889:       VecAXPY(x,one,tmp);
3890:       VecDestroy(&tmp);
3891:     }
3892:   }
3893:   PetscLogEventEnd(MAT_SolveTransposeAdd,mat,b,x,y);
3894:   PetscObjectStateIncrease((PetscObject)x);
3895:   return(0);
3896: }
3897: /* ----------------------------------------------------------------*/

3899: /*@
3900:    MatSOR - Computes relaxation (SOR, Gauss-Seidel) sweeps.

3902:    Neighbor-wise Collective on Mat

3904:    Input Parameters:
3905: +  mat - the matrix
3906: .  b - the right hand side
3907: .  omega - the relaxation factor
3908: .  flag - flag indicating the type of SOR (see below)
3909: .  shift -  diagonal shift
3910: .  its - the number of iterations
3911: -  lits - the number of local iterations

3913:    Output Parameters:
3914: .  x - the solution (can contain an initial guess, use option SOR_ZERO_INITIAL_GUESS to indicate no guess)

3916:    SOR Flags:
3917: +     SOR_FORWARD_SWEEP - forward SOR
3918: .     SOR_BACKWARD_SWEEP - backward SOR
3919: .     SOR_SYMMETRIC_SWEEP - SSOR (symmetric SOR)
3920: .     SOR_LOCAL_FORWARD_SWEEP - local forward SOR
3921: .     SOR_LOCAL_BACKWARD_SWEEP - local forward SOR
3922: .     SOR_LOCAL_SYMMETRIC_SWEEP - local SSOR
3923: .     SOR_APPLY_UPPER, SOR_APPLY_LOWER - applies
3924:          upper/lower triangular part of matrix to
3925:          vector (with omega)
3926: -     SOR_ZERO_INITIAL_GUESS - zero initial guess

3928:    Notes:
3929:    SOR_LOCAL_FORWARD_SWEEP, SOR_LOCAL_BACKWARD_SWEEP, and
3930:    SOR_LOCAL_SYMMETRIC_SWEEP perform separate independent smoothings
3931:    on each processor.

3933:    Application programmers will not generally use MatSOR() directly,
3934:    but instead will employ the KSP/PC interface.

3936:    Notes:
3937:     for BAIJ, SBAIJ, and AIJ matrices with Inodes this does a block SOR smoothing, otherwise it does a pointwise smoothing

3939:    Notes for Advanced Users:
3940:    The flags are implemented as bitwise inclusive or operations.
3941:    For example, use (SOR_ZERO_INITIAL_GUESS | SOR_SYMMETRIC_SWEEP)
3942:    to specify a zero initial guess for SSOR.

3944:    Most users should employ the simplified KSP interface for linear solvers
3945:    instead of working directly with matrix algebra routines such as this.
3946:    See, e.g., KSPCreate().

3948:    Vectors x and b CANNOT be the same

3950:    Developer Note: We should add block SOR support for AIJ matrices with block size set to great than one and no inodes

3952:    Level: developer

3954: @*/
3955: PetscErrorCode MatSOR(Mat mat,Vec b,PetscReal omega,MatSORType flag,PetscReal shift,PetscInt its,PetscInt lits,Vec x)
3956: {

3966:   if (!mat->ops->sor) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
3967:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
3968:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
3969:   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);
3970:   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);
3971:   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);
3972:   if (its <= 0) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONG,"Relaxation requires global its %D positive",its);
3973:   if (lits <= 0) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONG,"Relaxation requires local its %D positive",lits);
3974:   if (b == x) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_IDN,"b and x vector cannot be the same");

3976:   MatCheckPreallocated(mat,1);
3977:   PetscLogEventBegin(MAT_SOR,mat,b,x,0);
3978:   ierr =(*mat->ops->sor)(mat,b,omega,flag,shift,its,lits,x);
3979:   PetscLogEventEnd(MAT_SOR,mat,b,x,0);
3980:   PetscObjectStateIncrease((PetscObject)x);
3981:   return(0);
3982: }

3984: /*
3985:       Default matrix copy routine.
3986: */
3987: PetscErrorCode MatCopy_Basic(Mat A,Mat B,MatStructure str)
3988: {
3989:   PetscErrorCode    ierr;
3990:   PetscInt          i,rstart = 0,rend = 0,nz;
3991:   const PetscInt    *cwork;
3992:   const PetscScalar *vwork;

3995:   if (B->assembled) {
3996:     MatZeroEntries(B);
3997:   }
3998:   if (str == SAME_NONZERO_PATTERN) {
3999:     MatGetOwnershipRange(A,&rstart,&rend);
4000:     for (i=rstart; i<rend; i++) {
4001:       MatGetRow(A,i,&nz,&cwork,&vwork);
4002:       MatSetValues(B,1,&i,nz,cwork,vwork,INSERT_VALUES);
4003:       MatRestoreRow(A,i,&nz,&cwork,&vwork);
4004:     }
4005:   } else {
4006:     MatAYPX(B,0.0,A,str);
4007:   }
4008:   MatAssemblyBegin(B,MAT_FINAL_ASSEMBLY);
4009:   MatAssemblyEnd(B,MAT_FINAL_ASSEMBLY);
4010:   return(0);
4011: }

4013: /*@
4014:    MatCopy - Copies a matrix to another matrix.

4016:    Collective on Mat

4018:    Input Parameters:
4019: +  A - the matrix
4020: -  str - SAME_NONZERO_PATTERN or DIFFERENT_NONZERO_PATTERN

4022:    Output Parameter:
4023: .  B - where the copy is put

4025:    Notes:
4026:    If you use SAME_NONZERO_PATTERN then the two matrices had better have the
4027:    same nonzero pattern or the routine will crash.

4029:    MatCopy() copies the matrix entries of a matrix to another existing
4030:    matrix (after first zeroing the second matrix).  A related routine is
4031:    MatConvert(), which first creates a new matrix and then copies the data.

4033:    Level: intermediate

4035: .seealso: MatConvert(), MatDuplicate()

4037: @*/
4038: PetscErrorCode MatCopy(Mat A,Mat B,MatStructure str)
4039: {
4041:   PetscInt       i;

4049:   MatCheckPreallocated(B,2);
4050:   if (!A->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
4051:   if (A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
4052:   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);
4053:   MatCheckPreallocated(A,1);
4054:   if (A == B) return(0);

4056:   PetscLogEventBegin(MAT_Copy,A,B,0,0);
4057:   if (A->ops->copy) {
4058:     (*A->ops->copy)(A,B,str);
4059:   } else { /* generic conversion */
4060:     MatCopy_Basic(A,B,str);
4061:   }

4063:   B->stencil.dim = A->stencil.dim;
4064:   B->stencil.noc = A->stencil.noc;
4065:   for (i=0; i<=A->stencil.dim; i++) {
4066:     B->stencil.dims[i]   = A->stencil.dims[i];
4067:     B->stencil.starts[i] = A->stencil.starts[i];
4068:   }

4070:   PetscLogEventEnd(MAT_Copy,A,B,0,0);
4071:   PetscObjectStateIncrease((PetscObject)B);
4072:   return(0);
4073: }

4075: /*@C
4076:    MatConvert - Converts a matrix to another matrix, either of the same
4077:    or different type.

4079:    Collective on Mat

4081:    Input Parameters:
4082: +  mat - the matrix
4083: .  newtype - new matrix type.  Use MATSAME to create a new matrix of the
4084:    same type as the original matrix.
4085: -  reuse - denotes if the destination matrix is to be created or reused.
4086:    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
4087:    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).

4089:    Output Parameter:
4090: .  M - pointer to place new matrix

4092:    Notes:
4093:    MatConvert() first creates a new matrix and then copies the data from
4094:    the first matrix.  A related routine is MatCopy(), which copies the matrix
4095:    entries of one matrix to another already existing matrix context.

4097:    Cannot be used to convert a sequential matrix to parallel or parallel to sequential,
4098:    the MPI communicator of the generated matrix is always the same as the communicator
4099:    of the input matrix.

4101:    Level: intermediate

4103: .seealso: MatCopy(), MatDuplicate()
4104: @*/
4105: PetscErrorCode MatConvert(Mat mat, MatType newtype,MatReuse reuse,Mat *M)
4106: {
4108:   PetscBool      sametype,issame,flg,issymmetric,ishermitian;
4109:   char           convname[256],mtype[256];
4110:   Mat            B;

4116:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
4117:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
4118:   MatCheckPreallocated(mat,1);

4120:   PetscOptionsGetString(((PetscObject)mat)->options,((PetscObject)mat)->prefix,"-matconvert_type",mtype,256,&flg);
4121:   if (flg) newtype = mtype;

4123:   PetscObjectTypeCompare((PetscObject)mat,newtype,&sametype);
4124:   PetscStrcmp(newtype,"same",&issame);
4125:   if ((reuse == MAT_INPLACE_MATRIX) && (mat != *M)) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"MAT_INPLACE_MATRIX requires same input and output matrix");
4126:   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");

4128:   if ((reuse == MAT_INPLACE_MATRIX) && (issame || sametype)) {
4129:     PetscInfo3(mat,"Early return for inplace %s %d %d\n",((PetscObject)mat)->type_name,sametype,issame);
4130:     return(0);
4131:   }

4133:   /* Cache Mat options because some converter use MatHeaderReplace  */
4134:   issymmetric = mat->symmetric;
4135:   ishermitian = mat->hermitian;

4137:   if ((sametype || issame) && (reuse==MAT_INITIAL_MATRIX) && mat->ops->duplicate) {
4138:     PetscInfo3(mat,"Calling duplicate for initial matrix %s %d %d\n",((PetscObject)mat)->type_name,sametype,issame);
4139:     (*mat->ops->duplicate)(mat,MAT_COPY_VALUES,M);
4140:   } else {
4141:     PetscErrorCode (*conv)(Mat, MatType,MatReuse,Mat*)=NULL;
4142:     const char     *prefix[3] = {"seq","mpi",""};
4143:     PetscInt       i;
4144:     /*
4145:        Order of precedence:
4146:        0) See if newtype is a superclass of the current matrix.
4147:        1) See if a specialized converter is known to the current matrix.
4148:        2) See if a specialized converter is known to the desired matrix class.
4149:        3) See if a good general converter is registered for the desired class
4150:           (as of 6/27/03 only MATMPIADJ falls into this category).
4151:        4) See if a good general converter is known for the current matrix.
4152:        5) Use a really basic converter.
4153:     */

4155:     /* 0) See if newtype is a superclass of the current matrix.
4156:           i.e mat is mpiaij and newtype is aij */
4157:     for (i=0; i<2; i++) {
4158:       PetscStrncpy(convname,prefix[i],sizeof(convname));
4159:       PetscStrlcat(convname,newtype,sizeof(convname));
4160:       PetscStrcmp(convname,((PetscObject)mat)->type_name,&flg);
4161:       PetscInfo3(mat,"Check superclass %s %s -> %d\n",convname,((PetscObject)mat)->type_name,flg);
4162:       if (flg) {
4163:         if (reuse == MAT_INPLACE_MATRIX) {
4164:           return(0);
4165:         } else if (reuse == MAT_INITIAL_MATRIX && mat->ops->duplicate) {
4166:           (*mat->ops->duplicate)(mat,MAT_COPY_VALUES,M);
4167:           return(0);
4168:         } else if (reuse == MAT_REUSE_MATRIX && mat->ops->copy) {
4169:           MatCopy(mat,*M,SAME_NONZERO_PATTERN);
4170:           return(0);
4171:         }
4172:       }
4173:     }
4174:     /* 1) See if a specialized converter is known to the current matrix and the desired class */
4175:     for (i=0; i<3; i++) {
4176:       PetscStrncpy(convname,"MatConvert_",sizeof(convname));
4177:       PetscStrlcat(convname,((PetscObject)mat)->type_name,sizeof(convname));
4178:       PetscStrlcat(convname,"_",sizeof(convname));
4179:       PetscStrlcat(convname,prefix[i],sizeof(convname));
4180:       PetscStrlcat(convname,issame ? ((PetscObject)mat)->type_name : newtype,sizeof(convname));
4181:       PetscStrlcat(convname,"_C",sizeof(convname));
4182:       PetscObjectQueryFunction((PetscObject)mat,convname,&conv);
4183:       PetscInfo3(mat,"Check specialized (1) %s (%s) -> %d\n",convname,((PetscObject)mat)->type_name,!!conv);
4184:       if (conv) goto foundconv;
4185:     }

4187:     /* 2)  See if a specialized converter is known to the desired matrix class. */
4188:     MatCreate(PetscObjectComm((PetscObject)mat),&B);
4189:     MatSetSizes(B,mat->rmap->n,mat->cmap->n,mat->rmap->N,mat->cmap->N);
4190:     MatSetType(B,newtype);
4191:     for (i=0; i<3; i++) {
4192:       PetscStrncpy(convname,"MatConvert_",sizeof(convname));
4193:       PetscStrlcat(convname,((PetscObject)mat)->type_name,sizeof(convname));
4194:       PetscStrlcat(convname,"_",sizeof(convname));
4195:       PetscStrlcat(convname,prefix[i],sizeof(convname));
4196:       PetscStrlcat(convname,newtype,sizeof(convname));
4197:       PetscStrlcat(convname,"_C",sizeof(convname));
4198:       PetscObjectQueryFunction((PetscObject)B,convname,&conv);
4199:       PetscInfo3(mat,"Check specialized (2) %s (%s) -> %d\n",convname,((PetscObject)B)->type_name,!!conv);
4200:       if (conv) {
4201:         MatDestroy(&B);
4202:         goto foundconv;
4203:       }
4204:     }

4206:     /* 3) See if a good general converter is registered for the desired class */
4207:     conv = B->ops->convertfrom;
4208:     PetscInfo2(mat,"Check convertfrom (%s) -> %d\n",((PetscObject)B)->type_name,!!conv);
4209:     MatDestroy(&B);
4210:     if (conv) goto foundconv;

4212:     /* 4) See if a good general converter is known for the current matrix */
4213:     if (mat->ops->convert) conv = mat->ops->convert;

4215:     PetscInfo2(mat,"Check general convert (%s) -> %d\n",((PetscObject)mat)->type_name,!!conv);
4216:     if (conv) goto foundconv;

4218:     /* 5) Use a really basic converter. */
4219:     PetscInfo(mat,"Using MatConvert_Basic\n");
4220:     conv = MatConvert_Basic;

4222: foundconv:
4223:     PetscLogEventBegin(MAT_Convert,mat,0,0,0);
4224:     (*conv)(mat,newtype,reuse,M);
4225:     if (mat->rmap->mapping && mat->cmap->mapping && !(*M)->rmap->mapping && !(*M)->cmap->mapping) {
4226:       /* the block sizes must be same if the mappings are copied over */
4227:       (*M)->rmap->bs = mat->rmap->bs;
4228:       (*M)->cmap->bs = mat->cmap->bs;
4229:       PetscObjectReference((PetscObject)mat->rmap->mapping);
4230:       PetscObjectReference((PetscObject)mat->cmap->mapping);
4231:       (*M)->rmap->mapping = mat->rmap->mapping;
4232:       (*M)->cmap->mapping = mat->cmap->mapping;
4233:     }
4234:     (*M)->stencil.dim = mat->stencil.dim;
4235:     (*M)->stencil.noc = mat->stencil.noc;
4236:     for (i=0; i<=mat->stencil.dim; i++) {
4237:       (*M)->stencil.dims[i]   = mat->stencil.dims[i];
4238:       (*M)->stencil.starts[i] = mat->stencil.starts[i];
4239:     }
4240:     PetscLogEventEnd(MAT_Convert,mat,0,0,0);
4241:   }
4242:   PetscObjectStateIncrease((PetscObject)*M);

4244:   /* Copy Mat options */
4245:   if (issymmetric) {
4246:     MatSetOption(*M,MAT_SYMMETRIC,PETSC_TRUE);
4247:   }
4248:   if (ishermitian) {
4249:     MatSetOption(*M,MAT_HERMITIAN,PETSC_TRUE);
4250:   }
4251:   return(0);
4252: }

4254: /*@C
4255:    MatFactorGetSolverType - Returns name of the package providing the factorization routines

4257:    Not Collective

4259:    Input Parameter:
4260: .  mat - the matrix, must be a factored matrix

4262:    Output Parameter:
4263: .   type - the string name of the package (do not free this string)

4265:    Notes:
4266:       In Fortran you pass in a empty string and the package name will be copied into it.
4267:     (Make sure the string is long enough)

4269:    Level: intermediate

4271: .seealso: MatCopy(), MatDuplicate(), MatGetFactorAvailable(), MatGetFactor()
4272: @*/
4273: PetscErrorCode MatFactorGetSolverType(Mat mat, MatSolverType *type)
4274: {
4275:   PetscErrorCode ierr, (*conv)(Mat,MatSolverType*);

4280:   if (!mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Only for factored matrix");
4281:   PetscObjectQueryFunction((PetscObject)mat,"MatFactorGetSolverType_C",&conv);
4282:   if (!conv) {
4283:     *type = MATSOLVERPETSC;
4284:   } else {
4285:     (*conv)(mat,type);
4286:   }
4287:   return(0);
4288: }

4290: typedef struct _MatSolverTypeForSpecifcType* MatSolverTypeForSpecifcType;
4291: struct _MatSolverTypeForSpecifcType {
4292:   MatType                        mtype;
4293:   PetscErrorCode                 (*getfactor[4])(Mat,MatFactorType,Mat*);
4294:   MatSolverTypeForSpecifcType next;
4295: };

4297: typedef struct _MatSolverTypeHolder* MatSolverTypeHolder;
4298: struct _MatSolverTypeHolder {
4299:   char                           *name;
4300:   MatSolverTypeForSpecifcType handlers;
4301:   MatSolverTypeHolder         next;
4302: };

4304: static MatSolverTypeHolder MatSolverTypeHolders = NULL;

4306: /*@C
4307:    MatSolvePackageRegister - Registers a MatSolverType that works for a particular matrix type

4309:    Input Parameters:
4310: +    package - name of the package, for example petsc or superlu
4311: .    mtype - the matrix type that works with this package
4312: .    ftype - the type of factorization supported by the package
4313: -    getfactor - routine that will create the factored matrix ready to be used

4315:     Level: intermediate

4317: .seealso: MatCopy(), MatDuplicate(), MatGetFactorAvailable()
4318: @*/
4319: PetscErrorCode MatSolverTypeRegister(MatSolverType package,MatType mtype,MatFactorType ftype,PetscErrorCode (*getfactor)(Mat,MatFactorType,Mat*))
4320: {
4321:   PetscErrorCode              ierr;
4322:   MatSolverTypeHolder         next = MatSolverTypeHolders,prev = NULL;
4323:   PetscBool                   flg;
4324:   MatSolverTypeForSpecifcType inext,iprev = NULL;

4327:   MatInitializePackage();
4328:   if (!next) {
4329:     PetscNew(&MatSolverTypeHolders);
4330:     PetscStrallocpy(package,&MatSolverTypeHolders->name);
4331:     PetscNew(&MatSolverTypeHolders->handlers);
4332:     PetscStrallocpy(mtype,(char **)&MatSolverTypeHolders->handlers->mtype);
4333:     MatSolverTypeHolders->handlers->getfactor[(int)ftype-1] = getfactor;
4334:     return(0);
4335:   }
4336:   while (next) {
4337:     PetscStrcasecmp(package,next->name,&flg);
4338:     if (flg) {
4339:       if (!next->handlers) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_PLIB,"MatSolverTypeHolder is missing handlers");
4340:       inext = next->handlers;
4341:       while (inext) {
4342:         PetscStrcasecmp(mtype,inext->mtype,&flg);
4343:         if (flg) {
4344:           inext->getfactor[(int)ftype-1] = getfactor;
4345:           return(0);
4346:         }
4347:         iprev = inext;
4348:         inext = inext->next;
4349:       }
4350:       PetscNew(&iprev->next);
4351:       PetscStrallocpy(mtype,(char **)&iprev->next->mtype);
4352:       iprev->next->getfactor[(int)ftype-1] = getfactor;
4353:       return(0);
4354:     }
4355:     prev = next;
4356:     next = next->next;
4357:   }
4358:   PetscNew(&prev->next);
4359:   PetscStrallocpy(package,&prev->next->name);
4360:   PetscNew(&prev->next->handlers);
4361:   PetscStrallocpy(mtype,(char **)&prev->next->handlers->mtype);
4362:   prev->next->handlers->getfactor[(int)ftype-1] = getfactor;
4363:   return(0);
4364: }

4366: /*@C
4367:    MatSolvePackageGet - Get's the function that creates the factor matrix if it exist

4369:    Input Parameters:
4370: +    package - name of the package, for example petsc or superlu
4371: .    ftype - the type of factorization supported by the package
4372: -    mtype - the matrix type that works with this package

4374:    Output Parameters:
4375: +   foundpackage - PETSC_TRUE if the package was registered
4376: .   foundmtype - PETSC_TRUE if the package supports the requested mtype
4377: -   getfactor - routine that will create the factored matrix ready to be used or NULL if not found

4379:     Level: intermediate

4381: .seealso: MatCopy(), MatDuplicate(), MatGetFactorAvailable()
4382: @*/
4383: PetscErrorCode MatSolverTypeGet(MatSolverType package,MatType mtype,MatFactorType ftype,PetscBool *foundpackage,PetscBool *foundmtype,PetscErrorCode (**getfactor)(Mat,MatFactorType,Mat*))
4384: {
4385:   PetscErrorCode              ierr;
4386:   MatSolverTypeHolder         next = MatSolverTypeHolders;
4387:   PetscBool                   flg;
4388:   MatSolverTypeForSpecifcType inext;

4391:   if (foundpackage) *foundpackage = PETSC_FALSE;
4392:   if (foundmtype)   *foundmtype   = PETSC_FALSE;
4393:   if (getfactor)    *getfactor    = NULL;

4395:   if (package) {
4396:     while (next) {
4397:       PetscStrcasecmp(package,next->name,&flg);
4398:       if (flg) {
4399:         if (foundpackage) *foundpackage = PETSC_TRUE;
4400:         inext = next->handlers;
4401:         while (inext) {
4402:           PetscStrbeginswith(mtype,inext->mtype,&flg);
4403:           if (flg) {
4404:             if (foundmtype) *foundmtype = PETSC_TRUE;
4405:             if (getfactor)  *getfactor  = inext->getfactor[(int)ftype-1];
4406:             return(0);
4407:           }
4408:           inext = inext->next;
4409:         }
4410:       }
4411:       next = next->next;
4412:     }
4413:   } else {
4414:     while (next) {
4415:       inext = next->handlers;
4416:       while (inext) {
4417:         PetscStrbeginswith(mtype,inext->mtype,&flg);
4418:         if (flg && inext->getfactor[(int)ftype-1]) {
4419:           if (foundpackage) *foundpackage = PETSC_TRUE;
4420:           if (foundmtype)   *foundmtype   = PETSC_TRUE;
4421:           if (getfactor)    *getfactor    = inext->getfactor[(int)ftype-1];
4422:           return(0);
4423:         }
4424:         inext = inext->next;
4425:       }
4426:       next = next->next;
4427:     }
4428:   }
4429:   return(0);
4430: }

4432: PetscErrorCode MatSolverTypeDestroy(void)
4433: {
4434:   PetscErrorCode              ierr;
4435:   MatSolverTypeHolder         next = MatSolverTypeHolders,prev;
4436:   MatSolverTypeForSpecifcType inext,iprev;

4439:   while (next) {
4440:     PetscFree(next->name);
4441:     inext = next->handlers;
4442:     while (inext) {
4443:       PetscFree(inext->mtype);
4444:       iprev = inext;
4445:       inext = inext->next;
4446:       PetscFree(iprev);
4447:     }
4448:     prev = next;
4449:     next = next->next;
4450:     PetscFree(prev);
4451:   }
4452:   MatSolverTypeHolders = NULL;
4453:   return(0);
4454: }

4456: /*@C
4457:    MatGetFactor - Returns a matrix suitable to calls to MatXXFactorSymbolic()

4459:    Collective on Mat

4461:    Input Parameters:
4462: +  mat - the matrix
4463: .  type - name of solver type, for example, superlu, petsc (to use PETSc's default)
4464: -  ftype - factor type, MAT_FACTOR_LU, MAT_FACTOR_CHOLESKY, MAT_FACTOR_ICC, MAT_FACTOR_ILU,

4466:    Output Parameters:
4467: .  f - the factor matrix used with MatXXFactorSymbolic() calls

4469:    Notes:
4470:       Some PETSc matrix formats have alternative solvers available that are contained in alternative packages
4471:      such as pastix, superlu, mumps etc.

4473:       PETSc must have been ./configure to use the external solver, using the option --download-package

4475:    Level: intermediate

4477: .seealso: MatCopy(), MatDuplicate(), MatGetFactorAvailable()
4478: @*/
4479: PetscErrorCode MatGetFactor(Mat mat, MatSolverType type,MatFactorType ftype,Mat *f)
4480: {
4481:   PetscErrorCode ierr,(*conv)(Mat,MatFactorType,Mat*);
4482:   PetscBool      foundpackage,foundmtype;


4488:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
4489:   MatCheckPreallocated(mat,1);

4491:   MatSolverTypeGet(type,((PetscObject)mat)->type_name,ftype,&foundpackage,&foundmtype,&conv);
4492:   if (!foundpackage) {
4493:     if (type) {
4494:       SETERRQ4(PetscObjectComm((PetscObject)mat),PETSC_ERR_MISSING_FACTOR,"Could not locate solver package %s for factorization type %s and matrix type %s. Perhaps you must ./configure with --download-%s",type,MatFactorTypes[ftype],((PetscObject)mat)->type_name,type);
4495:     } else {
4496:       SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_MISSING_FACTOR,"Could not locate a solver package for factorization type %s and matrix type %s.",MatFactorTypes[ftype],((PetscObject)mat)->type_name);
4497:     }
4498:   }
4499:   if (!foundmtype) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_MISSING_FACTOR,"MatSolverType %s does not support matrix type %s",type,((PetscObject)mat)->type_name);
4500:   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);

4502:   (*conv)(mat,ftype,f);
4503:   return(0);
4504: }

4506: /*@C
4507:    MatGetFactorAvailable - Returns a a flag if matrix supports particular package and factor type

4509:    Not Collective

4511:    Input Parameters:
4512: +  mat - the matrix
4513: .  type - name of solver type, for example, superlu, petsc (to use PETSc's default)
4514: -  ftype - factor type, MAT_FACTOR_LU, MAT_FACTOR_CHOLESKY, MAT_FACTOR_ICC, MAT_FACTOR_ILU,

4516:    Output Parameter:
4517: .    flg - PETSC_TRUE if the factorization is available

4519:    Notes:
4520:       Some PETSc matrix formats have alternative solvers available that are contained in alternative packages
4521:      such as pastix, superlu, mumps etc.

4523:       PETSc must have been ./configure to use the external solver, using the option --download-package

4525:    Level: intermediate

4527: .seealso: MatCopy(), MatDuplicate(), MatGetFactor()
4528: @*/
4529: PetscErrorCode MatGetFactorAvailable(Mat mat, MatSolverType type,MatFactorType ftype,PetscBool  *flg)
4530: {
4531:   PetscErrorCode ierr, (*gconv)(Mat,MatFactorType,Mat*);


4537:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
4538:   MatCheckPreallocated(mat,1);

4540:   *flg = PETSC_FALSE;
4541:   MatSolverTypeGet(type,((PetscObject)mat)->type_name,ftype,NULL,NULL,&gconv);
4542:   if (gconv) {
4543:     *flg = PETSC_TRUE;
4544:   }
4545:   return(0);
4546: }

4548:  #include <petscdmtypes.h>

4550: /*@
4551:    MatDuplicate - Duplicates a matrix including the non-zero structure.

4553:    Collective on Mat

4555:    Input Parameters:
4556: +  mat - the matrix
4557: -  op - One of MAT_DO_NOT_COPY_VALUES, MAT_COPY_VALUES, or MAT_SHARE_NONZERO_PATTERN.
4558:         See the manual page for MatDuplicateOption for an explanation of these options.

4560:    Output Parameter:
4561: .  M - pointer to place new matrix

4563:    Level: intermediate

4565:    Notes:
4566:     You cannot change the nonzero pattern for the parent or child matrix if you use MAT_SHARE_NONZERO_PATTERN.
4567:     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.

4569: .seealso: MatCopy(), MatConvert(), MatDuplicateOption
4570: @*/
4571: PetscErrorCode MatDuplicate(Mat mat,MatDuplicateOption op,Mat *M)
4572: {
4574:   Mat            B;
4575:   PetscInt       i;
4576:   DM             dm;
4577:   void           (*viewf)(void);

4583:   if (op == MAT_COPY_VALUES && !mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"MAT_COPY_VALUES not allowed for unassembled matrix");
4584:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
4585:   MatCheckPreallocated(mat,1);

4587:   *M = 0;
4588:   if (!mat->ops->duplicate) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Not written for matrix type %s\n",((PetscObject)mat)->type_name);
4589:   PetscLogEventBegin(MAT_Convert,mat,0,0,0);
4590:   (*mat->ops->duplicate)(mat,op,M);
4591:   B    = *M;

4593:   MatGetOperation(mat,MATOP_VIEW,&viewf);
4594:   if (viewf) {
4595:     MatSetOperation(B,MATOP_VIEW,viewf);
4596:   }

4598:   B->stencil.dim = mat->stencil.dim;
4599:   B->stencil.noc = mat->stencil.noc;
4600:   for (i=0; i<=mat->stencil.dim; i++) {
4601:     B->stencil.dims[i]   = mat->stencil.dims[i];
4602:     B->stencil.starts[i] = mat->stencil.starts[i];
4603:   }

4605:   B->nooffproczerorows = mat->nooffproczerorows;
4606:   B->nooffprocentries  = mat->nooffprocentries;

4608:   PetscObjectQuery((PetscObject) mat, "__PETSc_dm", (PetscObject*) &dm);
4609:   if (dm) {
4610:     PetscObjectCompose((PetscObject) B, "__PETSc_dm", (PetscObject) dm);
4611:   }
4612:   PetscLogEventEnd(MAT_Convert,mat,0,0,0);
4613:   PetscObjectStateIncrease((PetscObject)B);
4614:   return(0);
4615: }

4617: /*@
4618:    MatGetDiagonal - Gets the diagonal of a matrix.

4620:    Logically Collective on Mat

4622:    Input Parameters:
4623: +  mat - the matrix
4624: -  v - the vector for storing the diagonal

4626:    Output Parameter:
4627: .  v - the diagonal of the matrix

4629:    Level: intermediate

4631:    Note:
4632:    Currently only correct in parallel for square matrices.

4634: .seealso: MatGetRow(), MatCreateSubMatrices(), MatCreateSubMatrix(), MatGetRowMaxAbs()
4635: @*/
4636: PetscErrorCode MatGetDiagonal(Mat mat,Vec v)
4637: {

4644:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
4645:   if (!mat->ops->getdiagonal) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
4646:   MatCheckPreallocated(mat,1);

4648:   (*mat->ops->getdiagonal)(mat,v);
4649:   PetscObjectStateIncrease((PetscObject)v);
4650:   return(0);
4651: }

4653: /*@C
4654:    MatGetRowMin - Gets the minimum value (of the real part) of each
4655:         row of the matrix

4657:    Logically Collective on Mat

4659:    Input Parameters:
4660: .  mat - the matrix

4662:    Output Parameter:
4663: +  v - the vector for storing the maximums
4664: -  idx - the indices of the column found for each row (optional)

4666:    Level: intermediate

4668:    Notes:
4669:     The result of this call are the same as if one converted the matrix to dense format
4670:       and found the minimum value in each row (i.e. the implicit zeros are counted as zeros).

4672:     This code is only implemented for a couple of matrix formats.

4674: .seealso: MatGetDiagonal(), MatCreateSubMatrices(), MatCreateSubMatrix(), MatGetRowMaxAbs(),
4675:           MatGetRowMax()
4676: @*/
4677: PetscErrorCode MatGetRowMin(Mat mat,Vec v,PetscInt idx[])
4678: {

4685:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
4686:   if (!mat->ops->getrowmax) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
4687:   MatCheckPreallocated(mat,1);

4689:   (*mat->ops->getrowmin)(mat,v,idx);
4690:   PetscObjectStateIncrease((PetscObject)v);
4691:   return(0);
4692: }

4694: /*@C
4695:    MatGetRowMinAbs - Gets the minimum value (in absolute value) of each
4696:         row of the matrix

4698:    Logically Collective on Mat

4700:    Input Parameters:
4701: .  mat - the matrix

4703:    Output Parameter:
4704: +  v - the vector for storing the minimums
4705: -  idx - the indices of the column found for each row (or NULL if not needed)

4707:    Level: intermediate

4709:    Notes:
4710:     if a row is completely empty or has only 0.0 values then the idx[] value for that
4711:     row is 0 (the first column).

4713:     This code is only implemented for a couple of matrix formats.

4715: .seealso: MatGetDiagonal(), MatCreateSubMatrices(), MatCreateSubMatrix(), MatGetRowMax(), MatGetRowMaxAbs(), MatGetRowMin()
4716: @*/
4717: PetscErrorCode MatGetRowMinAbs(Mat mat,Vec v,PetscInt idx[])
4718: {

4725:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
4726:   if (!mat->ops->getrowminabs) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
4727:   MatCheckPreallocated(mat,1);
4728:   if (idx) {PetscArrayzero(idx,mat->rmap->n);}

4730:   (*mat->ops->getrowminabs)(mat,v,idx);
4731:   PetscObjectStateIncrease((PetscObject)v);
4732:   return(0);
4733: }

4735: /*@C
4736:    MatGetRowMax - Gets the maximum value (of the real part) of each
4737:         row of the matrix

4739:    Logically Collective on Mat

4741:    Input Parameters:
4742: .  mat - the matrix

4744:    Output Parameter:
4745: +  v - the vector for storing the maximums
4746: -  idx - the indices of the column found for each row (optional)

4748:    Level: intermediate

4750:    Notes:
4751:     The result of this call are the same as if one converted the matrix to dense format
4752:       and found the minimum value in each row (i.e. the implicit zeros are counted as zeros).

4754:     This code is only implemented for a couple of matrix formats.

4756: .seealso: MatGetDiagonal(), MatCreateSubMatrices(), MatCreateSubMatrix(), MatGetRowMaxAbs(), MatGetRowMin()
4757: @*/
4758: PetscErrorCode MatGetRowMax(Mat mat,Vec v,PetscInt idx[])
4759: {

4766:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
4767:   if (!mat->ops->getrowmax) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
4768:   MatCheckPreallocated(mat,1);

4770:   (*mat->ops->getrowmax)(mat,v,idx);
4771:   PetscObjectStateIncrease((PetscObject)v);
4772:   return(0);
4773: }

4775: /*@C
4776:    MatGetRowMaxAbs - Gets the maximum value (in absolute value) of each
4777:         row of the matrix

4779:    Logically Collective on Mat

4781:    Input Parameters:
4782: .  mat - the matrix

4784:    Output Parameter:
4785: +  v - the vector for storing the maximums
4786: -  idx - the indices of the column found for each row (or NULL if not needed)

4788:    Level: intermediate

4790:    Notes:
4791:     if a row is completely empty or has only 0.0 values then the idx[] value for that
4792:     row is 0 (the first column).

4794:     This code is only implemented for a couple of matrix formats.

4796: .seealso: MatGetDiagonal(), MatCreateSubMatrices(), MatCreateSubMatrix(), MatGetRowMax(), MatGetRowMin()
4797: @*/
4798: PetscErrorCode MatGetRowMaxAbs(Mat mat,Vec v,PetscInt idx[])
4799: {

4806:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
4807:   if (!mat->ops->getrowmaxabs) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
4808:   MatCheckPreallocated(mat,1);
4809:   if (idx) {PetscArrayzero(idx,mat->rmap->n);}

4811:   (*mat->ops->getrowmaxabs)(mat,v,idx);
4812:   PetscObjectStateIncrease((PetscObject)v);
4813:   return(0);
4814: }

4816: /*@
4817:    MatGetRowSum - Gets the sum of each row of the matrix

4819:    Logically or Neighborhood Collective on Mat

4821:    Input Parameters:
4822: .  mat - the matrix

4824:    Output Parameter:
4825: .  v - the vector for storing the sum of rows

4827:    Level: intermediate

4829:    Notes:
4830:     This code is slow since it is not currently specialized for different formats

4832: .seealso: MatGetDiagonal(), MatCreateSubMatrices(), MatCreateSubMatrix(), MatGetRowMax(), MatGetRowMin()
4833: @*/
4834: PetscErrorCode MatGetRowSum(Mat mat, Vec v)
4835: {
4836:   Vec            ones;

4843:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
4844:   MatCheckPreallocated(mat,1);
4845:   MatCreateVecs(mat,&ones,NULL);
4846:   VecSet(ones,1.);
4847:   MatMult(mat,ones,v);
4848:   VecDestroy(&ones);
4849:   return(0);
4850: }

4852: /*@
4853:    MatTranspose - Computes an in-place or out-of-place transpose of a matrix.

4855:    Collective on Mat

4857:    Input Parameter:
4858: +  mat - the matrix to transpose
4859: -  reuse - either MAT_INITIAL_MATRIX, MAT_REUSE_MATRIX, or MAT_INPLACE_MATRIX

4861:    Output Parameters:
4862: .  B - the transpose

4864:    Notes:
4865:      If you use MAT_INPLACE_MATRIX then you must pass in &mat for B

4867:      MAT_REUSE_MATRIX causes the B matrix from a previous call to this function with MAT_INITIAL_MATRIX to be used

4869:      Consider using MatCreateTranspose() instead if you only need a matrix that behaves like the transpose, but don't need the storage to be changed.

4871:    Level: intermediate

4873: .seealso: MatMultTranspose(), MatMultTransposeAdd(), MatIsTranspose(), MatReuse
4874: @*/
4875: PetscErrorCode MatTranspose(Mat mat,MatReuse reuse,Mat *B)
4876: {

4882:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
4883:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
4884:   if (!mat->ops->transpose) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
4885:   if (reuse == MAT_INPLACE_MATRIX && mat != *B) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"MAT_INPLACE_MATRIX requires last matrix to match first");
4886:   if (reuse == MAT_REUSE_MATRIX && mat == *B) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Perhaps you mean MAT_INPLACE_MATRIX");
4887:   MatCheckPreallocated(mat,1);

4889:   PetscLogEventBegin(MAT_Transpose,mat,0,0,0);
4890:   (*mat->ops->transpose)(mat,reuse,B);
4891:   PetscLogEventEnd(MAT_Transpose,mat,0,0,0);
4892:   if (B) {PetscObjectStateIncrease((PetscObject)*B);}
4893:   return(0);
4894: }

4896: /*@
4897:    MatIsTranspose - Test whether a matrix is another one's transpose,
4898:         or its own, in which case it tests symmetry.

4900:    Collective on Mat

4902:    Input Parameter:
4903: +  A - the matrix to test
4904: -  B - the matrix to test against, this can equal the first parameter

4906:    Output Parameters:
4907: .  flg - the result

4909:    Notes:
4910:    Only available for SeqAIJ/MPIAIJ matrices. The sequential algorithm
4911:    has a running time of the order of the number of nonzeros; the parallel
4912:    test involves parallel copies of the block-offdiagonal parts of the matrix.

4914:    Level: intermediate

4916: .seealso: MatTranspose(), MatIsSymmetric(), MatIsHermitian()
4917: @*/
4918: PetscErrorCode MatIsTranspose(Mat A,Mat B,PetscReal tol,PetscBool  *flg)
4919: {
4920:   PetscErrorCode ierr,(*f)(Mat,Mat,PetscReal,PetscBool*),(*g)(Mat,Mat,PetscReal,PetscBool*);

4926:   PetscObjectQueryFunction((PetscObject)A,"MatIsTranspose_C",&f);
4927:   PetscObjectQueryFunction((PetscObject)B,"MatIsTranspose_C",&g);
4928:   *flg = PETSC_FALSE;
4929:   if (f && g) {
4930:     if (f == g) {
4931:       (*f)(A,B,tol,flg);
4932:     } else SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_NOTSAMETYPE,"Matrices do not have the same comparator for symmetry test");
4933:   } else {
4934:     MatType mattype;
4935:     if (!f) {
4936:       MatGetType(A,&mattype);
4937:     } else {
4938:       MatGetType(B,&mattype);
4939:     }
4940:     SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Matrix of type %s does not support checking for transpose",mattype);
4941:   }
4942:   return(0);
4943: }

4945: /*@
4946:    MatHermitianTranspose - Computes an in-place or out-of-place transpose of a matrix in complex conjugate.

4948:    Collective on Mat

4950:    Input Parameter:
4951: +  mat - the matrix to transpose and complex conjugate
4952: -  reuse - MAT_INITIAL_MATRIX to create a new matrix, MAT_INPLACE_MATRIX to reuse the first argument to store the transpose

4954:    Output Parameters:
4955: .  B - the Hermitian

4957:    Level: intermediate

4959: .seealso: MatTranspose(), MatMultTranspose(), MatMultTransposeAdd(), MatIsTranspose(), MatReuse
4960: @*/
4961: PetscErrorCode MatHermitianTranspose(Mat mat,MatReuse reuse,Mat *B)
4962: {

4966:   MatTranspose(mat,reuse,B);
4967: #if defined(PETSC_USE_COMPLEX)
4968:   MatConjugate(*B);
4969: #endif
4970:   return(0);
4971: }

4973: /*@
4974:    MatIsHermitianTranspose - Test whether a matrix is another one's Hermitian transpose,

4976:    Collective on Mat

4978:    Input Parameter:
4979: +  A - the matrix to test
4980: -  B - the matrix to test against, this can equal the first parameter

4982:    Output Parameters:
4983: .  flg - the result

4985:    Notes:
4986:    Only available for SeqAIJ/MPIAIJ matrices. The sequential algorithm
4987:    has a running time of the order of the number of nonzeros; the parallel
4988:    test involves parallel copies of the block-offdiagonal parts of the matrix.

4990:    Level: intermediate

4992: .seealso: MatTranspose(), MatIsSymmetric(), MatIsHermitian(), MatIsTranspose()
4993: @*/
4994: PetscErrorCode MatIsHermitianTranspose(Mat A,Mat B,PetscReal tol,PetscBool  *flg)
4995: {
4996:   PetscErrorCode ierr,(*f)(Mat,Mat,PetscReal,PetscBool*),(*g)(Mat,Mat,PetscReal,PetscBool*);

5002:   PetscObjectQueryFunction((PetscObject)A,"MatIsHermitianTranspose_C",&f);
5003:   PetscObjectQueryFunction((PetscObject)B,"MatIsHermitianTranspose_C",&g);
5004:   if (f && g) {
5005:     if (f==g) {
5006:       (*f)(A,B,tol,flg);
5007:     } else SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_NOTSAMETYPE,"Matrices do not have the same comparator for Hermitian test");
5008:   }
5009:   return(0);
5010: }

5012: /*@
5013:    MatPermute - Creates a new matrix with rows and columns permuted from the
5014:    original.

5016:    Collective on Mat

5018:    Input Parameters:
5019: +  mat - the matrix to permute
5020: .  row - row permutation, each processor supplies only the permutation for its rows
5021: -  col - column permutation, each processor supplies only the permutation for its columns

5023:    Output Parameters:
5024: .  B - the permuted matrix

5026:    Level: advanced

5028:    Note:
5029:    The index sets map from row/col of permuted matrix to row/col of original matrix.
5030:    The index sets should be on the same communicator as Mat and have the same local sizes.

5032: .seealso: MatGetOrdering(), ISAllGather()

5034: @*/
5035: PetscErrorCode MatPermute(Mat mat,IS row,IS col,Mat *B)
5036: {

5045:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
5046:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
5047:   if (!mat->ops->permute) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"MatPermute not available for Mat type %s",((PetscObject)mat)->type_name);
5048:   MatCheckPreallocated(mat,1);

5050:   (*mat->ops->permute)(mat,row,col,B);
5051:   PetscObjectStateIncrease((PetscObject)*B);
5052:   return(0);
5053: }

5055: /*@
5056:    MatEqual - Compares two matrices.

5058:    Collective on Mat

5060:    Input Parameters:
5061: +  A - the first matrix
5062: -  B - the second matrix

5064:    Output Parameter:
5065: .  flg - PETSC_TRUE if the matrices are equal; PETSC_FALSE otherwise.

5067:    Level: intermediate

5069: @*/
5070: PetscErrorCode MatEqual(Mat A,Mat B,PetscBool  *flg)
5071: {

5081:   MatCheckPreallocated(B,2);
5082:   if (!A->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
5083:   if (!B->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
5084:   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);
5085:   if (!A->ops->equal) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Mat type %s",((PetscObject)A)->type_name);
5086:   if (!B->ops->equal) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Mat type %s",((PetscObject)B)->type_name);
5087:   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);
5088:   MatCheckPreallocated(A,1);

5090:   (*A->ops->equal)(A,B,flg);
5091:   return(0);
5092: }

5094: /*@
5095:    MatDiagonalScale - Scales a matrix on the left and right by diagonal
5096:    matrices that are stored as vectors.  Either of the two scaling
5097:    matrices can be NULL.

5099:    Collective on Mat

5101:    Input Parameters:
5102: +  mat - the matrix to be scaled
5103: .  l - the left scaling vector (or NULL)
5104: -  r - the right scaling vector (or NULL)

5106:    Notes:
5107:    MatDiagonalScale() computes A = LAR, where
5108:    L = a diagonal matrix (stored as a vector), R = a diagonal matrix (stored as a vector)
5109:    The L scales the rows of the matrix, the R scales the columns of the matrix.

5111:    Level: intermediate


5114: .seealso: MatScale(), MatShift(), MatDiagonalSet()
5115: @*/
5116: PetscErrorCode MatDiagonalScale(Mat mat,Vec l,Vec r)
5117: {

5123:   if (!mat->ops->diagonalscale) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
5126:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
5127:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
5128:   MatCheckPreallocated(mat,1);

5130:   PetscLogEventBegin(MAT_Scale,mat,0,0,0);
5131:   (*mat->ops->diagonalscale)(mat,l,r);
5132:   PetscLogEventEnd(MAT_Scale,mat,0,0,0);
5133:   PetscObjectStateIncrease((PetscObject)mat);
5134:   return(0);
5135: }

5137: /*@
5138:     MatScale - Scales all elements of a matrix by a given number.

5140:     Logically Collective on Mat

5142:     Input Parameters:
5143: +   mat - the matrix to be scaled
5144: -   a  - the scaling value

5146:     Output Parameter:
5147: .   mat - the scaled matrix

5149:     Level: intermediate

5151: .seealso: MatDiagonalScale()
5152: @*/
5153: PetscErrorCode MatScale(Mat mat,PetscScalar a)
5154: {

5160:   if (a != (PetscScalar)1.0 && !mat->ops->scale) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
5161:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
5162:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
5164:   MatCheckPreallocated(mat,1);

5166:   PetscLogEventBegin(MAT_Scale,mat,0,0,0);
5167:   if (a != (PetscScalar)1.0) {
5168:     (*mat->ops->scale)(mat,a);
5169:     PetscObjectStateIncrease((PetscObject)mat);
5170:   }
5171:   PetscLogEventEnd(MAT_Scale,mat,0,0,0);
5172:   return(0);
5173: }

5175: /*@
5176:    MatNorm - Calculates various norms of a matrix.

5178:    Collective on Mat

5180:    Input Parameters:
5181: +  mat - the matrix
5182: -  type - the type of norm, NORM_1, NORM_FROBENIUS, NORM_INFINITY

5184:    Output Parameters:
5185: .  nrm - the resulting norm

5187:    Level: intermediate

5189: @*/
5190: PetscErrorCode MatNorm(Mat mat,NormType type,PetscReal *nrm)
5191: {


5199:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
5200:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
5201:   if (!mat->ops->norm) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
5202:   MatCheckPreallocated(mat,1);

5204:   (*mat->ops->norm)(mat,type,nrm);
5205:   return(0);
5206: }

5208: /*
5209:      This variable is used to prevent counting of MatAssemblyBegin() that
5210:    are called from within a MatAssemblyEnd().
5211: */
5212: static PetscInt MatAssemblyEnd_InUse = 0;
5213: /*@
5214:    MatAssemblyBegin - Begins assembling the matrix.  This routine should
5215:    be called after completing all calls to MatSetValues().

5217:    Collective on Mat

5219:    Input Parameters:
5220: +  mat - the matrix
5221: -  type - type of assembly, either MAT_FLUSH_ASSEMBLY or MAT_FINAL_ASSEMBLY

5223:    Notes:
5224:    MatSetValues() generally caches the values.  The matrix is ready to
5225:    use only after MatAssemblyBegin() and MatAssemblyEnd() have been called.
5226:    Use MAT_FLUSH_ASSEMBLY when switching between ADD_VALUES and INSERT_VALUES
5227:    in MatSetValues(); use MAT_FINAL_ASSEMBLY for the final assembly before
5228:    using the matrix.

5230:    ALL processes that share a matrix MUST call MatAssemblyBegin() and MatAssemblyEnd() the SAME NUMBER of times, and each time with the
5231:    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
5232:    a global collective operation requring all processes that share the matrix.

5234:    Space for preallocated nonzeros that is not filled by a call to MatSetValues() or a related routine are compressed
5235:    out by assembly. If you intend to use that extra space on a subsequent assembly, be sure to insert explicit zeros
5236:    before MAT_FINAL_ASSEMBLY so the space is not compressed out.

5238:    Level: beginner

5240: .seealso: MatAssemblyEnd(), MatSetValues(), MatAssembled()
5241: @*/
5242: PetscErrorCode MatAssemblyBegin(Mat mat,MatAssemblyType type)
5243: {

5249:   MatCheckPreallocated(mat,1);
5250:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix.\nDid you forget to call MatSetUnfactored()?");
5251:   if (mat->assembled) {
5252:     mat->was_assembled = PETSC_TRUE;
5253:     mat->assembled     = PETSC_FALSE;
5254:   }

5256:   if (!MatAssemblyEnd_InUse) {
5257:     PetscLogEventBegin(MAT_AssemblyBegin,mat,0,0,0);
5258:     if (mat->ops->assemblybegin) {(*mat->ops->assemblybegin)(mat,type);}
5259:     PetscLogEventEnd(MAT_AssemblyBegin,mat,0,0,0);
5260:   } else if (mat->ops->assemblybegin) {
5261:     (*mat->ops->assemblybegin)(mat,type);
5262:   }
5263:   return(0);
5264: }

5266: /*@
5267:    MatAssembled - Indicates if a matrix has been assembled and is ready for
5268:      use; for example, in matrix-vector product.

5270:    Not Collective

5272:    Input Parameter:
5273: .  mat - the matrix

5275:    Output Parameter:
5276: .  assembled - PETSC_TRUE or PETSC_FALSE

5278:    Level: advanced

5280: .seealso: MatAssemblyEnd(), MatSetValues(), MatAssemblyBegin()
5281: @*/
5282: PetscErrorCode MatAssembled(Mat mat,PetscBool  *assembled)
5283: {
5287:   *assembled = mat->assembled;
5288:   return(0);
5289: }

5291: /*@
5292:    MatAssemblyEnd - Completes assembling the matrix.  This routine should
5293:    be called after MatAssemblyBegin().

5295:    Collective on Mat

5297:    Input Parameters:
5298: +  mat - the matrix
5299: -  type - type of assembly, either MAT_FLUSH_ASSEMBLY or MAT_FINAL_ASSEMBLY

5301:    Options Database Keys:
5302: +  -mat_view ::ascii_info - Prints info on matrix at conclusion of MatEndAssembly()
5303: .  -mat_view ::ascii_info_detail - Prints more detailed info
5304: .  -mat_view - Prints matrix in ASCII format
5305: .  -mat_view ::ascii_matlab - Prints matrix in Matlab format
5306: .  -mat_view draw - PetscDraws nonzero structure of matrix, using MatView() and PetscDrawOpenX().
5307: .  -display <name> - Sets display name (default is host)
5308: .  -draw_pause <sec> - Sets number of seconds to pause after display
5309: .  -mat_view socket - Sends matrix to socket, can be accessed from Matlab (See Users-Manual: Chapter 12 Using MATLAB with PETSc )
5310: .  -viewer_socket_machine <machine> - Machine to use for socket
5311: .  -viewer_socket_port <port> - Port number to use for socket
5312: -  -mat_view binary:filename[:append] - Save matrix to file in binary format

5314:    Notes:
5315:    MatSetValues() generally caches the values.  The matrix is ready to
5316:    use only after MatAssemblyBegin() and MatAssemblyEnd() have been called.
5317:    Use MAT_FLUSH_ASSEMBLY when switching between ADD_VALUES and INSERT_VALUES
5318:    in MatSetValues(); use MAT_FINAL_ASSEMBLY for the final assembly before
5319:    using the matrix.

5321:    Space for preallocated nonzeros that is not filled by a call to MatSetValues() or a related routine are compressed
5322:    out by assembly. If you intend to use that extra space on a subsequent assembly, be sure to insert explicit zeros
5323:    before MAT_FINAL_ASSEMBLY so the space is not compressed out.

5325:    Level: beginner

5327: .seealso: MatAssemblyBegin(), MatSetValues(), PetscDrawOpenX(), PetscDrawCreate(), MatView(), MatAssembled(), PetscViewerSocketOpen()
5328: @*/
5329: PetscErrorCode MatAssemblyEnd(Mat mat,MatAssemblyType type)
5330: {
5331:   PetscErrorCode  ierr;
5332:   static PetscInt inassm = 0;
5333:   PetscBool       flg    = PETSC_FALSE;


5339:   inassm++;
5340:   MatAssemblyEnd_InUse++;
5341:   if (MatAssemblyEnd_InUse == 1) { /* Do the logging only the first time through */
5342:     PetscLogEventBegin(MAT_AssemblyEnd,mat,0,0,0);
5343:     if (mat->ops->assemblyend) {
5344:       (*mat->ops->assemblyend)(mat,type);
5345:     }
5346:     PetscLogEventEnd(MAT_AssemblyEnd,mat,0,0,0);
5347:   } else if (mat->ops->assemblyend) {
5348:     (*mat->ops->assemblyend)(mat,type);
5349:   }

5351:   /* Flush assembly is not a true assembly */
5352:   if (type != MAT_FLUSH_ASSEMBLY) {
5353:     mat->num_ass++;
5354:     mat->assembled        = PETSC_TRUE;
5355:     mat->ass_nonzerostate = mat->nonzerostate;
5356:   }

5358:   mat->insertmode = NOT_SET_VALUES;
5359:   MatAssemblyEnd_InUse--;
5360:   PetscObjectStateIncrease((PetscObject)mat);
5361:   if (!mat->symmetric_eternal) {
5362:     mat->symmetric_set              = PETSC_FALSE;
5363:     mat->hermitian_set              = PETSC_FALSE;
5364:     mat->structurally_symmetric_set = PETSC_FALSE;
5365:   }
5366:   if (inassm == 1 && type != MAT_FLUSH_ASSEMBLY) {
5367:     MatViewFromOptions(mat,NULL,"-mat_view");

5369:     if (mat->checksymmetryonassembly) {
5370:       MatIsSymmetric(mat,mat->checksymmetrytol,&flg);
5371:       if (flg) {
5372:         PetscPrintf(PetscObjectComm((PetscObject)mat),"Matrix is symmetric (tolerance %g)\n",(double)mat->checksymmetrytol);
5373:       } else {
5374:         PetscPrintf(PetscObjectComm((PetscObject)mat),"Matrix is not symmetric (tolerance %g)\n",(double)mat->checksymmetrytol);
5375:       }
5376:     }
5377:     if (mat->nullsp && mat->checknullspaceonassembly) {
5378:       MatNullSpaceTest(mat->nullsp,mat,NULL);
5379:     }
5380:   }
5381:   inassm--;
5382:   return(0);
5383: }

5385: /*@
5386:    MatSetOption - Sets a parameter option for a matrix. Some options
5387:    may be specific to certain storage formats.  Some options
5388:    determine how values will be inserted (or added). Sorted,
5389:    row-oriented input will generally assemble the fastest. The default
5390:    is row-oriented.

5392:    Logically Collective on Mat for certain operations, such as MAT_SPD, not collective for MAT_ROW_ORIENTED, see MatOption

5394:    Input Parameters:
5395: +  mat - the matrix
5396: .  option - the option, one of those listed below (and possibly others),
5397: -  flg - turn the option on (PETSC_TRUE) or off (PETSC_FALSE)

5399:   Options Describing Matrix Structure:
5400: +    MAT_SPD - symmetric positive definite
5401: .    MAT_SYMMETRIC - symmetric in terms of both structure and value
5402: .    MAT_HERMITIAN - transpose is the complex conjugation
5403: .    MAT_STRUCTURALLY_SYMMETRIC - symmetric nonzero structure
5404: -    MAT_SYMMETRY_ETERNAL - if you would like the symmetry/Hermitian flag
5405:                             you set to be kept with all future use of the matrix
5406:                             including after MatAssemblyBegin/End() which could
5407:                             potentially change the symmetry structure, i.e. you
5408:                             KNOW the matrix will ALWAYS have the property you set.
5409:                             Note that setting this flag alone implies nothing about whether the matrix is symmetric/Hermitian;
5410:                             the relevant flags must be set independently.


5413:    Options For Use with MatSetValues():
5414:    Insert a logically dense subblock, which can be
5415: .    MAT_ROW_ORIENTED - row-oriented (default)

5417:    Note these options reflect the data you pass in with MatSetValues(); it has
5418:    nothing to do with how the data is stored internally in the matrix
5419:    data structure.

5421:    When (re)assembling a matrix, we can restrict the input for
5422:    efficiency/debugging purposes.  These options include:
5423: +    MAT_NEW_NONZERO_LOCATIONS - additional insertions will be allowed if they generate a new nonzero (slow)
5424: .    MAT_NEW_DIAGONALS - new diagonals will be allowed (for block diagonal format only)
5425: .    MAT_IGNORE_OFF_PROC_ENTRIES - drops off-processor entries
5426: .    MAT_NEW_NONZERO_LOCATION_ERR - generates an error for new matrix entry
5427: .    MAT_USE_HASH_TABLE - uses a hash table to speed up matrix assembly
5428: .    MAT_NO_OFF_PROC_ENTRIES - you know each process will only set values for its own rows, will generate an error if
5429:         any process sets values for another process. This avoids all reductions in the MatAssembly routines and thus improves
5430:         performance for very large process counts.
5431: -    MAT_SUBSET_OFF_PROC_ENTRIES - you know that the first assembly after setting this flag will set a superset
5432:         of the off-process entries required for all subsequent assemblies. This avoids a rendezvous step in the MatAssembly
5433:         functions, instead sending only neighbor messages.

5435:    Notes:
5436:    Except for MAT_UNUSED_NONZERO_LOCATION_ERR and  MAT_ROW_ORIENTED all processes that share the matrix must pass the same value in flg!

5438:    Some options are relevant only for particular matrix types and
5439:    are thus ignored by others.  Other options are not supported by
5440:    certain matrix types and will generate an error message if set.

5442:    If using a Fortran 77 module to compute a matrix, one may need to
5443:    use the column-oriented option (or convert to the row-oriented
5444:    format).

5446:    MAT_NEW_NONZERO_LOCATIONS set to PETSC_FALSE indicates that any add or insertion
5447:    that would generate a new entry in the nonzero structure is instead
5448:    ignored.  Thus, if memory has not alredy been allocated for this particular
5449:    data, then the insertion is ignored. For dense matrices, in which
5450:    the entire array is allocated, no entries are ever ignored.
5451:    Set after the first MatAssemblyEnd(). If this option is set then the MatAssemblyBegin/End() processes has one less global reduction

5453:    MAT_NEW_NONZERO_LOCATION_ERR set to PETSC_TRUE indicates that any add or insertion
5454:    that would generate a new entry in the nonzero structure instead produces
5455:    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

5457:    MAT_NEW_NONZERO_ALLOCATION_ERR set to PETSC_TRUE indicates that any add or insertion
5458:    that would generate a new entry that has not been preallocated will
5459:    instead produce an error. (Currently supported for AIJ and BAIJ formats
5460:    only.) This is a useful flag when debugging matrix memory preallocation.
5461:    If this option is set then the MatAssemblyBegin/End() processes has one less global reduction

5463:    MAT_IGNORE_OFF_PROC_ENTRIES set to PETSC_TRUE indicates entries destined for
5464:    other processors should be dropped, rather than stashed.
5465:    This is useful if you know that the "owning" processor is also
5466:    always generating the correct matrix entries, so that PETSc need
5467:    not transfer duplicate entries generated on another processor.

5469:    MAT_USE_HASH_TABLE indicates that a hash table be used to improve the
5470:    searches during matrix assembly. When this flag is set, the hash table
5471:    is created during the first Matrix Assembly. This hash table is
5472:    used the next time through, during MatSetVaules()/MatSetVaulesBlocked()
5473:    to improve the searching of indices. MAT_NEW_NONZERO_LOCATIONS flag
5474:    should be used with MAT_USE_HASH_TABLE flag. This option is currently
5475:    supported by MATMPIBAIJ format only.

5477:    MAT_KEEP_NONZERO_PATTERN indicates when MatZeroRows() is called the zeroed entries
5478:    are kept in the nonzero structure

5480:    MAT_IGNORE_ZERO_ENTRIES - for AIJ/IS matrices this will stop zero values from creating
5481:    a zero location in the matrix

5483:    MAT_USE_INODES - indicates using inode version of the code - works with AIJ matrix types

5485:    MAT_NO_OFF_PROC_ZERO_ROWS - you know each process will only zero its own rows. This avoids all reductions in the
5486:         zero row routines and thus improves performance for very large process counts.

5488:    MAT_IGNORE_LOWER_TRIANGULAR - For SBAIJ matrices will ignore any insertions you make in the lower triangular
5489:         part of the matrix (since they should match the upper triangular part).

5491:    MAT_SORTED_FULL - each process provides exactly its local rows; all column indices for a given row are passed in a
5492:                      single call to MatSetValues(), preallocation is perfect, row oriented, INSERT_VALUES is used. Common
5493:                      with finite difference schemes with non-periodic boundary conditions.
5494:    Notes:
5495:     Can only be called after MatSetSizes() and MatSetType() have been set.

5497:    Level: intermediate

5499: .seealso:  MatOption, Mat

5501: @*/
5502: PetscErrorCode MatSetOption(Mat mat,MatOption op,PetscBool flg)
5503: {

5509:   if (op > 0) {
5512:   }

5514:   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);
5515:   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()");

5517:   switch (op) {
5518:   case MAT_NO_OFF_PROC_ENTRIES:
5519:     mat->nooffprocentries = flg;
5520:     return(0);
5521:     break;
5522:   case MAT_SUBSET_OFF_PROC_ENTRIES:
5523:     mat->assembly_subset = flg;
5524:     if (!mat->assembly_subset) { /* See the same logic in VecAssembly wrt VEC_SUBSET_OFF_PROC_ENTRIES */
5525: #if !defined(PETSC_HAVE_MPIUNI)
5526:       MatStashScatterDestroy_BTS(&mat->stash);
5527: #endif
5528:       mat->stash.first_assembly_done = PETSC_FALSE;
5529:     }
5530:     return(0);
5531:   case MAT_NO_OFF_PROC_ZERO_ROWS:
5532:     mat->nooffproczerorows = flg;
5533:     return(0);
5534:     break;
5535:   case MAT_SPD:
5536:     mat->spd_set = PETSC_TRUE;
5537:     mat->spd     = flg;
5538:     if (flg) {
5539:       mat->symmetric                  = PETSC_TRUE;
5540:       mat->structurally_symmetric     = PETSC_TRUE;
5541:       mat->symmetric_set              = PETSC_TRUE;
5542:       mat->structurally_symmetric_set = PETSC_TRUE;
5543:     }
5544:     break;
5545:   case MAT_SYMMETRIC:
5546:     mat->symmetric = flg;
5547:     if (flg) mat->structurally_symmetric = PETSC_TRUE;
5548:     mat->symmetric_set              = PETSC_TRUE;
5549:     mat->structurally_symmetric_set = flg;
5550: #if !defined(PETSC_USE_COMPLEX)
5551:     mat->hermitian     = flg;
5552:     mat->hermitian_set = PETSC_TRUE;
5553: #endif
5554:     break;
5555:   case MAT_HERMITIAN:
5556:     mat->hermitian = flg;
5557:     if (flg) mat->structurally_symmetric = PETSC_TRUE;
5558:     mat->hermitian_set              = PETSC_TRUE;
5559:     mat->structurally_symmetric_set = flg;
5560: #if !defined(PETSC_USE_COMPLEX)
5561:     mat->symmetric     = flg;
5562:     mat->symmetric_set = PETSC_TRUE;
5563: #endif
5564:     break;
5565:   case MAT_STRUCTURALLY_SYMMETRIC:
5566:     mat->structurally_symmetric     = flg;
5567:     mat->structurally_symmetric_set = PETSC_TRUE;
5568:     break;
5569:   case MAT_SYMMETRY_ETERNAL:
5570:     mat->symmetric_eternal = flg;
5571:     break;
5572:   case MAT_STRUCTURE_ONLY:
5573:     mat->structure_only = flg;
5574:     break;
5575:   case MAT_SORTED_FULL:
5576:     mat->sortedfull = flg;
5577:     break;
5578:   default:
5579:     break;
5580:   }
5581:   if (mat->ops->setoption) {
5582:     (*mat->ops->setoption)(mat,op,flg);
5583:   }
5584:   return(0);
5585: }

5587: /*@
5588:    MatGetOption - Gets a parameter option that has been set for a matrix.

5590:    Logically Collective on Mat for certain operations, such as MAT_SPD, not collective for MAT_ROW_ORIENTED, see MatOption

5592:    Input Parameters:
5593: +  mat - the matrix
5594: -  option - the option, this only responds to certain options, check the code for which ones

5596:    Output Parameter:
5597: .  flg - turn the option on (PETSC_TRUE) or off (PETSC_FALSE)

5599:     Notes:
5600:     Can only be called after MatSetSizes() and MatSetType() have been set.

5602:    Level: intermediate

5604: .seealso:  MatOption, MatSetOption()

5606: @*/
5607: PetscErrorCode MatGetOption(Mat mat,MatOption op,PetscBool *flg)
5608: {

5613:   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);
5614:   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()");

5616:   switch (op) {
5617:   case MAT_NO_OFF_PROC_ENTRIES:
5618:     *flg = mat->nooffprocentries;
5619:     break;
5620:   case MAT_NO_OFF_PROC_ZERO_ROWS:
5621:     *flg = mat->nooffproczerorows;
5622:     break;
5623:   case MAT_SYMMETRIC:
5624:     *flg = mat->symmetric;
5625:     break;
5626:   case MAT_HERMITIAN:
5627:     *flg = mat->hermitian;
5628:     break;
5629:   case MAT_STRUCTURALLY_SYMMETRIC:
5630:     *flg = mat->structurally_symmetric;
5631:     break;
5632:   case MAT_SYMMETRY_ETERNAL:
5633:     *flg = mat->symmetric_eternal;
5634:     break;
5635:   case MAT_SPD:
5636:     *flg = mat->spd;
5637:     break;
5638:   default:
5639:     break;
5640:   }
5641:   return(0);
5642: }

5644: /*@
5645:    MatZeroEntries - Zeros all entries of a matrix.  For sparse matrices
5646:    this routine retains the old nonzero structure.

5648:    Logically Collective on Mat

5650:    Input Parameters:
5651: .  mat - the matrix

5653:    Level: intermediate

5655:    Notes:
5656:     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.
5657:    See the Performance chapter of the users manual for information on preallocating matrices.

5659: .seealso: MatZeroRows()
5660: @*/
5661: PetscErrorCode MatZeroEntries(Mat mat)
5662: {

5668:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
5669:   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");
5670:   if (!mat->ops->zeroentries) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
5671:   MatCheckPreallocated(mat,1);

5673:   PetscLogEventBegin(MAT_ZeroEntries,mat,0,0,0);
5674:   (*mat->ops->zeroentries)(mat);
5675:   PetscLogEventEnd(MAT_ZeroEntries,mat,0,0,0);
5676:   PetscObjectStateIncrease((PetscObject)mat);
5677:   return(0);
5678: }

5680: /*@
5681:    MatZeroRowsColumns - Zeros all entries (except possibly the main diagonal)
5682:    of a set of rows and columns of a matrix.

5684:    Collective on Mat

5686:    Input Parameters:
5687: +  mat - the matrix
5688: .  numRows - the number of rows to remove
5689: .  rows - the global row indices
5690: .  diag - value put in all diagonals of eliminated rows (0.0 will even eliminate diagonal entry)
5691: .  x - optional vector of solutions for zeroed rows (other entries in vector are not used)
5692: -  b - optional vector of right hand side, that will be adjusted by provided solution

5694:    Notes:
5695:    This does not change the nonzero structure of the matrix, it merely zeros those entries in the matrix.

5697:    The user can set a value in the diagonal entry (or for the AIJ and
5698:    row formats can optionally remove the main diagonal entry from the
5699:    nonzero structure as well, by passing 0.0 as the final argument).

5701:    For the parallel case, all processes that share the matrix (i.e.,
5702:    those in the communicator used for matrix creation) MUST call this
5703:    routine, regardless of whether any rows being zeroed are owned by
5704:    them.

5706:    Each processor can indicate any rows in the entire matrix to be zeroed (i.e. each process does NOT have to
5707:    list only rows local to itself).

5709:    The option MAT_NO_OFF_PROC_ZERO_ROWS does not apply to this routine.

5711:    Level: intermediate

5713: .seealso: MatZeroRowsIS(), MatZeroRows(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
5714:           MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
5715: @*/
5716: PetscErrorCode MatZeroRowsColumns(Mat mat,PetscInt numRows,const PetscInt rows[],PetscScalar diag,Vec x,Vec b)
5717: {

5724:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
5725:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
5726:   if (!mat->ops->zerorowscolumns) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
5727:   MatCheckPreallocated(mat,1);

5729:   (*mat->ops->zerorowscolumns)(mat,numRows,rows,diag,x,b);
5730:   MatViewFromOptions(mat,NULL,"-mat_view");
5731:   PetscObjectStateIncrease((PetscObject)mat);
5732:   return(0);
5733: }

5735: /*@
5736:    MatZeroRowsColumnsIS - Zeros all entries (except possibly the main diagonal)
5737:    of a set of rows and columns of a matrix.

5739:    Collective on Mat

5741:    Input Parameters:
5742: +  mat - the matrix
5743: .  is - the rows to zero
5744: .  diag - value put in all diagonals of eliminated rows (0.0 will even eliminate diagonal entry)
5745: .  x - optional vector of solutions for zeroed rows (other entries in vector are not used)
5746: -  b - optional vector of right hand side, that will be adjusted by provided solution

5748:    Notes:
5749:    This does not change the nonzero structure of the matrix, it merely zeros those entries in the matrix.

5751:    The user can set a value in the diagonal entry (or for the AIJ and
5752:    row formats can optionally remove the main diagonal entry from the
5753:    nonzero structure as well, by passing 0.0 as the final argument).

5755:    For the parallel case, all processes that share the matrix (i.e.,
5756:    those in the communicator used for matrix creation) MUST call this
5757:    routine, regardless of whether any rows being zeroed are owned by
5758:    them.

5760:    Each processor can indicate any rows in the entire matrix to be zeroed (i.e. each process does NOT have to
5761:    list only rows local to itself).

5763:    The option MAT_NO_OFF_PROC_ZERO_ROWS does not apply to this routine.

5765:    Level: intermediate

5767: .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
5768:           MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRows(), MatZeroRowsColumnsStencil()
5769: @*/
5770: PetscErrorCode MatZeroRowsColumnsIS(Mat mat,IS is,PetscScalar diag,Vec x,Vec b)
5771: {
5773:   PetscInt       numRows;
5774:   const PetscInt *rows;

5781:   ISGetLocalSize(is,&numRows);
5782:   ISGetIndices(is,&rows);
5783:   MatZeroRowsColumns(mat,numRows,rows,diag,x,b);
5784:   ISRestoreIndices(is,&rows);
5785:   return(0);
5786: }

5788: /*@
5789:    MatZeroRows - Zeros all entries (except possibly the main diagonal)
5790:    of a set of rows of a matrix.

5792:    Collective on Mat

5794:    Input Parameters:
5795: +  mat - the matrix
5796: .  numRows - the number of rows to remove
5797: .  rows - the global row indices
5798: .  diag - value put in all diagonals of eliminated rows (0.0 will even eliminate diagonal entry)
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: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
5829:           MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
5830: @*/
5831: PetscErrorCode MatZeroRows(Mat mat,PetscInt numRows,const PetscInt rows[],PetscScalar diag,Vec x,Vec b)
5832: {

5839:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
5840:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
5841:   if (!mat->ops->zerorows) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
5842:   MatCheckPreallocated(mat,1);

5844:   (*mat->ops->zerorows)(mat,numRows,rows,diag,x,b);
5845:   MatViewFromOptions(mat,NULL,"-mat_view");
5846:   PetscObjectStateIncrease((PetscObject)mat);
5847:   return(0);
5848: }

5850: /*@
5851:    MatZeroRowsIS - Zeros all entries (except possibly the main diagonal)
5852:    of a set of rows of a matrix.

5854:    Collective on Mat

5856:    Input Parameters:
5857: +  mat - the matrix
5858: .  is - index set of rows to remove
5859: .  diag - value put in all diagonals of eliminated rows
5860: .  x - optional vector of solutions for zeroed rows (other entries in vector are not used)
5861: -  b - optional vector of right hand side, that will be adjusted by provided solution

5863:    Notes:
5864:    For the AIJ and BAIJ matrix formats this removes the old nonzero structure,
5865:    but does not release memory.  For the dense and block diagonal
5866:    formats this does not alter the nonzero structure.

5868:    If the option MatSetOption(mat,MAT_KEEP_NONZERO_PATTERN,PETSC_TRUE) the nonzero structure
5869:    of the matrix is not changed (even for AIJ and BAIJ matrices) the values are
5870:    merely zeroed.

5872:    The user can set a value in the diagonal entry (or for the AIJ and
5873:    row formats can optionally remove the main diagonal entry from the
5874:    nonzero structure as well, by passing 0.0 as the final argument).

5876:    For the parallel case, all processes that share the matrix (i.e.,
5877:    those in the communicator used for matrix creation) MUST call this
5878:    routine, regardless of whether any rows being zeroed are owned by
5879:    them.

5881:    Each processor can indicate any rows in the entire matrix to be zeroed (i.e. each process does NOT have to
5882:    list only rows local to itself).

5884:    You can call MatSetOption(mat,MAT_NO_OFF_PROC_ZERO_ROWS,PETSC_TRUE) if each process indicates only rows it
5885:    owns that are to be zeroed. This saves a global synchronization in the implementation.

5887:    Level: intermediate

5889: .seealso: MatZeroRows(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
5890:           MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
5891: @*/
5892: PetscErrorCode MatZeroRowsIS(Mat mat,IS is,PetscScalar diag,Vec x,Vec b)
5893: {
5894:   PetscInt       numRows;
5895:   const PetscInt *rows;

5902:   ISGetLocalSize(is,&numRows);
5903:   ISGetIndices(is,&rows);
5904:   MatZeroRows(mat,numRows,rows,diag,x,b);
5905:   ISRestoreIndices(is,&rows);
5906:   return(0);
5907: }

5909: /*@
5910:    MatZeroRowsStencil - Zeros all entries (except possibly the main diagonal)
5911:    of a set of rows of a matrix. These rows must be local to the process.

5913:    Collective on Mat

5915:    Input Parameters:
5916: +  mat - the matrix
5917: .  numRows - the number of rows to remove
5918: .  rows - the grid coordinates (and component number when dof > 1) for matrix rows
5919: .  diag - value put in all diagonals of eliminated rows (0.0 will even eliminate diagonal entry)
5920: .  x - optional vector of solutions for zeroed rows (other entries in vector are not used)
5921: -  b - optional vector of right hand side, that will be adjusted by provided solution

5923:    Notes:
5924:    For the AIJ and BAIJ matrix formats this removes the old nonzero structure,
5925:    but does not release memory.  For the dense and block diagonal
5926:    formats this does not alter the nonzero structure.

5928:    If the option MatSetOption(mat,MAT_KEEP_NONZERO_PATTERN,PETSC_TRUE) the nonzero structure
5929:    of the matrix is not changed (even for AIJ and BAIJ matrices) the values are
5930:    merely zeroed.

5932:    The user can set a value in the diagonal entry (or for the AIJ and
5933:    row formats can optionally remove the main diagonal entry from the
5934:    nonzero structure as well, by passing 0.0 as the final argument).

5936:    For the parallel case, all processes that share the matrix (i.e.,
5937:    those in the communicator used for matrix creation) MUST call this
5938:    routine, regardless of whether any rows being zeroed are owned by
5939:    them.

5941:    Each processor can indicate any rows in the entire matrix to be zeroed (i.e. each process does NOT have to
5942:    list only rows local to itself).

5944:    The grid coordinates are across the entire grid, not just the local portion

5946:    In Fortran idxm and idxn should be declared as
5947: $     MatStencil idxm(4,m)
5948:    and the values inserted using
5949: $    idxm(MatStencil_i,1) = i
5950: $    idxm(MatStencil_j,1) = j
5951: $    idxm(MatStencil_k,1) = k
5952: $    idxm(MatStencil_c,1) = c
5953:    etc

5955:    For periodic boundary conditions use negative indices for values to the left (below 0; that are to be
5956:    obtained by wrapping values from right edge). For values to the right of the last entry using that index plus one
5957:    etc to obtain values that obtained by wrapping the values from the left edge. This does not work for anything but the
5958:    DM_BOUNDARY_PERIODIC boundary type.

5960:    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
5961:    a single value per point) you can skip filling those indices.

5963:    Level: intermediate

5965: .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsl(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
5966:           MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
5967: @*/
5968: PetscErrorCode MatZeroRowsStencil(Mat mat,PetscInt numRows,const MatStencil rows[],PetscScalar diag,Vec x,Vec b)
5969: {
5970:   PetscInt       dim     = mat->stencil.dim;
5971:   PetscInt       sdim    = dim - (1 - (PetscInt) mat->stencil.noc);
5972:   PetscInt       *dims   = mat->stencil.dims+1;
5973:   PetscInt       *starts = mat->stencil.starts;
5974:   PetscInt       *dxm    = (PetscInt*) rows;
5975:   PetscInt       *jdxm, i, j, tmp, numNewRows = 0;


5983:   PetscMalloc1(numRows, &jdxm);
5984:   for (i = 0; i < numRows; ++i) {
5985:     /* Skip unused dimensions (they are ordered k, j, i, c) */
5986:     for (j = 0; j < 3-sdim; ++j) dxm++;
5987:     /* Local index in X dir */
5988:     tmp = *dxm++ - starts[0];
5989:     /* Loop over remaining dimensions */
5990:     for (j = 0; j < dim-1; ++j) {
5991:       /* If nonlocal, set index to be negative */
5992:       if ((*dxm++ - starts[j+1]) < 0 || tmp < 0) tmp = PETSC_MIN_INT;
5993:       /* Update local index */
5994:       else tmp = tmp*dims[j] + *(dxm-1) - starts[j+1];
5995:     }
5996:     /* Skip component slot if necessary */
5997:     if (mat->stencil.noc) dxm++;
5998:     /* Local row number */
5999:     if (tmp >= 0) {
6000:       jdxm[numNewRows++] = tmp;
6001:     }
6002:   }
6003:   MatZeroRowsLocal(mat,numNewRows,jdxm,diag,x,b);
6004:   PetscFree(jdxm);
6005:   return(0);
6006: }

6008: /*@
6009:    MatZeroRowsColumnsStencil - Zeros all row and column entries (except possibly the main diagonal)
6010:    of a set of rows and columns of a matrix.

6012:    Collective on Mat

6014:    Input Parameters:
6015: +  mat - the matrix
6016: .  numRows - the number of rows/columns to remove
6017: .  rows - the grid coordinates (and component number when dof > 1) for matrix rows
6018: .  diag - value put in all diagonals of eliminated rows (0.0 will even eliminate diagonal entry)
6019: .  x - optional vector of solutions for zeroed rows (other entries in vector are not used)
6020: -  b - optional vector of right hand side, that will be adjusted by provided solution

6022:    Notes:
6023:    For the AIJ and BAIJ matrix formats this removes the old nonzero structure,
6024:    but does not release memory.  For the dense and block diagonal
6025:    formats this does not alter the nonzero structure.

6027:    If the option MatSetOption(mat,MAT_KEEP_NONZERO_PATTERN,PETSC_TRUE) the nonzero structure
6028:    of the matrix is not changed (even for AIJ and BAIJ matrices) the values are
6029:    merely zeroed.

6031:    The user can set a value in the diagonal entry (or for the AIJ and
6032:    row formats can optionally remove the main diagonal entry from the
6033:    nonzero structure as well, by passing 0.0 as the final argument).

6035:    For the parallel case, all processes that share the matrix (i.e.,
6036:    those in the communicator used for matrix creation) MUST call this
6037:    routine, regardless of whether any rows being zeroed are owned by
6038:    them.

6040:    Each processor can indicate any rows in the entire matrix to be zeroed (i.e. each process does NOT have to
6041:    list only rows local to itself, but the row/column numbers are given in local numbering).

6043:    The grid coordinates are across the entire grid, not just the local portion

6045:    In Fortran idxm and idxn should be declared as
6046: $     MatStencil idxm(4,m)
6047:    and the values inserted using
6048: $    idxm(MatStencil_i,1) = i
6049: $    idxm(MatStencil_j,1) = j
6050: $    idxm(MatStencil_k,1) = k
6051: $    idxm(MatStencil_c,1) = c
6052:    etc

6054:    For periodic boundary conditions use negative indices for values to the left (below 0; that are to be
6055:    obtained by wrapping values from right edge). For values to the right of the last entry using that index plus one
6056:    etc to obtain values that obtained by wrapping the values from the left edge. This does not work for anything but the
6057:    DM_BOUNDARY_PERIODIC boundary type.

6059:    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
6060:    a single value per point) you can skip filling those indices.

6062:    Level: intermediate

6064: .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
6065:           MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRows()
6066: @*/
6067: PetscErrorCode MatZeroRowsColumnsStencil(Mat mat,PetscInt numRows,const MatStencil rows[],PetscScalar diag,Vec x,Vec b)
6068: {
6069:   PetscInt       dim     = mat->stencil.dim;
6070:   PetscInt       sdim    = dim - (1 - (PetscInt) mat->stencil.noc);
6071:   PetscInt       *dims   = mat->stencil.dims+1;
6072:   PetscInt       *starts = mat->stencil.starts;
6073:   PetscInt       *dxm    = (PetscInt*) rows;
6074:   PetscInt       *jdxm, i, j, tmp, numNewRows = 0;


6082:   PetscMalloc1(numRows, &jdxm);
6083:   for (i = 0; i < numRows; ++i) {
6084:     /* Skip unused dimensions (they are ordered k, j, i, c) */
6085:     for (j = 0; j < 3-sdim; ++j) dxm++;
6086:     /* Local index in X dir */
6087:     tmp = *dxm++ - starts[0];
6088:     /* Loop over remaining dimensions */
6089:     for (j = 0; j < dim-1; ++j) {
6090:       /* If nonlocal, set index to be negative */
6091:       if ((*dxm++ - starts[j+1]) < 0 || tmp < 0) tmp = PETSC_MIN_INT;
6092:       /* Update local index */
6093:       else tmp = tmp*dims[j] + *(dxm-1) - starts[j+1];
6094:     }
6095:     /* Skip component slot if necessary */
6096:     if (mat->stencil.noc) dxm++;
6097:     /* Local row number */
6098:     if (tmp >= 0) {
6099:       jdxm[numNewRows++] = tmp;
6100:     }
6101:   }
6102:   MatZeroRowsColumnsLocal(mat,numNewRows,jdxm,diag,x,b);
6103:   PetscFree(jdxm);
6104:   return(0);
6105: }

6107: /*@C
6108:    MatZeroRowsLocal - Zeros all entries (except possibly the main diagonal)
6109:    of a set of rows of a matrix; using local numbering of rows.

6111:    Collective on Mat

6113:    Input Parameters:
6114: +  mat - the matrix
6115: .  numRows - the number of rows to remove
6116: .  rows - the global row indices
6117: .  diag - value put in all diagonals of eliminated rows
6118: .  x - optional vector of solutions for zeroed rows (other entries in vector are not used)
6119: -  b - optional vector of right hand side, that will be adjusted by provided solution

6121:    Notes:
6122:    Before calling MatZeroRowsLocal(), the user must first set the
6123:    local-to-global mapping by calling MatSetLocalToGlobalMapping().

6125:    For the AIJ matrix formats this removes the old nonzero structure,
6126:    but does not release memory.  For the dense and block diagonal
6127:    formats this does not alter the nonzero structure.

6129:    If the option MatSetOption(mat,MAT_KEEP_NONZERO_PATTERN,PETSC_TRUE) the nonzero structure
6130:    of the matrix is not changed (even for AIJ and BAIJ matrices) the values are
6131:    merely zeroed.

6133:    The user can set a value in the diagonal entry (or for the AIJ and
6134:    row formats can optionally remove the main diagonal entry from the
6135:    nonzero structure as well, by passing 0.0 as the final argument).

6137:    You can call MatSetOption(mat,MAT_NO_OFF_PROC_ZERO_ROWS,PETSC_TRUE) if each process indicates only rows it
6138:    owns that are to be zeroed. This saves a global synchronization in the implementation.

6140:    Level: intermediate

6142: .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRows(), MatSetOption(),
6143:           MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
6144: @*/
6145: PetscErrorCode MatZeroRowsLocal(Mat mat,PetscInt numRows,const PetscInt rows[],PetscScalar diag,Vec x,Vec b)
6146: {

6153:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6154:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6155:   MatCheckPreallocated(mat,1);

6157:   if (mat->ops->zerorowslocal) {
6158:     (*mat->ops->zerorowslocal)(mat,numRows,rows,diag,x,b);
6159:   } else {
6160:     IS             is, newis;
6161:     const PetscInt *newRows;

6163:     if (!mat->rmap->mapping) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Need to provide local to global mapping to matrix first");
6164:     ISCreateGeneral(PETSC_COMM_SELF,numRows,rows,PETSC_COPY_VALUES,&is);
6165:     ISLocalToGlobalMappingApplyIS(mat->rmap->mapping,is,&newis);
6166:     ISGetIndices(newis,&newRows);
6167:     (*mat->ops->zerorows)(mat,numRows,newRows,diag,x,b);
6168:     ISRestoreIndices(newis,&newRows);
6169:     ISDestroy(&newis);
6170:     ISDestroy(&is);
6171:   }
6172:   PetscObjectStateIncrease((PetscObject)mat);
6173:   return(0);
6174: }

6176: /*@
6177:    MatZeroRowsLocalIS - Zeros all entries (except possibly the main diagonal)
6178:    of a set of rows of a matrix; using local numbering of rows.

6180:    Collective on Mat

6182:    Input Parameters:
6183: +  mat - the matrix
6184: .  is - index set of rows to remove
6185: .  diag - value put in all diagonals of eliminated rows
6186: .  x - optional vector of solutions for zeroed rows (other entries in vector are not used)
6187: -  b - optional vector of right hand side, that will be adjusted by provided solution

6189:    Notes:
6190:    Before calling MatZeroRowsLocalIS(), the user must first set the
6191:    local-to-global mapping by calling MatSetLocalToGlobalMapping().

6193:    For the AIJ matrix formats this removes the old nonzero structure,
6194:    but does not release memory.  For the dense and block diagonal
6195:    formats this does not alter the nonzero structure.

6197:    If the option MatSetOption(mat,MAT_KEEP_NONZERO_PATTERN,PETSC_TRUE) the nonzero structure
6198:    of the matrix is not changed (even for AIJ and BAIJ matrices) the values are
6199:    merely zeroed.

6201:    The user can set a value in the diagonal entry (or for the AIJ and
6202:    row formats can optionally remove the main diagonal entry from the
6203:    nonzero structure as well, by passing 0.0 as the final argument).

6205:    You can call MatSetOption(mat,MAT_NO_OFF_PROC_ZERO_ROWS,PETSC_TRUE) if each process indicates only rows it
6206:    owns that are to be zeroed. This saves a global synchronization in the implementation.

6208:    Level: intermediate

6210: .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRows(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
6211:           MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
6212: @*/
6213: PetscErrorCode MatZeroRowsLocalIS(Mat mat,IS is,PetscScalar diag,Vec x,Vec b)
6214: {
6216:   PetscInt       numRows;
6217:   const PetscInt *rows;

6223:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6224:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6225:   MatCheckPreallocated(mat,1);

6227:   ISGetLocalSize(is,&numRows);
6228:   ISGetIndices(is,&rows);
6229:   MatZeroRowsLocal(mat,numRows,rows,diag,x,b);
6230:   ISRestoreIndices(is,&rows);
6231:   return(0);
6232: }

6234: /*@
6235:    MatZeroRowsColumnsLocal - Zeros all entries (except possibly the main diagonal)
6236:    of a set of rows and columns of a matrix; using local numbering of rows.

6238:    Collective on Mat

6240:    Input Parameters:
6241: +  mat - the matrix
6242: .  numRows - the number of rows to remove
6243: .  rows - the global row indices
6244: .  diag - value put in all diagonals of eliminated rows
6245: .  x - optional vector of solutions for zeroed rows (other entries in vector are not used)
6246: -  b - optional vector of right hand side, that will be adjusted by provided solution

6248:    Notes:
6249:    Before calling MatZeroRowsColumnsLocal(), the user must first set the
6250:    local-to-global mapping by calling MatSetLocalToGlobalMapping().

6252:    The user can set a value in the diagonal entry (or for the AIJ and
6253:    row formats can optionally remove the main diagonal entry from the
6254:    nonzero structure as well, by passing 0.0 as the final argument).

6256:    Level: intermediate

6258: .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
6259:           MatZeroRows(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
6260: @*/
6261: PetscErrorCode MatZeroRowsColumnsLocal(Mat mat,PetscInt numRows,const PetscInt rows[],PetscScalar diag,Vec x,Vec b)
6262: {
6264:   IS             is, newis;
6265:   const PetscInt *newRows;

6271:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6272:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6273:   MatCheckPreallocated(mat,1);

6275:   if (!mat->cmap->mapping) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Need to provide local to global mapping to matrix first");
6276:   ISCreateGeneral(PETSC_COMM_SELF,numRows,rows,PETSC_COPY_VALUES,&is);
6277:   ISLocalToGlobalMappingApplyIS(mat->cmap->mapping,is,&newis);
6278:   ISGetIndices(newis,&newRows);
6279:   (*mat->ops->zerorowscolumns)(mat,numRows,newRows,diag,x,b);
6280:   ISRestoreIndices(newis,&newRows);
6281:   ISDestroy(&newis);
6282:   ISDestroy(&is);
6283:   PetscObjectStateIncrease((PetscObject)mat);
6284:   return(0);
6285: }

6287: /*@
6288:    MatZeroRowsColumnsLocalIS - Zeros all entries (except possibly the main diagonal)
6289:    of a set of rows and columns of a matrix; using local numbering of rows.

6291:    Collective on Mat

6293:    Input Parameters:
6294: +  mat - the matrix
6295: .  is - index set of rows to remove
6296: .  diag - value put in all diagonals of eliminated rows
6297: .  x - optional vector of solutions for zeroed rows (other entries in vector are not used)
6298: -  b - optional vector of right hand side, that will be adjusted by provided solution

6300:    Notes:
6301:    Before calling MatZeroRowsColumnsLocalIS(), the user must first set the
6302:    local-to-global mapping by calling MatSetLocalToGlobalMapping().

6304:    The user can set a value in the diagonal entry (or for the AIJ and
6305:    row formats can optionally remove the main diagonal entry from the
6306:    nonzero structure as well, by passing 0.0 as the final argument).

6308:    Level: intermediate

6310: .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
6311:           MatZeroRowsColumnsLocal(), MatZeroRows(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
6312: @*/
6313: PetscErrorCode MatZeroRowsColumnsLocalIS(Mat mat,IS is,PetscScalar diag,Vec x,Vec b)
6314: {
6316:   PetscInt       numRows;
6317:   const PetscInt *rows;

6323:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6324:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6325:   MatCheckPreallocated(mat,1);

6327:   ISGetLocalSize(is,&numRows);
6328:   ISGetIndices(is,&rows);
6329:   MatZeroRowsColumnsLocal(mat,numRows,rows,diag,x,b);
6330:   ISRestoreIndices(is,&rows);
6331:   return(0);
6332: }

6334: /*@C
6335:    MatGetSize - Returns the numbers of rows and columns in a matrix.

6337:    Not Collective

6339:    Input Parameter:
6340: .  mat - the matrix

6342:    Output Parameters:
6343: +  m - the number of global rows
6344: -  n - the number of global columns

6346:    Note: both output parameters can be NULL on input.

6348:    Level: beginner

6350: .seealso: MatGetLocalSize()
6351: @*/
6352: PetscErrorCode MatGetSize(Mat mat,PetscInt *m,PetscInt *n)
6353: {
6356:   if (m) *m = mat->rmap->N;
6357:   if (n) *n = mat->cmap->N;
6358:   return(0);
6359: }

6361: /*@C
6362:    MatGetLocalSize - Returns the number of rows and columns in a matrix
6363:    stored locally.  This information may be implementation dependent, so
6364:    use with care.

6366:    Not Collective

6368:    Input Parameters:
6369: .  mat - the matrix

6371:    Output Parameters:
6372: +  m - the number of local rows
6373: -  n - the number of local columns

6375:    Note: both output parameters can be NULL on input.

6377:    Level: beginner

6379: .seealso: MatGetSize()
6380: @*/
6381: PetscErrorCode MatGetLocalSize(Mat mat,PetscInt *m,PetscInt *n)
6382: {
6387:   if (m) *m = mat->rmap->n;
6388:   if (n) *n = mat->cmap->n;
6389:   return(0);
6390: }

6392: /*@C
6393:    MatGetOwnershipRangeColumn - Returns the range of matrix columns associated with rows of a vector one multiplies by that owned by
6394:    this processor. (The columns of the "diagonal block")

6396:    Not Collective, unless matrix has not been allocated, then collective on Mat

6398:    Input Parameters:
6399: .  mat - the matrix

6401:    Output Parameters:
6402: +  m - the global index of the first local column
6403: -  n - one more than the global index of the last local column

6405:    Notes:
6406:     both output parameters can be NULL on input.

6408:    Level: developer

6410: .seealso:  MatGetOwnershipRange(), MatGetOwnershipRanges(), MatGetOwnershipRangesColumn()

6412: @*/
6413: PetscErrorCode MatGetOwnershipRangeColumn(Mat mat,PetscInt *m,PetscInt *n)
6414: {
6420:   MatCheckPreallocated(mat,1);
6421:   if (m) *m = mat->cmap->rstart;
6422:   if (n) *n = mat->cmap->rend;
6423:   return(0);
6424: }

6426: /*@C
6427:    MatGetOwnershipRange - Returns the range of matrix rows owned by
6428:    this processor, assuming that the matrix is laid out with the first
6429:    n1 rows on the first processor, the next n2 rows on the second, etc.
6430:    For certain parallel layouts this range may not be well defined.

6432:    Not Collective

6434:    Input Parameters:
6435: .  mat - the matrix

6437:    Output Parameters:
6438: +  m - the global index of the first local row
6439: -  n - one more than the global index of the last local row

6441:    Note: Both output parameters can be NULL on input.
6442: $  This function requires that the matrix be preallocated. If you have not preallocated, consider using
6443: $    PetscSplitOwnership(MPI_Comm comm, PetscInt *n, PetscInt *N)
6444: $  and then MPI_Scan() to calculate prefix sums of the local sizes.

6446:    Level: beginner

6448: .seealso:   MatGetOwnershipRanges(), MatGetOwnershipRangeColumn(), MatGetOwnershipRangesColumn(), PetscSplitOwnership(), PetscSplitOwnershipBlock()

6450: @*/
6451: PetscErrorCode MatGetOwnershipRange(Mat mat,PetscInt *m,PetscInt *n)
6452: {
6458:   MatCheckPreallocated(mat,1);
6459:   if (m) *m = mat->rmap->rstart;
6460:   if (n) *n = mat->rmap->rend;
6461:   return(0);
6462: }

6464: /*@C
6465:    MatGetOwnershipRanges - Returns the range of matrix rows owned by
6466:    each process

6468:    Not Collective, unless matrix has not been allocated, then collective on Mat

6470:    Input Parameters:
6471: .  mat - the matrix

6473:    Output Parameters:
6474: .  ranges - start of each processors portion plus one more than the total length at the end

6476:    Level: beginner

6478: .seealso:   MatGetOwnershipRange(), MatGetOwnershipRangeColumn(), MatGetOwnershipRangesColumn()

6480: @*/
6481: PetscErrorCode MatGetOwnershipRanges(Mat mat,const PetscInt **ranges)
6482: {

6488:   MatCheckPreallocated(mat,1);
6489:   PetscLayoutGetRanges(mat->rmap,ranges);
6490:   return(0);
6491: }

6493: /*@C
6494:    MatGetOwnershipRangesColumn - Returns the range of matrix columns associated with rows of a vector one multiplies by that owned by
6495:    this processor. (The columns of the "diagonal blocks" for each process)

6497:    Not Collective, unless matrix has not been allocated, then collective on Mat

6499:    Input Parameters:
6500: .  mat - the matrix

6502:    Output Parameters:
6503: .  ranges - start of each processors portion plus one more then the total length at the end

6505:    Level: beginner

6507: .seealso:   MatGetOwnershipRange(), MatGetOwnershipRangeColumn(), MatGetOwnershipRanges()

6509: @*/
6510: PetscErrorCode MatGetOwnershipRangesColumn(Mat mat,const PetscInt **ranges)
6511: {

6517:   MatCheckPreallocated(mat,1);
6518:   PetscLayoutGetRanges(mat->cmap,ranges);
6519:   return(0);
6520: }

6522: /*@C
6523:    MatGetOwnershipIS - Get row and column ownership as index sets

6525:    Not Collective

6527:    Input Arguments:
6528: .  A - matrix of type Elemental

6530:    Output Arguments:
6531: +  rows - rows in which this process owns elements
6532: -  cols - columns in which this process owns elements

6534:    Level: intermediate

6536: .seealso: MatGetOwnershipRange(), MatGetOwnershipRangeColumn(), MatSetValues(), MATELEMENTAL
6537: @*/
6538: PetscErrorCode MatGetOwnershipIS(Mat A,IS *rows,IS *cols)
6539: {
6540:   PetscErrorCode ierr,(*f)(Mat,IS*,IS*);

6543:   MatCheckPreallocated(A,1);
6544:   PetscObjectQueryFunction((PetscObject)A,"MatGetOwnershipIS_C",&f);
6545:   if (f) {
6546:     (*f)(A,rows,cols);
6547:   } else {   /* Create a standard row-based partition, each process is responsible for ALL columns in their row block */
6548:     if (rows) {ISCreateStride(PETSC_COMM_SELF,A->rmap->n,A->rmap->rstart,1,rows);}
6549:     if (cols) {ISCreateStride(PETSC_COMM_SELF,A->cmap->N,0,1,cols);}
6550:   }
6551:   return(0);
6552: }

6554: /*@C
6555:    MatILUFactorSymbolic - Performs symbolic ILU factorization of a matrix.
6556:    Uses levels of fill only, not drop tolerance. Use MatLUFactorNumeric()
6557:    to complete the factorization.

6559:    Collective on Mat

6561:    Input Parameters:
6562: +  mat - the matrix
6563: .  row - row permutation
6564: .  column - column permutation
6565: -  info - structure containing
6566: $      levels - number of levels of fill.
6567: $      expected fill - as ratio of original fill.
6568: $      1 or 0 - indicating force fill on diagonal (improves robustness for matrices
6569:                 missing diagonal entries)

6571:    Output Parameters:
6572: .  fact - new matrix that has been symbolically factored

6574:    Notes:
6575:     See Users-Manual: ch_mat for additional information about choosing the fill factor for better efficiency.

6577:    Most users should employ the simplified KSP interface for linear solvers
6578:    instead of working directly with matrix algebra routines such as this.
6579:    See, e.g., KSPCreate().

6581:    Level: developer

6583: .seealso: MatLUFactorSymbolic(), MatLUFactorNumeric(), MatCholeskyFactor()
6584:           MatGetOrdering(), MatFactorInfo

6586:     Note: this uses the definition of level of fill as in Y. Saad, 2003

6588:     Developer Note: fortran interface is not autogenerated as the f90
6589:     interface defintion cannot be generated correctly [due to MatFactorInfo]

6591:    References:
6592:      Y. Saad, Iterative methods for sparse linear systems Philadelphia: Society for Industrial and Applied Mathematics, 2003
6593: @*/
6594: PetscErrorCode MatILUFactorSymbolic(Mat fact,Mat mat,IS row,IS col,const MatFactorInfo *info)
6595: {

6605:   if (info->levels < 0) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_OUTOFRANGE,"Levels of fill negative %D",(PetscInt)info->levels);
6606:   if (info->fill < 1.0) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_OUTOFRANGE,"Expected fill less than 1.0 %g",(double)info->fill);
6607:   if (!(fact)->ops->ilufactorsymbolic) {
6608:     MatSolverType spackage;
6609:     MatFactorGetSolverType(fact,&spackage);
6610:     SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Matrix type %s symbolic ILU using solver package %s",((PetscObject)mat)->type_name,spackage);
6611:   }
6612:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6613:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6614:   MatCheckPreallocated(mat,2);

6616:   PetscLogEventBegin(MAT_ILUFactorSymbolic,mat,row,col,0);
6617:   (fact->ops->ilufactorsymbolic)(fact,mat,row,col,info);
6618:   PetscLogEventEnd(MAT_ILUFactorSymbolic,mat,row,col,0);
6619:   return(0);
6620: }

6622: /*@C
6623:    MatICCFactorSymbolic - Performs symbolic incomplete
6624:    Cholesky factorization for a symmetric matrix.  Use
6625:    MatCholeskyFactorNumeric() to complete the factorization.

6627:    Collective on Mat

6629:    Input Parameters:
6630: +  mat - the matrix
6631: .  perm - row and column permutation
6632: -  info - structure containing
6633: $      levels - number of levels of fill.
6634: $      expected fill - as ratio of original fill.

6636:    Output Parameter:
6637: .  fact - the factored matrix

6639:    Notes:
6640:    Most users should employ the KSP interface for linear solvers
6641:    instead of working directly with matrix algebra routines such as this.
6642:    See, e.g., KSPCreate().

6644:    Level: developer

6646: .seealso: MatCholeskyFactorNumeric(), MatCholeskyFactor(), MatFactorInfo

6648:     Note: this uses the definition of level of fill as in Y. Saad, 2003

6650:     Developer Note: fortran interface is not autogenerated as the f90
6651:     interface defintion cannot be generated correctly [due to MatFactorInfo]

6653:    References:
6654:      Y. Saad, Iterative methods for sparse linear systems Philadelphia: Society for Industrial and Applied Mathematics, 2003
6655: @*/
6656: PetscErrorCode MatICCFactorSymbolic(Mat fact,Mat mat,IS perm,const MatFactorInfo *info)
6657: {

6666:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6667:   if (info->levels < 0) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_OUTOFRANGE,"Levels negative %D",(PetscInt) info->levels);
6668:   if (info->fill < 1.0) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_OUTOFRANGE,"Expected fill less than 1.0 %g",(double)info->fill);
6669:   if (!(fact)->ops->iccfactorsymbolic) {
6670:     MatSolverType spackage;
6671:     MatFactorGetSolverType(fact,&spackage);
6672:     SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Matrix type %s symbolic ICC using solver package %s",((PetscObject)mat)->type_name,spackage);
6673:   }
6674:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6675:   MatCheckPreallocated(mat,2);

6677:   PetscLogEventBegin(MAT_ICCFactorSymbolic,mat,perm,0,0);
6678:   (fact->ops->iccfactorsymbolic)(fact,mat,perm,info);
6679:   PetscLogEventEnd(MAT_ICCFactorSymbolic,mat,perm,0,0);
6680:   return(0);
6681: }

6683: /*@C
6684:    MatCreateSubMatrices - Extracts several submatrices from a matrix. If submat
6685:    points to an array of valid matrices, they may be reused to store the new
6686:    submatrices.

6688:    Collective on Mat

6690:    Input Parameters:
6691: +  mat - the matrix
6692: .  n   - the number of submatrixes to be extracted (on this processor, may be zero)
6693: .  irow, icol - index sets of rows and columns to extract
6694: -  scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX

6696:    Output Parameter:
6697: .  submat - the array of submatrices

6699:    Notes:
6700:    MatCreateSubMatrices() can extract ONLY sequential submatrices
6701:    (from both sequential and parallel matrices). Use MatCreateSubMatrix()
6702:    to extract a parallel submatrix.

6704:    Some matrix types place restrictions on the row and column
6705:    indices, such as that they be sorted or that they be equal to each other.

6707:    The index sets may not have duplicate entries.

6709:    When extracting submatrices from a parallel matrix, each processor can
6710:    form a different submatrix by setting the rows and columns of its
6711:    individual index sets according to the local submatrix desired.

6713:    When finished using the submatrices, the user should destroy
6714:    them with MatDestroySubMatrices().

6716:    MAT_REUSE_MATRIX can only be used when the nonzero structure of the
6717:    original matrix has not changed from that last call to MatCreateSubMatrices().

6719:    This routine creates the matrices in submat; you should NOT create them before
6720:    calling it. It also allocates the array of matrix pointers submat.

6722:    For BAIJ matrices the index sets must respect the block structure, that is if they
6723:    request one row/column in a block, they must request all rows/columns that are in
6724:    that block. For example, if the block size is 2 you cannot request just row 0 and
6725:    column 0.

6727:    Fortran Note:
6728:    The Fortran interface is slightly different from that given below; it
6729:    requires one to pass in  as submat a Mat (integer) array of size at least n+1.

6731:    Level: advanced


6734: .seealso: MatDestroySubMatrices(), MatCreateSubMatrix(), MatGetRow(), MatGetDiagonal(), MatReuse
6735: @*/
6736: PetscErrorCode MatCreateSubMatrices(Mat mat,PetscInt n,const IS irow[],const IS icol[],MatReuse scall,Mat *submat[])
6737: {
6739:   PetscInt       i;
6740:   PetscBool      eq;

6745:   if (n) {
6750:   }
6752:   if (n && scall == MAT_REUSE_MATRIX) {
6755:   }
6756:   if (!mat->ops->createsubmatrices) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
6757:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6758:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6759:   MatCheckPreallocated(mat,1);

6761:   PetscLogEventBegin(MAT_CreateSubMats,mat,0,0,0);
6762:   (*mat->ops->createsubmatrices)(mat,n,irow,icol,scall,submat);
6763:   PetscLogEventEnd(MAT_CreateSubMats,mat,0,0,0);
6764:   for (i=0; i<n; i++) {
6765:     (*submat)[i]->factortype = MAT_FACTOR_NONE;  /* in case in place factorization was previously done on submatrix */
6766:     ISEqualUnsorted(irow[i],icol[i],&eq);
6767:     if (eq) {
6768:       MatPropagateSymmetryOptions(mat,(*submat)[i]);
6769:     }
6770:   }
6771:   return(0);
6772: }

6774: /*@C
6775:    MatCreateSubMatricesMPI - Extracts MPI submatrices across a sub communicator of mat (by pairs of IS that may live on subcomms).

6777:    Collective on Mat

6779:    Input Parameters:
6780: +  mat - the matrix
6781: .  n   - the number of submatrixes to be extracted
6782: .  irow, icol - index sets of rows and columns to extract
6783: -  scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX

6785:    Output Parameter:
6786: .  submat - the array of submatrices

6788:    Level: advanced


6791: .seealso: MatCreateSubMatrices(), MatCreateSubMatrix(), MatGetRow(), MatGetDiagonal(), MatReuse
6792: @*/
6793: PetscErrorCode MatCreateSubMatricesMPI(Mat mat,PetscInt n,const IS irow[],const IS icol[],MatReuse scall,Mat *submat[])
6794: {
6796:   PetscInt       i;
6797:   PetscBool      eq;

6802:   if (n) {
6807:   }
6809:   if (n && scall == MAT_REUSE_MATRIX) {
6812:   }
6813:   if (!mat->ops->createsubmatricesmpi) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
6814:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6815:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6816:   MatCheckPreallocated(mat,1);

6818:   PetscLogEventBegin(MAT_CreateSubMats,mat,0,0,0);
6819:   (*mat->ops->createsubmatricesmpi)(mat,n,irow,icol,scall,submat);
6820:   PetscLogEventEnd(MAT_CreateSubMats,mat,0,0,0);
6821:   for (i=0; i<n; i++) {
6822:     ISEqualUnsorted(irow[i],icol[i],&eq);
6823:     if (eq) {
6824:       MatPropagateSymmetryOptions(mat,(*submat)[i]);
6825:     }
6826:   }
6827:   return(0);
6828: }

6830: /*@C
6831:    MatDestroyMatrices - Destroys an array of matrices.

6833:    Collective on Mat

6835:    Input Parameters:
6836: +  n - the number of local matrices
6837: -  mat - the matrices (note that this is a pointer to the array of matrices)

6839:    Level: advanced

6841:     Notes:
6842:     Frees not only the matrices, but also the array that contains the matrices
6843:            In Fortran will not free the array.

6845: .seealso: MatCreateSubMatrices() MatDestroySubMatrices()
6846: @*/
6847: PetscErrorCode MatDestroyMatrices(PetscInt n,Mat *mat[])
6848: {
6850:   PetscInt       i;

6853:   if (!*mat) return(0);
6854:   if (n < 0) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Trying to destroy negative number of matrices %D",n);

6857:   for (i=0; i<n; i++) {
6858:     MatDestroy(&(*mat)[i]);
6859:   }

6861:   /* memory is allocated even if n = 0 */
6862:   PetscFree(*mat);
6863:   return(0);
6864: }

6866: /*@C
6867:    MatDestroySubMatrices - Destroys a set of matrices obtained with MatCreateSubMatrices().

6869:    Collective on Mat

6871:    Input Parameters:
6872: +  n - the number of local matrices
6873: -  mat - the matrices (note that this is a pointer to the array of matrices, just to match the calling
6874:                        sequence of MatCreateSubMatrices())

6876:    Level: advanced

6878:     Notes:
6879:     Frees not only the matrices, but also the array that contains the matrices
6880:            In Fortran will not free the array.

6882: .seealso: MatCreateSubMatrices()
6883: @*/
6884: PetscErrorCode MatDestroySubMatrices(PetscInt n,Mat *mat[])
6885: {
6887:   Mat            mat0;

6890:   if (!*mat) return(0);
6891:   /* mat[] is an array of length n+1, see MatCreateSubMatrices_xxx() */
6892:   if (n < 0) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Trying to destroy negative number of matrices %D",n);

6895:   mat0 = (*mat)[0];
6896:   if (mat0 && mat0->ops->destroysubmatrices) {
6897:     (mat0->ops->destroysubmatrices)(n,mat);
6898:   } else {
6899:     MatDestroyMatrices(n,mat);
6900:   }
6901:   return(0);
6902: }

6904: /*@C
6905:    MatGetSeqNonzeroStructure - Extracts the sequential nonzero structure from a matrix.

6907:    Collective on Mat

6909:    Input Parameters:
6910: .  mat - the matrix

6912:    Output Parameter:
6913: .  matstruct - the sequential matrix with the nonzero structure of mat

6915:   Level: intermediate

6917: .seealso: MatDestroySeqNonzeroStructure(), MatCreateSubMatrices(), MatDestroyMatrices()
6918: @*/
6919: PetscErrorCode MatGetSeqNonzeroStructure(Mat mat,Mat *matstruct)
6920: {


6928:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6929:   MatCheckPreallocated(mat,1);

6931:   if (!mat->ops->getseqnonzerostructure) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Not for matrix type %s\n",((PetscObject)mat)->type_name);
6932:   PetscLogEventBegin(MAT_GetSeqNonzeroStructure,mat,0,0,0);
6933:   (*mat->ops->getseqnonzerostructure)(mat,matstruct);
6934:   PetscLogEventEnd(MAT_GetSeqNonzeroStructure,mat,0,0,0);
6935:   return(0);
6936: }

6938: /*@C
6939:    MatDestroySeqNonzeroStructure - Destroys matrix obtained with MatGetSeqNonzeroStructure().

6941:    Collective on Mat

6943:    Input Parameters:
6944: .  mat - the matrix (note that this is a pointer to the array of matrices, just to match the calling
6945:                        sequence of MatGetSequentialNonzeroStructure())

6947:    Level: advanced

6949:     Notes:
6950:     Frees not only the matrices, but also the array that contains the matrices

6952: .seealso: MatGetSeqNonzeroStructure()
6953: @*/
6954: PetscErrorCode MatDestroySeqNonzeroStructure(Mat *mat)
6955: {

6960:   MatDestroy(mat);
6961:   return(0);
6962: }

6964: /*@
6965:    MatIncreaseOverlap - Given a set of submatrices indicated by index sets,
6966:    replaces the index sets by larger ones that represent submatrices with
6967:    additional overlap.

6969:    Collective on Mat

6971:    Input Parameters:
6972: +  mat - the matrix
6973: .  n   - the number of index sets
6974: .  is  - the array of index sets (these index sets will changed during the call)
6975: -  ov  - the additional overlap requested

6977:    Options Database:
6978: .  -mat_increase_overlap_scalable - use a scalable algorithm to compute the overlap (supported by MPIAIJ matrix)

6980:    Level: developer


6983: .seealso: MatCreateSubMatrices()
6984: @*/
6985: PetscErrorCode MatIncreaseOverlap(Mat mat,PetscInt n,IS is[],PetscInt ov)
6986: {

6992:   if (n < 0) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Must have one or more domains, you have %D",n);
6993:   if (n) {
6996:   }
6997:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6998:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6999:   MatCheckPreallocated(mat,1);

7001:   if (!ov) return(0);
7002:   if (!mat->ops->increaseoverlap) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
7003:   PetscLogEventBegin(MAT_IncreaseOverlap,mat,0,0,0);
7004:   (*mat->ops->increaseoverlap)(mat,n,is,ov);
7005:   PetscLogEventEnd(MAT_IncreaseOverlap,mat,0,0,0);
7006:   return(0);
7007: }


7010: PetscErrorCode MatIncreaseOverlapSplit_Single(Mat,IS*,PetscInt);

7012: /*@
7013:    MatIncreaseOverlapSplit - Given a set of submatrices indicated by index sets across
7014:    a sub communicator, replaces the index sets by larger ones that represent submatrices with
7015:    additional overlap.

7017:    Collective on Mat

7019:    Input Parameters:
7020: +  mat - the matrix
7021: .  n   - the number of index sets
7022: .  is  - the array of index sets (these index sets will changed during the call)
7023: -  ov  - the additional overlap requested

7025:    Options Database:
7026: .  -mat_increase_overlap_scalable - use a scalable algorithm to compute the overlap (supported by MPIAIJ matrix)

7028:    Level: developer


7031: .seealso: MatCreateSubMatrices()
7032: @*/
7033: PetscErrorCode MatIncreaseOverlapSplit(Mat mat,PetscInt n,IS is[],PetscInt ov)
7034: {
7035:   PetscInt       i;

7041:   if (n < 0) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Must have one or more domains, you have %D",n);
7042:   if (n) {
7045:   }
7046:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
7047:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
7048:   MatCheckPreallocated(mat,1);
7049:   if (!ov) return(0);
7050:   PetscLogEventBegin(MAT_IncreaseOverlap,mat,0,0,0);
7051:   for(i=0; i<n; i++){
7052:          MatIncreaseOverlapSplit_Single(mat,&is[i],ov);
7053:   }
7054:   PetscLogEventEnd(MAT_IncreaseOverlap,mat,0,0,0);
7055:   return(0);
7056: }




7061: /*@
7062:    MatGetBlockSize - Returns the matrix block size.

7064:    Not Collective

7066:    Input Parameter:
7067: .  mat - the matrix

7069:    Output Parameter:
7070: .  bs - block size

7072:    Notes:
7073:     Block row formats are MATSEQBAIJ, MATMPIBAIJ, MATSEQSBAIJ, MATMPISBAIJ. These formats ALWAYS have square block storage in the matrix.

7075:    If the block size has not been set yet this routine returns 1.

7077:    Level: intermediate

7079: .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSizes()
7080: @*/
7081: PetscErrorCode MatGetBlockSize(Mat mat,PetscInt *bs)
7082: {
7086:   *bs = PetscAbs(mat->rmap->bs);
7087:   return(0);
7088: }

7090: /*@
7091:    MatGetBlockSizes - Returns the matrix block row and column sizes.

7093:    Not Collective

7095:    Input Parameter:
7096: .  mat - the matrix

7098:    Output Parameter:
7099: +  rbs - row block size
7100: -  cbs - column block size

7102:    Notes:
7103:     Block row formats are MATSEQBAIJ, MATMPIBAIJ, MATSEQSBAIJ, MATMPISBAIJ. These formats ALWAYS have square block storage in the matrix.
7104:     If you pass a different block size for the columns than the rows, the row block size determines the square block storage.

7106:    If a block size has not been set yet this routine returns 1.

7108:    Level: intermediate

7110: .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSize(), MatSetBlockSize(), MatSetBlockSizes()
7111: @*/
7112: PetscErrorCode MatGetBlockSizes(Mat mat,PetscInt *rbs, PetscInt *cbs)
7113: {
7118:   if (rbs) *rbs = PetscAbs(mat->rmap->bs);
7119:   if (cbs) *cbs = PetscAbs(mat->cmap->bs);
7120:   return(0);
7121: }

7123: /*@
7124:    MatSetBlockSize - Sets the matrix block size.

7126:    Logically Collective on Mat

7128:    Input Parameters:
7129: +  mat - the matrix
7130: -  bs - block size

7132:    Notes:
7133:     Block row formats are MATSEQBAIJ, MATMPIBAIJ, MATSEQSBAIJ, MATMPISBAIJ. These formats ALWAYS have square block storage in the matrix.
7134:     This must be called before MatSetUp() or MatXXXSetPreallocation() (or will default to 1) and the block size cannot be changed later.

7136:     For MATMPIAIJ and MATSEQAIJ matrix formats, this function can be called at a later stage, provided that the specified block size
7137:     is compatible with the matrix local sizes.

7139:    Level: intermediate

7141: .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSize(), MatSetBlockSizes(), MatGetBlockSizes()
7142: @*/
7143: PetscErrorCode MatSetBlockSize(Mat mat,PetscInt bs)
7144: {

7150:   MatSetBlockSizes(mat,bs,bs);
7151:   return(0);
7152: }

7154: /*@
7155:    MatSetVariableBlockSizes - Sets a diagonal blocks of the matrix that need not be of the same size

7157:    Logically Collective on Mat

7159:    Input Parameters:
7160: +  mat - the matrix
7161: .  nblocks - the number of blocks on this process
7162: -  bsizes - the block sizes

7164:    Notes:
7165:     Currently used by PCVPBJACOBI for SeqAIJ matrices

7167:    Level: intermediate

7169: .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSize(), MatSetBlockSizes(), MatGetBlockSizes(), MatGetVariableBlockSizes()
7170: @*/
7171: PetscErrorCode MatSetVariableBlockSizes(Mat mat,PetscInt nblocks,PetscInt *bsizes)
7172: {
7174:   PetscInt       i,ncnt = 0, nlocal;

7178:   if (nblocks < 0) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Number of local blocks must be great than or equal to zero");
7179:   MatGetLocalSize(mat,&nlocal,NULL);
7180:   for (i=0; i<nblocks; i++) ncnt += bsizes[i];
7181:   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);
7182:   PetscFree(mat->bsizes);
7183:   mat->nblocks = nblocks;
7184:   PetscMalloc1(nblocks,&mat->bsizes);
7185:   PetscArraycpy(mat->bsizes,bsizes,nblocks);
7186:   return(0);
7187: }

7189: /*@C
7190:    MatGetVariableBlockSizes - Gets a diagonal blocks of the matrix that need not be of the same size

7192:    Logically Collective on Mat

7194:    Input Parameters:
7195: .  mat - the matrix

7197:    Output Parameters:
7198: +  nblocks - the number of blocks on this process
7199: -  bsizes - the block sizes

7201:    Notes: Currently not supported from Fortran

7203:    Level: intermediate

7205: .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSize(), MatSetBlockSizes(), MatGetBlockSizes(), MatSetVariableBlockSizes()
7206: @*/
7207: PetscErrorCode MatGetVariableBlockSizes(Mat mat,PetscInt *nblocks,const PetscInt **bsizes)
7208: {
7211:   *nblocks = mat->nblocks;
7212:   *bsizes  = mat->bsizes;
7213:   return(0);
7214: }

7216: /*@
7217:    MatSetBlockSizes - Sets the matrix block row and column sizes.

7219:    Logically Collective on Mat

7221:    Input Parameters:
7222: +  mat - the matrix
7223: .  rbs - row block size
7224: -  cbs - column block size

7226:    Notes:
7227:     Block row formats are MATSEQBAIJ, MATMPIBAIJ, MATSEQSBAIJ, MATMPISBAIJ. These formats ALWAYS have square block storage in the matrix.
7228:     If you pass a different block size for the columns than the rows, the row block size determines the square block storage.
7229:     This must be called before MatSetUp() or MatXXXSetPreallocation() (or will default to 1) and the block size cannot be changed later.

7231:     For MATMPIAIJ and MATSEQAIJ matrix formats, this function can be called at a later stage, provided that the specified block sizes
7232:     are compatible with the matrix local sizes.

7234:     The row and column block size determine the blocksize of the "row" and "column" vectors returned by MatCreateVecs().

7236:    Level: intermediate

7238: .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSize(), MatSetBlockSize(), MatGetBlockSizes()
7239: @*/
7240: PetscErrorCode MatSetBlockSizes(Mat mat,PetscInt rbs,PetscInt cbs)
7241: {

7248:   if (mat->ops->setblocksizes) {
7249:     (*mat->ops->setblocksizes)(mat,rbs,cbs);
7250:   }
7251:   if (mat->rmap->refcnt) {
7252:     ISLocalToGlobalMapping l2g = NULL;
7253:     PetscLayout            nmap = NULL;

7255:     PetscLayoutDuplicate(mat->rmap,&nmap);
7256:     if (mat->rmap->mapping) {
7257:       ISLocalToGlobalMappingDuplicate(mat->rmap->mapping,&l2g);
7258:     }
7259:     PetscLayoutDestroy(&mat->rmap);
7260:     mat->rmap = nmap;
7261:     mat->rmap->mapping = l2g;
7262:   }
7263:   if (mat->cmap->refcnt) {
7264:     ISLocalToGlobalMapping l2g = NULL;
7265:     PetscLayout            nmap = NULL;

7267:     PetscLayoutDuplicate(mat->cmap,&nmap);
7268:     if (mat->cmap->mapping) {
7269:       ISLocalToGlobalMappingDuplicate(mat->cmap->mapping,&l2g);
7270:     }
7271:     PetscLayoutDestroy(&mat->cmap);
7272:     mat->cmap = nmap;
7273:     mat->cmap->mapping = l2g;
7274:   }
7275:   PetscLayoutSetBlockSize(mat->rmap,rbs);
7276:   PetscLayoutSetBlockSize(mat->cmap,cbs);
7277:   return(0);
7278: }

7280: /*@
7281:    MatSetBlockSizesFromMats - Sets the matrix block row and column sizes to match a pair of matrices

7283:    Logically Collective on Mat

7285:    Input Parameters:
7286: +  mat - the matrix
7287: .  fromRow - matrix from which to copy row block size
7288: -  fromCol - matrix from which to copy column block size (can be same as fromRow)

7290:    Level: developer

7292: .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSize(), MatSetBlockSizes()
7293: @*/
7294: PetscErrorCode MatSetBlockSizesFromMats(Mat mat,Mat fromRow,Mat fromCol)
7295: {

7302:   if (fromRow->rmap->bs > 0) {PetscLayoutSetBlockSize(mat->rmap,fromRow->rmap->bs);}
7303:   if (fromCol->cmap->bs > 0) {PetscLayoutSetBlockSize(mat->cmap,fromCol->cmap->bs);}
7304:   return(0);
7305: }

7307: /*@
7308:    MatResidual - Default routine to calculate the residual.

7310:    Collective on Mat

7312:    Input Parameters:
7313: +  mat - the matrix
7314: .  b   - the right-hand-side
7315: -  x   - the approximate solution

7317:    Output Parameter:
7318: .  r - location to store the residual

7320:    Level: developer

7322: .seealso: PCMGSetResidual()
7323: @*/
7324: PetscErrorCode MatResidual(Mat mat,Vec b,Vec x,Vec r)
7325: {

7334:   MatCheckPreallocated(mat,1);
7335:   PetscLogEventBegin(MAT_Residual,mat,0,0,0);
7336:   if (!mat->ops->residual) {
7337:     MatMult(mat,x,r);
7338:     VecAYPX(r,-1.0,b);
7339:   } else {
7340:     (*mat->ops->residual)(mat,b,x,r);
7341:   }
7342:   PetscLogEventEnd(MAT_Residual,mat,0,0,0);
7343:   return(0);
7344: }

7346: /*@C
7347:     MatGetRowIJ - Returns the compressed row storage i and j indices for sequential matrices.

7349:    Collective on Mat

7351:     Input Parameters:
7352: +   mat - the matrix
7353: .   shift -  0 or 1 indicating we want the indices starting at 0 or 1
7354: .   symmetric - PETSC_TRUE or PETSC_FALSE indicating the matrix data structure should be   symmetrized
7355: -   inodecompressed - PETSC_TRUE or PETSC_FALSE  indicating if the nonzero structure of the
7356:                  inodes or the nonzero elements is wanted. For BAIJ matrices the compressed version is
7357:                  always used.

7359:     Output Parameters:
7360: +   n - number of rows in the (possibly compressed) matrix
7361: .   ia - the row pointers; that is ia[0] = 0, ia[row] = ia[row-1] + number of elements in that row of the matrix
7362: .   ja - the column indices
7363: -   done - indicates if the routine actually worked and returned appropriate ia[] and ja[] arrays; callers
7364:            are responsible for handling the case when done == PETSC_FALSE and ia and ja are not set

7366:     Level: developer

7368:     Notes:
7369:     You CANNOT change any of the ia[] or ja[] values.

7371:     Use MatRestoreRowIJ() when you are finished accessing the ia[] and ja[] values.

7373:     Fortran Notes:
7374:     In Fortran use
7375: $
7376: $      PetscInt ia(1), ja(1)
7377: $      PetscOffset iia, jja
7378: $      call MatGetRowIJ(mat,shift,symmetric,inodecompressed,n,ia,iia,ja,jja,done,ierr)
7379: $      ! Access the ith and jth entries via ia(iia + i) and ja(jja + j)

7381:      or
7382: $
7383: $    PetscInt, pointer :: ia(:),ja(:)
7384: $    call MatGetRowIJF90(mat,shift,symmetric,inodecompressed,n,ia,ja,done,ierr)
7385: $    ! Access the ith and jth entries via ia(i) and ja(j)

7387: .seealso: MatGetColumnIJ(), MatRestoreRowIJ(), MatSeqAIJGetArray()
7388: @*/
7389: PetscErrorCode MatGetRowIJ(Mat mat,PetscInt shift,PetscBool symmetric,PetscBool inodecompressed,PetscInt *n,const PetscInt *ia[],const PetscInt *ja[],PetscBool  *done)
7390: {

7400:   MatCheckPreallocated(mat,1);
7401:   if (!mat->ops->getrowij) *done = PETSC_FALSE;
7402:   else {
7403:     *done = PETSC_TRUE;
7404:     PetscLogEventBegin(MAT_GetRowIJ,mat,0,0,0);
7405:     (*mat->ops->getrowij)(mat,shift,symmetric,inodecompressed,n,ia,ja,done);
7406:     PetscLogEventEnd(MAT_GetRowIJ,mat,0,0,0);
7407:   }
7408:   return(0);
7409: }

7411: /*@C
7412:     MatGetColumnIJ - Returns the compressed column storage i and j indices for sequential matrices.

7414:     Collective on Mat

7416:     Input Parameters:
7417: +   mat - the matrix
7418: .   shift - 1 or zero indicating we want the indices starting at 0 or 1
7419: .   symmetric - PETSC_TRUE or PETSC_FALSE indicating the matrix data structure should be
7420:                 symmetrized
7421: .   inodecompressed - PETSC_TRUE or PETSC_FALSE indicating if the nonzero structure of the
7422:                  inodes or the nonzero elements is wanted. For BAIJ matrices the compressed version is
7423:                  always used.
7424: .   n - number of columns in the (possibly compressed) matrix
7425: .   ia - the column pointers; that is ia[0] = 0, ia[col] = i[col-1] + number of elements in that col of the matrix
7426: -   ja - the row indices

7428:     Output Parameters:
7429: .   done - PETSC_TRUE or PETSC_FALSE, indicating whether the values have been returned

7431:     Level: developer

7433: .seealso: MatGetRowIJ(), MatRestoreColumnIJ()
7434: @*/
7435: PetscErrorCode MatGetColumnIJ(Mat mat,PetscInt shift,PetscBool symmetric,PetscBool inodecompressed,PetscInt *n,const PetscInt *ia[],const PetscInt *ja[],PetscBool  *done)
7436: {

7446:   MatCheckPreallocated(mat,1);
7447:   if (!mat->ops->getcolumnij) *done = PETSC_FALSE;
7448:   else {
7449:     *done = PETSC_TRUE;
7450:     (*mat->ops->getcolumnij)(mat,shift,symmetric,inodecompressed,n,ia,ja,done);
7451:   }
7452:   return(0);
7453: }

7455: /*@C
7456:     MatRestoreRowIJ - Call after you are completed with the ia,ja indices obtained with
7457:     MatGetRowIJ().

7459:     Collective on Mat

7461:     Input Parameters:
7462: +   mat - the matrix
7463: .   shift - 1 or zero indicating we want the indices starting at 0 or 1
7464: .   symmetric - PETSC_TRUE or PETSC_FALSE indicating the matrix data structure should be
7465:                 symmetrized
7466: .   inodecompressed -  PETSC_TRUE or PETSC_FALSE indicating if the nonzero structure of the
7467:                  inodes or the nonzero elements is wanted. For BAIJ matrices the compressed version is
7468:                  always used.
7469: .   n - size of (possibly compressed) matrix
7470: .   ia - the row pointers
7471: -   ja - the column indices

7473:     Output Parameters:
7474: .   done - PETSC_TRUE or PETSC_FALSE indicated that the values have been returned

7476:     Note:
7477:     This routine zeros out n, ia, and ja. This is to prevent accidental
7478:     us of the array after it has been restored. If you pass NULL, it will
7479:     not zero the pointers.  Use of ia or ja after MatRestoreRowIJ() is invalid.

7481:     Level: developer

7483: .seealso: MatGetRowIJ(), MatRestoreColumnIJ()
7484: @*/
7485: PetscErrorCode MatRestoreRowIJ(Mat mat,PetscInt shift,PetscBool symmetric,PetscBool inodecompressed,PetscInt *n,const PetscInt *ia[],const PetscInt *ja[],PetscBool  *done)
7486: {

7495:   MatCheckPreallocated(mat,1);

7497:   if (!mat->ops->restorerowij) *done = PETSC_FALSE;
7498:   else {
7499:     *done = PETSC_TRUE;
7500:     (*mat->ops->restorerowij)(mat,shift,symmetric,inodecompressed,n,ia,ja,done);
7501:     if (n)  *n = 0;
7502:     if (ia) *ia = NULL;
7503:     if (ja) *ja = NULL;
7504:   }
7505:   return(0);
7506: }

7508: /*@C
7509:     MatRestoreColumnIJ - Call after you are completed with the ia,ja indices obtained with
7510:     MatGetColumnIJ().

7512:     Collective on Mat

7514:     Input Parameters:
7515: +   mat - the matrix
7516: .   shift - 1 or zero indicating we want the indices starting at 0 or 1
7517: -   symmetric - PETSC_TRUE or PETSC_FALSE indicating the matrix data structure should be
7518:                 symmetrized
7519: -   inodecompressed - PETSC_TRUE or PETSC_FALSE indicating if the nonzero structure of the
7520:                  inodes or the nonzero elements is wanted. For BAIJ matrices the compressed version is
7521:                  always used.

7523:     Output Parameters:
7524: +   n - size of (possibly compressed) matrix
7525: .   ia - the column pointers
7526: .   ja - the row indices
7527: -   done - PETSC_TRUE or PETSC_FALSE indicated that the values have been returned

7529:     Level: developer

7531: .seealso: MatGetColumnIJ(), MatRestoreRowIJ()
7532: @*/
7533: PetscErrorCode MatRestoreColumnIJ(Mat mat,PetscInt shift,PetscBool symmetric,PetscBool inodecompressed,PetscInt *n,const PetscInt *ia[],const PetscInt *ja[],PetscBool  *done)
7534: {

7543:   MatCheckPreallocated(mat,1);

7545:   if (!mat->ops->restorecolumnij) *done = PETSC_FALSE;
7546:   else {
7547:     *done = PETSC_TRUE;
7548:     (*mat->ops->restorecolumnij)(mat,shift,symmetric,inodecompressed,n,ia,ja,done);
7549:     if (n)  *n = 0;
7550:     if (ia) *ia = NULL;
7551:     if (ja) *ja = NULL;
7552:   }
7553:   return(0);
7554: }

7556: /*@C
7557:     MatColoringPatch -Used inside matrix coloring routines that
7558:     use MatGetRowIJ() and/or MatGetColumnIJ().

7560:     Collective on Mat

7562:     Input Parameters:
7563: +   mat - the matrix
7564: .   ncolors - max color value
7565: .   n   - number of entries in colorarray
7566: -   colorarray - array indicating color for each column

7568:     Output Parameters:
7569: .   iscoloring - coloring generated using colorarray information

7571:     Level: developer

7573: .seealso: MatGetRowIJ(), MatGetColumnIJ()

7575: @*/
7576: PetscErrorCode MatColoringPatch(Mat mat,PetscInt ncolors,PetscInt n,ISColoringValue colorarray[],ISColoring *iscoloring)
7577: {

7585:   MatCheckPreallocated(mat,1);

7587:   if (!mat->ops->coloringpatch) {
7588:     ISColoringCreate(PetscObjectComm((PetscObject)mat),ncolors,n,colorarray,PETSC_OWN_POINTER,iscoloring);
7589:   } else {
7590:     (*mat->ops->coloringpatch)(mat,ncolors,n,colorarray,iscoloring);
7591:   }
7592:   return(0);
7593: }


7596: /*@
7597:    MatSetUnfactored - Resets a factored matrix to be treated as unfactored.

7599:    Logically Collective on Mat

7601:    Input Parameter:
7602: .  mat - the factored matrix to be reset

7604:    Notes:
7605:    This routine should be used only with factored matrices formed by in-place
7606:    factorization via ILU(0) (or by in-place LU factorization for the MATSEQDENSE
7607:    format).  This option can save memory, for example, when solving nonlinear
7608:    systems with a matrix-free Newton-Krylov method and a matrix-based, in-place
7609:    ILU(0) preconditioner.

7611:    Note that one can specify in-place ILU(0) factorization by calling
7612: .vb
7613:      PCType(pc,PCILU);
7614:      PCFactorSeUseInPlace(pc);
7615: .ve
7616:    or by using the options -pc_type ilu -pc_factor_in_place

7618:    In-place factorization ILU(0) can also be used as a local
7619:    solver for the blocks within the block Jacobi or additive Schwarz
7620:    methods (runtime option: -sub_pc_factor_in_place).  See Users-Manual: ch_pc
7621:    for details on setting local solver options.

7623:    Most users should employ the simplified KSP interface for linear solvers
7624:    instead of working directly with matrix algebra routines such as this.
7625:    See, e.g., KSPCreate().

7627:    Level: developer

7629: .seealso: PCFactorSetUseInPlace(), PCFactorGetUseInPlace()

7631: @*/
7632: PetscErrorCode MatSetUnfactored(Mat mat)
7633: {

7639:   MatCheckPreallocated(mat,1);
7640:   mat->factortype = MAT_FACTOR_NONE;
7641:   if (!mat->ops->setunfactored) return(0);
7642:   (*mat->ops->setunfactored)(mat);
7643:   return(0);
7644: }

7646: /*MC
7647:     MatDenseGetArrayF90 - Accesses a matrix array from Fortran90.

7649:     Synopsis:
7650:     MatDenseGetArrayF90(Mat x,{Scalar, pointer :: xx_v(:,:)},integer ierr)

7652:     Not collective

7654:     Input Parameter:
7655: .   x - matrix

7657:     Output Parameters:
7658: +   xx_v - the Fortran90 pointer to the array
7659: -   ierr - error code

7661:     Example of Usage:
7662: .vb
7663:       PetscScalar, pointer xx_v(:,:)
7664:       ....
7665:       call MatDenseGetArrayF90(x,xx_v,ierr)
7666:       a = xx_v(3)
7667:       call MatDenseRestoreArrayF90(x,xx_v,ierr)
7668: .ve

7670:     Level: advanced

7672: .seealso:  MatDenseRestoreArrayF90(), MatDenseGetArray(), MatDenseRestoreArray(), MatSeqAIJGetArrayF90()

7674: M*/

7676: /*MC
7677:     MatDenseRestoreArrayF90 - Restores a matrix array that has been
7678:     accessed with MatDenseGetArrayF90().

7680:     Synopsis:
7681:     MatDenseRestoreArrayF90(Mat x,{Scalar, pointer :: xx_v(:,:)},integer ierr)

7683:     Not collective

7685:     Input Parameters:
7686: +   x - matrix
7687: -   xx_v - the Fortran90 pointer to the array

7689:     Output Parameter:
7690: .   ierr - error code

7692:     Example of Usage:
7693: .vb
7694:        PetscScalar, pointer xx_v(:,:)
7695:        ....
7696:        call MatDenseGetArrayF90(x,xx_v,ierr)
7697:        a = xx_v(3)
7698:        call MatDenseRestoreArrayF90(x,xx_v,ierr)
7699: .ve

7701:     Level: advanced

7703: .seealso:  MatDenseGetArrayF90(), MatDenseGetArray(), MatDenseRestoreArray(), MatSeqAIJRestoreArrayF90()

7705: M*/


7708: /*MC
7709:     MatSeqAIJGetArrayF90 - Accesses a matrix array from Fortran90.

7711:     Synopsis:
7712:     MatSeqAIJGetArrayF90(Mat x,{Scalar, pointer :: xx_v(:)},integer ierr)

7714:     Not collective

7716:     Input Parameter:
7717: .   x - matrix

7719:     Output Parameters:
7720: +   xx_v - the Fortran90 pointer to the array
7721: -   ierr - error code

7723:     Example of Usage:
7724: .vb
7725:       PetscScalar, pointer xx_v(:)
7726:       ....
7727:       call MatSeqAIJGetArrayF90(x,xx_v,ierr)
7728:       a = xx_v(3)
7729:       call MatSeqAIJRestoreArrayF90(x,xx_v,ierr)
7730: .ve

7732:     Level: advanced

7734: .seealso:  MatSeqAIJRestoreArrayF90(), MatSeqAIJGetArray(), MatSeqAIJRestoreArray(), MatDenseGetArrayF90()

7736: M*/

7738: /*MC
7739:     MatSeqAIJRestoreArrayF90 - Restores a matrix array that has been
7740:     accessed with MatSeqAIJGetArrayF90().

7742:     Synopsis:
7743:     MatSeqAIJRestoreArrayF90(Mat x,{Scalar, pointer :: xx_v(:)},integer ierr)

7745:     Not collective

7747:     Input Parameters:
7748: +   x - matrix
7749: -   xx_v - the Fortran90 pointer to the array

7751:     Output Parameter:
7752: .   ierr - error code

7754:     Example of Usage:
7755: .vb
7756:        PetscScalar, pointer xx_v(:)
7757:        ....
7758:        call MatSeqAIJGetArrayF90(x,xx_v,ierr)
7759:        a = xx_v(3)
7760:        call MatSeqAIJRestoreArrayF90(x,xx_v,ierr)
7761: .ve

7763:     Level: advanced

7765: .seealso:  MatSeqAIJGetArrayF90(), MatSeqAIJGetArray(), MatSeqAIJRestoreArray(), MatDenseRestoreArrayF90()

7767: M*/


7770: /*@
7771:     MatCreateSubMatrix - Gets a single submatrix on the same number of processors
7772:                       as the original matrix.

7774:     Collective on Mat

7776:     Input Parameters:
7777: +   mat - the original matrix
7778: .   isrow - parallel IS containing the rows this processor should obtain
7779: .   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.
7780: -   cll - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX

7782:     Output Parameter:
7783: .   newmat - the new submatrix, of the same type as the old

7785:     Level: advanced

7787:     Notes:
7788:     The submatrix will be able to be multiplied with vectors using the same layout as iscol.

7790:     Some matrix types place restrictions on the row and column indices, such
7791:     as that they be sorted or that they be equal to each other.

7793:     The index sets may not have duplicate entries.

7795:       The first time this is called you should use a cll of MAT_INITIAL_MATRIX,
7796:    the MatCreateSubMatrix() routine will create the newmat for you. Any additional calls
7797:    to this routine with a mat of the same nonzero structure and with a call of MAT_REUSE_MATRIX
7798:    will reuse the matrix generated the first time.  You should call MatDestroy() on newmat when
7799:    you are finished using it.

7801:     The communicator of the newly obtained matrix is ALWAYS the same as the communicator of
7802:     the input matrix.

7804:     If iscol is NULL then all columns are obtained (not supported in Fortran).

7806:    Example usage:
7807:    Consider the following 8x8 matrix with 34 non-zero values, that is
7808:    assembled across 3 processors. Let's assume that proc0 owns 3 rows,
7809:    proc1 owns 3 rows, proc2 owns 2 rows. This division can be shown
7810:    as follows:

7812: .vb
7813:             1  2  0  |  0  3  0  |  0  4
7814:     Proc0   0  5  6  |  7  0  0  |  8  0
7815:             9  0 10  | 11  0  0  | 12  0
7816:     -------------------------------------
7817:            13  0 14  | 15 16 17  |  0  0
7818:     Proc1   0 18  0  | 19 20 21  |  0  0
7819:             0  0  0  | 22 23  0  | 24  0
7820:     -------------------------------------
7821:     Proc2  25 26 27  |  0  0 28  | 29  0
7822:            30  0  0  | 31 32 33  |  0 34
7823: .ve

7825:     Suppose isrow = [0 1 | 4 | 6 7] and iscol = [1 2 | 3 4 5 | 6].  The resulting submatrix is

7827: .vb
7828:             2  0  |  0  3  0  |  0
7829:     Proc0   5  6  |  7  0  0  |  8
7830:     -------------------------------
7831:     Proc1  18  0  | 19 20 21  |  0
7832:     -------------------------------
7833:     Proc2  26 27  |  0  0 28  | 29
7834:             0  0  | 31 32 33  |  0
7835: .ve


7838: .seealso: MatCreateSubMatrices(), MatCreateSubMatricesMPI(), MatCreateSubMatrixVirtual(), MatSubMatrixVirtualUpdate()
7839: @*/
7840: PetscErrorCode MatCreateSubMatrix(Mat mat,IS isrow,IS iscol,MatReuse cll,Mat *newmat)
7841: {
7843:   PetscMPIInt    size;
7844:   Mat            *local;
7845:   IS             iscoltmp;
7846:   PetscBool      flg;

7855:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
7856:   if (cll == MAT_IGNORE_MATRIX) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Cannot use MAT_IGNORE_MATRIX");

7858:   MatCheckPreallocated(mat,1);
7859:   MPI_Comm_size(PetscObjectComm((PetscObject)mat),&size);

7861:   if (!iscol || isrow == iscol) {
7862:     PetscBool   stride;
7863:     PetscMPIInt grabentirematrix = 0,grab;
7864:     PetscObjectTypeCompare((PetscObject)isrow,ISSTRIDE,&stride);
7865:     if (stride) {
7866:       PetscInt first,step,n,rstart,rend;
7867:       ISStrideGetInfo(isrow,&first,&step);
7868:       if (step == 1) {
7869:         MatGetOwnershipRange(mat,&rstart,&rend);
7870:         if (rstart == first) {
7871:           ISGetLocalSize(isrow,&n);
7872:           if (n == rend-rstart) {
7873:             grabentirematrix = 1;
7874:           }
7875:         }
7876:       }
7877:     }
7878:     MPIU_Allreduce(&grabentirematrix,&grab,1,MPI_INT,MPI_MIN,PetscObjectComm((PetscObject)mat));
7879:     if (grab) {
7880:       PetscInfo(mat,"Getting entire matrix as submatrix\n");
7881:       if (cll == MAT_INITIAL_MATRIX) {
7882:         *newmat = mat;
7883:         PetscObjectReference((PetscObject)mat);
7884:       }
7885:       return(0);
7886:     }
7887:   }

7889:   if (!iscol) {
7890:     ISCreateStride(PetscObjectComm((PetscObject)mat),mat->cmap->n,mat->cmap->rstart,1,&iscoltmp);
7891:   } else {
7892:     iscoltmp = iscol;
7893:   }

7895:   /* if original matrix is on just one processor then use submatrix generated */
7896:   if (mat->ops->createsubmatrices && !mat->ops->createsubmatrix && size == 1 && cll == MAT_REUSE_MATRIX) {
7897:     MatCreateSubMatrices(mat,1,&isrow,&iscoltmp,MAT_REUSE_MATRIX,&newmat);
7898:     goto setproperties;
7899:   } else if (mat->ops->createsubmatrices && !mat->ops->createsubmatrix && size == 1) {
7900:     MatCreateSubMatrices(mat,1,&isrow,&iscoltmp,MAT_INITIAL_MATRIX,&local);
7901:     *newmat = *local;
7902:     PetscFree(local);
7903:     goto setproperties;
7904:   } else if (!mat->ops->createsubmatrix) {
7905:     /* Create a new matrix type that implements the operation using the full matrix */
7906:     PetscLogEventBegin(MAT_CreateSubMat,mat,0,0,0);
7907:     switch (cll) {
7908:     case MAT_INITIAL_MATRIX:
7909:       MatCreateSubMatrixVirtual(mat,isrow,iscoltmp,newmat);
7910:       break;
7911:     case MAT_REUSE_MATRIX:
7912:       MatSubMatrixVirtualUpdate(*newmat,mat,isrow,iscoltmp);
7913:       break;
7914:     default: SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_OUTOFRANGE,"Invalid MatReuse, must be either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX");
7915:     }
7916:     PetscLogEventEnd(MAT_CreateSubMat,mat,0,0,0);
7917:     goto setproperties;
7918:   }

7920:   if (!mat->ops->createsubmatrix) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
7921:   PetscLogEventBegin(MAT_CreateSubMat,mat,0,0,0);
7922:   (*mat->ops->createsubmatrix)(mat,isrow,iscoltmp,cll,newmat);
7923:   PetscLogEventEnd(MAT_CreateSubMat,mat,0,0,0);

7925: setproperties:
7926:   ISEqualUnsorted(isrow,iscoltmp,&flg);
7927:   if (flg) {
7928:     MatPropagateSymmetryOptions(mat,*newmat);
7929:   }
7930:   if (!iscol) {ISDestroy(&iscoltmp);}
7931:   if (*newmat && cll == MAT_INITIAL_MATRIX) {PetscObjectStateIncrease((PetscObject)*newmat);}
7932:   return(0);
7933: }

7935: /*@
7936:    MatPropagateSymmetryOptions - Propagates symmetry options set on a matrix to another matrix

7938:    Not Collective

7940:    Input Parameters:
7941: +  A - the matrix we wish to propagate options from
7942: -  B - the matrix we wish to propagate options to

7944:    Level: beginner

7946:    Notes: Propagates the options associated to MAT_SYMMETRY_ETERNAL, MAT_STRUCTURALLY_SYMMETRIC, MAT_HERMITIAN, MAT_SPD and MAT_SYMMETRIC

7948: .seealso: MatSetOption()
7949: @*/
7950: PetscErrorCode MatPropagateSymmetryOptions(Mat A, Mat B)
7951: {

7957:   if (A->symmetric_eternal) { /* symmetric_eternal does not have a corresponding *set flag */
7958:     MatSetOption(B,MAT_SYMMETRY_ETERNAL,A->symmetric_eternal);
7959:   }
7960:   if (A->structurally_symmetric_set) {
7961:     MatSetOption(B,MAT_STRUCTURALLY_SYMMETRIC,A->structurally_symmetric);
7962:   }
7963:   if (A->hermitian_set) {
7964:     MatSetOption(B,MAT_HERMITIAN,A->hermitian);
7965:   }
7966:   if (A->spd_set) {
7967:     MatSetOption(B,MAT_SPD,A->spd);
7968:   }
7969:   if (A->symmetric_set) {
7970:     MatSetOption(B,MAT_SYMMETRIC,A->symmetric);
7971:   }
7972:   return(0);
7973: }

7975: /*@
7976:    MatStashSetInitialSize - sets the sizes of the matrix stash, that is
7977:    used during the assembly process to store values that belong to
7978:    other processors.

7980:    Not Collective

7982:    Input Parameters:
7983: +  mat   - the matrix
7984: .  size  - the initial size of the stash.
7985: -  bsize - the initial size of the block-stash(if used).

7987:    Options Database Keys:
7988: +   -matstash_initial_size <size> or <size0,size1,...sizep-1>
7989: -   -matstash_block_initial_size <bsize>  or <bsize0,bsize1,...bsizep-1>

7991:    Level: intermediate

7993:    Notes:
7994:      The block-stash is used for values set with MatSetValuesBlocked() while
7995:      the stash is used for values set with MatSetValues()

7997:      Run with the option -info and look for output of the form
7998:      MatAssemblyBegin_MPIXXX:Stash has MM entries, uses nn mallocs.
7999:      to determine the appropriate value, MM, to use for size and
8000:      MatAssemblyBegin_MPIXXX:Block-Stash has BMM entries, uses nn mallocs.
8001:      to determine the value, BMM to use for bsize


8004: .seealso: MatAssemblyBegin(), MatAssemblyEnd(), Mat, MatStashGetInfo()

8006: @*/
8007: PetscErrorCode MatStashSetInitialSize(Mat mat,PetscInt size, PetscInt bsize)
8008: {

8014:   MatStashSetInitialSize_Private(&mat->stash,size);
8015:   MatStashSetInitialSize_Private(&mat->bstash,bsize);
8016:   return(0);
8017: }

8019: /*@
8020:    MatInterpolateAdd - w = y + A*x or A'*x depending on the shape of
8021:      the matrix

8023:    Neighbor-wise Collective on Mat

8025:    Input Parameters:
8026: +  mat   - the matrix
8027: .  x,y - the vectors
8028: -  w - where the result is stored

8030:    Level: intermediate

8032:    Notes:
8033:     w may be the same vector as y.

8035:     This allows one to use either the restriction or interpolation (its transpose)
8036:     matrix to do the interpolation

8038: .seealso: MatMultAdd(), MatMultTransposeAdd(), MatRestrict()

8040: @*/
8041: PetscErrorCode MatInterpolateAdd(Mat A,Vec x,Vec y,Vec w)
8042: {
8044:   PetscInt       M,N,Ny;

8052:   MatCheckPreallocated(A,1);
8053:   MatGetSize(A,&M,&N);
8054:   VecGetSize(y,&Ny);
8055:   if (M == Ny) {
8056:     MatMultAdd(A,x,y,w);
8057:   } else {
8058:     MatMultTransposeAdd(A,x,y,w);
8059:   }
8060:   return(0);
8061: }

8063: /*@
8064:    MatInterpolate - y = A*x or A'*x depending on the shape of
8065:      the matrix

8067:    Neighbor-wise Collective on Mat

8069:    Input Parameters:
8070: +  mat   - the matrix
8071: -  x,y - the vectors

8073:    Level: intermediate

8075:    Notes:
8076:     This allows one to use either the restriction or interpolation (its transpose)
8077:     matrix to do the interpolation

8079: .seealso: MatMultAdd(), MatMultTransposeAdd(), MatRestrict()

8081: @*/
8082: PetscErrorCode MatInterpolate(Mat A,Vec x,Vec y)
8083: {
8085:   PetscInt       M,N,Ny;

8092:   MatCheckPreallocated(A,1);
8093:   MatGetSize(A,&M,&N);
8094:   VecGetSize(y,&Ny);
8095:   if (M == Ny) {
8096:     MatMult(A,x,y);
8097:   } else {
8098:     MatMultTranspose(A,x,y);
8099:   }
8100:   return(0);
8101: }

8103: /*@
8104:    MatRestrict - y = A*x or A'*x

8106:    Neighbor-wise Collective on Mat

8108:    Input Parameters:
8109: +  mat   - the matrix
8110: -  x,y - the vectors

8112:    Level: intermediate

8114:    Notes:
8115:     This allows one to use either the restriction or interpolation (its transpose)
8116:     matrix to do the restriction

8118: .seealso: MatMultAdd(), MatMultTransposeAdd(), MatInterpolate()

8120: @*/
8121: PetscErrorCode MatRestrict(Mat A,Vec x,Vec y)
8122: {
8124:   PetscInt       M,N,Ny;

8131:   MatCheckPreallocated(A,1);

8133:   MatGetSize(A,&M,&N);
8134:   VecGetSize(y,&Ny);
8135:   if (M == Ny) {
8136:     MatMult(A,x,y);
8137:   } else {
8138:     MatMultTranspose(A,x,y);
8139:   }
8140:   return(0);
8141: }

8143: /*@
8144:    MatGetNullSpace - retrieves the null space of a matrix.

8146:    Logically Collective on Mat

8148:    Input Parameters:
8149: +  mat - the matrix
8150: -  nullsp - the null space object

8152:    Level: developer

8154: .seealso: MatCreate(), MatNullSpaceCreate(), MatSetNearNullSpace(), MatSetNullSpace()
8155: @*/
8156: PetscErrorCode MatGetNullSpace(Mat mat, MatNullSpace *nullsp)
8157: {
8161:   *nullsp = (mat->symmetric_set && mat->symmetric && !mat->nullsp) ? mat->transnullsp : mat->nullsp;
8162:   return(0);
8163: }

8165: /*@
8166:    MatSetNullSpace - attaches a null space to a matrix.

8168:    Logically Collective on Mat

8170:    Input Parameters:
8171: +  mat - the matrix
8172: -  nullsp - the null space object

8174:    Level: advanced

8176:    Notes:
8177:       This null space is used by the linear solvers. Overwrites any previous null space that may have been attached

8179:       For inconsistent singular systems (linear systems where the right hand side is not in the range of the operator) you also likely should
8180:       call MatSetTransposeNullSpace(). This allows the linear system to be solved in a least squares sense.

8182:       You can remove the null space by calling this routine with an nullsp of NULL


8185:       The fundamental theorem of linear algebra (Gilbert Strang, Introduction to Applied Mathematics, page 72) states that
8186:    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).
8187:    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
8188:    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
8189:    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).

8191:       Krylov solvers can produce the minimal norm solution to the least squares problem by utilizing MatNullSpaceRemove().

8193:     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
8194:     routine also automatically calls MatSetTransposeNullSpace().

8196: .seealso: MatCreate(), MatNullSpaceCreate(), MatSetNearNullSpace(), MatGetNullSpace(), MatSetTransposeNullSpace(), MatGetTransposeNullSpace(), MatNullSpaceRemove()
8197: @*/
8198: PetscErrorCode MatSetNullSpace(Mat mat,MatNullSpace nullsp)
8199: {

8205:   if (nullsp) {PetscObjectReference((PetscObject)nullsp);}
8206:   MatNullSpaceDestroy(&mat->nullsp);
8207:   mat->nullsp = nullsp;
8208:   if (mat->symmetric_set && mat->symmetric) {
8209:     MatSetTransposeNullSpace(mat,nullsp);
8210:   }
8211:   return(0);
8212: }

8214: /*@
8215:    MatGetTransposeNullSpace - retrieves the null space of the transpose of a matrix.

8217:    Logically Collective on Mat

8219:    Input Parameters:
8220: +  mat - the matrix
8221: -  nullsp - the null space object

8223:    Level: developer

8225: .seealso: MatCreate(), MatNullSpaceCreate(), MatSetNearNullSpace(), MatSetTransposeNullSpace(), MatSetNullSpace(), MatGetNullSpace()
8226: @*/
8227: PetscErrorCode MatGetTransposeNullSpace(Mat mat, MatNullSpace *nullsp)
8228: {
8233:   *nullsp = (mat->symmetric_set && mat->symmetric && !mat->transnullsp) ? mat->nullsp : mat->transnullsp;
8234:   return(0);
8235: }

8237: /*@
8238:    MatSetTransposeNullSpace - attaches a null space to a matrix.

8240:    Logically Collective on Mat

8242:    Input Parameters:
8243: +  mat - the matrix
8244: -  nullsp - the null space object

8246:    Level: advanced

8248:    Notes:
8249:       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.
8250:       You must also call MatSetNullSpace()


8253:       The fundamental theorem of linear algebra (Gilbert Strang, Introduction to Applied Mathematics, page 72) states that
8254:    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).
8255:    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
8256:    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
8257:    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).

8259:       Krylov solvers can produce the minimal norm solution to the least squares problem by utilizing MatNullSpaceRemove().

8261: .seealso: MatCreate(), MatNullSpaceCreate(), MatSetNearNullSpace(), MatGetNullSpace(), MatSetNullSpace(), MatGetTransposeNullSpace(), MatNullSpaceRemove()
8262: @*/
8263: PetscErrorCode MatSetTransposeNullSpace(Mat mat,MatNullSpace nullsp)
8264: {

8270:   if (nullsp) {PetscObjectReference((PetscObject)nullsp);}
8271:   MatNullSpaceDestroy(&mat->transnullsp);
8272:   mat->transnullsp = nullsp;
8273:   return(0);
8274: }

8276: /*@
8277:    MatSetNearNullSpace - attaches a null space to a matrix, which is often the null space (rigid body modes) of the operator without boundary conditions
8278:         This null space will be used to provide near null space vectors to a multigrid preconditioner built from this matrix.

8280:    Logically Collective on Mat

8282:    Input Parameters:
8283: +  mat - the matrix
8284: -  nullsp - the null space object

8286:    Level: advanced

8288:    Notes:
8289:       Overwrites any previous near null space that may have been attached

8291:       You can remove the null space by calling this routine with an nullsp of NULL

8293: .seealso: MatCreate(), MatNullSpaceCreate(), MatSetNullSpace(), MatNullSpaceCreateRigidBody(), MatGetNearNullSpace()
8294: @*/
8295: PetscErrorCode MatSetNearNullSpace(Mat mat,MatNullSpace nullsp)
8296: {

8303:   MatCheckPreallocated(mat,1);
8304:   if (nullsp) {PetscObjectReference((PetscObject)nullsp);}
8305:   MatNullSpaceDestroy(&mat->nearnullsp);
8306:   mat->nearnullsp = nullsp;
8307:   return(0);
8308: }

8310: /*@
8311:    MatGetNearNullSpace - Get null space attached with MatSetNearNullSpace()

8313:    Not Collective

8315:    Input Parameter:
8316: .  mat - the matrix

8318:    Output Parameter:
8319: .  nullsp - the null space object, NULL if not set

8321:    Level: developer

8323: .seealso: MatSetNearNullSpace(), MatGetNullSpace(), MatNullSpaceCreate()
8324: @*/
8325: PetscErrorCode MatGetNearNullSpace(Mat mat,MatNullSpace *nullsp)
8326: {
8331:   MatCheckPreallocated(mat,1);
8332:   *nullsp = mat->nearnullsp;
8333:   return(0);
8334: }

8336: /*@C
8337:    MatICCFactor - Performs in-place incomplete Cholesky factorization of matrix.

8339:    Collective on Mat

8341:    Input Parameters:
8342: +  mat - the matrix
8343: .  row - row/column permutation
8344: .  fill - expected fill factor >= 1.0
8345: -  level - level of fill, for ICC(k)

8347:    Notes:
8348:    Probably really in-place only when level of fill is zero, otherwise allocates
8349:    new space to store factored matrix and deletes previous memory.

8351:    Most users should employ the simplified KSP interface for linear solvers
8352:    instead of working directly with matrix algebra routines such as this.
8353:    See, e.g., KSPCreate().

8355:    Level: developer


8358: .seealso: MatICCFactorSymbolic(), MatLUFactorNumeric(), MatCholeskyFactor()

8360:     Developer Note: fortran interface is not autogenerated as the f90
8361:     interface defintion cannot be generated correctly [due to MatFactorInfo]

8363: @*/
8364: PetscErrorCode MatICCFactor(Mat mat,IS row,const MatFactorInfo *info)
8365: {

8373:   if (mat->rmap->N != mat->cmap->N) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONG,"matrix must be square");
8374:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
8375:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
8376:   if (!mat->ops->iccfactor) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
8377:   MatCheckPreallocated(mat,1);
8378:   (*mat->ops->iccfactor)(mat,row,info);
8379:   PetscObjectStateIncrease((PetscObject)mat);
8380:   return(0);
8381: }

8383: /*@
8384:    MatDiagonalScaleLocal - Scales columns of a matrix given the scaling values including the
8385:          ghosted ones.

8387:    Not Collective

8389:    Input Parameters:
8390: +  mat - the matrix
8391: -  diag = the diagonal values, including ghost ones

8393:    Level: developer

8395:    Notes:
8396:     Works only for MPIAIJ and MPIBAIJ matrices

8398: .seealso: MatDiagonalScale()
8399: @*/
8400: PetscErrorCode MatDiagonalScaleLocal(Mat mat,Vec diag)
8401: {
8403:   PetscMPIInt    size;


8410:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Matrix must be already assembled");
8411:   PetscLogEventBegin(MAT_Scale,mat,0,0,0);
8412:   MPI_Comm_size(PetscObjectComm((PetscObject)mat),&size);
8413:   if (size == 1) {
8414:     PetscInt n,m;
8415:     VecGetSize(diag,&n);
8416:     MatGetSize(mat,0,&m);
8417:     if (m == n) {
8418:       MatDiagonalScale(mat,0,diag);
8419:     } else SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"Only supported for sequential matrices when no ghost points/periodic conditions");
8420:   } else {
8421:     PetscUseMethod(mat,"MatDiagonalScaleLocal_C",(Mat,Vec),(mat,diag));
8422:   }
8423:   PetscLogEventEnd(MAT_Scale,mat,0,0,0);
8424:   PetscObjectStateIncrease((PetscObject)mat);
8425:   return(0);
8426: }

8428: /*@
8429:    MatGetInertia - Gets the inertia from a factored matrix

8431:    Collective on Mat

8433:    Input Parameter:
8434: .  mat - the matrix

8436:    Output Parameters:
8437: +   nneg - number of negative eigenvalues
8438: .   nzero - number of zero eigenvalues
8439: -   npos - number of positive eigenvalues

8441:    Level: advanced

8443:    Notes:
8444:     Matrix must have been factored by MatCholeskyFactor()


8447: @*/
8448: PetscErrorCode MatGetInertia(Mat mat,PetscInt *nneg,PetscInt *nzero,PetscInt *npos)
8449: {

8455:   if (!mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
8456:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Numeric factor mat is not assembled");
8457:   if (!mat->ops->getinertia) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
8458:   (*mat->ops->getinertia)(mat,nneg,nzero,npos);
8459:   return(0);
8460: }

8462: /* ----------------------------------------------------------------*/
8463: /*@C
8464:    MatSolves - Solves A x = b, given a factored matrix, for a collection of vectors

8466:    Neighbor-wise Collective on Mats

8468:    Input Parameters:
8469: +  mat - the factored matrix
8470: -  b - the right-hand-side vectors

8472:    Output Parameter:
8473: .  x - the result vectors

8475:    Notes:
8476:    The vectors b and x cannot be the same.  I.e., one cannot
8477:    call MatSolves(A,x,x).

8479:    Notes:
8480:    Most users should employ the simplified KSP interface for linear solvers
8481:    instead of working directly with matrix algebra routines such as this.
8482:    See, e.g., KSPCreate().

8484:    Level: developer

8486: .seealso: MatSolveAdd(), MatSolveTranspose(), MatSolveTransposeAdd(), MatSolve()
8487: @*/
8488: PetscErrorCode MatSolves(Mat mat,Vecs b,Vecs x)
8489: {

8495:   if (x == b) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"x and b must be different vectors");
8496:   if (!mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
8497:   if (!mat->rmap->N && !mat->cmap->N) return(0);

8499:   if (!mat->ops->solves) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
8500:   MatCheckPreallocated(mat,1);
8501:   PetscLogEventBegin(MAT_Solves,mat,0,0,0);
8502:   (*mat->ops->solves)(mat,b,x);
8503:   PetscLogEventEnd(MAT_Solves,mat,0,0,0);
8504:   return(0);
8505: }

8507: /*@
8508:    MatIsSymmetric - Test whether a matrix is symmetric

8510:    Collective on Mat

8512:    Input Parameter:
8513: +  A - the matrix to test
8514: -  tol - difference between value and its transpose less than this amount counts as equal (use 0.0 for exact transpose)

8516:    Output Parameters:
8517: .  flg - the result

8519:    Notes:
8520:     For real numbers MatIsSymmetric() and MatIsHermitian() return identical results

8522:    Level: intermediate

8524: .seealso: MatTranspose(), MatIsTranspose(), MatIsHermitian(), MatIsStructurallySymmetric(), MatSetOption(), MatIsSymmetricKnown()
8525: @*/
8526: PetscErrorCode MatIsSymmetric(Mat A,PetscReal tol,PetscBool  *flg)
8527: {


8534:   if (!A->symmetric_set) {
8535:     if (!A->ops->issymmetric) {
8536:       MatType mattype;
8537:       MatGetType(A,&mattype);
8538:       SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Matrix of type %s does not support checking for symmetric",mattype);
8539:     }
8540:     (*A->ops->issymmetric)(A,tol,flg);
8541:     if (!tol) {
8542:       MatSetOption(A,MAT_SYMMETRIC,*flg);
8543:     }
8544:   } else if (A->symmetric) {
8545:     *flg = PETSC_TRUE;
8546:   } else if (!tol) {
8547:     *flg = PETSC_FALSE;
8548:   } else {
8549:     if (!A->ops->issymmetric) {
8550:       MatType mattype;
8551:       MatGetType(A,&mattype);
8552:       SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Matrix of type %s does not support checking for symmetric",mattype);
8553:     }
8554:     (*A->ops->issymmetric)(A,tol,flg);
8555:   }
8556:   return(0);
8557: }

8559: /*@
8560:    MatIsHermitian - Test whether a matrix is Hermitian

8562:    Collective on Mat

8564:    Input Parameter:
8565: +  A - the matrix to test
8566: -  tol - difference between value and its transpose less than this amount counts as equal (use 0.0 for exact Hermitian)

8568:    Output Parameters:
8569: .  flg - the result

8571:    Level: intermediate

8573: .seealso: MatTranspose(), MatIsTranspose(), MatIsHermitian(), MatIsStructurallySymmetric(), MatSetOption(),
8574:           MatIsSymmetricKnown(), MatIsSymmetric()
8575: @*/
8576: PetscErrorCode MatIsHermitian(Mat A,PetscReal tol,PetscBool  *flg)
8577: {


8584:   if (!A->hermitian_set) {
8585:     if (!A->ops->ishermitian) {
8586:       MatType mattype;
8587:       MatGetType(A,&mattype);
8588:       SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Matrix of type %s does not support checking for hermitian",mattype);
8589:     }
8590:     (*A->ops->ishermitian)(A,tol,flg);
8591:     if (!tol) {
8592:       MatSetOption(A,MAT_HERMITIAN,*flg);
8593:     }
8594:   } else if (A->hermitian) {
8595:     *flg = PETSC_TRUE;
8596:   } else if (!tol) {
8597:     *flg = PETSC_FALSE;
8598:   } else {
8599:     if (!A->ops->ishermitian) {
8600:       MatType mattype;
8601:       MatGetType(A,&mattype);
8602:       SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Matrix of type %s does not support checking for hermitian",mattype);
8603:     }
8604:     (*A->ops->ishermitian)(A,tol,flg);
8605:   }
8606:   return(0);
8607: }

8609: /*@
8610:    MatIsSymmetricKnown - Checks the flag on the matrix to see if it is symmetric.

8612:    Not Collective

8614:    Input Parameter:
8615: .  A - the matrix to check

8617:    Output Parameters:
8618: +  set - if the symmetric flag is set (this tells you if the next flag is valid)
8619: -  flg - the result

8621:    Level: advanced

8623:    Note: Does not check the matrix values directly, so this may return unknown (set = PETSC_FALSE). Use MatIsSymmetric()
8624:          if you want it explicitly checked

8626: .seealso: MatTranspose(), MatIsTranspose(), MatIsHermitian(), MatIsStructurallySymmetric(), MatSetOption(), MatIsSymmetric()
8627: @*/
8628: PetscErrorCode MatIsSymmetricKnown(Mat A,PetscBool  *set,PetscBool  *flg)
8629: {
8634:   if (A->symmetric_set) {
8635:     *set = PETSC_TRUE;
8636:     *flg = A->symmetric;
8637:   } else {
8638:     *set = PETSC_FALSE;
8639:   }
8640:   return(0);
8641: }

8643: /*@
8644:    MatIsHermitianKnown - Checks the flag on the matrix to see if it is hermitian.

8646:    Not Collective

8648:    Input Parameter:
8649: .  A - the matrix to check

8651:    Output Parameters:
8652: +  set - if the hermitian flag is set (this tells you if the next flag is valid)
8653: -  flg - the result

8655:    Level: advanced

8657:    Note: Does not check the matrix values directly, so this may return unknown (set = PETSC_FALSE). Use MatIsHermitian()
8658:          if you want it explicitly checked

8660: .seealso: MatTranspose(), MatIsTranspose(), MatIsHermitian(), MatIsStructurallySymmetric(), MatSetOption(), MatIsSymmetric()
8661: @*/
8662: PetscErrorCode MatIsHermitianKnown(Mat A,PetscBool *set,PetscBool *flg)
8663: {
8668:   if (A->hermitian_set) {
8669:     *set = PETSC_TRUE;
8670:     *flg = A->hermitian;
8671:   } else {
8672:     *set = PETSC_FALSE;
8673:   }
8674:   return(0);
8675: }

8677: /*@
8678:    MatIsStructurallySymmetric - Test whether a matrix is structurally symmetric

8680:    Collective on Mat

8682:    Input Parameter:
8683: .  A - the matrix to test

8685:    Output Parameters:
8686: .  flg - the result

8688:    Level: intermediate

8690: .seealso: MatTranspose(), MatIsTranspose(), MatIsHermitian(), MatIsSymmetric(), MatSetOption()
8691: @*/
8692: PetscErrorCode MatIsStructurallySymmetric(Mat A,PetscBool *flg)
8693: {

8699:   if (!A->structurally_symmetric_set) {
8700:     if (!A->ops->isstructurallysymmetric) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Matrix of type %s does not support checking for structural symmetric",((PetscObject)A)->type_name);
8701:     (*A->ops->isstructurallysymmetric)(A,flg);
8702:     MatSetOption(A,MAT_STRUCTURALLY_SYMMETRIC,*flg);
8703:   } else *flg = A->structurally_symmetric;
8704:   return(0);
8705: }

8707: /*@
8708:    MatStashGetInfo - Gets how many values are currently in the matrix stash, i.e. need
8709:        to be communicated to other processors during the MatAssemblyBegin/End() process

8711:     Not collective

8713:    Input Parameter:
8714: .   vec - the vector

8716:    Output Parameters:
8717: +   nstash   - the size of the stash
8718: .   reallocs - the number of additional mallocs incurred.
8719: .   bnstash   - the size of the block stash
8720: -   breallocs - the number of additional mallocs incurred.in the block stash

8722:    Level: advanced

8724: .seealso: MatAssemblyBegin(), MatAssemblyEnd(), Mat, MatStashSetInitialSize()

8726: @*/
8727: PetscErrorCode MatStashGetInfo(Mat mat,PetscInt *nstash,PetscInt *reallocs,PetscInt *bnstash,PetscInt *breallocs)
8728: {

8732:   MatStashGetInfo_Private(&mat->stash,nstash,reallocs);
8733:   MatStashGetInfo_Private(&mat->bstash,bnstash,breallocs);
8734:   return(0);
8735: }

8737: /*@C
8738:    MatCreateVecs - Get vector(s) compatible with the matrix, i.e. with the same
8739:      parallel layout

8741:    Collective on Mat

8743:    Input Parameter:
8744: .  mat - the matrix

8746:    Output Parameter:
8747: +   right - (optional) vector that the matrix can be multiplied against
8748: -   left - (optional) vector that the matrix vector product can be stored in

8750:    Notes:
8751:     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().

8753:   Notes:
8754:     These are new vectors which are not owned by the Mat, they should be destroyed in VecDestroy() when no longer needed

8756:   Level: advanced

8758: .seealso: MatCreate(), VecDestroy()
8759: @*/
8760: PetscErrorCode MatCreateVecs(Mat mat,Vec *right,Vec *left)
8761: {

8767:   if (mat->ops->getvecs) {
8768:     (*mat->ops->getvecs)(mat,right,left);
8769:   } else {
8770:     PetscInt rbs,cbs;
8771:     MatGetBlockSizes(mat,&rbs,&cbs);
8772:     if (right) {
8773:       if (mat->cmap->n < 0) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"PetscLayout for columns not yet setup");
8774:       VecCreate(PetscObjectComm((PetscObject)mat),right);
8775:       VecSetSizes(*right,mat->cmap->n,PETSC_DETERMINE);
8776:       VecSetBlockSize(*right,cbs);
8777:       VecSetType(*right,mat->defaultvectype);
8778:       PetscLayoutReference(mat->cmap,&(*right)->map);
8779:     }
8780:     if (left) {
8781:       if (mat->rmap->n < 0) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"PetscLayout for rows not yet setup");
8782:       VecCreate(PetscObjectComm((PetscObject)mat),left);
8783:       VecSetSizes(*left,mat->rmap->n,PETSC_DETERMINE);
8784:       VecSetBlockSize(*left,rbs);
8785:       VecSetType(*left,mat->defaultvectype);
8786:       PetscLayoutReference(mat->rmap,&(*left)->map);
8787:     }
8788:   }
8789:   return(0);
8790: }

8792: /*@C
8793:    MatFactorInfoInitialize - Initializes a MatFactorInfo data structure
8794:      with default values.

8796:    Not Collective

8798:    Input Parameters:
8799: .    info - the MatFactorInfo data structure


8802:    Notes:
8803:     The solvers are generally used through the KSP and PC objects, for example
8804:           PCLU, PCILU, PCCHOLESKY, PCICC

8806:    Level: developer

8808: .seealso: MatFactorInfo

8810:     Developer Note: fortran interface is not autogenerated as the f90
8811:     interface defintion cannot be generated correctly [due to MatFactorInfo]

8813: @*/

8815: PetscErrorCode MatFactorInfoInitialize(MatFactorInfo *info)
8816: {

8820:   PetscMemzero(info,sizeof(MatFactorInfo));
8821:   return(0);
8822: }

8824: /*@
8825:    MatFactorSetSchurIS - Set indices corresponding to the Schur complement you wish to have computed

8827:    Collective on Mat

8829:    Input Parameters:
8830: +  mat - the factored matrix
8831: -  is - the index set defining the Schur indices (0-based)

8833:    Notes:
8834:     Call MatFactorSolveSchurComplement() or MatFactorSolveSchurComplementTranspose() after this call to solve a Schur complement system.

8836:    You can call MatFactorGetSchurComplement() or MatFactorCreateSchurComplement() after this call.

8838:    Level: developer

8840: .seealso: MatGetFactor(), MatFactorGetSchurComplement(), MatFactorRestoreSchurComplement(), MatFactorCreateSchurComplement(), MatFactorSolveSchurComplement(),
8841:           MatFactorSolveSchurComplementTranspose(), MatFactorSolveSchurComplement()

8843: @*/
8844: PetscErrorCode MatFactorSetSchurIS(Mat mat,IS is)
8845: {
8846:   PetscErrorCode ierr,(*f)(Mat,IS);

8854:   if (!mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Only for factored matrix");
8855:   PetscObjectQueryFunction((PetscObject)mat,"MatFactorSetSchurIS_C",&f);
8856:   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");
8857:   MatDestroy(&mat->schur);
8858:   (*f)(mat,is);
8859:   if (!mat->schur) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_PLIB,"Schur complement has not been created");
8860:   return(0);
8861: }

8863: /*@
8864:   MatFactorCreateSchurComplement - Create a Schur complement matrix object using Schur data computed during the factorization step

8866:    Logically Collective on Mat

8868:    Input Parameters:
8869: +  F - the factored matrix obtained by calling MatGetFactor() from PETSc-MUMPS interface
8870: .  S - location where to return the Schur complement, can be NULL
8871: -  status - the status of the Schur complement matrix, can be NULL

8873:    Notes:
8874:    You must call MatFactorSetSchurIS() before calling this routine.

8876:    The routine provides a copy of the Schur matrix stored within the solver data structures.
8877:    The caller must destroy the object when it is no longer needed.
8878:    If MatFactorInvertSchurComplement() has been called, the routine gets back the inverse.

8880:    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)

8882:    Developer Notes:
8883:     The reason this routine exists is because the representation of the Schur complement within the factor matrix may be different than a standard PETSc
8884:    matrix representation and we normally do not want to use the time or memory to make a copy as a regular PETSc matrix.

8886:    See MatCreateSchurComplement() or MatGetSchurComplement() for ways to create virtual or approximate Schur complements.

8888:    Level: advanced

8890:    References:

8892: .seealso: MatGetFactor(), MatFactorSetSchurIS(), MatFactorGetSchurComplement(), MatFactorSchurStatus
8893: @*/
8894: PetscErrorCode MatFactorCreateSchurComplement(Mat F,Mat* S,MatFactorSchurStatus* status)
8895: {

8902:   if (S) {
8903:     PetscErrorCode (*f)(Mat,Mat*);

8905:     PetscObjectQueryFunction((PetscObject)F,"MatFactorCreateSchurComplement_C",&f);
8906:     if (f) {
8907:       (*f)(F,S);
8908:     } else {
8909:       MatDuplicate(F->schur,MAT_COPY_VALUES,S);
8910:     }
8911:   }
8912:   if (status) *status = F->schur_status;
8913:   return(0);
8914: }

8916: /*@
8917:   MatFactorGetSchurComplement - Gets access to a Schur complement matrix using the current Schur data within a factored matrix

8919:    Logically Collective on Mat

8921:    Input Parameters:
8922: +  F - the factored matrix obtained by calling MatGetFactor()
8923: .  *S - location where to return the Schur complement, can be NULL
8924: -  status - the status of the Schur complement matrix, can be NULL

8926:    Notes:
8927:    You must call MatFactorSetSchurIS() before calling this routine.

8929:    Schur complement mode is currently implemented for sequential matrices.
8930:    The routine returns a the Schur Complement stored within the data strutures of the solver.
8931:    If MatFactorInvertSchurComplement() has previously been called, the returned matrix is actually the inverse of the Schur complement.
8932:    The returned matrix should not be destroyed; the caller should call MatFactorRestoreSchurComplement() when the object is no longer needed.

8934:    Use MatFactorCreateSchurComplement() to create a copy of the Schur complement matrix that is within a factored matrix

8936:    See MatCreateSchurComplement() or MatGetSchurComplement() for ways to create virtual or approximate Schur complements.

8938:    Level: advanced

8940:    References:

8942: .seealso: MatGetFactor(), MatFactorSetSchurIS(), MatFactorRestoreSchurComplement(), MatFactorCreateSchurComplement(), MatFactorSchurStatus
8943: @*/
8944: PetscErrorCode MatFactorGetSchurComplement(Mat F,Mat* S,MatFactorSchurStatus* status)
8945: {
8950:   if (S) *S = F->schur;
8951:   if (status) *status = F->schur_status;
8952:   return(0);
8953: }

8955: /*@
8956:   MatFactorRestoreSchurComplement - Restore the Schur complement matrix object obtained from a call to MatFactorGetSchurComplement

8958:    Logically Collective on Mat

8960:    Input Parameters:
8961: +  F - the factored matrix obtained by calling MatGetFactor()
8962: .  *S - location where the Schur complement is stored
8963: -  status - the status of the Schur complement matrix (see MatFactorSchurStatus)

8965:    Notes:

8967:    Level: advanced

8969:    References:

8971: .seealso: MatGetFactor(), MatFactorSetSchurIS(), MatFactorRestoreSchurComplement(), MatFactorCreateSchurComplement(), MatFactorSchurStatus
8972: @*/
8973: PetscErrorCode MatFactorRestoreSchurComplement(Mat F,Mat* S,MatFactorSchurStatus status)
8974: {

8979:   if (S) {
8981:     *S = NULL;
8982:   }
8983:   F->schur_status = status;
8984:   MatFactorUpdateSchurStatus_Private(F);
8985:   return(0);
8986: }

8988: /*@
8989:   MatFactorSolveSchurComplementTranspose - Solve the transpose of the Schur complement system computed during the factorization step

8991:    Logically Collective on Mat

8993:    Input Parameters:
8994: +  F - the factored matrix obtained by calling MatGetFactor()
8995: .  rhs - location where the right hand side of the Schur complement system is stored
8996: -  sol - location where the solution of the Schur complement system has to be returned

8998:    Notes:
8999:    The sizes of the vectors should match the size of the Schur complement

9001:    Must be called after MatFactorSetSchurIS()

9003:    Level: advanced

9005:    References:

9007: .seealso: MatGetFactor(), MatFactorSetSchurIS(), MatFactorSolveSchurComplement()
9008: @*/
9009: PetscErrorCode MatFactorSolveSchurComplementTranspose(Mat F, Vec rhs, Vec sol)
9010: {

9022:   MatFactorFactorizeSchurComplement(F);
9023:   switch (F->schur_status) {
9024:   case MAT_FACTOR_SCHUR_FACTORED:
9025:     MatSolveTranspose(F->schur,rhs,sol);
9026:     break;
9027:   case MAT_FACTOR_SCHUR_INVERTED:
9028:     MatMultTranspose(F->schur,rhs,sol);
9029:     break;
9030:   default:
9031:     SETERRQ1(PetscObjectComm((PetscObject)F),PETSC_ERR_SUP,"Unhandled MatFactorSchurStatus %D",F->schur_status);
9032:     break;
9033:   }
9034:   return(0);
9035: }

9037: /*@
9038:   MatFactorSolveSchurComplement - Solve the Schur complement system computed during the factorization step

9040:    Logically Collective on Mat

9042:    Input Parameters:
9043: +  F - the factored matrix obtained by calling MatGetFactor()
9044: .  rhs - location where the right hand side of the Schur complement system is stored
9045: -  sol - location where the solution of the Schur complement system has to be returned

9047:    Notes:
9048:    The sizes of the vectors should match the size of the Schur complement

9050:    Must be called after MatFactorSetSchurIS()

9052:    Level: advanced

9054:    References:

9056: .seealso: MatGetFactor(), MatFactorSetSchurIS(), MatFactorSolveSchurComplementTranspose()
9057: @*/
9058: PetscErrorCode MatFactorSolveSchurComplement(Mat F, Vec rhs, Vec sol)
9059: {

9071:   MatFactorFactorizeSchurComplement(F);
9072:   switch (F->schur_status) {
9073:   case MAT_FACTOR_SCHUR_FACTORED:
9074:     MatSolve(F->schur,rhs,sol);
9075:     break;
9076:   case MAT_FACTOR_SCHUR_INVERTED:
9077:     MatMult(F->schur,rhs,sol);
9078:     break;
9079:   default:
9080:     SETERRQ1(PetscObjectComm((PetscObject)F),PETSC_ERR_SUP,"Unhandled MatFactorSchurStatus %D",F->schur_status);
9081:     break;
9082:   }
9083:   return(0);
9084: }

9086: /*@
9087:   MatFactorInvertSchurComplement - Invert the Schur complement matrix computed during the factorization step

9089:    Logically Collective on Mat

9091:    Input Parameters:
9092: .  F - the factored matrix obtained by calling MatGetFactor()

9094:    Notes:
9095:     Must be called after MatFactorSetSchurIS().

9097:    Call MatFactorGetSchurComplement() or  MatFactorCreateSchurComplement() AFTER this call to actually compute the inverse and get access to it.

9099:    Level: advanced

9101:    References:

9103: .seealso: MatGetFactor(), MatFactorSetSchurIS(), MatFactorGetSchurComplement(), MatFactorCreateSchurComplement()
9104: @*/
9105: PetscErrorCode MatFactorInvertSchurComplement(Mat F)
9106: {

9112:   if (F->schur_status == MAT_FACTOR_SCHUR_INVERTED) return(0);
9113:   MatFactorFactorizeSchurComplement(F);
9114:   MatFactorInvertSchurComplement_Private(F);
9115:   F->schur_status = MAT_FACTOR_SCHUR_INVERTED;
9116:   return(0);
9117: }

9119: /*@
9120:   MatFactorFactorizeSchurComplement - Factorize the Schur complement matrix computed during the factorization step

9122:    Logically Collective on Mat

9124:    Input Parameters:
9125: .  F - the factored matrix obtained by calling MatGetFactor()

9127:    Notes:
9128:     Must be called after MatFactorSetSchurIS().

9130:    Level: advanced

9132:    References:

9134: .seealso: MatGetFactor(), MatFactorSetSchurIS(), MatFactorInvertSchurComplement()
9135: @*/
9136: PetscErrorCode MatFactorFactorizeSchurComplement(Mat F)
9137: {

9143:   if (F->schur_status == MAT_FACTOR_SCHUR_INVERTED || F->schur_status == MAT_FACTOR_SCHUR_FACTORED) return(0);
9144:   MatFactorFactorizeSchurComplement_Private(F);
9145:   F->schur_status = MAT_FACTOR_SCHUR_FACTORED;
9146:   return(0);
9147: }

9149: /*@
9150:    MatPtAP - Creates the matrix product C = P^T * A * P

9152:    Neighbor-wise Collective on Mat

9154:    Input Parameters:
9155: +  A - the matrix
9156: .  P - the projection matrix
9157: .  scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
9158: -  fill - expected fill as ratio of nnz(C)/(nnz(A) + nnz(P)), use PETSC_DEFAULT if you do not have a good estimate
9159:           if the result is a dense matrix this is irrelevent

9161:    Output Parameters:
9162: .  C - the product matrix

9164:    Notes:
9165:    C will be created and must be destroyed by the user with MatDestroy().

9167:    For matrix types without special implementation the function fallbacks to MatMatMult() followed by MatTransposeMatMult().

9169:    Level: intermediate

9171: .seealso: MatMatMult(), MatRARt()
9172: @*/
9173: PetscErrorCode MatPtAP(Mat A,Mat P,MatReuse scall,PetscReal fill,Mat *C)
9174: {

9178:   if (scall == MAT_INPLACE_MATRIX) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Inplace product not supported");

9180:   if (scall == MAT_INITIAL_MATRIX) {
9181:     MatProductCreate(A,P,NULL,C);
9182:     MatProductSetType(*C,MATPRODUCT_PtAP);
9183:     MatProductSetAlgorithm(*C,"default");
9184:     MatProductSetFill(*C,fill);

9186:     (*C)->product->api_user = PETSC_TRUE;
9187:     MatProductSetFromOptions(*C);
9188:     MatProductSymbolic(*C);
9189:   } else {
9190:     Mat_Product *product = (*C)->product;
9191:     if (product) { /* user may chage input matrices A or B when REUSE */
9192:       MatProductReplaceMats(A,P,NULL,*C);
9193:     } else SETERRQ(PetscObjectComm((PetscObject)(*C)),PETSC_ERR_SUP,"Call MatProductCreate() or MatProductReplaceProduct() first");
9194:   }

9196:   MatProductNumeric(*C);
9197:   if (A->symmetric_set && A->symmetric) {
9198:     MatSetOption(*C,MAT_SYMMETRIC,PETSC_TRUE);
9199:   }
9200:   return(0);
9201: }

9203: /*@
9204:    MatRARt - Creates the matrix product C = R * A * R^T

9206:    Neighbor-wise Collective on Mat

9208:    Input Parameters:
9209: +  A - the matrix
9210: .  R - the projection matrix
9211: .  scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
9212: -  fill - expected fill as ratio of nnz(C)/nnz(A), use PETSC_DEFAULT if you do not have a good estimate
9213:           if the result is a dense matrix this is irrelevent

9215:    Output Parameters:
9216: .  C - the product matrix

9218:    Notes:
9219:    C will be created and must be destroyed by the user with MatDestroy().

9221:    This routine is currently only implemented for pairs of AIJ matrices and classes
9222:    which inherit from AIJ. Due to PETSc sparse matrix block row distribution among processes,
9223:    parallel MatRARt is implemented via explicit transpose of R, which could be very expensive.
9224:    We recommend using MatPtAP().

9226:    Level: intermediate

9228: .seealso: MatMatMult(), MatPtAP()
9229: @*/
9230: PetscErrorCode MatRARt(Mat A,Mat R,MatReuse scall,PetscReal fill,Mat *C)
9231: {

9235:   if (scall == MAT_INPLACE_MATRIX) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Inplace product not supported");

9237:   if (scall == MAT_INITIAL_MATRIX) {
9238:     MatProductCreate(A,R,NULL,C);
9239:     MatProductSetType(*C,MATPRODUCT_RARt);
9240:     MatProductSetAlgorithm(*C,"default");
9241:     MatProductSetFill(*C,fill);

9243:     (*C)->product->api_user = PETSC_TRUE;
9244:     MatProductSetFromOptions(*C);
9245:     MatProductSymbolic(*C);
9246:   } else { /* scall == MAT_REUSE_MATRIX */
9247:     Mat_Product *product = (*C)->product;
9248:     if (product) {
9249:       /* user may chage input matrices A or R when REUSE */
9250:       MatProductReplaceMats(A,R,NULL,*C);
9251:     } else SETERRQ(PetscObjectComm((PetscObject)(*C)),PETSC_ERR_SUP,"Call MatProductCreate() or MatProductReplaceProduct() first");
9252:   }

9254:   MatProductNumeric(*C);
9255:   return(0);
9256: }

9258: /*@
9259:    MatMatMult - Performs Matrix-Matrix Multiplication C=A*B.

9261:    Neighbor-wise Collective on Mat

9263:    Input Parameters:
9264: +  A - the left matrix
9265: .  B - the right matrix
9266: .  scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
9267: -  fill - expected fill as ratio of nnz(C)/(nnz(A) + nnz(B)), use PETSC_DEFAULT if you do not have a good estimate
9268:           if the result is a dense matrix this is irrelevent

9270:    Output Parameters:
9271: .  C - the product matrix

9273:    Notes:
9274:    Unless scall is MAT_REUSE_MATRIX C will be created.

9276:    MAT_REUSE_MATRIX can only be used if the matrices A and B have the same nonzero pattern as in the previous call and C was obtained from a previous
9277:    call to this function with MAT_INITIAL_MATRIX.

9279:    To determine the correct fill value, run with -info and search for the string "Fill ratio" to see the value actually needed.

9281:    If you have many matrices with the same non-zero structure to multiply, you should use MatProductCreate()/MatProductSymbolic(C)/ReplaceMats(), and call MatProductNumeric() repeatedly.

9283:    In the special case where matrix B (and hence C) are dense you can create the correctly sized matrix C yourself and then call this routine with MAT_REUSE_MATRIX, rather than first having MatMatMult() create it for you. You can NEVER do this if the matrix C is sparse.

9285:    Level: intermediate

9287: .seealso: MatTransposeMatMult(), MatMatTransposeMult(), MatPtAP()
9288: @*/
9289: PetscErrorCode MatMatMult(Mat A,Mat B,MatReuse scall,PetscReal fill,Mat *C)
9290: {

9294:   if (scall == MAT_INPLACE_MATRIX) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Inplace product not supported");

9296:   if (scall == MAT_INITIAL_MATRIX) {
9297:     MatProductCreate(A,B,NULL,C);
9298:     MatProductSetType(*C,MATPRODUCT_AB);
9299:     MatProductSetAlgorithm(*C,"default");
9300:     MatProductSetFill(*C,fill);

9302:     (*C)->product->api_user = PETSC_TRUE;
9303:     MatProductSetFromOptions(*C);
9304:     MatProductSymbolic(*C);
9305:   } else { /* scall == MAT_REUSE_MATRIX */
9306:     Mat_Product *product = (*C)->product;
9307:     if (!product) {
9308:       /* user provide the dense matrix *C without calling MatProductCreate() */
9309:       PetscBool seqdense,mpidense,dense;
9310: #if defined(PETSC_HAVE_CUDA)
9311:       PetscBool seqdensecuda;
9312: #endif
9313:       PetscObjectTypeCompare((PetscObject)(*C),MATSEQDENSE,&seqdense);
9314:       PetscObjectTypeCompare((PetscObject)(*C),MATMPIDENSE,&mpidense);
9315:       PetscObjectTypeCompare((PetscObject)(*C),MATDENSE,&dense);
9316: #if defined(PETSC_HAVE_CUDA)
9317:       PetscObjectTypeCompare((PetscObject)(*C),MATSEQDENSECUDA,&seqdensecuda);
9318:       if (seqdense || mpidense || dense || seqdensecuda) {
9319: #else
9320:       if (seqdense || mpidense || dense) {
9321: #endif
9322:         /* user wants to reuse an assembled dense matrix */
9323:         /* Create product -- see MatCreateProduct() */
9324:         PetscNewLog(*C,&product);
9325:         product->A        = A; product->Areplaced = PETSC_FALSE;
9326:         product->B        = B; product->Breplaced = PETSC_FALSE;
9327:         product->C        = NULL;
9328:         product->alg      = MATPRODUCTALGORITHM_DEFAULT;
9329:         product->fill     = fill;
9330:         product->api_user = PETSC_TRUE;
9331:         (*C)->product     = product;

9333:         MatProductSetType(*C,MATPRODUCT_AB);
9334:         MatProductSetFromOptions(*C);
9335:         if (!(*C)->assembled) {
9336:           MatProductSymbolic(*C);
9337:         }
9338:       } else SETERRQ(PetscObjectComm((PetscObject)(*C)),PETSC_ERR_SUP,"Call MatProductCreate() or MatProductReplaceProduct() first");
9339:     } else { /* user may chage input matrices A or B when REUSE */
9340:       MatProductReplaceMats(A,B,NULL,*C);
9341:     }
9342:   }
9343:   MatProductNumeric(*C);
9344:   return(0);
9345: }

9347: /*@
9348:    MatMatTransposeMult - Performs Matrix-Matrix Multiplication C=A*B^T.

9350:    Neighbor-wise Collective on Mat

9352:    Input Parameters:
9353: +  A - the left matrix
9354: .  B - the right matrix
9355: .  scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
9356: -  fill - expected fill as ratio of nnz(C)/(nnz(A) + nnz(B)), use PETSC_DEFAULT if not known

9358:    Output Parameters:
9359: .  C - the product matrix

9361:    Notes:
9362:    C will be created if MAT_INITIAL_MATRIX and must be destroyed by the user with MatDestroy().

9364:    MAT_REUSE_MATRIX can only be used if the matrices A and B have the same nonzero pattern as in the previous call

9366:   To determine the correct fill value, run with -info and search for the string "Fill ratio" to see the value
9367:    actually needed.

9369:    This routine is currently only implemented for pairs of SeqAIJ matrices, for the SeqDense class,
9370:    and for pairs of MPIDense matrices.

9372:    Options Database Keys:
9373: .  -matmattransmult_mpidense_mpidense_via {allgatherv,cyclic} - Choose between algorthims for MPIDense matrices: the
9374:                                                                 first redundantly copies the transposed B matrix on each process and requiers O(log P) communication complexity;
9375:                                                                 the second never stores more than one portion of the B matrix at a time by requires O(P) communication complexity.

9377:    Level: intermediate

9379: .seealso: MatMatMult(), MatTransposeMatMult() MatPtAP()
9380: @*/
9381: PetscErrorCode MatMatTransposeMult(Mat A,Mat B,MatReuse scall,PetscReal fill,Mat *C)
9382: {

9386:   if (scall == MAT_INPLACE_MATRIX) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Inplace product not supported");

9388:   if (scall == MAT_INITIAL_MATRIX) {
9389:     MatProductCreate(A,B,NULL,C);
9390:     MatProductSetType(*C, MATPRODUCT_ABt);
9391:     MatProductSetAlgorithm(*C,"default");
9392:     MatProductSetFill(*C,fill);

9394:     (*C)->product->api_user = PETSC_TRUE;
9395:     MatProductSetFromOptions(*C);
9396:     MatProductSymbolic(*C);
9397:   } else {
9398:     Mat_Product *product = (*C)->product;
9399:     if (!product) {
9400:       PetscBool seqdense,mpidense,dense;
9401:       PetscObjectTypeCompare((PetscObject)(*C),MATSEQDENSE,&seqdense);
9402:       PetscObjectTypeCompare((PetscObject)(*C),MATMPIDENSE,&mpidense);
9403:       PetscObjectTypeCompare((PetscObject)(*C),MATDENSE,&dense);
9404:       if ((*C)->assembled && (seqdense || mpidense || dense)) {
9405:         /* user wants to reuse an assembled dense matrix */
9406:         /* Create product -- see MatCreateProduct() */
9407:         PetscNewLog(*C,&product);
9408:         product->A        = A; product->Areplaced = PETSC_FALSE;
9409:         product->B        = B; product->Breplaced = PETSC_FALSE;
9410:         product->C        = NULL;
9411:         product->alg      = MATPRODUCTALGORITHM_DEFAULT;
9412:         product->fill     = fill;
9413:         product->api_user = PETSC_TRUE;
9414:         (*C)->product     = product;

9416:         MatProductSetType(*C,MATPRODUCT_ABt);
9417:         MatProductSetFromOptions(*C);
9418:         MatProductSymbolic(*C);
9419:       } else SETERRQ(PetscObjectComm((PetscObject)(*C)),PETSC_ERR_SUP,"Call MatProductCreate() first");
9420:     } else { /* user may chage input matrices A or B when REUSE */
9421:       MatProductReplaceMats(A,B,NULL,*C);
9422:     }
9423:   }
9424:   MatProductNumeric(*C);
9425:   return(0);
9426: }

9428: /*@
9429:    MatTransposeMatMult - Performs Matrix-Matrix Multiplication C=A^T*B.

9431:    Neighbor-wise Collective on Mat

9433:    Input Parameters:
9434: +  A - the left matrix
9435: .  B - the right matrix
9436: .  scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
9437: -  fill - expected fill as ratio of nnz(C)/(nnz(A) + nnz(B)), use PETSC_DEFAULT if not known

9439:    Output Parameters:
9440: .  C - the product matrix

9442:    Notes:
9443:    C will be created if MAT_INITIAL_MATRIX and must be destroyed by the user with MatDestroy().

9445:    MAT_REUSE_MATRIX can only be used if the matrices A and B have the same nonzero pattern as in the previous call.

9447:   To determine the correct fill value, run with -info and search for the string "Fill ratio" to see the value
9448:    actually needed.

9450:    This routine is currently implemented for pairs of AIJ matrices and pairs of SeqDense matrices and classes
9451:    which inherit from SeqAIJ.  C will be of same type as the input matrices.

9453:    Level: intermediate

9455: .seealso: MatMatMult(), MatMatTransposeMult(), MatPtAP()
9456: @*/
9457: PetscErrorCode MatTransposeMatMult(Mat A,Mat B,MatReuse scall,PetscReal fill,Mat *C)
9458: {

9462:   if (scall == MAT_INPLACE_MATRIX) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Inplace product not supported");

9464:   if (scall == MAT_INITIAL_MATRIX) {
9465:     MatProductCreate(A,B,NULL,C);
9466:     MatProductSetType(*C,MATPRODUCT_AtB);
9467:     MatProductSetAlgorithm(*C,"default");
9468:     MatProductSetFill(*C,fill);

9470:     (*C)->product->api_user = PETSC_TRUE;
9471:     MatProductSetFromOptions(*C);
9472:     MatProductSymbolic(*C);
9473:   } else {
9474:     Mat_Product *product = (*C)->product;
9475:     if (!product) {
9476:       PetscBool seqdense,mpidense,dense;
9477:       PetscObjectTypeCompare((PetscObject)(*C),MATSEQDENSE,&seqdense);
9478:       PetscObjectTypeCompare((PetscObject)(*C),MATMPIDENSE,&mpidense);
9479:       PetscObjectTypeCompare((PetscObject)(*C),MATDENSE,&dense);
9480:       if ((*C)->assembled && (seqdense || mpidense || dense)) {
9481:         /* user wants to reuse an assembled dense matrix */
9482:         /* Create product -- see MatCreateProduct() */
9483:         PetscNewLog(*C,&product);
9484:         product->A        = A; product->Areplaced = PETSC_FALSE;
9485:         product->B        = B; product->Breplaced = PETSC_FALSE;
9486:         product->C        = NULL;
9487:         product->alg      = MATPRODUCTALGORITHM_DEFAULT;
9488:         product->fill     = fill;
9489:         product->api_user = PETSC_TRUE;
9490:         (*C)->product     = product;

9492:         MatProductSetType(*C,MATPRODUCT_AtB);
9493:         MatProductSetFromOptions(*C);
9494:       } else SETERRQ(PetscObjectComm((PetscObject)(*C)),PETSC_ERR_SUP,"Call MatProductCreate() first");
9495:     } else { /* user may chage input matrices A or B when REUSE */
9496:       MatProductReplaceMats(A,B,NULL,*C);
9497:     }
9498:   }
9499:   MatProductNumeric(*C);
9500:   return(0);
9501: }

9503: /*@
9504:    MatMatMatMult - Performs Matrix-Matrix-Matrix Multiplication D=A*B*C.

9506:    Neighbor-wise Collective on Mat

9508:    Input Parameters:
9509: +  A - the left matrix
9510: .  B - the middle matrix
9511: .  C - the right matrix
9512: .  scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
9513: -  fill - expected fill as ratio of nnz(D)/(nnz(A) + nnz(B)+nnz(C)), use PETSC_DEFAULT if you do not have a good estimate
9514:           if the result is a dense matrix this is irrelevent

9516:    Output Parameters:
9517: .  D - the product matrix

9519:    Notes:
9520:    Unless scall is MAT_REUSE_MATRIX D will be created.

9522:    MAT_REUSE_MATRIX can only be used if the matrices A, B and C have the same nonzero pattern as in the previous call

9524:    To determine the correct fill value, run with -info and search for the string "Fill ratio" to see the value
9525:    actually needed.

9527:    If you have many matrices with the same non-zero structure to multiply, you
9528:    should use MAT_REUSE_MATRIX in all calls but the first or

9530:    Level: intermediate

9532: .seealso: MatMatMult, MatPtAP()
9533: @*/
9534: PetscErrorCode MatMatMatMult(Mat A,Mat B,Mat C,MatReuse scall,PetscReal fill,Mat *D)
9535: {

9539:   if (scall == MAT_INPLACE_MATRIX) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Inplace product not supported");

9541:   if (scall == MAT_INITIAL_MATRIX) {
9542:     MatProductCreate(A,B,C,D);
9543:     MatProductSetType(*D,MATPRODUCT_ABC);
9544:     MatProductSetAlgorithm(*D,"default");
9545:     MatProductSetFill(*D,fill);

9547:     (*D)->product->api_user = PETSC_TRUE;
9548:     MatProductSetFromOptions(*D);

9550:     MatProductSymbolic(*D);
9551:   } else { /* user may chage input matrices when REUSE */
9552:     MatProductReplaceMats(A,B,C,*D);
9553:   }

9555:   MatProductNumeric(*D);
9556:   return(0);
9557: }

9559: /*@
9560:    MatCreateRedundantMatrix - Create redundant matrices and put them into processors of subcommunicators.

9562:    Collective on Mat

9564:    Input Parameters:
9565: +  mat - the matrix
9566: .  nsubcomm - the number of subcommunicators (= number of redundant parallel or sequential matrices)
9567: .  subcomm - MPI communicator split from the communicator where mat resides in (or MPI_COMM_NULL if nsubcomm is used)
9568: -  reuse - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX

9570:    Output Parameter:
9571: .  matredundant - redundant matrix

9573:    Notes:
9574:    MAT_REUSE_MATRIX can only be used when the nonzero structure of the
9575:    original matrix has not changed from that last call to MatCreateRedundantMatrix().

9577:    This routine creates the duplicated matrices in subcommunicators; you should NOT create them before
9578:    calling it.

9580:    Level: advanced


9583: .seealso: MatDestroy()
9584: @*/
9585: PetscErrorCode MatCreateRedundantMatrix(Mat mat,PetscInt nsubcomm,MPI_Comm subcomm,MatReuse reuse,Mat *matredundant)
9586: {
9588:   MPI_Comm       comm;
9589:   PetscMPIInt    size;
9590:   PetscInt       mloc_sub,nloc_sub,rstart,rend,M=mat->rmap->N,N=mat->cmap->N,bs=mat->rmap->bs;
9591:   Mat_Redundant  *redund=NULL;
9592:   PetscSubcomm   psubcomm=NULL;
9593:   MPI_Comm       subcomm_in=subcomm;
9594:   Mat            *matseq;
9595:   IS             isrow,iscol;
9596:   PetscBool      newsubcomm=PETSC_FALSE;

9600:   if (nsubcomm && reuse == MAT_REUSE_MATRIX) {
9603:   }

9605:   MPI_Comm_size(PetscObjectComm((PetscObject)mat),&size);
9606:   if (size == 1 || nsubcomm == 1) {
9607:     if (reuse == MAT_INITIAL_MATRIX) {
9608:       MatDuplicate(mat,MAT_COPY_VALUES,matredundant);
9609:     } else {
9610:       if (*matredundant == mat) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONG,"MAT_REUSE_MATRIX means reuse the matrix passed in as the final argument, not the original matrix");
9611:       MatCopy(mat,*matredundant,SAME_NONZERO_PATTERN);
9612:     }
9613:     return(0);
9614:   }

9616:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
9617:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
9618:   MatCheckPreallocated(mat,1);

9620:   PetscLogEventBegin(MAT_RedundantMat,mat,0,0,0);
9621:   if (subcomm_in == MPI_COMM_NULL && reuse == MAT_INITIAL_MATRIX) { /* get subcomm if user does not provide subcomm */
9622:     /* create psubcomm, then get subcomm */
9623:     PetscObjectGetComm((PetscObject)mat,&comm);
9624:     MPI_Comm_size(comm,&size);
9625:     if (nsubcomm < 1 || nsubcomm > size) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"nsubcomm must between 1 and %D",size);

9627:     PetscSubcommCreate(comm,&psubcomm);
9628:     PetscSubcommSetNumber(psubcomm,nsubcomm);
9629:     PetscSubcommSetType(psubcomm,PETSC_SUBCOMM_CONTIGUOUS);
9630:     PetscSubcommSetFromOptions(psubcomm);
9631:     PetscCommDuplicate(PetscSubcommChild(psubcomm),&subcomm,NULL);
9632:     newsubcomm = PETSC_TRUE;
9633:     PetscSubcommDestroy(&psubcomm);
9634:   }

9636:   /* get isrow, iscol and a local sequential matrix matseq[0] */
9637:   if (reuse == MAT_INITIAL_MATRIX) {
9638:     mloc_sub = PETSC_DECIDE;
9639:     nloc_sub = PETSC_DECIDE;
9640:     if (bs < 1) {
9641:       PetscSplitOwnership(subcomm,&mloc_sub,&M);
9642:       PetscSplitOwnership(subcomm,&nloc_sub,&N);
9643:     } else {
9644:       PetscSplitOwnershipBlock(subcomm,bs,&mloc_sub,&M);
9645:       PetscSplitOwnershipBlock(subcomm,bs,&nloc_sub,&N);
9646:     }
9647:     MPI_Scan(&mloc_sub,&rend,1,MPIU_INT,MPI_SUM,subcomm);
9648:     rstart = rend - mloc_sub;
9649:     ISCreateStride(PETSC_COMM_SELF,mloc_sub,rstart,1,&isrow);
9650:     ISCreateStride(PETSC_COMM_SELF,N,0,1,&iscol);
9651:   } else { /* reuse == MAT_REUSE_MATRIX */
9652:     if (*matredundant == mat) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONG,"MAT_REUSE_MATRIX means reuse the matrix passed in as the final argument, not the original matrix");
9653:     /* retrieve subcomm */
9654:     PetscObjectGetComm((PetscObject)(*matredundant),&subcomm);
9655:     redund = (*matredundant)->redundant;
9656:     isrow  = redund->isrow;
9657:     iscol  = redund->iscol;
9658:     matseq = redund->matseq;
9659:   }
9660:   MatCreateSubMatrices(mat,1,&isrow,&iscol,reuse,&matseq);

9662:   /* get matredundant over subcomm */
9663:   if (reuse == MAT_INITIAL_MATRIX) {
9664:     MatCreateMPIMatConcatenateSeqMat(subcomm,matseq[0],nloc_sub,reuse,matredundant);

9666:     /* create a supporting struct and attach it to C for reuse */
9667:     PetscNewLog(*matredundant,&redund);
9668:     (*matredundant)->redundant = redund;
9669:     redund->isrow              = isrow;
9670:     redund->iscol              = iscol;
9671:     redund->matseq             = matseq;
9672:     if (newsubcomm) {
9673:       redund->subcomm          = subcomm;
9674:     } else {
9675:       redund->subcomm          = MPI_COMM_NULL;
9676:     }
9677:   } else {
9678:     MatCreateMPIMatConcatenateSeqMat(subcomm,matseq[0],PETSC_DECIDE,reuse,matredundant);
9679:   }
9680:   PetscLogEventEnd(MAT_RedundantMat,mat,0,0,0);
9681:   return(0);
9682: }

9684: /*@C
9685:    MatGetMultiProcBlock - Create multiple [bjacobi] 'parallel submatrices' from
9686:    a given 'mat' object. Each submatrix can span multiple procs.

9688:    Collective on Mat

9690:    Input Parameters:
9691: +  mat - the matrix
9692: .  subcomm - the subcommunicator obtained by com_split(comm)
9693: -  scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX

9695:    Output Parameter:
9696: .  subMat - 'parallel submatrices each spans a given subcomm

9698:   Notes:
9699:   The submatrix partition across processors is dictated by 'subComm' a
9700:   communicator obtained by com_split(comm). The comm_split
9701:   is not restriced to be grouped with consecutive original ranks.

9703:   Due the comm_split() usage, the parallel layout of the submatrices
9704:   map directly to the layout of the original matrix [wrt the local
9705:   row,col partitioning]. So the original 'DiagonalMat' naturally maps
9706:   into the 'DiagonalMat' of the subMat, hence it is used directly from
9707:   the subMat. However the offDiagMat looses some columns - and this is
9708:   reconstructed with MatSetValues()

9710:   Level: advanced


9713: .seealso: MatCreateSubMatrices()
9714: @*/
9715: PetscErrorCode   MatGetMultiProcBlock(Mat mat, MPI_Comm subComm, MatReuse scall,Mat *subMat)
9716: {
9718:   PetscMPIInt    commsize,subCommSize;

9721:   MPI_Comm_size(PetscObjectComm((PetscObject)mat),&commsize);
9722:   MPI_Comm_size(subComm,&subCommSize);
9723:   if (subCommSize > commsize) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_OUTOFRANGE,"CommSize %D < SubCommZize %D",commsize,subCommSize);

9725:   if (scall == MAT_REUSE_MATRIX && *subMat == mat) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONG,"MAT_REUSE_MATRIX means reuse the matrix passed in as the final argument, not the original matrix");
9726:   PetscLogEventBegin(MAT_GetMultiProcBlock,mat,0,0,0);
9727:   (*mat->ops->getmultiprocblock)(mat,subComm,scall,subMat);
9728:   PetscLogEventEnd(MAT_GetMultiProcBlock,mat,0,0,0);
9729:   return(0);
9730: }

9732: /*@
9733:    MatGetLocalSubMatrix - Gets a reference to a submatrix specified in local numbering

9735:    Not Collective

9737:    Input Arguments:
9738: +  mat - matrix to extract local submatrix from
9739: .  isrow - local row indices for submatrix
9740: -  iscol - local column indices for submatrix

9742:    Output Arguments:
9743: .  submat - the submatrix

9745:    Level: intermediate

9747:    Notes:
9748:    The submat should be returned with MatRestoreLocalSubMatrix().

9750:    Depending on the format of mat, the returned submat may not implement MatMult().  Its communicator may be
9751:    the same as mat, it may be PETSC_COMM_SELF, or some other subcomm of mat's.

9753:    The submat always implements MatSetValuesLocal().  If isrow and iscol have the same block size, then
9754:    MatSetValuesBlockedLocal() will also be implemented.

9756:    The mat must have had a ISLocalToGlobalMapping provided to it with MatSetLocalToGlobalMapping(). Note that
9757:    matrices obtained with DMCreateMatrix() generally already have the local to global mapping provided.

9759: .seealso: MatRestoreLocalSubMatrix(), MatCreateLocalRef(), MatSetLocalToGlobalMapping()
9760: @*/
9761: PetscErrorCode MatGetLocalSubMatrix(Mat mat,IS isrow,IS iscol,Mat *submat)
9762: {

9771:   if (!mat->rmap->mapping) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Matrix must have local to global mapping provided before this call");

9773:   if (mat->ops->getlocalsubmatrix) {
9774:     (*mat->ops->getlocalsubmatrix)(mat,isrow,iscol,submat);
9775:   } else {
9776:     MatCreateLocalRef(mat,isrow,iscol,submat);
9777:   }
9778:   return(0);
9779: }

9781: /*@
9782:    MatRestoreLocalSubMatrix - Restores a reference to a submatrix specified in local numbering

9784:    Not Collective

9786:    Input Arguments:
9787:    mat - matrix to extract local submatrix from
9788:    isrow - local row indices for submatrix
9789:    iscol - local column indices for submatrix
9790:    submat - the submatrix

9792:    Level: intermediate

9794: .seealso: MatGetLocalSubMatrix()
9795: @*/
9796: PetscErrorCode MatRestoreLocalSubMatrix(Mat mat,IS isrow,IS iscol,Mat *submat)
9797: {

9806:   if (*submat) {
9808:   }

9810:   if (mat->ops->restorelocalsubmatrix) {
9811:     (*mat->ops->restorelocalsubmatrix)(mat,isrow,iscol,submat);
9812:   } else {
9813:     MatDestroy(submat);
9814:   }
9815:   *submat = NULL;
9816:   return(0);
9817: }

9819: /* --------------------------------------------------------*/
9820: /*@
9821:    MatFindZeroDiagonals - Finds all the rows of a matrix that have zero or no diagonal entry in the matrix

9823:    Collective on Mat

9825:    Input Parameter:
9826: .  mat - the matrix

9828:    Output Parameter:
9829: .  is - if any rows have zero diagonals this contains the list of them

9831:    Level: developer

9833: .seealso: MatMultTranspose(), MatMultAdd(), MatMultTransposeAdd()
9834: @*/
9835: PetscErrorCode MatFindZeroDiagonals(Mat mat,IS *is)
9836: {

9842:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
9843:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");

9845:   if (!mat->ops->findzerodiagonals) {
9846:     Vec                diag;
9847:     const PetscScalar *a;
9848:     PetscInt          *rows;
9849:     PetscInt           rStart, rEnd, r, nrow = 0;

9851:     MatCreateVecs(mat, &diag, NULL);
9852:     MatGetDiagonal(mat, diag);
9853:     MatGetOwnershipRange(mat, &rStart, &rEnd);
9854:     VecGetArrayRead(diag, &a);
9855:     for (r = 0; r < rEnd-rStart; ++r) if (a[r] == 0.0) ++nrow;
9856:     PetscMalloc1(nrow, &rows);
9857:     nrow = 0;
9858:     for (r = 0; r < rEnd-rStart; ++r) if (a[r] == 0.0) rows[nrow++] = r+rStart;
9859:     VecRestoreArrayRead(diag, &a);
9860:     VecDestroy(&diag);
9861:     ISCreateGeneral(PetscObjectComm((PetscObject) mat), nrow, rows, PETSC_OWN_POINTER, is);
9862:   } else {
9863:     (*mat->ops->findzerodiagonals)(mat, is);
9864:   }
9865:   return(0);
9866: }

9868: /*@
9869:    MatFindOffBlockDiagonalEntries - Finds all the rows of a matrix that have entries outside of the main diagonal block (defined by the matrix block size)

9871:    Collective on Mat

9873:    Input Parameter:
9874: .  mat - the matrix

9876:    Output Parameter:
9877: .  is - contains the list of rows with off block diagonal entries

9879:    Level: developer

9881: .seealso: MatMultTranspose(), MatMultAdd(), MatMultTransposeAdd()
9882: @*/
9883: PetscErrorCode MatFindOffBlockDiagonalEntries(Mat mat,IS *is)
9884: {

9890:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
9891:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");

9893:   if (!mat->ops->findoffblockdiagonalentries) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Matrix type %s does not have a find off block diagonal entries defined",((PetscObject)mat)->type_name);
9894:   (*mat->ops->findoffblockdiagonalentries)(mat,is);
9895:   return(0);
9896: }

9898: /*@C
9899:   MatInvertBlockDiagonal - Inverts the block diagonal entries.

9901:   Collective on Mat

9903:   Input Parameters:
9904: . mat - the matrix

9906:   Output Parameters:
9907: . values - the block inverses in column major order (FORTRAN-like)

9909:    Note:
9910:    This routine is not available from Fortran.

9912:   Level: advanced

9914: .seealso: MatInvertBockDiagonalMat
9915: @*/
9916: PetscErrorCode MatInvertBlockDiagonal(Mat mat,const PetscScalar **values)
9917: {

9922:   if (!mat->assembled) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
9923:   if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
9924:   if (!mat->ops->invertblockdiagonal) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Not supported for type %s",((PetscObject)mat)->type_name);
9925:   (*mat->ops->invertblockdiagonal)(mat,values);
9926:   return(0);
9927: }

9929: /*@C
9930:   MatInvertVariableBlockDiagonal - Inverts the block diagonal entries.

9932:   Collective on Mat

9934:   Input Parameters:
9935: + mat - the matrix
9936: . nblocks - the number of blocks
9937: - bsizes - the size of each block

9939:   Output Parameters:
9940: . values - the block inverses in column major order (FORTRAN-like)

9942:    Note:
9943:    This routine is not available from Fortran.

9945:   Level: advanced

9947: .seealso: MatInvertBockDiagonal()
9948: @*/
9949: PetscErrorCode MatInvertVariableBlockDiagonal(Mat mat,PetscInt nblocks,const PetscInt *bsizes,PetscScalar *values)
9950: {

9955:   if (!mat->assembled) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
9956:   if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
9957:   if (!mat->ops->invertvariableblockdiagonal) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Not supported for type",((PetscObject)mat)->type_name);
9958:   (*mat->ops->invertvariableblockdiagonal)(mat,nblocks,bsizes,values);
9959:   return(0);
9960: }

9962: /*@
9963:   MatInvertBlockDiagonalMat - set matrix C to be the inverted block diagonal of matrix A

9965:   Collective on Mat

9967:   Input Parameters:
9968: . A - the matrix

9970:   Output Parameters:
9971: . C - matrix with inverted block diagonal of A.  This matrix should be created and may have its type set.

9973:   Notes: the blocksize of the matrix is used to determine the blocks on the diagonal of C

9975:   Level: advanced

9977: .seealso: MatInvertBockDiagonal()
9978: @*/
9979: PetscErrorCode MatInvertBlockDiagonalMat(Mat A,Mat C)
9980: {
9981:   PetscErrorCode     ierr;
9982:   const PetscScalar *vals;
9983:   PetscInt          *dnnz;
9984:   PetscInt           M,N,m,n,rstart,rend,bs,i,j;

9987:   MatInvertBlockDiagonal(A,&vals);
9988:   MatGetBlockSize(A,&bs);
9989:   MatGetSize(A,&M,&N);
9990:   MatGetLocalSize(A,&m,&n);
9991:   MatSetSizes(C,m,n,M,N);
9992:   MatSetBlockSize(C,bs);
9993:   PetscMalloc1(m/bs,&dnnz);
9994:   for (j = 0; j < m/bs; j++) dnnz[j] = 1;
9995:   MatXAIJSetPreallocation(C,bs,dnnz,NULL,NULL,NULL);
9996:   PetscFree(dnnz);
9997:   MatGetOwnershipRange(C,&rstart,&rend);
9998:   MatSetOption(C,MAT_ROW_ORIENTED,PETSC_FALSE);
9999:   for (i = rstart/bs; i < rend/bs; i++) {
10000:     MatSetValuesBlocked(C,1,&i,1,&i,&vals[(i-rstart/bs)*bs*bs],INSERT_VALUES);
10001:   }
10002:   MatAssemblyBegin(C,MAT_FINAL_ASSEMBLY);
10003:   MatAssemblyEnd(C,MAT_FINAL_ASSEMBLY);
10004:   MatSetOption(C,MAT_ROW_ORIENTED,PETSC_TRUE);
10005:   return(0);
10006: }

10008: /*@C
10009:     MatTransposeColoringDestroy - Destroys a coloring context for matrix product C=A*B^T that was created
10010:     via MatTransposeColoringCreate().

10012:     Collective on MatTransposeColoring

10014:     Input Parameter:
10015: .   c - coloring context

10017:     Level: intermediate

10019: .seealso: MatTransposeColoringCreate()
10020: @*/
10021: PetscErrorCode MatTransposeColoringDestroy(MatTransposeColoring *c)
10022: {
10023:   PetscErrorCode       ierr;
10024:   MatTransposeColoring matcolor=*c;

10027:   if (!matcolor) return(0);
10028:   if (--((PetscObject)matcolor)->refct > 0) {matcolor = 0; return(0);}

10030:   PetscFree3(matcolor->ncolumns,matcolor->nrows,matcolor->colorforrow);
10031:   PetscFree(matcolor->rows);
10032:   PetscFree(matcolor->den2sp);
10033:   PetscFree(matcolor->colorforcol);
10034:   PetscFree(matcolor->columns);
10035:   if (matcolor->brows>0) {
10036:     PetscFree(matcolor->lstart);
10037:   }
10038:   PetscHeaderDestroy(c);
10039:   return(0);
10040: }

10042: /*@C
10043:     MatTransColoringApplySpToDen - Given a symbolic matrix product C=A*B^T for which
10044:     a MatTransposeColoring context has been created, computes a dense B^T by Apply
10045:     MatTransposeColoring to sparse B.

10047:     Collective on MatTransposeColoring

10049:     Input Parameters:
10050: +   B - sparse matrix B
10051: .   Btdense - symbolic dense matrix B^T
10052: -   coloring - coloring context created with MatTransposeColoringCreate()

10054:     Output Parameter:
10055: .   Btdense - dense matrix B^T

10057:     Level: advanced

10059:      Notes:
10060:     These are used internally for some implementations of MatRARt()

10062: .seealso: MatTransposeColoringCreate(), MatTransposeColoringDestroy(), MatTransColoringApplyDenToSp()

10064: @*/
10065: PetscErrorCode MatTransColoringApplySpToDen(MatTransposeColoring coloring,Mat B,Mat Btdense)
10066: {


10074:   if (!B->ops->transcoloringapplysptoden) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Not supported for this matrix type %s",((PetscObject)B)->type_name);
10075:   (B->ops->transcoloringapplysptoden)(coloring,B,Btdense);
10076:   return(0);
10077: }

10079: /*@C
10080:     MatTransColoringApplyDenToSp - Given a symbolic matrix product Csp=A*B^T for which
10081:     a MatTransposeColoring context has been created and a dense matrix Cden=A*Btdense
10082:     in which Btdens is obtained from MatTransColoringApplySpToDen(), recover sparse matrix
10083:     Csp from Cden.

10085:     Collective on MatTransposeColoring

10087:     Input Parameters:
10088: +   coloring - coloring context created with MatTransposeColoringCreate()
10089: -   Cden - matrix product of a sparse matrix and a dense matrix Btdense

10091:     Output Parameter:
10092: .   Csp - sparse matrix

10094:     Level: advanced

10096:      Notes:
10097:     These are used internally for some implementations of MatRARt()

10099: .seealso: MatTransposeColoringCreate(), MatTransposeColoringDestroy(), MatTransColoringApplySpToDen()

10101: @*/
10102: PetscErrorCode MatTransColoringApplyDenToSp(MatTransposeColoring matcoloring,Mat Cden,Mat Csp)
10103: {


10111:   if (!Csp->ops->transcoloringapplydentosp) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Not supported for this matrix type %s",((PetscObject)Csp)->type_name);
10112:   (Csp->ops->transcoloringapplydentosp)(matcoloring,Cden,Csp);
10113:   return(0);
10114: }

10116: /*@C
10117:    MatTransposeColoringCreate - Creates a matrix coloring context for matrix product C=A*B^T.

10119:    Collective on Mat

10121:    Input Parameters:
10122: +  mat - the matrix product C
10123: -  iscoloring - the coloring of the matrix; usually obtained with MatColoringCreate() or DMCreateColoring()

10125:     Output Parameter:
10126: .   color - the new coloring context

10128:     Level: intermediate

10130: .seealso: MatTransposeColoringDestroy(),  MatTransColoringApplySpToDen(),
10131:            MatTransColoringApplyDenToSp()
10132: @*/
10133: PetscErrorCode MatTransposeColoringCreate(Mat mat,ISColoring iscoloring,MatTransposeColoring *color)
10134: {
10135:   MatTransposeColoring c;
10136:   MPI_Comm             comm;
10137:   PetscErrorCode       ierr;

10140:   PetscLogEventBegin(MAT_TransposeColoringCreate,mat,0,0,0);
10141:   PetscObjectGetComm((PetscObject)mat,&comm);
10142:   PetscHeaderCreate(c,MAT_TRANSPOSECOLORING_CLASSID,"MatTransposeColoring","Matrix product C=A*B^T via coloring","Mat",comm,MatTransposeColoringDestroy,NULL);

10144:   c->ctype = iscoloring->ctype;
10145:   if (mat->ops->transposecoloringcreate) {
10146:     (*mat->ops->transposecoloringcreate)(mat,iscoloring,c);
10147:   } else SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Code not yet written for matrix type %s",((PetscObject)mat)->type_name);

10149:   *color = c;
10150:   PetscLogEventEnd(MAT_TransposeColoringCreate,mat,0,0,0);
10151:   return(0);
10152: }

10154: /*@
10155:       MatGetNonzeroState - Returns a 64 bit integer representing the current state of nonzeros in the matrix. If the
10156:         matrix has had no new nonzero locations added to the matrix since the previous call then the value will be the
10157:         same, otherwise it will be larger

10159:      Not Collective

10161:   Input Parameter:
10162: .    A  - the matrix

10164:   Output Parameter:
10165: .    state - the current state

10167:   Notes:
10168:     You can only compare states from two different calls to the SAME matrix, you cannot compare calls between
10169:          different matrices

10171:   Level: intermediate

10173: @*/
10174: PetscErrorCode MatGetNonzeroState(Mat mat,PetscObjectState *state)
10175: {
10178:   *state = mat->nonzerostate;
10179:   return(0);
10180: }

10182: /*@
10183:       MatCreateMPIMatConcatenateSeqMat - Creates a single large PETSc matrix by concatenating sequential
10184:                  matrices from each processor

10186:     Collective

10188:    Input Parameters:
10189: +    comm - the communicators the parallel matrix will live on
10190: .    seqmat - the input sequential matrices
10191: .    n - number of local columns (or PETSC_DECIDE)
10192: -    reuse - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX

10194:    Output Parameter:
10195: .    mpimat - the parallel matrix generated

10197:     Level: advanced

10199:    Notes:
10200:     The number of columns of the matrix in EACH processor MUST be the same.

10202: @*/
10203: PetscErrorCode MatCreateMPIMatConcatenateSeqMat(MPI_Comm comm,Mat seqmat,PetscInt n,MatReuse reuse,Mat *mpimat)
10204: {

10208:   if (!seqmat->ops->creatempimatconcatenateseqmat) SETERRQ1(PetscObjectComm((PetscObject)seqmat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)seqmat)->type_name);
10209:   if (reuse == MAT_REUSE_MATRIX && seqmat == *mpimat) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONG,"MAT_REUSE_MATRIX means reuse the matrix passed in as the final argument, not the original matrix");

10211:   PetscLogEventBegin(MAT_Merge,seqmat,0,0,0);
10212:   (*seqmat->ops->creatempimatconcatenateseqmat)(comm,seqmat,n,reuse,mpimat);
10213:   PetscLogEventEnd(MAT_Merge,seqmat,0,0,0);
10214:   return(0);
10215: }

10217: /*@
10218:      MatSubdomainsCreateCoalesce - Creates index subdomains by coalescing adjacent
10219:                  ranks' ownership ranges.

10221:     Collective on A

10223:    Input Parameters:
10224: +    A   - the matrix to create subdomains from
10225: -    N   - requested number of subdomains


10228:    Output Parameters:
10229: +    n   - number of subdomains resulting on this rank
10230: -    iss - IS list with indices of subdomains on this rank

10232:     Level: advanced

10234:     Notes:
10235:     number of subdomains must be smaller than the communicator size
10236: @*/
10237: PetscErrorCode MatSubdomainsCreateCoalesce(Mat A,PetscInt N,PetscInt *n,IS *iss[])
10238: {
10239:   MPI_Comm        comm,subcomm;
10240:   PetscMPIInt     size,rank,color;
10241:   PetscInt        rstart,rend,k;
10242:   PetscErrorCode  ierr;

10245:   PetscObjectGetComm((PetscObject)A,&comm);
10246:   MPI_Comm_size(comm,&size);
10247:   MPI_Comm_rank(comm,&rank);
10248:   if (N < 1 || N >= (PetscInt)size) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONG,"number of subdomains must be > 0 and < %D, got N = %D",size,N);
10249:   *n = 1;
10250:   k = ((PetscInt)size)/N + ((PetscInt)size%N>0); /* There are up to k ranks to a color */
10251:   color = rank/k;
10252:   MPI_Comm_split(comm,color,rank,&subcomm);
10253:   PetscMalloc1(1,iss);
10254:   MatGetOwnershipRange(A,&rstart,&rend);
10255:   ISCreateStride(subcomm,rend-rstart,rstart,1,iss[0]);
10256:   MPI_Comm_free(&subcomm);
10257:   return(0);
10258: }

10260: /*@
10261:    MatGalerkin - Constructs the coarse grid problem via Galerkin projection.

10263:    If the interpolation and restriction operators are the same, uses MatPtAP.
10264:    If they are not the same, use MatMatMatMult.

10266:    Once the coarse grid problem is constructed, correct for interpolation operators
10267:    that are not of full rank, which can legitimately happen in the case of non-nested
10268:    geometric multigrid.

10270:    Input Parameters:
10271: +  restrct - restriction operator
10272: .  dA - fine grid matrix
10273: .  interpolate - interpolation operator
10274: .  reuse - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
10275: -  fill - expected fill, use PETSC_DEFAULT if you do not have a good estimate

10277:    Output Parameters:
10278: .  A - the Galerkin coarse matrix

10280:    Options Database Key:
10281: .  -pc_mg_galerkin <both,pmat,mat,none>

10283:    Level: developer

10285: .seealso: MatPtAP(), MatMatMatMult()
10286: @*/
10287: PetscErrorCode  MatGalerkin(Mat restrct, Mat dA, Mat interpolate, MatReuse reuse, PetscReal fill, Mat *A)
10288: {
10290:   IS             zerorows;
10291:   Vec            diag;

10294:   if (reuse == MAT_INPLACE_MATRIX) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Inplace product not supported");
10295:   /* Construct the coarse grid matrix */
10296:   if (interpolate == restrct) {
10297:     MatPtAP(dA,interpolate,reuse,fill,A);
10298:   } else {
10299:     MatMatMatMult(restrct,dA,interpolate,reuse,fill,A);
10300:   }

10302:   /* If the interpolation matrix is not of full rank, A will have zero rows.
10303:      This can legitimately happen in the case of non-nested geometric multigrid.
10304:      In that event, we set the rows of the matrix to the rows of the identity,
10305:      ignoring the equations (as the RHS will also be zero). */

10307:   MatFindZeroRows(*A, &zerorows);

10309:   if (zerorows != NULL) { /* if there are any zero rows */
10310:     MatCreateVecs(*A, &diag, NULL);
10311:     MatGetDiagonal(*A, diag);
10312:     VecISSet(diag, zerorows, 1.0);
10313:     MatDiagonalSet(*A, diag, INSERT_VALUES);
10314:     VecDestroy(&diag);
10315:     ISDestroy(&zerorows);
10316:   }
10317:   return(0);
10318: }

10320: /*@C
10321:     MatSetOperation - Allows user to set a matrix operation for any matrix type

10323:    Logically Collective on Mat

10325:     Input Parameters:
10326: +   mat - the matrix
10327: .   op - the name of the operation
10328: -   f - the function that provides the operation

10330:    Level: developer

10332:     Usage:
10333: $      extern PetscErrorCode usermult(Mat,Vec,Vec);
10334: $      MatCreateXXX(comm,...&A);
10335: $      MatSetOperation(A,MATOP_MULT,(void(*)(void))usermult);

10337:     Notes:
10338:     See the file include/petscmat.h for a complete list of matrix
10339:     operations, which all have the form MATOP_<OPERATION>, where
10340:     <OPERATION> is the name (in all capital letters) of the
10341:     user interface routine (e.g., MatMult() -> MATOP_MULT).

10343:     All user-provided functions (except for MATOP_DESTROY) should have the same calling
10344:     sequence as the usual matrix interface routines, since they
10345:     are intended to be accessed via the usual matrix interface
10346:     routines, e.g.,
10347: $       MatMult(Mat,Vec,Vec) -> usermult(Mat,Vec,Vec)

10349:     In particular each function MUST return an error code of 0 on success and
10350:     nonzero on failure.

10352:     This routine is distinct from MatShellSetOperation() in that it can be called on any matrix type.

10354: .seealso: MatGetOperation(), MatCreateShell(), MatShellSetContext(), MatShellSetOperation()
10355: @*/
10356: PetscErrorCode MatSetOperation(Mat mat,MatOperation op,void (*f)(void))
10357: {
10360:   if (op == MATOP_VIEW && !mat->ops->viewnative && f != (void (*)(void))(mat->ops->view)) {
10361:     mat->ops->viewnative = mat->ops->view;
10362:   }
10363:   (((void(**)(void))mat->ops)[op]) = f;
10364:   return(0);
10365: }

10367: /*@C
10368:     MatGetOperation - Gets a matrix operation for any matrix type.

10370:     Not Collective

10372:     Input Parameters:
10373: +   mat - the matrix
10374: -   op - the name of the operation

10376:     Output Parameter:
10377: .   f - the function that provides the operation

10379:     Level: developer

10381:     Usage:
10382: $      PetscErrorCode (*usermult)(Mat,Vec,Vec);
10383: $      MatGetOperation(A,MATOP_MULT,(void(**)(void))&usermult);

10385:     Notes:
10386:     See the file include/petscmat.h for a complete list of matrix
10387:     operations, which all have the form MATOP_<OPERATION>, where
10388:     <OPERATION> is the name (in all capital letters) of the
10389:     user interface routine (e.g., MatMult() -> MATOP_MULT).

10391:     This routine is distinct from MatShellGetOperation() in that it can be called on any matrix type.

10393: .seealso: MatSetOperation(), MatCreateShell(), MatShellGetContext(), MatShellGetOperation()
10394: @*/
10395: PetscErrorCode MatGetOperation(Mat mat,MatOperation op,void(**f)(void))
10396: {
10399:   *f = (((void (**)(void))mat->ops)[op]);
10400:   return(0);
10401: }

10403: /*@
10404:     MatHasOperation - Determines whether the given matrix supports the particular
10405:     operation.

10407:    Not Collective

10409:    Input Parameters:
10410: +  mat - the matrix
10411: -  op - the operation, for example, MATOP_GET_DIAGONAL

10413:    Output Parameter:
10414: .  has - either PETSC_TRUE or PETSC_FALSE

10416:    Level: advanced

10418:    Notes:
10419:    See the file include/petscmat.h for a complete list of matrix
10420:    operations, which all have the form MATOP_<OPERATION>, where
10421:    <OPERATION> is the name (in all capital letters) of the
10422:    user-level routine.  E.g., MatNorm() -> MATOP_NORM.

10424: .seealso: MatCreateShell()
10425: @*/
10426: PetscErrorCode MatHasOperation(Mat mat,MatOperation op,PetscBool *has)
10427: {

10434:   if (mat->ops->hasoperation) {
10435:     (*mat->ops->hasoperation)(mat,op,has);
10436:   } else {
10437:     if (((void**)mat->ops)[op]) *has =  PETSC_TRUE;
10438:     else {
10439:       *has = PETSC_FALSE;
10440:       if (op == MATOP_CREATE_SUBMATRIX) {
10441:         PetscMPIInt size;

10443:         MPI_Comm_size(PetscObjectComm((PetscObject)mat),&size);
10444:         if (size == 1) {
10445:           MatHasOperation(mat,MATOP_CREATE_SUBMATRICES,has);
10446:         }
10447:       }
10448:     }
10449:   }
10450:   return(0);
10451: }

10453: /*@
10454:     MatHasCongruentLayouts - Determines whether the rows and columns layouts
10455:     of the matrix are congruent

10457:    Collective on mat

10459:    Input Parameters:
10460: .  mat - the matrix

10462:    Output Parameter:
10463: .  cong - either PETSC_TRUE or PETSC_FALSE

10465:    Level: beginner

10467:    Notes:

10469: .seealso: MatCreate(), MatSetSizes()
10470: @*/
10471: PetscErrorCode MatHasCongruentLayouts(Mat mat,PetscBool *cong)
10472: {

10479:   if (!mat->rmap || !mat->cmap) {
10480:     *cong = mat->rmap == mat->cmap ? PETSC_TRUE : PETSC_FALSE;
10481:     return(0);
10482:   }
10483:   if (mat->congruentlayouts == PETSC_DECIDE) { /* first time we compare rows and cols layouts */
10484:     PetscLayoutCompare(mat->rmap,mat->cmap,cong);
10485:     if (*cong) mat->congruentlayouts = 1;
10486:     else       mat->congruentlayouts = 0;
10487:   } else *cong = mat->congruentlayouts ? PETSC_TRUE : PETSC_FALSE;
10488:   return(0);
10489: }

10491: /*@
10492:     MatFreeIntermediateDataStructures - Free intermediate data structures created for reuse,
10493:     e.g., matrx product of MatPtAP.

10495:    Collective on mat

10497:    Input Parameters:
10498: .  mat - the matrix

10500:    Output Parameter:
10501: .  mat - the matrix with intermediate data structures released

10503:    Level: advanced

10505:    Notes:

10507: .seealso: MatPtAP(), MatMatMult()
10508: @*/
10509: PetscErrorCode MatFreeIntermediateDataStructures(Mat mat)
10510: {

10516:   if (mat->ops->freeintermediatedatastructures) {
10517:     (*mat->ops->freeintermediatedatastructures)(mat);
10518:   }
10519:   return(0);
10520: }