Actual source code: matrix.c

petsc-master 2020-01-21
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 the 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         iascii,ibinary,isstring;
977:   PetscViewerFormat format;
978:   PetscMPIInt       size;
979: #if defined(PETSC_HAVE_SAWS)
980:   PetscBool         issaws;
981: #endif

986:   if (!viewer) {
987:     PetscViewerASCIIGetStdout(PetscObjectComm((PetscObject)mat),&viewer);
988:   }
991:   MatCheckPreallocated(mat,1);
992:   PetscViewerGetFormat(viewer,&format);
993:   MPI_Comm_size(PetscObjectComm((PetscObject)mat),&size);
994:   if (size == 1 && format == PETSC_VIEWER_LOAD_BALANCE) return(0);
995:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERBINARY,&ibinary);
996:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERSTRING,&isstring);
997:   if (ibinary) {
998:     PetscBool mpiio;
999:     PetscViewerBinaryGetUseMPIIO(viewer,&mpiio);
1000:     if (mpiio) SETERRQ(PetscObjectComm((PetscObject)viewer),PETSC_ERR_SUP,"PETSc matrix viewers do not support using MPI-IO, turn off that flag");
1001:   }

1003:   PetscLogEventBegin(MAT_View,mat,viewer,0,0);
1004:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERASCII,&iascii);
1005:   if ((!iascii || (format != PETSC_VIEWER_ASCII_INFO || format == PETSC_VIEWER_ASCII_INFO_DETAIL)) && mat->factortype) {
1006:     SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"No viewers for factored matrix except ASCII info or info_detailed");
1007:   }

1009: #if defined(PETSC_HAVE_SAWS)
1010:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERSAWS,&issaws);
1011: #endif
1012:   if (iascii) {
1013:     if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ORDER,"Must call MatAssemblyBegin/End() before viewing matrix");
1014:     PetscObjectPrintClassNamePrefixType((PetscObject)mat,viewer);
1015:     if (format == PETSC_VIEWER_ASCII_INFO || format == PETSC_VIEWER_ASCII_INFO_DETAIL) {
1016:       MatNullSpace nullsp,transnullsp;

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

1049:     PetscObjectName((PetscObject)mat);
1050:     MPI_Comm_rank(PETSC_COMM_WORLD,&rank);
1051:     if (!((PetscObject)mat)->amsmem && !rank) {
1052:       PetscObjectViewSAWs((PetscObject)mat,viewer);
1053:     }
1054: #endif
1055:   } else if (isstring) {
1056:     const char *type;
1057:     MatGetType(mat,&type);
1058:     PetscViewerStringSPrintf(viewer," MatType: %-7.7s",type);
1059:     if (mat->ops->view) {(*mat->ops->view)(mat,viewer);}
1060:   }
1061:   if ((format == PETSC_VIEWER_NATIVE || format == PETSC_VIEWER_LOAD_BALANCE) && mat->ops->viewnative) {
1062:     PetscViewerASCIIPushTab(viewer);
1063:     (*mat->ops->viewnative)(mat,viewer);
1064:     PetscViewerASCIIPopTab(viewer);
1065:   } else if (mat->ops->view) {
1066:     PetscViewerASCIIPushTab(viewer);
1067:     (*mat->ops->view)(mat,viewer);
1068:     PetscViewerASCIIPopTab(viewer);
1069:   }
1070:   if (iascii) {
1071:     PetscViewerGetFormat(viewer,&format);
1072:     if (format == PETSC_VIEWER_ASCII_INFO || format == PETSC_VIEWER_ASCII_INFO_DETAIL) {
1073:       PetscViewerASCIIPopTab(viewer);
1074:     }
1075:   }
1076:   PetscLogEventEnd(MAT_View,mat,viewer,0,0);
1077:   return(0);
1078: }

1080: #if defined(PETSC_USE_DEBUG)
1081: #include <../src/sys/totalview/tv_data_display.h>
1082: PETSC_UNUSED static int TV_display_type(const struct _p_Mat *mat)
1083: {
1084:   TV_add_row("Local rows", "int", &mat->rmap->n);
1085:   TV_add_row("Local columns", "int", &mat->cmap->n);
1086:   TV_add_row("Global rows", "int", &mat->rmap->N);
1087:   TV_add_row("Global columns", "int", &mat->cmap->N);
1088:   TV_add_row("Typename", TV_ascii_string_type, ((PetscObject)mat)->type_name);
1089:   return TV_format_OK;
1090: }
1091: #endif

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

1099:    Collective on PetscViewer

1101:    Input Parameters:
1102: +  newmat - the newly loaded matrix, this needs to have been created with MatCreate()
1103:             or some related function before a call to MatLoad()
1104: -  viewer - binary/HDF5 file viewer

1106:    Options Database Keys:
1107:    Used with block matrix formats (MATSEQBAIJ,  ...) to specify
1108:    block size
1109: .    -matload_block_size <bs>

1111:    Level: beginner

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

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

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

1126:    In parallel, each processor can load a subset of rows (or the
1127:    entire matrix).  This routine is especially useful when a large
1128:    matrix is stored on disk and only part of it is desired on each
1129:    processor.  For example, a parallel solver may access only some of
1130:    the rows from each processor.  The algorithm used here reads
1131:    relatively small blocks of data rather than reading the entire
1132:    matrix and then subsetting it.

1134:    Viewer's PetscViewerType must be either PETSCVIEWERBINARY or PETSCVIEWERHDF5.
1135:    Such viewer can be created using PetscViewerBinaryOpen()/PetscViewerHDF5Open(),
1136:    or the sequence like
1137: $    PetscViewer v;
1138: $    PetscViewerCreate(PETSC_COMM_WORLD,&v);
1139: $    PetscViewerSetType(v,PETSCVIEWERBINARY);
1140: $    PetscViewerSetFromOptions(v);
1141: $    PetscViewerFileSetMode(v,FILE_MODE_READ);
1142: $    PetscViewerFileSetName(v,"datafile");
1143:    The optional PetscViewerSetFromOptions() call allows to override PetscViewerSetType() using option
1144: $ -viewer_type {binary,hdf5}

1146:    See the example src/ksp/ksp/examples/tutorials/ex27.c with the first approach,
1147:    and src/mat/examples/tutorials/ex10.c with the second approach.

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

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

1160: $    PetscInt    MAT_FILE_CLASSID
1161: $    PetscInt    number of rows
1162: $    PetscInt    number of columns
1163: $    PetscInt    total number of nonzeros
1164: $    PetscInt    *number nonzeros in each row
1165: $    PetscInt    *column indices of all nonzeros (starting index is zero)
1166: $    PetscScalar *values of all nonzeros

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

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

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

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

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

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

1196:    Corresponding MatView() is not yet implemented.

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

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

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

1209:  @*/
1210: PetscErrorCode MatLoad(Mat newmat,PetscViewer viewer)
1211: {
1213:   PetscBool      flg;


1219:   if (!((PetscObject)newmat)->type_name) {
1220:     MatSetType(newmat,MATAIJ);
1221:   }

1223:   flg  = PETSC_FALSE;
1224:   PetscOptionsGetBool(((PetscObject)newmat)->options,((PetscObject)newmat)->prefix,"-matload_symmetric",&flg,NULL);
1225:   if (flg) {
1226:     MatSetOption(newmat,MAT_SYMMETRIC,PETSC_TRUE);
1227:     MatSetOption(newmat,MAT_SYMMETRY_ETERNAL,PETSC_TRUE);
1228:   }
1229:   flg  = PETSC_FALSE;
1230:   PetscOptionsGetBool(((PetscObject)newmat)->options,((PetscObject)newmat)->prefix,"-matload_spd",&flg,NULL);
1231:   if (flg) {
1232:     MatSetOption(newmat,MAT_SPD,PETSC_TRUE);
1233:   }

1235:   if (!newmat->ops->load) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"MatLoad is not supported for type %s",((PetscObject)newmat)->type_name);
1236:   PetscLogEventBegin(MAT_Load,viewer,0,0,0);
1237:   (*newmat->ops->load)(newmat,viewer);
1238:   PetscLogEventEnd(MAT_Load,viewer,0,0,0);
1239:   return(0);
1240: }

1242: PetscErrorCode MatDestroy_Redundant(Mat_Redundant **redundant)
1243: {
1245:   Mat_Redundant  *redund = *redundant;
1246:   PetscInt       i;

1249:   if (redund){
1250:     if (redund->matseq) { /* via MatCreateSubMatrices()  */
1251:       ISDestroy(&redund->isrow);
1252:       ISDestroy(&redund->iscol);
1253:       MatDestroySubMatrices(1,&redund->matseq);
1254:     } else {
1255:       PetscFree2(redund->send_rank,redund->recv_rank);
1256:       PetscFree(redund->sbuf_j);
1257:       PetscFree(redund->sbuf_a);
1258:       for (i=0; i<redund->nrecvs; i++) {
1259:         PetscFree(redund->rbuf_j[i]);
1260:         PetscFree(redund->rbuf_a[i]);
1261:       }
1262:       PetscFree4(redund->sbuf_nz,redund->rbuf_nz,redund->rbuf_j,redund->rbuf_a);
1263:     }

1265:     if (redund->subcomm) {
1266:       PetscCommDestroy(&redund->subcomm);
1267:     }
1268:     PetscFree(redund);
1269:   }
1270:   return(0);
1271: }

1273: /*@
1274:    MatDestroy - Frees space taken by a matrix.

1276:    Collective on Mat

1278:    Input Parameter:
1279: .  A - the matrix

1281:    Level: beginner

1283: @*/
1284: PetscErrorCode MatDestroy(Mat *A)
1285: {

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

1293:   /* if memory was published with SAWs then destroy it */
1294:   PetscObjectSAWsViewOff((PetscObject)*A);
1295:   if ((*A)->ops->destroy) {
1296:     (*(*A)->ops->destroy)(*A);
1297:   }

1299:   PetscFree((*A)->defaultvectype);
1300:   PetscFree((*A)->bsizes);
1301:   PetscFree((*A)->solvertype);
1302:   MatDestroy_Redundant(&(*A)->redundant);
1303:   MatNullSpaceDestroy(&(*A)->nullsp);
1304:   MatNullSpaceDestroy(&(*A)->transnullsp);
1305:   MatNullSpaceDestroy(&(*A)->nearnullsp);
1306:   MatDestroy(&(*A)->schur);
1307:   PetscLayoutDestroy(&(*A)->rmap);
1308:   PetscLayoutDestroy(&(*A)->cmap);
1309:   PetscHeaderDestroy(A);
1310:   return(0);
1311: }

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

1318:    Not Collective

1320:    Input Parameters:
1321: +  mat - the matrix
1322: .  v - a logically two-dimensional array of values
1323: .  m, idxm - the number of rows and their global indices
1324: .  n, idxn - the number of columns and their global indices
1325: -  addv - either ADD_VALUES or INSERT_VALUES, where
1326:    ADD_VALUES adds values to any existing entries, and
1327:    INSERT_VALUES replaces existing entries with new values

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

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

1335:    Calls to MatSetValues() with the INSERT_VALUES and ADD_VALUES
1336:    options cannot be mixed without intervening calls to the assembly
1337:    routines.

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

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

1347:    Efficiency Alert:
1348:    The routine MatSetValuesBlocked() may offer much better efficiency
1349:    for users of block sparse formats (MATSEQBAIJ and MATMPIBAIJ).

1351:    Level: beginner

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

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

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

1375:   if (mat->insertmode == NOT_SET_VALUES) {
1376:     mat->insertmode = addv;
1377:   }
1378: #if defined(PETSC_USE_DEBUG)
1379:   else if (mat->insertmode != addv) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Cannot mix add values and insert values");
1380:   if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
1381:   if (!mat->ops->setvalues) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);

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

1395:   if (mat->assembled) {
1396:     mat->was_assembled = PETSC_TRUE;
1397:     mat->assembled     = PETSC_FALSE;
1398:   }
1399:   PetscLogEventBegin(MAT_SetValues,mat,0,0,0);
1400:   (*mat->ops->setvalues)(mat,m,idxm,n,idxn,v,addv);
1401:   PetscLogEventEnd(MAT_SetValues,mat,0,0,0);
1402:   return(0);
1403: }


1406: /*@
1407:    MatSetValuesRowLocal - Inserts a row (block row for BAIJ matrices) of nonzero
1408:         values into a matrix

1410:    Not Collective

1412:    Input Parameters:
1413: +  mat - the matrix
1414: .  row - the (block) row to set
1415: -  v - a logically two-dimensional array of values

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

1420:    All the nonzeros in the row must be provided

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

1424:    The row must belong to this process

1426:    Level: intermediate

1428: .seealso: MatSetOption(), MatAssemblyBegin(), MatAssemblyEnd(), MatSetValuesBlocked(), MatSetValuesLocal(),
1429:           InsertMode, INSERT_VALUES, ADD_VALUES, MatSetValues(), MatSetValuesRow(), MatSetLocalToGlobalMapping()
1430: @*/
1431: PetscErrorCode MatSetValuesRowLocal(Mat mat,PetscInt row,const PetscScalar v[])
1432: {
1434:   PetscInt       globalrow;

1440:   ISLocalToGlobalMappingApply(mat->rmap->mapping,1,&row,&globalrow);
1441:   MatSetValuesRow(mat,globalrow,v);
1442:   return(0);
1443: }

1445: /*@
1446:    MatSetValuesRow - Inserts a row (block row for BAIJ matrices) of nonzero
1447:         values into a matrix

1449:    Not Collective

1451:    Input Parameters:
1452: +  mat - the matrix
1453: .  row - the (block) row to set
1454: -  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

1456:    Notes:
1457:    The values, v, are column-oriented for the block version.

1459:    All the nonzeros in the row must be provided

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

1463:    The row must belong to this process

1465:    Level: advanced

1467: .seealso: MatSetOption(), MatAssemblyBegin(), MatAssemblyEnd(), MatSetValuesBlocked(), MatSetValuesLocal(),
1468:           InsertMode, INSERT_VALUES, ADD_VALUES, MatSetValues()
1469: @*/
1470: PetscErrorCode MatSetValuesRow(Mat mat,PetscInt row,const PetscScalar v[])
1471: {

1477:   MatCheckPreallocated(mat,1);
1479: #if defined(PETSC_USE_DEBUG)
1480:   if (mat->insertmode == ADD_VALUES) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Cannot mix add and insert values");
1481:   if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
1482: #endif
1483:   mat->insertmode = INSERT_VALUES;

1485:   if (mat->assembled) {
1486:     mat->was_assembled = PETSC_TRUE;
1487:     mat->assembled     = PETSC_FALSE;
1488:   }
1489:   PetscLogEventBegin(MAT_SetValues,mat,0,0,0);
1490:   if (!mat->ops->setvaluesrow) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
1491:   (*mat->ops->setvaluesrow)(mat,row,v);
1492:   PetscLogEventEnd(MAT_SetValues,mat,0,0,0);
1493:   return(0);
1494: }

1496: /*@
1497:    MatSetValuesStencil - Inserts or adds a block of values into a matrix.
1498:      Using structured grid indexing

1500:    Not Collective

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

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

1516:    Calls to MatSetValuesStencil() with the INSERT_VALUES and ADD_VALUES
1517:    options cannot be mixed without intervening calls to the assembly
1518:    routines.

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

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

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

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

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

1536:    In Fortran idxm and idxn should be declared as
1537: $     MatStencil idxm(4,m),idxn(4,n)
1538:    and the values inserted using
1539: $    idxm(MatStencil_i,1) = i
1540: $    idxm(MatStencil_j,1) = j
1541: $    idxm(MatStencil_k,1) = k
1542: $    idxm(MatStencil_c,1) = c
1543:    etc

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

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

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

1556:    Efficiency Alert:
1557:    The routine MatSetValuesBlockedStencil() may offer much better efficiency
1558:    for users of block sparse formats (MATSEQBAIJ and MATMPIBAIJ).

1560:    Level: beginner

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

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

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

1610: /*@
1611:    MatSetValuesBlockedStencil - Inserts or adds a block of values into a matrix.
1612:      Using structured grid indexing

1614:    Not Collective

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

1627:    Notes:
1628:    By default the values, v, are row-oriented and unsorted.
1629:    See MatSetOption() for other options.

1631:    Calls to MatSetValuesBlockedStencil() with the INSERT_VALUES and ADD_VALUES
1632:    options cannot be mixed without intervening calls to the assembly
1633:    routines.

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

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

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

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

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

1651:    In Fortran idxm and idxn should be declared as
1652: $     MatStencil idxm(4,m),idxn(4,n)
1653:    and the values inserted using
1654: $    idxm(MatStencil_i,1) = i
1655: $    idxm(MatStencil_j,1) = j
1656: $    idxm(MatStencil_k,1) = k
1657:    etc

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

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

1667:    Level: beginner

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

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

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

1719: /*@
1720:    MatSetStencil - Sets the grid information for setting values into a matrix via
1721:         MatSetValuesStencil()

1723:    Not Collective

1725:    Input Parameters:
1726: +  mat - the matrix
1727: .  dim - dimension of the grid 1, 2, or 3
1728: .  dims - number of grid points in x, y, and z direction, including ghost points on your processor
1729: .  starts - starting point of ghost nodes on your processor in x, y, and z direction
1730: -  dof - number of degrees of freedom per node


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

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

1739:    Level: beginner

1741: .seealso: MatSetOption(), MatAssemblyBegin(), MatAssemblyEnd(), MatSetValuesBlocked(), MatSetValuesLocal()
1742:           MatSetValues(), MatSetValuesBlockedStencil(), MatSetValuesStencil()
1743: @*/
1744: PetscErrorCode MatSetStencil(Mat mat,PetscInt dim,const PetscInt dims[],const PetscInt starts[],PetscInt dof)
1745: {
1746:   PetscInt i;


1753:   mat->stencil.dim = dim + (dof > 1);
1754:   for (i=0; i<dim; i++) {
1755:     mat->stencil.dims[i]   = dims[dim-i-1];      /* copy the values in backwards */
1756:     mat->stencil.starts[i] = starts[dim-i-1];
1757:   }
1758:   mat->stencil.dims[dim]   = dof;
1759:   mat->stencil.starts[dim] = 0;
1760:   mat->stencil.noc         = (PetscBool)(dof == 1);
1761:   return(0);
1762: }

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

1767:    Not Collective

1769:    Input Parameters:
1770: +  mat - the matrix
1771: .  v - a logically two-dimensional array of values
1772: .  m, idxm - the number of block rows and their global block indices
1773: .  n, idxn - the number of block columns and their global block indices
1774: -  addv - either ADD_VALUES or INSERT_VALUES, where
1775:    ADD_VALUES adds values to any existing entries, and
1776:    INSERT_VALUES replaces existing entries with new values

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

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

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

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

1794:    Calls to MatSetValuesBlocked() with the INSERT_VALUES and ADD_VALUES
1795:    options cannot be mixed without intervening calls to the assembly
1796:    routines.

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

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

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

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

1827:    Level: intermediate

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

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

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

1886: /*@
1887:    MatGetValues - Gets a block of values from a matrix.

1889:    Not Collective; currently only returns a local block

1891:    Input Parameters:
1892: +  mat - the matrix
1893: .  v - a logically two-dimensional array for storing the values
1894: .  m, idxm - the number of rows and their global indices
1895: -  n, idxn - the number of columns and their global indices

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

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

1905:    MatGetValues() requires that the matrix has been assembled
1906:    with MatAssemblyBegin()/MatAssemblyEnd().  Thus, calls to
1907:    MatSetValues() and MatGetValues() CANNOT be made in succession
1908:    without intermediate matrix assembly.

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

1913:    Level: advanced

1915: .seealso: MatGetRow(), MatCreateSubMatrices(), MatSetValues()
1916: @*/
1917: PetscErrorCode MatGetValues(Mat mat,PetscInt m,const PetscInt idxm[],PetscInt n,const PetscInt idxn[],PetscScalar v[])
1918: {

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

1933:   PetscLogEventBegin(MAT_GetValues,mat,0,0,0);
1934:   (*mat->ops->getvalues)(mat,m,idxm,n,idxn,v);
1935:   PetscLogEventEnd(MAT_GetValues,mat,0,0,0);
1936:   return(0);
1937: }

1939: /*@C
1940:    MatGetValuesLocal - retrieves values into certain locations of a matrix,
1941:    using a local numbering of the nodes.

1943:    Not Collective

1945:    Input Parameters:
1946: +  mat - the matrix
1947: .  nrow, irow - number of rows and their local indices
1948: -  ncol, icol - number of columns and their local indices

1950:    Output Parameter:
1951: .  y -  a logically two-dimensional array of values

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

1956:    Level: advanced

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

1962: .seealso:  MatAssemblyBegin(), MatAssemblyEnd(), MatSetValues(), MatSetLocalToGlobalMapping(),
1963:            MatSetValuesLocal()
1964: @*/
1965: PetscErrorCode MatGetValuesLocal(Mat mat,PetscInt nrow,const PetscInt irow[],PetscInt ncol,const PetscInt icol[],PetscScalar y[])
1966: {

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

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

2007:   Not Collective

2009:   Input Parameters:
2010: + mat - the matrix
2011: . nb - the number of blocks
2012: . bs - the number of rows (and columns) in each block
2013: . rows - a concatenation of the rows for each block
2014: - v - a concatenation of logically two-dimensional arrays of values

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

2019:   Level: advanced

2021: .seealso: MatSetOption(), MatAssemblyBegin(), MatAssemblyEnd(), MatSetValuesBlocked(), MatSetValuesLocal(),
2022:           InsertMode, INSERT_VALUES, ADD_VALUES, MatSetValues()
2023: @*/
2024: PetscErrorCode MatSetValuesBatch(Mat mat, PetscInt nb, PetscInt bs, PetscInt rows[], const PetscScalar v[])
2025: {

2033: #if defined(PETSC_USE_DEBUG)
2034:   if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2035: #endif

2037:   PetscLogEventBegin(MAT_SetValuesBatch,mat,0,0,0);
2038:   if (mat->ops->setvaluesbatch) {
2039:     (*mat->ops->setvaluesbatch)(mat,nb,bs,rows,v);
2040:   } else {
2041:     PetscInt b;
2042:     for (b = 0; b < nb; ++b) {
2043:       MatSetValues(mat, bs, &rows[b*bs], bs, &rows[b*bs], &v[b*bs*bs], ADD_VALUES);
2044:     }
2045:   }
2046:   PetscLogEventEnd(MAT_SetValuesBatch,mat,0,0,0);
2047:   return(0);
2048: }

2050: /*@
2051:    MatSetLocalToGlobalMapping - Sets a local-to-global numbering for use by
2052:    the routine MatSetValuesLocal() to allow users to insert matrix entries
2053:    using a local (per-processor) numbering.

2055:    Not Collective

2057:    Input Parameters:
2058: +  x - the matrix
2059: .  rmapping - row mapping created with ISLocalToGlobalMappingCreate()   or ISLocalToGlobalMappingCreateIS()
2060: - cmapping - column mapping

2062:    Level: intermediate


2065: .seealso:  MatAssemblyBegin(), MatAssemblyEnd(), MatSetValues(), MatSetValuesLocal()
2066: @*/
2067: PetscErrorCode MatSetLocalToGlobalMapping(Mat x,ISLocalToGlobalMapping rmapping,ISLocalToGlobalMapping cmapping)
2068: {


2077:   if (x->ops->setlocaltoglobalmapping) {
2078:     (*x->ops->setlocaltoglobalmapping)(x,rmapping,cmapping);
2079:   } else {
2080:     PetscLayoutSetISLocalToGlobalMapping(x->rmap,rmapping);
2081:     PetscLayoutSetISLocalToGlobalMapping(x->cmap,cmapping);
2082:   }
2083:   return(0);
2084: }


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

2090:    Not Collective

2092:    Input Parameters:
2093: .  A - the matrix

2095:    Output Parameters:
2096: + rmapping - row mapping
2097: - cmapping - column mapping

2099:    Level: advanced


2102: .seealso:  MatSetValuesLocal()
2103: @*/
2104: PetscErrorCode MatGetLocalToGlobalMapping(Mat A,ISLocalToGlobalMapping *rmapping,ISLocalToGlobalMapping *cmapping)
2105: {
2111:   if (rmapping) *rmapping = A->rmap->mapping;
2112:   if (cmapping) *cmapping = A->cmap->mapping;
2113:   return(0);
2114: }

2116: /*@
2117:    MatGetLayouts - Gets the PetscLayout objects for rows and columns

2119:    Not Collective

2121:    Input Parameters:
2122: .  A - the matrix

2124:    Output Parameters:
2125: + rmap - row layout
2126: - cmap - column layout

2128:    Level: advanced

2130: .seealso:  MatCreateVecs(), MatGetLocalToGlobalMapping()
2131: @*/
2132: PetscErrorCode MatGetLayouts(Mat A,PetscLayout *rmap,PetscLayout *cmap)
2133: {
2139:   if (rmap) *rmap = A->rmap;
2140:   if (cmap) *cmap = A->cmap;
2141:   return(0);
2142: }

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

2148:    Not Collective

2150:    Input Parameters:
2151: +  mat - the matrix
2152: .  nrow, irow - number of rows and their local indices
2153: .  ncol, icol - number of columns and their local indices
2154: .  y -  a logically two-dimensional array of values
2155: -  addv - either INSERT_VALUES or ADD_VALUES, where
2156:    ADD_VALUES adds values to any existing entries, and
2157:    INSERT_VALUES replaces existing entries with new values

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

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

2165:    Calls to MatSetValuesLocal() with the INSERT_VALUES and ADD_VALUES
2166:    options cannot be mixed without intervening calls to the assembly
2167:    routines.

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

2172:    Level: intermediate

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

2178: .seealso:  MatAssemblyBegin(), MatAssemblyEnd(), MatSetValues(), MatSetLocalToGlobalMapping(),
2179:            MatSetValueLocal(), MatGetValuesLocal()
2180: @*/
2181: PetscErrorCode MatSetValuesLocal(Mat mat,PetscInt nrow,const PetscInt irow[],PetscInt ncol,const PetscInt icol[],const PetscScalar y[],InsertMode addv)
2182: {

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

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

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

2231:    Not Collective

2233:    Input Parameters:
2234: +  x - the matrix
2235: .  nrow, irow - number of rows and their local indices
2236: .  ncol, icol - number of columns and their local indices
2237: .  y -  a logically two-dimensional array of values
2238: -  addv - either INSERT_VALUES or ADD_VALUES, where
2239:    ADD_VALUES adds values to any existing entries, and
2240:    INSERT_VALUES replaces existing entries with new values

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

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

2249:    Calls to MatSetValuesBlockedLocal() with the INSERT_VALUES and ADD_VALUES
2250:    options cannot be mixed without intervening calls to the assembly
2251:    routines.

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

2256:    Level: intermediate

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

2262: .seealso:  MatSetBlockSize(), MatSetLocalToGlobalMapping(), MatAssemblyBegin(), MatAssemblyEnd(),
2263:            MatSetValuesLocal(),  MatSetValuesBlocked()
2264: @*/
2265: PetscErrorCode MatSetValuesBlockedLocal(Mat mat,PetscInt nrow,const PetscInt irow[],PetscInt ncol,const PetscInt icol[],const PetscScalar y[],InsertMode addv)
2266: {

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

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

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

2328:    Collective on Mat

2330:    Input Parameters:
2331: +  mat - the matrix
2332: -  x   - the vector to be multiplied

2334:    Output Parameters:
2335: .  y - the result

2337:    Notes:
2338:    The vectors x and y cannot be the same.  I.e., one cannot
2339:    call MatMult(A,y,y).

2341:    Level: developer

2343: .seealso: MatMultTranspose(), MatMultAdd(), MatMultTransposeAdd()
2344: @*/
2345: PetscErrorCode MatMultDiagonalBlock(Mat mat,Vec x,Vec y)
2346: {


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

2360:   if (!mat->ops->multdiagonalblock) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Matrix type %s does not have a multiply defined",((PetscObject)mat)->type_name);
2361:   (*mat->ops->multdiagonalblock)(mat,x,y);
2362:   PetscObjectStateIncrease((PetscObject)y);
2363:   return(0);
2364: }

2366: /* --------------------------------------------------------*/
2367: /*@
2368:    MatMult - Computes the matrix-vector product, y = Ax.

2370:    Neighbor-wise Collective on Mat

2372:    Input Parameters:
2373: +  mat - the matrix
2374: -  x   - the vector to be multiplied

2376:    Output Parameters:
2377: .  y - the result

2379:    Notes:
2380:    The vectors x and y cannot be the same.  I.e., one cannot
2381:    call MatMult(A,y,y).

2383:    Level: beginner

2385: .seealso: MatMultTranspose(), MatMultAdd(), MatMultTransposeAdd()
2386: @*/
2387: PetscErrorCode MatMult(Mat mat,Vec x,Vec y)
2388: {

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

2408:   VecLockReadPush(x);
2409:   if (!mat->ops->mult) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Matrix type %s does not have a multiply defined",((PetscObject)mat)->type_name);
2410:   PetscLogEventBegin(MAT_Mult,mat,x,y,0);
2411:   (*mat->ops->mult)(mat,x,y);
2412:   PetscLogEventEnd(MAT_Mult,mat,x,y,0);
2413:   if (mat->erroriffailure) {VecValidValues(y,3,PETSC_FALSE);}
2414:   VecLockReadPop(x);
2415:   return(0);
2416: }

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

2421:    Neighbor-wise Collective on Mat

2423:    Input Parameters:
2424: +  mat - the matrix
2425: -  x   - the vector to be multiplied

2427:    Output Parameters:
2428: .  y - the result

2430:    Notes:
2431:    The vectors x and y cannot be the same.  I.e., one cannot
2432:    call MatMultTranspose(A,y,y).

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

2437:    Level: beginner

2439: .seealso: MatMult(), MatMultAdd(), MatMultTransposeAdd(), MatMultHermitianTranspose(), MatTranspose()
2440: @*/
2441: PetscErrorCode MatMultTranspose(Mat mat,Vec x,Vec y)
2442: {


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

2461:   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);
2462:   PetscLogEventBegin(MAT_MultTranspose,mat,x,y,0);
2463:   VecLockReadPush(x);
2464:   (*mat->ops->multtranspose)(mat,x,y);
2465:   VecLockReadPop(x);
2466:   PetscLogEventEnd(MAT_MultTranspose,mat,x,y,0);
2467:   PetscObjectStateIncrease((PetscObject)y);
2468:   if (mat->erroriffailure) {VecValidValues(y,3,PETSC_FALSE);}
2469:   return(0);
2470: }

2472: /*@
2473:    MatMultHermitianTranspose - Computes matrix Hermitian transpose times a vector.

2475:    Neighbor-wise Collective on Mat

2477:    Input Parameters:
2478: +  mat - the matrix
2479: -  x   - the vector to be multilplied

2481:    Output Parameters:
2482: .  y - the result

2484:    Notes:
2485:    The vectors x and y cannot be the same.  I.e., one cannot
2486:    call MatMultHermitianTranspose(A,y,y).

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

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

2492:    Level: beginner

2494: .seealso: MatMult(), MatMultAdd(), MatMultHermitianTransposeAdd(), MatMultTranspose()
2495: @*/
2496: PetscErrorCode MatMultHermitianTranspose(Mat mat,Vec x,Vec y)
2497: {
2499:   Vec            w;


2507:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2508:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2509:   if (x == y) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"x and y must be different vectors");
2510: #if !defined(PETSC_HAVE_CONSTRAINTS)
2511:   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);
2512:   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);
2513: #endif
2514:   MatCheckPreallocated(mat,1);

2516:   PetscLogEventBegin(MAT_MultHermitianTranspose,mat,x,y,0);
2517:   if (mat->ops->multhermitiantranspose) {
2518:     VecLockReadPush(x);
2519:     (*mat->ops->multhermitiantranspose)(mat,x,y);
2520:     VecLockReadPop(x);
2521:   } else {
2522:     VecDuplicate(x,&w);
2523:     VecCopy(x,w);
2524:     VecConjugate(w);
2525:     MatMultTranspose(mat,w,y);
2526:     VecDestroy(&w);
2527:     VecConjugate(y);
2528:   }
2529:   PetscLogEventEnd(MAT_MultHermitianTranspose,mat,x,y,0);
2530:   PetscObjectStateIncrease((PetscObject)y);
2531:   return(0);
2532: }

2534: /*@
2535:     MatMultAdd -  Computes v3 = v2 + A * v1.

2537:     Neighbor-wise Collective on Mat

2539:     Input Parameters:
2540: +   mat - the matrix
2541: -   v1, v2 - the vectors

2543:     Output Parameters:
2544: .   v3 - the result

2546:     Notes:
2547:     The vectors v1 and v3 cannot be the same.  I.e., one cannot
2548:     call MatMultAdd(A,v1,v2,v1).

2550:     Level: beginner

2552: .seealso: MatMultTranspose(), MatMult(), MatMultTransposeAdd()
2553: @*/
2554: PetscErrorCode MatMultAdd(Mat mat,Vec v1,Vec v2,Vec v3)
2555: {


2565:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2566:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2567:   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);
2568:   /* 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);
2569:      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); */
2570:   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);
2571:   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);
2572:   if (v1 == v3) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"v1 and v3 must be different vectors");
2573:   MatCheckPreallocated(mat,1);

2575:   if (!mat->ops->multadd) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"No MatMultAdd() for matrix type %s",((PetscObject)mat)->type_name);
2576:   PetscLogEventBegin(MAT_MultAdd,mat,v1,v2,v3);
2577:   VecLockReadPush(v1);
2578:   (*mat->ops->multadd)(mat,v1,v2,v3);
2579:   VecLockReadPop(v1);
2580:   PetscLogEventEnd(MAT_MultAdd,mat,v1,v2,v3);
2581:   PetscObjectStateIncrease((PetscObject)v3);
2582:   return(0);
2583: }

2585: /*@
2586:    MatMultTransposeAdd - Computes v3 = v2 + A' * v1.

2588:    Neighbor-wise Collective on Mat

2590:    Input Parameters:
2591: +  mat - the matrix
2592: -  v1, v2 - the vectors

2594:    Output Parameters:
2595: .  v3 - the result

2597:    Notes:
2598:    The vectors v1 and v3 cannot be the same.  I.e., one cannot
2599:    call MatMultTransposeAdd(A,v1,v2,v1).

2601:    Level: beginner

2603: .seealso: MatMultTranspose(), MatMultAdd(), MatMult()
2604: @*/
2605: PetscErrorCode MatMultTransposeAdd(Mat mat,Vec v1,Vec v2,Vec v3)
2606: {


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

2625:   PetscLogEventBegin(MAT_MultTransposeAdd,mat,v1,v2,v3);
2626:   VecLockReadPush(v1);
2627:   (*mat->ops->multtransposeadd)(mat,v1,v2,v3);
2628:   VecLockReadPop(v1);
2629:   PetscLogEventEnd(MAT_MultTransposeAdd,mat,v1,v2,v3);
2630:   PetscObjectStateIncrease((PetscObject)v3);
2631:   return(0);
2632: }

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

2637:    Neighbor-wise Collective on Mat

2639:    Input Parameters:
2640: +  mat - the matrix
2641: -  v1, v2 - the vectors

2643:    Output Parameters:
2644: .  v3 - the result

2646:    Notes:
2647:    The vectors v1 and v3 cannot be the same.  I.e., one cannot
2648:    call MatMultHermitianTransposeAdd(A,v1,v2,v1).

2650:    Level: beginner

2652: .seealso: MatMultHermitianTranspose(), MatMultTranspose(), MatMultAdd(), MatMult()
2653: @*/
2654: PetscErrorCode MatMultHermitianTransposeAdd(Mat mat,Vec v1,Vec v2,Vec v3)
2655: {


2665:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2666:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2667:   if (v1 == v3) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"v1 and v3 must be different vectors");
2668:   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);
2669:   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);
2670:   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);
2671:   MatCheckPreallocated(mat,1);

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

2699: /*@
2700:    MatMultConstrained - The inner multiplication routine for a
2701:    constrained matrix P^T A P.

2703:    Neighbor-wise Collective on Mat

2705:    Input Parameters:
2706: +  mat - the matrix
2707: -  x   - the vector to be multilplied

2709:    Output Parameters:
2710: .  y - the result

2712:    Notes:
2713:    The vectors x and y cannot be the same.  I.e., one cannot
2714:    call MatMult(A,y,y).

2716:    Level: beginner

2718: .seealso: MatMult(), MatMultTranspose(), MatMultAdd(), MatMultTransposeAdd()
2719: @*/
2720: PetscErrorCode MatMultConstrained(Mat mat,Vec x,Vec y)
2721: {

2728:   if (!mat->assembled) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2729:   if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2730:   if (x == y) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"x and y must be different vectors");
2731:   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);
2732:   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);
2733:   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);

2735:   PetscLogEventBegin(MAT_MultConstrained,mat,x,y,0);
2736:   VecLockReadPush(x);
2737:   (*mat->ops->multconstrained)(mat,x,y);
2738:   VecLockReadPop(x);
2739:   PetscLogEventEnd(MAT_MultConstrained,mat,x,y,0);
2740:   PetscObjectStateIncrease((PetscObject)y);
2741:   return(0);
2742: }

2744: /*@
2745:    MatMultTransposeConstrained - The inner multiplication routine for a
2746:    constrained matrix P^T A^T P.

2748:    Neighbor-wise Collective on Mat

2750:    Input Parameters:
2751: +  mat - the matrix
2752: -  x   - the vector to be multilplied

2754:    Output Parameters:
2755: .  y - the result

2757:    Notes:
2758:    The vectors x and y cannot be the same.  I.e., one cannot
2759:    call MatMult(A,y,y).

2761:    Level: beginner

2763: .seealso: MatMult(), MatMultTranspose(), MatMultAdd(), MatMultTransposeAdd()
2764: @*/
2765: PetscErrorCode MatMultTransposeConstrained(Mat mat,Vec x,Vec y)
2766: {

2773:   if (!mat->assembled) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2774:   if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2775:   if (x == y) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"x and y must be different vectors");
2776:   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);
2777:   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);

2779:   PetscLogEventBegin(MAT_MultConstrained,mat,x,y,0);
2780:   (*mat->ops->multtransposeconstrained)(mat,x,y);
2781:   PetscLogEventEnd(MAT_MultConstrained,mat,x,y,0);
2782:   PetscObjectStateIncrease((PetscObject)y);
2783:   return(0);
2784: }

2786: /*@C
2787:    MatGetFactorType - gets the type of factorization it is

2789:    Not Collective

2791:    Input Parameters:
2792: .  mat - the matrix

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

2797:    Level: intermediate

2799: .seealso: MatFactorType, MatGetFactor(), MatSetFactorType()
2800: @*/
2801: PetscErrorCode MatGetFactorType(Mat mat,MatFactorType *t)
2802: {
2807:   *t = mat->factortype;
2808:   return(0);
2809: }

2811: /*@C
2812:    MatSetFactorType - sets the type of factorization it is

2814:    Logically Collective on Mat

2816:    Input Parameters:
2817: +  mat - the matrix
2818: -  t - the type, one of MAT_FACTOR_NONE, MAT_FACTOR_LU, MAT_FACTOR_CHOLESKY, MAT_FACTOR_ILU, MAT_FACTOR_ICC,MAT_FACTOR_ILUDT

2820:    Level: intermediate

2822: .seealso: MatFactorType, MatGetFactor(), MatGetFactorType()
2823: @*/
2824: PetscErrorCode MatSetFactorType(Mat mat, MatFactorType t)
2825: {
2829:   mat->factortype = t;
2830:   return(0);
2831: }

2833: /* ------------------------------------------------------------*/
2834: /*@C
2835:    MatGetInfo - Returns information about matrix storage (number of
2836:    nonzeros, memory, etc.).

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

2840:    Input Parameters:
2841: .  mat - the matrix

2843:    Output Parameters:
2844: +  flag - flag indicating the type of parameters to be returned
2845:    (MAT_LOCAL - local matrix, MAT_GLOBAL_MAX - maximum over all processors,
2846:    MAT_GLOBAL_SUM - sum over all processors)
2847: -  info - matrix information context

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

2858:    Example for C/C++ Users:
2859:    See the file ${PETSC_DIR}/include/petscmat.h for a complete list of
2860:    data within the MatInfo context.  For example,
2861: .vb
2862:       MatInfo info;
2863:       Mat     A;
2864:       double  mal, nz_a, nz_u;

2866:       MatGetInfo(A,MAT_LOCAL,&info);
2867:       mal  = info.mallocs;
2868:       nz_a = info.nz_allocated;
2869: .ve

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

2882:       call MatGetInfo(A,MAT_LOCAL,info,ierr)
2883:       mal = info(MAT_INFO_MALLOCS)
2884:       nz_a = info(MAT_INFO_NZ_ALLOCATED)
2885: .ve

2887:     Level: intermediate

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

2892: .seealso: MatStashGetInfo()

2894: @*/
2895: PetscErrorCode MatGetInfo(Mat mat,MatInfoType flag,MatInfo *info)
2896: {

2903:   if (!mat->ops->getinfo) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
2904:   MatCheckPreallocated(mat,1);
2905:   (*mat->ops->getinfo)(mat,flag,info);
2906:   return(0);
2907: }

2909: /*
2910:    This is used by external packages where it is not easy to get the info from the actual
2911:    matrix factorization.
2912: */
2913: PetscErrorCode MatGetInfo_External(Mat A,MatInfoType flag,MatInfo *info)
2914: {

2918:   PetscMemzero(info,sizeof(MatInfo));
2919:   return(0);
2920: }

2922: /* ----------------------------------------------------------*/

2924: /*@C
2925:    MatLUFactor - Performs in-place LU factorization of matrix.

2927:    Collective on Mat

2929:    Input Parameters:
2930: +  mat - the matrix
2931: .  row - row permutation
2932: .  col - column permutation
2933: -  info - options for factorization, includes
2934: $          fill - expected fill as ratio of original fill.
2935: $          dtcol - pivot tolerance (0 no pivot, 1 full column pivoting)
2936: $                   Run with the option -info to determine an optimal value to use

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

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

2946:    Level: developer

2948: .seealso: MatLUFactorSymbolic(), MatLUFactorNumeric(), MatCholeskyFactor(),
2949:           MatGetOrdering(), MatSetUnfactored(), MatFactorInfo, MatGetFactor()

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

2954: @*/
2955: PetscErrorCode MatLUFactor(Mat mat,IS row,IS col,const MatFactorInfo *info)
2956: {
2958:   MatFactorInfo  tinfo;

2966:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2967:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2968:   if (!mat->ops->lufactor) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
2969:   MatCheckPreallocated(mat,1);
2970:   if (!info) {
2971:     MatFactorInfoInitialize(&tinfo);
2972:     info = &tinfo;
2973:   }

2975:   PetscLogEventBegin(MAT_LUFactor,mat,row,col,0);
2976:   (*mat->ops->lufactor)(mat,row,col,info);
2977:   PetscLogEventEnd(MAT_LUFactor,mat,row,col,0);
2978:   PetscObjectStateIncrease((PetscObject)mat);
2979:   return(0);
2980: }

2982: /*@C
2983:    MatILUFactor - Performs in-place ILU factorization of matrix.

2985:    Collective on Mat

2987:    Input Parameters:
2988: +  mat - the matrix
2989: .  row - row permutation
2990: .  col - column permutation
2991: -  info - structure containing
2992: $      levels - number of levels of fill.
2993: $      expected fill - as ratio of original fill.
2994: $      1 or 0 - indicating force fill on diagonal (improves robustness for matrices
2995:                 missing diagonal entries)

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

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

3005:    Level: developer

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

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

3012: @*/
3013: PetscErrorCode MatILUFactor(Mat mat,IS row,IS col,const MatFactorInfo *info)
3014: {

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

3029:   PetscLogEventBegin(MAT_ILUFactor,mat,row,col,0);
3030:   (*mat->ops->ilufactor)(mat,row,col,info);
3031:   PetscLogEventEnd(MAT_ILUFactor,mat,row,col,0);
3032:   PetscObjectStateIncrease((PetscObject)mat);
3033:   return(0);
3034: }

3036: /*@C
3037:    MatLUFactorSymbolic - Performs symbolic LU factorization of matrix.
3038:    Call this routine before calling MatLUFactorNumeric().

3040:    Collective on Mat

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


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

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

3059:    Level: developer

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

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

3066: @*/
3067: PetscErrorCode MatLUFactorSymbolic(Mat fact,Mat mat,IS row,IS col,const MatFactorInfo *info)
3068: {
3070:   MatFactorInfo  tinfo;

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

3092:   PetscLogEventBegin(MAT_LUFactorSymbolic,mat,row,col,0);
3093:   (fact->ops->lufactorsymbolic)(fact,mat,row,col,info);
3094:   PetscLogEventEnd(MAT_LUFactorSymbolic,mat,row,col,0);
3095:   PetscObjectStateIncrease((PetscObject)fact);
3096:   return(0);
3097: }

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

3103:    Collective on Mat

3105:    Input Parameters:
3106: +  fact - the factor matrix obtained with MatGetFactor()
3107: .  mat - the matrix
3108: -  info - options for factorization

3110:    Notes:
3111:    See MatLUFactor() for in-place factorization.  See
3112:    MatCholeskyFactorNumeric() for the symmetric, positive definite case.

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

3118:    Level: developer

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

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

3125: @*/
3126: PetscErrorCode MatLUFactorNumeric(Mat fact,Mat mat,const MatFactorInfo *info)
3127: {
3128:   MatFactorInfo  tinfo;

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

3139:   if (!(fact)->ops->lufactornumeric) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s numeric LU",((PetscObject)mat)->type_name);
3140:   MatCheckPreallocated(mat,2);
3141:   if (!info) {
3142:     MatFactorInfoInitialize(&tinfo);
3143:     info = &tinfo;
3144:   }

3146:   PetscLogEventBegin(MAT_LUFactorNumeric,mat,fact,0,0);
3147:   (fact->ops->lufactornumeric)(fact,mat,info);
3148:   PetscLogEventEnd(MAT_LUFactorNumeric,mat,fact,0,0);
3149:   MatViewFromOptions(fact,NULL,"-mat_factor_view");
3150:   PetscObjectStateIncrease((PetscObject)fact);
3151:   return(0);
3152: }

3154: /*@C
3155:    MatCholeskyFactor - Performs in-place Cholesky factorization of a
3156:    symmetric matrix.

3158:    Collective on Mat

3160:    Input Parameters:
3161: +  mat - the matrix
3162: .  perm - row and column permutations
3163: -  f - expected fill as ratio of original fill

3165:    Notes:
3166:    See MatLUFactor() for the nonsymmetric case.  See also
3167:    MatCholeskyFactorSymbolic(), and MatCholeskyFactorNumeric().

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

3173:    Level: developer

3175: .seealso: MatLUFactor(), MatCholeskyFactorSymbolic(), MatCholeskyFactorNumeric()
3176:           MatGetOrdering()

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

3181: @*/
3182: PetscErrorCode MatCholeskyFactor(Mat mat,IS perm,const MatFactorInfo *info)
3183: {
3185:   MatFactorInfo  tinfo;

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

3202:   PetscLogEventBegin(MAT_CholeskyFactor,mat,perm,0,0);
3203:   (*mat->ops->choleskyfactor)(mat,perm,info);
3204:   PetscLogEventEnd(MAT_CholeskyFactor,mat,perm,0,0);
3205:   PetscObjectStateIncrease((PetscObject)mat);
3206:   return(0);
3207: }

3209: /*@C
3210:    MatCholeskyFactorSymbolic - Performs symbolic Cholesky factorization
3211:    of a symmetric matrix.

3213:    Collective on Mat

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

3224:    Notes:
3225:    See MatLUFactorSymbolic() for the nonsymmetric case.  See also
3226:    MatCholeskyFactor() and MatCholeskyFactorNumeric().

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

3232:    Level: developer

3234: .seealso: MatLUFactorSymbolic(), MatCholeskyFactor(), MatCholeskyFactorNumeric()
3235:           MatGetOrdering()

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

3240: @*/
3241: PetscErrorCode MatCholeskyFactorSymbolic(Mat fact,Mat mat,IS perm,const MatFactorInfo *info)
3242: {
3244:   MatFactorInfo  tinfo;

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

3266:   PetscLogEventBegin(MAT_CholeskyFactorSymbolic,mat,perm,0,0);
3267:   (fact->ops->choleskyfactorsymbolic)(fact,mat,perm,info);
3268:   PetscLogEventEnd(MAT_CholeskyFactorSymbolic,mat,perm,0,0);
3269:   PetscObjectStateIncrease((PetscObject)fact);
3270:   return(0);
3271: }

3273: /*@C
3274:    MatCholeskyFactorNumeric - Performs numeric Cholesky factorization
3275:    of a symmetric matrix. Call this routine after first calling
3276:    MatCholeskyFactorSymbolic().

3278:    Collective on Mat

3280:    Input Parameters:
3281: +  fact - the factor matrix obtained with MatGetFactor()
3282: .  mat - the initial matrix
3283: .  info - options for factorization
3284: -  fact - the symbolic factor of mat


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

3292:    Level: developer

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

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

3299: @*/
3300: PetscErrorCode MatCholeskyFactorNumeric(Mat fact,Mat mat,const MatFactorInfo *info)
3301: {
3302:   MatFactorInfo  tinfo;

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

3319:   PetscLogEventBegin(MAT_CholeskyFactorNumeric,mat,fact,0,0);
3320:   (fact->ops->choleskyfactornumeric)(fact,mat,info);
3321:   PetscLogEventEnd(MAT_CholeskyFactorNumeric,mat,fact,0,0);
3322:   MatViewFromOptions(fact,NULL,"-mat_factor_view");
3323:   PetscObjectStateIncrease((PetscObject)fact);
3324:   return(0);
3325: }

3327: /* ----------------------------------------------------------------*/
3328: /*@
3329:    MatSolve - Solves A x = b, given a factored matrix.

3331:    Neighbor-wise Collective on Mat

3333:    Input Parameters:
3334: +  mat - the factored matrix
3335: -  b - the right-hand-side vector

3337:    Output Parameter:
3338: .  x - the result vector

3340:    Notes:
3341:    The vectors b and x cannot be the same.  I.e., one cannot
3342:    call MatSolve(A,x,x).

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

3349:    Level: developer

3351: .seealso: MatSolveAdd(), MatSolveTranspose(), MatSolveTransposeAdd()
3352: @*/
3353: PetscErrorCode MatSolve(Mat mat,Vec b,Vec x)
3354: {

3364:   if (x == b) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"x and b must be different vectors");
3365:   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);
3366:   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);
3367:   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);
3368:   if (!mat->rmap->N && !mat->cmap->N) return(0);
3369:   MatCheckPreallocated(mat,1);

3371:   PetscLogEventBegin(MAT_Solve,mat,b,x,0);
3372:   if (mat->factorerrortype) {
3373:     PetscInfo1(mat,"MatFactorError %D\n",mat->factorerrortype);
3374:     VecSetInf(x);
3375:   } else {
3376:     if (!mat->ops->solve) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
3377:     (*mat->ops->solve)(mat,b,x);
3378:   }
3379:   PetscLogEventEnd(MAT_Solve,mat,b,x,0);
3380:   PetscObjectStateIncrease((PetscObject)x);
3381:   return(0);
3382: }

3384: static PetscErrorCode MatMatSolve_Basic(Mat A,Mat B,Mat X,PetscBool trans)
3385: {
3387:   Vec            b,x;
3388:   PetscInt       m,N,i;
3389:   PetscScalar    *bb,*xx;

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

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

3418:    Neighbor-wise Collective on Mat

3420:    Input Parameters:
3421: +  A - the factored matrix
3422: -  B - the right-hand-side matrix MATDENSE (or sparse -- when using MUMPS)

3424:    Output Parameter:
3425: .  X - the result matrix (dense matrix)

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

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

3437:    Level: developer

3439: .seealso: MatMatSolveTranspose(), MatLUFactor(), MatCholeskyFactor()
3440: @*/
3441: PetscErrorCode MatMatSolve(Mat A,Mat B,Mat X)
3442: {

3452:   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);
3453:   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);
3454:   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");
3455:   if (!A->rmap->N && !A->cmap->N) return(0);
3456:   if (!A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
3457:   MatCheckPreallocated(A,1);

3459:   PetscLogEventBegin(MAT_MatSolve,A,B,X,0);
3460:   if (!A->ops->matsolve) {
3461:     PetscInfo1(A,"Mat type %s using basic MatMatSolve\n",((PetscObject)A)->type_name);
3462:     MatMatSolve_Basic(A,B,X,PETSC_FALSE);
3463:   } else {
3464:     (*A->ops->matsolve)(A,B,X);
3465:   }
3466:   PetscLogEventEnd(MAT_MatSolve,A,B,X,0);
3467:   PetscObjectStateIncrease((PetscObject)X);
3468:   return(0);
3469: }

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

3474:    Neighbor-wise Collective on Mat

3476:    Input Parameters:
3477: +  A - the factored matrix
3478: -  B - the right-hand-side matrix  (dense matrix)

3480:    Output Parameter:
3481: .  X - the result matrix (dense matrix)

3483:    Notes:
3484:    The matrices B and X cannot be the same.  I.e., one cannot
3485:    call MatMatSolveTranspose(A,X,X).

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

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

3495:    Level: developer

3497: .seealso: MatMatSolve(), MatLUFactor(), MatCholeskyFactor()
3498: @*/
3499: PetscErrorCode MatMatSolveTranspose(Mat A,Mat B,Mat X)
3500: {

3510:   if (X == B) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_IDN,"X and B must be different matrices");
3511:   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);
3512:   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);
3513:   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);
3514:   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");
3515:   if (!A->rmap->N && !A->cmap->N) return(0);
3516:   if (!A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
3517:   MatCheckPreallocated(A,1);

3519:   PetscLogEventBegin(MAT_MatSolve,A,B,X,0);
3520:   if (!A->ops->matsolvetranspose) {
3521:     PetscInfo1(A,"Mat type %s using basic MatMatSolveTranspose\n",((PetscObject)A)->type_name);
3522:     MatMatSolve_Basic(A,B,X,PETSC_TRUE);
3523:   } else {
3524:     (*A->ops->matsolvetranspose)(A,B,X);
3525:   }
3526:   PetscLogEventEnd(MAT_MatSolve,A,B,X,0);
3527:   PetscObjectStateIncrease((PetscObject)X);
3528:   return(0);
3529: }

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

3534:    Neighbor-wise Collective on Mat

3536:    Input Parameters:
3537: +  A - the factored matrix
3538: -  Bt - the transpose of right-hand-side matrix

3540:    Output Parameter:
3541: .  X - the result matrix (dense matrix)

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

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

3551:    Level: developer

3553: .seealso: MatMatSolve(), MatMatSolveTranspose(), MatLUFactor(), MatCholeskyFactor()
3554: @*/
3555: PetscErrorCode MatMatTransposeSolve(Mat A,Mat Bt,Mat X)
3556: {


3567:   if (X == Bt) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_IDN,"X and B must be different matrices");
3568:   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);
3569:   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);
3570:   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");
3571:   if (!A->rmap->N && !A->cmap->N) return(0);
3572:   if (!A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
3573:   MatCheckPreallocated(A,1);

3575:   if (!A->ops->mattransposesolve) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Mat type %s",((PetscObject)A)->type_name);
3576:   PetscLogEventBegin(MAT_MatTrSolve,A,Bt,X,0);
3577:   (*A->ops->mattransposesolve)(A,Bt,X);
3578:   PetscLogEventEnd(MAT_MatTrSolve,A,Bt,X,0);
3579:   PetscObjectStateIncrease((PetscObject)X);
3580:   return(0);
3581: }

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

3587:    Neighbor-wise Collective on Mat

3589:    Input Parameters:
3590: +  mat - the factored matrix
3591: -  b - the right-hand-side vector

3593:    Output Parameter:
3594: .  x - the result vector

3596:    Notes:
3597:    MatSolve() should be used for most applications, as it performs
3598:    a forward solve followed by a backward solve.

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

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

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

3613:    Level: developer

3615: .seealso: MatSolve(), MatBackwardSolve()
3616: @*/
3617: PetscErrorCode MatForwardSolve(Mat mat,Vec b,Vec x)
3618: {

3628:   if (x == b) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"x and b must be different vectors");
3629:   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);
3630:   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);
3631:   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);
3632:   if (!mat->rmap->N && !mat->cmap->N) return(0);
3633:   MatCheckPreallocated(mat,1);

3635:   if (!mat->ops->forwardsolve) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
3636:   PetscLogEventBegin(MAT_ForwardSolve,mat,b,x,0);
3637:   (*mat->ops->forwardsolve)(mat,b,x);
3638:   PetscLogEventEnd(MAT_ForwardSolve,mat,b,x,0);
3639:   PetscObjectStateIncrease((PetscObject)x);
3640:   return(0);
3641: }

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

3647:    Neighbor-wise Collective on Mat

3649:    Input Parameters:
3650: +  mat - the factored matrix
3651: -  b - the right-hand-side vector

3653:    Output Parameter:
3654: .  x - the result vector

3656:    Notes:
3657:    MatSolve() should be used for most applications, as it performs
3658:    a forward solve followed by a backward solve.

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

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

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

3673:    Level: developer

3675: .seealso: MatSolve(), MatForwardSolve()
3676: @*/
3677: PetscErrorCode MatBackwardSolve(Mat mat,Vec b,Vec x)
3678: {

3688:   if (x == b) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"x and b must be different vectors");
3689:   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);
3690:   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);
3691:   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);
3692:   if (!mat->rmap->N && !mat->cmap->N) return(0);
3693:   MatCheckPreallocated(mat,1);

3695:   if (!mat->ops->backwardsolve) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
3696:   PetscLogEventBegin(MAT_BackwardSolve,mat,b,x,0);
3697:   (*mat->ops->backwardsolve)(mat,b,x);
3698:   PetscLogEventEnd(MAT_BackwardSolve,mat,b,x,0);
3699:   PetscObjectStateIncrease((PetscObject)x);
3700:   return(0);
3701: }

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

3706:    Neighbor-wise Collective on Mat

3708:    Input Parameters:
3709: +  mat - the factored matrix
3710: .  b - the right-hand-side vector
3711: -  y - the vector to be added to

3713:    Output Parameter:
3714: .  x - the result vector

3716:    Notes:
3717:    The vectors b and x cannot be the same.  I.e., one cannot
3718:    call MatSolveAdd(A,x,y,x).

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

3724:    Level: developer

3726: .seealso: MatSolve(), MatSolveTranspose(), MatSolveTransposeAdd()
3727: @*/
3728: PetscErrorCode MatSolveAdd(Mat mat,Vec b,Vec y,Vec x)
3729: {
3730:   PetscScalar    one = 1.0;
3731:   Vec            tmp;

3743:   if (x == b) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"x and b must be different vectors");
3744:   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);
3745:   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);
3746:   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);
3747:   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);
3748:   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);
3749:   if (!mat->rmap->N && !mat->cmap->N) return(0);
3750:    MatCheckPreallocated(mat,1);

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

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

3780:    Neighbor-wise Collective on Mat

3782:    Input Parameters:
3783: +  mat - the factored matrix
3784: -  b - the right-hand-side vector

3786:    Output Parameter:
3787: .  x - the result vector

3789:    Notes:
3790:    The vectors b and x cannot be the same.  I.e., one cannot
3791:    call MatSolveTranspose(A,x,x).

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

3797:    Level: developer

3799: .seealso: MatSolve(), MatSolveAdd(), MatSolveTransposeAdd()
3800: @*/
3801: PetscErrorCode MatSolveTranspose(Mat mat,Vec b,Vec x)
3802: {

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

3830: /*@
3831:    MatSolveTransposeAdd - Computes x = y + inv(Transpose(A)) b, given a
3832:                       factored matrix.

3834:    Neighbor-wise Collective on Mat

3836:    Input Parameters:
3837: +  mat - the factored matrix
3838: .  b - the right-hand-side vector
3839: -  y - the vector to be added to

3841:    Output Parameter:
3842: .  x - the result vector

3844:    Notes:
3845:    The vectors b and x cannot be the same.  I.e., one cannot
3846:    call MatSolveTransposeAdd(A,x,y,x).

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

3852:    Level: developer

3854: .seealso: MatSolve(), MatSolveAdd(), MatSolveTranspose()
3855: @*/
3856: PetscErrorCode MatSolveTransposeAdd(Mat mat,Vec b,Vec y,Vec x)
3857: {
3858:   PetscScalar    one = 1.0;
3860:   Vec            tmp;

3871:   if (x == b) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"x and b must be different vectors");
3872:   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);
3873:   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);
3874:   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);
3875:   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);
3876:   if (!mat->rmap->N && !mat->cmap->N) return(0);
3877:    MatCheckPreallocated(mat,1);

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

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

3908:    Neighbor-wise Collective on Mat

3910:    Input Parameters:
3911: +  mat - the matrix
3912: .  b - the right hand side
3913: .  omega - the relaxation factor
3914: .  flag - flag indicating the type of SOR (see below)
3915: .  shift -  diagonal shift
3916: .  its - the number of iterations
3917: -  lits - the number of local iterations

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

3922:    SOR Flags:
3923: +     SOR_FORWARD_SWEEP - forward SOR
3924: .     SOR_BACKWARD_SWEEP - backward SOR
3925: .     SOR_SYMMETRIC_SWEEP - SSOR (symmetric SOR)
3926: .     SOR_LOCAL_FORWARD_SWEEP - local forward SOR
3927: .     SOR_LOCAL_BACKWARD_SWEEP - local forward SOR
3928: .     SOR_LOCAL_SYMMETRIC_SWEEP - local SSOR
3929: .     SOR_APPLY_UPPER, SOR_APPLY_LOWER - applies
3930:          upper/lower triangular part of matrix to
3931:          vector (with omega)
3932: -     SOR_ZERO_INITIAL_GUESS - zero initial guess

3934:    Notes:
3935:    SOR_LOCAL_FORWARD_SWEEP, SOR_LOCAL_BACKWARD_SWEEP, and
3936:    SOR_LOCAL_SYMMETRIC_SWEEP perform separate independent smoothings
3937:    on each processor.

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

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

3945:    Notes for Advanced Users:
3946:    The flags are implemented as bitwise inclusive or operations.
3947:    For example, use (SOR_ZERO_INITIAL_GUESS | SOR_SYMMETRIC_SWEEP)
3948:    to specify a zero initial guess for SSOR.

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

3954:    Vectors x and b CANNOT be the same

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

3958:    Level: developer

3960: @*/
3961: PetscErrorCode MatSOR(Mat mat,Vec b,PetscReal omega,MatSORType flag,PetscReal shift,PetscInt its,PetscInt lits,Vec x)
3962: {

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

3982:   MatCheckPreallocated(mat,1);
3983:   PetscLogEventBegin(MAT_SOR,mat,b,x,0);
3984:   ierr =(*mat->ops->sor)(mat,b,omega,flag,shift,its,lits,x);
3985:   PetscLogEventEnd(MAT_SOR,mat,b,x,0);
3986:   PetscObjectStateIncrease((PetscObject)x);
3987:   return(0);
3988: }

3990: /*
3991:       Default matrix copy routine.
3992: */
3993: PetscErrorCode MatCopy_Basic(Mat A,Mat B,MatStructure str)
3994: {
3995:   PetscErrorCode    ierr;
3996:   PetscInt          i,rstart = 0,rend = 0,nz;
3997:   const PetscInt    *cwork;
3998:   const PetscScalar *vwork;

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

4019: /*@
4020:    MatCopy - Copies a matrix to another matrix.

4022:    Collective on Mat

4024:    Input Parameters:
4025: +  A - the matrix
4026: -  str - SAME_NONZERO_PATTERN or DIFFERENT_NONZERO_PATTERN

4028:    Output Parameter:
4029: .  B - where the copy is put

4031:    Notes:
4032:    If you use SAME_NONZERO_PATTERN then the two matrices had better have the
4033:    same nonzero pattern or the routine will crash.

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

4039:    Level: intermediate

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

4043: @*/
4044: PetscErrorCode MatCopy(Mat A,Mat B,MatStructure str)
4045: {
4047:   PetscInt       i;

4055:   MatCheckPreallocated(B,2);
4056:   if (!A->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
4057:   if (A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
4058:   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);
4059:   MatCheckPreallocated(A,1);
4060:   if (A == B) return(0);

4062:   PetscLogEventBegin(MAT_Copy,A,B,0,0);
4063:   if (A->ops->copy) {
4064:     (*A->ops->copy)(A,B,str);
4065:   } else { /* generic conversion */
4066:     MatCopy_Basic(A,B,str);
4067:   }

4069:   B->stencil.dim = A->stencil.dim;
4070:   B->stencil.noc = A->stencil.noc;
4071:   for (i=0; i<=A->stencil.dim; i++) {
4072:     B->stencil.dims[i]   = A->stencil.dims[i];
4073:     B->stencil.starts[i] = A->stencil.starts[i];
4074:   }

4076:   PetscLogEventEnd(MAT_Copy,A,B,0,0);
4077:   PetscObjectStateIncrease((PetscObject)B);
4078:   return(0);
4079: }

4081: /*@C
4082:    MatConvert - Converts a matrix to another matrix, either of the same
4083:    or different type.

4085:    Collective on Mat

4087:    Input Parameters:
4088: +  mat - the matrix
4089: .  newtype - new matrix type.  Use MATSAME to create a new matrix of the
4090:    same type as the original matrix.
4091: -  reuse - denotes if the destination matrix is to be created or reused.
4092:    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
4093:    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).

4095:    Output Parameter:
4096: .  M - pointer to place new matrix

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

4103:    Cannot be used to convert a sequential matrix to parallel or parallel to sequential,
4104:    the MPI communicator of the generated matrix is always the same as the communicator
4105:    of the input matrix.

4107:    Level: intermediate

4109: .seealso: MatCopy(), MatDuplicate()
4110: @*/
4111: PetscErrorCode MatConvert(Mat mat, MatType newtype,MatReuse reuse,Mat *M)
4112: {
4114:   PetscBool      sametype,issame,flg,issymmetric,ishermitian;
4115:   char           convname[256],mtype[256];
4116:   Mat            B;

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

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

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

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

4139:   /* Cache Mat options because some converter use MatHeaderReplace  */
4140:   issymmetric = mat->symmetric;
4141:   ishermitian = mat->hermitian;

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

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

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

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

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

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

4224:     /* 5) Use a really basic converter. */
4225:     PetscInfo(mat,"Using MatConvert_Basic\n");
4226:     conv = MatConvert_Basic;

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

4250:   /* Copy Mat options */
4251:   if (issymmetric) {
4252:     MatSetOption(*M,MAT_SYMMETRIC,PETSC_TRUE);
4253:   }
4254:   if (ishermitian) {
4255:     MatSetOption(*M,MAT_HERMITIAN,PETSC_TRUE);
4256:   }
4257:   return(0);
4258: }

4260: /*@C
4261:    MatFactorGetSolverType - Returns name of the package providing the factorization routines

4263:    Not Collective

4265:    Input Parameter:
4266: .  mat - the matrix, must be a factored matrix

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

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

4275:    Level: intermediate

4277: .seealso: MatCopy(), MatDuplicate(), MatGetFactorAvailable(), MatGetFactor()
4278: @*/
4279: PetscErrorCode MatFactorGetSolverType(Mat mat, MatSolverType *type)
4280: {
4281:   PetscErrorCode ierr, (*conv)(Mat,MatSolverType*);

4286:   if (!mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Only for factored matrix");
4287:   PetscObjectQueryFunction((PetscObject)mat,"MatFactorGetSolverType_C",&conv);
4288:   if (!conv) {
4289:     *type = MATSOLVERPETSC;
4290:   } else {
4291:     (*conv)(mat,type);
4292:   }
4293:   return(0);
4294: }

4296: typedef struct _MatSolverTypeForSpecifcType* MatSolverTypeForSpecifcType;
4297: struct _MatSolverTypeForSpecifcType {
4298:   MatType                        mtype;
4299:   PetscErrorCode                 (*getfactor[4])(Mat,MatFactorType,Mat*);
4300:   MatSolverTypeForSpecifcType next;
4301: };

4303: typedef struct _MatSolverTypeHolder* MatSolverTypeHolder;
4304: struct _MatSolverTypeHolder {
4305:   char                           *name;
4306:   MatSolverTypeForSpecifcType handlers;
4307:   MatSolverTypeHolder         next;
4308: };

4310: static MatSolverTypeHolder MatSolverTypeHolders = NULL;

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

4315:    Input Parameters:
4316: +    package - name of the package, for example petsc or superlu
4317: .    mtype - the matrix type that works with this package
4318: .    ftype - the type of factorization supported by the package
4319: -    getfactor - routine that will create the factored matrix ready to be used

4321:     Level: intermediate

4323: .seealso: MatCopy(), MatDuplicate(), MatGetFactorAvailable()
4324: @*/
4325: PetscErrorCode MatSolverTypeRegister(MatSolverType package,MatType mtype,MatFactorType ftype,PetscErrorCode (*getfactor)(Mat,MatFactorType,Mat*))
4326: {
4327:   PetscErrorCode              ierr;
4328:   MatSolverTypeHolder         next = MatSolverTypeHolders,prev = NULL;
4329:   PetscBool                   flg;
4330:   MatSolverTypeForSpecifcType inext,iprev = NULL;

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

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

4375:    Input Parameters:
4376: +    package - name of the package, for example petsc or superlu
4377: .    ftype - the type of factorization supported by the package
4378: -    mtype - the matrix type that works with this package

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

4385:     Level: intermediate

4387: .seealso: MatCopy(), MatDuplicate(), MatGetFactorAvailable()
4388: @*/
4389: PetscErrorCode MatSolverTypeGet(MatSolverType package,MatType mtype,MatFactorType ftype,PetscBool *foundpackage,PetscBool *foundmtype,PetscErrorCode (**getfactor)(Mat,MatFactorType,Mat*))
4390: {
4391:   PetscErrorCode              ierr;
4392:   MatSolverTypeHolder         next = MatSolverTypeHolders;
4393:   PetscBool                   flg;
4394:   MatSolverTypeForSpecifcType inext;

4397:   if (foundpackage) *foundpackage = PETSC_FALSE;
4398:   if (foundmtype)   *foundmtype   = PETSC_FALSE;
4399:   if (getfactor)    *getfactor    = NULL;

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

4438: PetscErrorCode MatSolverTypeDestroy(void)
4439: {
4440:   PetscErrorCode              ierr;
4441:   MatSolverTypeHolder         next = MatSolverTypeHolders,prev;
4442:   MatSolverTypeForSpecifcType inext,iprev;

4445:   while (next) {
4446:     PetscFree(next->name);
4447:     inext = next->handlers;
4448:     while (inext) {
4449:       PetscFree(inext->mtype);
4450:       iprev = inext;
4451:       inext = inext->next;
4452:       PetscFree(iprev);
4453:     }
4454:     prev = next;
4455:     next = next->next;
4456:     PetscFree(prev);
4457:   }
4458:   MatSolverTypeHolders = NULL;
4459:   return(0);
4460: }

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

4465:    Collective on Mat

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

4472:    Output Parameters:
4473: .  f - the factor matrix used with MatXXFactorSymbolic() calls

4475:    Notes:
4476:       Some PETSc matrix formats have alternative solvers available that are contained in alternative packages
4477:      such as pastix, superlu, mumps etc.

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

4481:    Level: intermediate

4483: .seealso: MatCopy(), MatDuplicate(), MatGetFactorAvailable()
4484: @*/
4485: PetscErrorCode MatGetFactor(Mat mat, MatSolverType type,MatFactorType ftype,Mat *f)
4486: {
4487:   PetscErrorCode ierr,(*conv)(Mat,MatFactorType,Mat*);
4488:   PetscBool      foundpackage,foundmtype;


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

4497:   MatSolverTypeGet(type,((PetscObject)mat)->type_name,ftype,&foundpackage,&foundmtype,&conv);
4498:   if (!foundpackage) {
4499:     if (type) {
4500:       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);
4501:     } else {
4502:       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);
4503:     }
4504:   }
4505:   if (!foundmtype) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_MISSING_FACTOR,"MatSolverType %s does not support matrix type %s",type,((PetscObject)mat)->type_name);
4506:   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);

4508:   (*conv)(mat,ftype,f);
4509:   return(0);
4510: }

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

4515:    Not Collective

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

4522:    Output Parameter:
4523: .    flg - PETSC_TRUE if the factorization is available

4525:    Notes:
4526:       Some PETSc matrix formats have alternative solvers available that are contained in alternative packages
4527:      such as pastix, superlu, mumps etc.

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

4531:    Level: intermediate

4533: .seealso: MatCopy(), MatDuplicate(), MatGetFactor()
4534: @*/
4535: PetscErrorCode MatGetFactorAvailable(Mat mat, MatSolverType type,MatFactorType ftype,PetscBool  *flg)
4536: {
4537:   PetscErrorCode ierr, (*gconv)(Mat,MatFactorType,Mat*);


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

4546:   *flg = PETSC_FALSE;
4547:   MatSolverTypeGet(type,((PetscObject)mat)->type_name,ftype,NULL,NULL,&gconv);
4548:   if (gconv) {
4549:     *flg = PETSC_TRUE;
4550:   }
4551:   return(0);
4552: }

4554:  #include <petscdmtypes.h>

4556: /*@
4557:    MatDuplicate - Duplicates a matrix including the non-zero structure.

4559:    Collective on Mat

4561:    Input Parameters:
4562: +  mat - the matrix
4563: -  op - One of MAT_DO_NOT_COPY_VALUES, MAT_COPY_VALUES, or MAT_SHARE_NONZERO_PATTERN.
4564:         See the manual page for MatDuplicateOption for an explanation of these options.

4566:    Output Parameter:
4567: .  M - pointer to place new matrix

4569:    Level: intermediate

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

4575: .seealso: MatCopy(), MatConvert(), MatDuplicateOption
4576: @*/
4577: PetscErrorCode MatDuplicate(Mat mat,MatDuplicateOption op,Mat *M)
4578: {
4580:   Mat            B;
4581:   PetscInt       i;
4582:   DM             dm;
4583:   void           (*viewf)(void);

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

4593:   *M = 0;
4594:   if (!mat->ops->duplicate) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Not written for matrix type %s\n",((PetscObject)mat)->type_name);
4595:   PetscLogEventBegin(MAT_Convert,mat,0,0,0);
4596:   (*mat->ops->duplicate)(mat,op,M);
4597:   B    = *M;

4599:   MatGetOperation(mat,MATOP_VIEW,&viewf);
4600:   if (viewf) {
4601:     MatSetOperation(B,MATOP_VIEW,viewf);
4602:   }

4604:   B->stencil.dim = mat->stencil.dim;
4605:   B->stencil.noc = mat->stencil.noc;
4606:   for (i=0; i<=mat->stencil.dim; i++) {
4607:     B->stencil.dims[i]   = mat->stencil.dims[i];
4608:     B->stencil.starts[i] = mat->stencil.starts[i];
4609:   }

4611:   B->nooffproczerorows = mat->nooffproczerorows;
4612:   B->nooffprocentries  = mat->nooffprocentries;

4614:   PetscObjectQuery((PetscObject) mat, "__PETSc_dm", (PetscObject*) &dm);
4615:   if (dm) {
4616:     PetscObjectCompose((PetscObject) B, "__PETSc_dm", (PetscObject) dm);
4617:   }
4618:   PetscLogEventEnd(MAT_Convert,mat,0,0,0);
4619:   PetscObjectStateIncrease((PetscObject)B);
4620:   return(0);
4621: }

4623: /*@
4624:    MatGetDiagonal - Gets the diagonal of a matrix.

4626:    Logically Collective on Mat

4628:    Input Parameters:
4629: +  mat - the matrix
4630: -  v - the vector for storing the diagonal

4632:    Output Parameter:
4633: .  v - the diagonal of the matrix

4635:    Level: intermediate

4637:    Note:
4638:    Currently only correct in parallel for square matrices.

4640: .seealso: MatGetRow(), MatCreateSubMatrices(), MatCreateSubMatrix(), MatGetRowMaxAbs()
4641: @*/
4642: PetscErrorCode MatGetDiagonal(Mat mat,Vec v)
4643: {

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

4654:   (*mat->ops->getdiagonal)(mat,v);
4655:   PetscObjectStateIncrease((PetscObject)v);
4656:   return(0);
4657: }

4659: /*@C
4660:    MatGetRowMin - Gets the minimum value (of the real part) of each
4661:         row of the matrix

4663:    Logically Collective on Mat

4665:    Input Parameters:
4666: .  mat - the matrix

4668:    Output Parameter:
4669: +  v - the vector for storing the maximums
4670: -  idx - the indices of the column found for each row (optional)

4672:    Level: intermediate

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

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

4680: .seealso: MatGetDiagonal(), MatCreateSubMatrices(), MatCreateSubMatrix(), MatGetRowMaxAbs(),
4681:           MatGetRowMax()
4682: @*/
4683: PetscErrorCode MatGetRowMin(Mat mat,Vec v,PetscInt idx[])
4684: {

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

4695:   (*mat->ops->getrowmin)(mat,v,idx);
4696:   PetscObjectStateIncrease((PetscObject)v);
4697:   return(0);
4698: }

4700: /*@C
4701:    MatGetRowMinAbs - Gets the minimum value (in absolute value) of each
4702:         row of the matrix

4704:    Logically Collective on Mat

4706:    Input Parameters:
4707: .  mat - the matrix

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

4713:    Level: intermediate

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

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

4721: .seealso: MatGetDiagonal(), MatCreateSubMatrices(), MatCreateSubMatrix(), MatGetRowMax(), MatGetRowMaxAbs(), MatGetRowMin()
4722: @*/
4723: PetscErrorCode MatGetRowMinAbs(Mat mat,Vec v,PetscInt idx[])
4724: {

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

4736:   (*mat->ops->getrowminabs)(mat,v,idx);
4737:   PetscObjectStateIncrease((PetscObject)v);
4738:   return(0);
4739: }

4741: /*@C
4742:    MatGetRowMax - Gets the maximum value (of the real part) of each
4743:         row of the matrix

4745:    Logically Collective on Mat

4747:    Input Parameters:
4748: .  mat - the matrix

4750:    Output Parameter:
4751: +  v - the vector for storing the maximums
4752: -  idx - the indices of the column found for each row (optional)

4754:    Level: intermediate

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

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

4762: .seealso: MatGetDiagonal(), MatCreateSubMatrices(), MatCreateSubMatrix(), MatGetRowMaxAbs(), MatGetRowMin()
4763: @*/
4764: PetscErrorCode MatGetRowMax(Mat mat,Vec v,PetscInt idx[])
4765: {

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

4776:   (*mat->ops->getrowmax)(mat,v,idx);
4777:   PetscObjectStateIncrease((PetscObject)v);
4778:   return(0);
4779: }

4781: /*@C
4782:    MatGetRowMaxAbs - Gets the maximum value (in absolute value) of each
4783:         row of the matrix

4785:    Logically Collective on Mat

4787:    Input Parameters:
4788: .  mat - the matrix

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

4794:    Level: intermediate

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

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

4802: .seealso: MatGetDiagonal(), MatCreateSubMatrices(), MatCreateSubMatrix(), MatGetRowMax(), MatGetRowMin()
4803: @*/
4804: PetscErrorCode MatGetRowMaxAbs(Mat mat,Vec v,PetscInt idx[])
4805: {

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

4817:   (*mat->ops->getrowmaxabs)(mat,v,idx);
4818:   PetscObjectStateIncrease((PetscObject)v);
4819:   return(0);
4820: }

4822: /*@
4823:    MatGetRowSum - Gets the sum of each row of the matrix

4825:    Logically or Neighborhood Collective on Mat

4827:    Input Parameters:
4828: .  mat - the matrix

4830:    Output Parameter:
4831: .  v - the vector for storing the sum of rows

4833:    Level: intermediate

4835:    Notes:
4836:     This code is slow since it is not currently specialized for different formats

4838: .seealso: MatGetDiagonal(), MatCreateSubMatrices(), MatCreateSubMatrix(), MatGetRowMax(), MatGetRowMin()
4839: @*/
4840: PetscErrorCode MatGetRowSum(Mat mat, Vec v)
4841: {
4842:   Vec            ones;

4849:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
4850:   MatCheckPreallocated(mat,1);
4851:   MatCreateVecs(mat,&ones,NULL);
4852:   VecSet(ones,1.);
4853:   MatMult(mat,ones,v);
4854:   VecDestroy(&ones);
4855:   return(0);
4856: }

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

4861:    Collective on Mat

4863:    Input Parameter:
4864: +  mat - the matrix to transpose
4865: -  reuse - either MAT_INITIAL_MATRIX, MAT_REUSE_MATRIX, or MAT_INPLACE_MATRIX

4867:    Output Parameters:
4868: .  B - the transpose

4870:    Notes:
4871:      If you use MAT_INPLACE_MATRIX then you must pass in &mat for B

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

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

4877:    Level: intermediate

4879: .seealso: MatMultTranspose(), MatMultTransposeAdd(), MatIsTranspose(), MatReuse
4880: @*/
4881: PetscErrorCode MatTranspose(Mat mat,MatReuse reuse,Mat *B)
4882: {

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

4895:   PetscLogEventBegin(MAT_Transpose,mat,0,0,0);
4896:   (*mat->ops->transpose)(mat,reuse,B);
4897:   PetscLogEventEnd(MAT_Transpose,mat,0,0,0);
4898:   if (B) {PetscObjectStateIncrease((PetscObject)*B);}
4899:   return(0);
4900: }

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

4906:    Collective on Mat

4908:    Input Parameter:
4909: +  A - the matrix to test
4910: -  B - the matrix to test against, this can equal the first parameter

4912:    Output Parameters:
4913: .  flg - the result

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

4920:    Level: intermediate

4922: .seealso: MatTranspose(), MatIsSymmetric(), MatIsHermitian()
4923: @*/
4924: PetscErrorCode MatIsTranspose(Mat A,Mat B,PetscReal tol,PetscBool  *flg)
4925: {
4926:   PetscErrorCode ierr,(*f)(Mat,Mat,PetscReal,PetscBool*),(*g)(Mat,Mat,PetscReal,PetscBool*);

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

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

4954:    Collective on Mat

4956:    Input Parameter:
4957: +  mat - the matrix to transpose and complex conjugate
4958: -  reuse - MAT_INITIAL_MATRIX to create a new matrix, MAT_INPLACE_MATRIX to reuse the first argument to store the transpose

4960:    Output Parameters:
4961: .  B - the Hermitian

4963:    Level: intermediate

4965: .seealso: MatTranspose(), MatMultTranspose(), MatMultTransposeAdd(), MatIsTranspose(), MatReuse
4966: @*/
4967: PetscErrorCode MatHermitianTranspose(Mat mat,MatReuse reuse,Mat *B)
4968: {

4972:   MatTranspose(mat,reuse,B);
4973: #if defined(PETSC_USE_COMPLEX)
4974:   MatConjugate(*B);
4975: #endif
4976:   return(0);
4977: }

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

4982:    Collective on Mat

4984:    Input Parameter:
4985: +  A - the matrix to test
4986: -  B - the matrix to test against, this can equal the first parameter

4988:    Output Parameters:
4989: .  flg - the result

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

4996:    Level: intermediate

4998: .seealso: MatTranspose(), MatIsSymmetric(), MatIsHermitian(), MatIsTranspose()
4999: @*/
5000: PetscErrorCode MatIsHermitianTranspose(Mat A,Mat B,PetscReal tol,PetscBool  *flg)
5001: {
5002:   PetscErrorCode ierr,(*f)(Mat,Mat,PetscReal,PetscBool*),(*g)(Mat,Mat,PetscReal,PetscBool*);

5008:   PetscObjectQueryFunction((PetscObject)A,"MatIsHermitianTranspose_C",&f);
5009:   PetscObjectQueryFunction((PetscObject)B,"MatIsHermitianTranspose_C",&g);
5010:   if (f && g) {
5011:     if (f==g) {
5012:       (*f)(A,B,tol,flg);
5013:     } else SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_NOTSAMETYPE,"Matrices do not have the same comparator for Hermitian test");
5014:   }
5015:   return(0);
5016: }

5018: /*@
5019:    MatPermute - Creates a new matrix with rows and columns permuted from the
5020:    original.

5022:    Collective on Mat

5024:    Input Parameters:
5025: +  mat - the matrix to permute
5026: .  row - row permutation, each processor supplies only the permutation for its rows
5027: -  col - column permutation, each processor supplies only the permutation for its columns

5029:    Output Parameters:
5030: .  B - the permuted matrix

5032:    Level: advanced

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

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

5040: @*/
5041: PetscErrorCode MatPermute(Mat mat,IS row,IS col,Mat *B)
5042: {

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

5056:   (*mat->ops->permute)(mat,row,col,B);
5057:   PetscObjectStateIncrease((PetscObject)*B);
5058:   return(0);
5059: }

5061: /*@
5062:    MatEqual - Compares two matrices.

5064:    Collective on Mat

5066:    Input Parameters:
5067: +  A - the first matrix
5068: -  B - the second matrix

5070:    Output Parameter:
5071: .  flg - PETSC_TRUE if the matrices are equal; PETSC_FALSE otherwise.

5073:    Level: intermediate

5075: @*/
5076: PetscErrorCode MatEqual(Mat A,Mat B,PetscBool  *flg)
5077: {

5087:   MatCheckPreallocated(B,2);
5088:   if (!A->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
5089:   if (!B->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
5090:   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);
5091:   if (!A->ops->equal) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Mat type %s",((PetscObject)A)->type_name);
5092:   if (!B->ops->equal) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Mat type %s",((PetscObject)B)->type_name);
5093:   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);
5094:   MatCheckPreallocated(A,1);

5096:   (*A->ops->equal)(A,B,flg);
5097:   return(0);
5098: }

5100: /*@
5101:    MatDiagonalScale - Scales a matrix on the left and right by diagonal
5102:    matrices that are stored as vectors.  Either of the two scaling
5103:    matrices can be NULL.

5105:    Collective on Mat

5107:    Input Parameters:
5108: +  mat - the matrix to be scaled
5109: .  l - the left scaling vector (or NULL)
5110: -  r - the right scaling vector (or NULL)

5112:    Notes:
5113:    MatDiagonalScale() computes A = LAR, where
5114:    L = a diagonal matrix (stored as a vector), R = a diagonal matrix (stored as a vector)
5115:    The L scales the rows of the matrix, the R scales the columns of the matrix.

5117:    Level: intermediate


5120: .seealso: MatScale(), MatShift(), MatDiagonalSet()
5121: @*/
5122: PetscErrorCode MatDiagonalScale(Mat mat,Vec l,Vec r)
5123: {

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

5136:   PetscLogEventBegin(MAT_Scale,mat,0,0,0);
5137:   (*mat->ops->diagonalscale)(mat,l,r);
5138:   PetscLogEventEnd(MAT_Scale,mat,0,0,0);
5139:   PetscObjectStateIncrease((PetscObject)mat);
5140:   return(0);
5141: }

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

5146:     Logically Collective on Mat

5148:     Input Parameters:
5149: +   mat - the matrix to be scaled
5150: -   a  - the scaling value

5152:     Output Parameter:
5153: .   mat - the scaled matrix

5155:     Level: intermediate

5157: .seealso: MatDiagonalScale()
5158: @*/
5159: PetscErrorCode MatScale(Mat mat,PetscScalar a)
5160: {

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

5172:   PetscLogEventBegin(MAT_Scale,mat,0,0,0);
5173:   if (a != (PetscScalar)1.0) {
5174:     (*mat->ops->scale)(mat,a);
5175:     PetscObjectStateIncrease((PetscObject)mat);
5176:   }
5177:   PetscLogEventEnd(MAT_Scale,mat,0,0,0);
5178:   return(0);
5179: }

5181: /*@
5182:    MatNorm - Calculates various norms of a matrix.

5184:    Collective on Mat

5186:    Input Parameters:
5187: +  mat - the matrix
5188: -  type - the type of norm, NORM_1, NORM_FROBENIUS, NORM_INFINITY

5190:    Output Parameters:
5191: .  nrm - the resulting norm

5193:    Level: intermediate

5195: @*/
5196: PetscErrorCode MatNorm(Mat mat,NormType type,PetscReal *nrm)
5197: {


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

5210:   (*mat->ops->norm)(mat,type,nrm);
5211:   return(0);
5212: }

5214: /*
5215:      This variable is used to prevent counting of MatAssemblyBegin() that
5216:    are called from within a MatAssemblyEnd().
5217: */
5218: static PetscInt MatAssemblyEnd_InUse = 0;
5219: /*@
5220:    MatAssemblyBegin - Begins assembling the matrix.  This routine should
5221:    be called after completing all calls to MatSetValues().

5223:    Collective on Mat

5225:    Input Parameters:
5226: +  mat - the matrix
5227: -  type - type of assembly, either MAT_FLUSH_ASSEMBLY or MAT_FINAL_ASSEMBLY

5229:    Notes:
5230:    MatSetValues() generally caches the values.  The matrix is ready to
5231:    use only after MatAssemblyBegin() and MatAssemblyEnd() have been called.
5232:    Use MAT_FLUSH_ASSEMBLY when switching between ADD_VALUES and INSERT_VALUES
5233:    in MatSetValues(); use MAT_FINAL_ASSEMBLY for the final assembly before
5234:    using the matrix.

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

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

5244:    Level: beginner

5246: .seealso: MatAssemblyEnd(), MatSetValues(), MatAssembled()
5247: @*/
5248: PetscErrorCode MatAssemblyBegin(Mat mat,MatAssemblyType type)
5249: {

5255:   MatCheckPreallocated(mat,1);
5256:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix.\nDid you forget to call MatSetUnfactored()?");
5257:   if (mat->assembled) {
5258:     mat->was_assembled = PETSC_TRUE;
5259:     mat->assembled     = PETSC_FALSE;
5260:   }

5262:   if (!MatAssemblyEnd_InUse) {
5263:     PetscLogEventBegin(MAT_AssemblyBegin,mat,0,0,0);
5264:     if (mat->ops->assemblybegin) {(*mat->ops->assemblybegin)(mat,type);}
5265:     PetscLogEventEnd(MAT_AssemblyBegin,mat,0,0,0);
5266:   } else if (mat->ops->assemblybegin) {
5267:     (*mat->ops->assemblybegin)(mat,type);
5268:   }
5269:   return(0);
5270: }

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

5276:    Not Collective

5278:    Input Parameter:
5279: .  mat - the matrix

5281:    Output Parameter:
5282: .  assembled - PETSC_TRUE or PETSC_FALSE

5284:    Level: advanced

5286: .seealso: MatAssemblyEnd(), MatSetValues(), MatAssemblyBegin()
5287: @*/
5288: PetscErrorCode MatAssembled(Mat mat,PetscBool  *assembled)
5289: {
5293:   *assembled = mat->assembled;
5294:   return(0);
5295: }

5297: /*@
5298:    MatAssemblyEnd - Completes assembling the matrix.  This routine should
5299:    be called after MatAssemblyBegin().

5301:    Collective on Mat

5303:    Input Parameters:
5304: +  mat - the matrix
5305: -  type - type of assembly, either MAT_FLUSH_ASSEMBLY or MAT_FINAL_ASSEMBLY

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

5320:    Notes:
5321:    MatSetValues() generally caches the values.  The matrix is ready to
5322:    use only after MatAssemblyBegin() and MatAssemblyEnd() have been called.
5323:    Use MAT_FLUSH_ASSEMBLY when switching between ADD_VALUES and INSERT_VALUES
5324:    in MatSetValues(); use MAT_FINAL_ASSEMBLY for the final assembly before
5325:    using the matrix.

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

5331:    Level: beginner

5333: .seealso: MatAssemblyBegin(), MatSetValues(), PetscDrawOpenX(), PetscDrawCreate(), MatView(), MatAssembled(), PetscViewerSocketOpen()
5334: @*/
5335: PetscErrorCode MatAssemblyEnd(Mat mat,MatAssemblyType type)
5336: {
5337:   PetscErrorCode  ierr;
5338:   static PetscInt inassm = 0;
5339:   PetscBool       flg    = PETSC_FALSE;


5345:   inassm++;
5346:   MatAssemblyEnd_InUse++;
5347:   if (MatAssemblyEnd_InUse == 1) { /* Do the logging only the first time through */
5348:     PetscLogEventBegin(MAT_AssemblyEnd,mat,0,0,0);
5349:     if (mat->ops->assemblyend) {
5350:       (*mat->ops->assemblyend)(mat,type);
5351:     }
5352:     PetscLogEventEnd(MAT_AssemblyEnd,mat,0,0,0);
5353:   } else if (mat->ops->assemblyend) {
5354:     (*mat->ops->assemblyend)(mat,type);
5355:   }

5357:   /* Flush assembly is not a true assembly */
5358:   if (type != MAT_FLUSH_ASSEMBLY) {
5359:     mat->num_ass++;
5360:     mat->assembled        = PETSC_TRUE;
5361:     mat->ass_nonzerostate = mat->nonzerostate;
5362:   }

5364:   mat->insertmode = NOT_SET_VALUES;
5365:   MatAssemblyEnd_InUse--;
5366:   PetscObjectStateIncrease((PetscObject)mat);
5367:   if (!mat->symmetric_eternal) {
5368:     mat->symmetric_set              = PETSC_FALSE;
5369:     mat->hermitian_set              = PETSC_FALSE;
5370:     mat->structurally_symmetric_set = PETSC_FALSE;
5371:   }
5372:   if (inassm == 1 && type != MAT_FLUSH_ASSEMBLY) {
5373:     MatViewFromOptions(mat,NULL,"-mat_view");

5375:     if (mat->checksymmetryonassembly) {
5376:       MatIsSymmetric(mat,mat->checksymmetrytol,&flg);
5377:       if (flg) {
5378:         PetscPrintf(PetscObjectComm((PetscObject)mat),"Matrix is symmetric (tolerance %g)\n",(double)mat->checksymmetrytol);
5379:       } else {
5380:         PetscPrintf(PetscObjectComm((PetscObject)mat),"Matrix is not symmetric (tolerance %g)\n",(double)mat->checksymmetrytol);
5381:       }
5382:     }
5383:     if (mat->nullsp && mat->checknullspaceonassembly) {
5384:       MatNullSpaceTest(mat->nullsp,mat,NULL);
5385:     }
5386:   }
5387:   inassm--;
5388:   return(0);
5389: }

5391: /*@
5392:    MatSetOption - Sets a parameter option for a matrix. Some options
5393:    may be specific to certain storage formats.  Some options
5394:    determine how values will be inserted (or added). Sorted,
5395:    row-oriented input will generally assemble the fastest. The default
5396:    is row-oriented.

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

5400:    Input Parameters:
5401: +  mat - the matrix
5402: .  option - the option, one of those listed below (and possibly others),
5403: -  flg - turn the option on (PETSC_TRUE) or off (PETSC_FALSE)

5405:   Options Describing Matrix Structure:
5406: +    MAT_SPD - symmetric positive definite
5407: .    MAT_SYMMETRIC - symmetric in terms of both structure and value
5408: .    MAT_HERMITIAN - transpose is the complex conjugation
5409: .    MAT_STRUCTURALLY_SYMMETRIC - symmetric nonzero structure
5410: -    MAT_SYMMETRY_ETERNAL - if you would like the symmetry/Hermitian flag
5411:                             you set to be kept with all future use of the matrix
5412:                             including after MatAssemblyBegin/End() which could
5413:                             potentially change the symmetry structure, i.e. you
5414:                             KNOW the matrix will ALWAYS have the property you set.


5417:    Options For Use with MatSetValues():
5418:    Insert a logically dense subblock, which can be
5419: .    MAT_ROW_ORIENTED - row-oriented (default)

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

5501:    Level: intermediate

5503: .seealso:  MatOption, Mat

5505: @*/
5506: PetscErrorCode MatSetOption(Mat mat,MatOption op,PetscBool flg)
5507: {

5513:   if (op > 0) {
5516:   }

5518:   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);
5519:   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()");

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

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

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

5596:    Input Parameters:
5597: +  mat - the matrix
5598: -  option - the option, this only responds to certain options, check the code for which ones

5600:    Output Parameter:
5601: .  flg - turn the option on (PETSC_TRUE) or off (PETSC_FALSE)

5603:     Notes:
5604:     Can only be called after MatSetSizes() and MatSetType() have been set.

5606:    Level: intermediate

5608: .seealso:  MatOption, MatSetOption()

5610: @*/
5611: PetscErrorCode MatGetOption(Mat mat,MatOption op,PetscBool *flg)
5612: {

5617:   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);
5618:   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()");

5620:   switch (op) {
5621:   case MAT_NO_OFF_PROC_ENTRIES:
5622:     *flg = mat->nooffprocentries;
5623:     break;
5624:   case MAT_NO_OFF_PROC_ZERO_ROWS:
5625:     *flg = mat->nooffproczerorows;
5626:     break;
5627:   case MAT_SYMMETRIC:
5628:     *flg = mat->symmetric;
5629:     break;
5630:   case MAT_HERMITIAN:
5631:     *flg = mat->hermitian;
5632:     break;
5633:   case MAT_STRUCTURALLY_SYMMETRIC:
5634:     *flg = mat->structurally_symmetric;
5635:     break;
5636:   case MAT_SYMMETRY_ETERNAL:
5637:     *flg = mat->symmetric_eternal;
5638:     break;
5639:   case MAT_SPD:
5640:     *flg = mat->spd;
5641:     break;
5642:   default:
5643:     break;
5644:   }
5645:   return(0);
5646: }

5648: /*@
5649:    MatZeroEntries - Zeros all entries of a matrix.  For sparse matrices
5650:    this routine retains the old nonzero structure.

5652:    Logically Collective on Mat

5654:    Input Parameters:
5655: .  mat - the matrix

5657:    Level: intermediate

5659:    Notes:
5660:     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.
5661:    See the Performance chapter of the users manual for information on preallocating matrices.

5663: .seealso: MatZeroRows()
5664: @*/
5665: PetscErrorCode MatZeroEntries(Mat mat)
5666: {

5672:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
5673:   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");
5674:   if (!mat->ops->zeroentries) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
5675:   MatCheckPreallocated(mat,1);

5677:   PetscLogEventBegin(MAT_ZeroEntries,mat,0,0,0);
5678:   (*mat->ops->zeroentries)(mat);
5679:   PetscLogEventEnd(MAT_ZeroEntries,mat,0,0,0);
5680:   PetscObjectStateIncrease((PetscObject)mat);
5681:   return(0);
5682: }

5684: /*@
5685:    MatZeroRowsColumns - Zeros all entries (except possibly the main diagonal)
5686:    of a set of rows and columns of a matrix.

5688:    Collective on Mat

5690:    Input Parameters:
5691: +  mat - the matrix
5692: .  numRows - the number of rows to remove
5693: .  rows - the global row indices
5694: .  diag - value put in all diagonals of eliminated rows (0.0 will even eliminate diagonal entry)
5695: .  x - optional vector of solutions for zeroed rows (other entries in vector are not used)
5696: -  b - optional vector of right hand side, that will be adjusted by provided solution

5698:    Notes:
5699:    This does not change the nonzero structure of the matrix, it merely zeros those entries in the matrix.

5701:    The user can set a value in the diagonal entry (or for the AIJ and
5702:    row formats can optionally remove the main diagonal entry from the
5703:    nonzero structure as well, by passing 0.0 as the final argument).

5705:    For the parallel case, all processes that share the matrix (i.e.,
5706:    those in the communicator used for matrix creation) MUST call this
5707:    routine, regardless of whether any rows being zeroed are owned by
5708:    them.

5710:    Each processor can indicate any rows in the entire matrix to be zeroed (i.e. each process does NOT have to
5711:    list only rows local to itself).

5713:    The option MAT_NO_OFF_PROC_ZERO_ROWS does not apply to this routine.

5715:    Level: intermediate

5717: .seealso: MatZeroRowsIS(), MatZeroRows(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
5718:           MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
5719: @*/
5720: PetscErrorCode MatZeroRowsColumns(Mat mat,PetscInt numRows,const PetscInt rows[],PetscScalar diag,Vec x,Vec b)
5721: {

5728:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
5729:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
5730:   if (!mat->ops->zerorowscolumns) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
5731:   MatCheckPreallocated(mat,1);

5733:   (*mat->ops->zerorowscolumns)(mat,numRows,rows,diag,x,b);
5734:   MatViewFromOptions(mat,NULL,"-mat_view");
5735:   PetscObjectStateIncrease((PetscObject)mat);
5736:   return(0);
5737: }

5739: /*@
5740:    MatZeroRowsColumnsIS - Zeros all entries (except possibly the main diagonal)
5741:    of a set of rows and columns of a matrix.

5743:    Collective on Mat

5745:    Input Parameters:
5746: +  mat - the matrix
5747: .  is - the rows to zero
5748: .  diag - value put in all diagonals of eliminated rows (0.0 will even eliminate diagonal entry)
5749: .  x - optional vector of solutions for zeroed rows (other entries in vector are not used)
5750: -  b - optional vector of right hand side, that will be adjusted by provided solution

5752:    Notes:
5753:    This does not change the nonzero structure of the matrix, it merely zeros those entries in the matrix.

5755:    The user can set a value in the diagonal entry (or for the AIJ and
5756:    row formats can optionally remove the main diagonal entry from the
5757:    nonzero structure as well, by passing 0.0 as the final argument).

5759:    For the parallel case, all processes that share the matrix (i.e.,
5760:    those in the communicator used for matrix creation) MUST call this
5761:    routine, regardless of whether any rows being zeroed are owned by
5762:    them.

5764:    Each processor can indicate any rows in the entire matrix to be zeroed (i.e. each process does NOT have to
5765:    list only rows local to itself).

5767:    The option MAT_NO_OFF_PROC_ZERO_ROWS does not apply to this routine.

5769:    Level: intermediate

5771: .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
5772:           MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRows(), MatZeroRowsColumnsStencil()
5773: @*/
5774: PetscErrorCode MatZeroRowsColumnsIS(Mat mat,IS is,PetscScalar diag,Vec x,Vec b)
5775: {
5777:   PetscInt       numRows;
5778:   const PetscInt *rows;

5785:   ISGetLocalSize(is,&numRows);
5786:   ISGetIndices(is,&rows);
5787:   MatZeroRowsColumns(mat,numRows,rows,diag,x,b);
5788:   ISRestoreIndices(is,&rows);
5789:   return(0);
5790: }

5792: /*@
5793:    MatZeroRows - Zeros all entries (except possibly the main diagonal)
5794:    of a set of rows of a matrix.

5796:    Collective on Mat

5798:    Input Parameters:
5799: +  mat - the matrix
5800: .  numRows - the number of rows to remove
5801: .  rows - the global row indices
5802: .  diag - value put in all diagonals of eliminated rows (0.0 will even eliminate diagonal entry)
5803: .  x - optional vector of solutions for zeroed rows (other entries in vector are not used)
5804: -  b - optional vector of right hand side, that will be adjusted by provided solution

5806:    Notes:
5807:    For the AIJ and BAIJ matrix formats this removes the old nonzero structure,
5808:    but does not release memory.  For the dense and block diagonal
5809:    formats this does not alter the nonzero structure.

5811:    If the option MatSetOption(mat,MAT_KEEP_NONZERO_PATTERN,PETSC_TRUE) the nonzero structure
5812:    of the matrix is not changed (even for AIJ and BAIJ matrices) the values are
5813:    merely zeroed.

5815:    The user can set a value in the diagonal entry (or for the AIJ and
5816:    row formats can optionally remove the main diagonal entry from the
5817:    nonzero structure as well, by passing 0.0 as the final argument).

5819:    For the parallel case, all processes that share the matrix (i.e.,
5820:    those in the communicator used for matrix creation) MUST call this
5821:    routine, regardless of whether any rows being zeroed are owned by
5822:    them.

5824:    Each processor can indicate any rows in the entire matrix to be zeroed (i.e. each process does NOT have to
5825:    list only rows local to itself).

5827:    You can call MatSetOption(mat,MAT_NO_OFF_PROC_ZERO_ROWS,PETSC_TRUE) if each process indicates only rows it
5828:    owns that are to be zeroed. This saves a global synchronization in the implementation.

5830:    Level: intermediate

5832: .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
5833:           MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
5834: @*/
5835: PetscErrorCode MatZeroRows(Mat mat,PetscInt numRows,const PetscInt rows[],PetscScalar diag,Vec x,Vec b)
5836: {

5843:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
5844:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
5845:   if (!mat->ops->zerorows) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
5846:   MatCheckPreallocated(mat,1);

5848:   (*mat->ops->zerorows)(mat,numRows,rows,diag,x,b);
5849:   MatViewFromOptions(mat,NULL,"-mat_view");
5850:   PetscObjectStateIncrease((PetscObject)mat);
5851:   return(0);
5852: }

5854: /*@
5855:    MatZeroRowsIS - Zeros all entries (except possibly the main diagonal)
5856:    of a set of rows of a matrix.

5858:    Collective on Mat

5860:    Input Parameters:
5861: +  mat - the matrix
5862: .  is - index set of rows to remove
5863: .  diag - value put in all diagonals of eliminated rows
5864: .  x - optional vector of solutions for zeroed rows (other entries in vector are not used)
5865: -  b - optional vector of right hand side, that will be adjusted by provided solution

5867:    Notes:
5868:    For the AIJ and BAIJ matrix formats this removes the old nonzero structure,
5869:    but does not release memory.  For the dense and block diagonal
5870:    formats this does not alter the nonzero structure.

5872:    If the option MatSetOption(mat,MAT_KEEP_NONZERO_PATTERN,PETSC_TRUE) the nonzero structure
5873:    of the matrix is not changed (even for AIJ and BAIJ matrices) the values are
5874:    merely zeroed.

5876:    The user can set a value in the diagonal entry (or for the AIJ and
5877:    row formats can optionally remove the main diagonal entry from the
5878:    nonzero structure as well, by passing 0.0 as the final argument).

5880:    For the parallel case, all processes that share the matrix (i.e.,
5881:    those in the communicator used for matrix creation) MUST call this
5882:    routine, regardless of whether any rows being zeroed are owned by
5883:    them.

5885:    Each processor can indicate any rows in the entire matrix to be zeroed (i.e. each process does NOT have to
5886:    list only rows local to itself).

5888:    You can call MatSetOption(mat,MAT_NO_OFF_PROC_ZERO_ROWS,PETSC_TRUE) if each process indicates only rows it
5889:    owns that are to be zeroed. This saves a global synchronization in the implementation.

5891:    Level: intermediate

5893: .seealso: MatZeroRows(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
5894:           MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
5895: @*/
5896: PetscErrorCode MatZeroRowsIS(Mat mat,IS is,PetscScalar diag,Vec x,Vec b)
5897: {
5898:   PetscInt       numRows;
5899:   const PetscInt *rows;

5906:   ISGetLocalSize(is,&numRows);
5907:   ISGetIndices(is,&rows);
5908:   MatZeroRows(mat,numRows,rows,diag,x,b);
5909:   ISRestoreIndices(is,&rows);
5910:   return(0);
5911: }

5913: /*@
5914:    MatZeroRowsStencil - Zeros all entries (except possibly the main diagonal)
5915:    of a set of rows of a matrix. These rows must be local to the process.

5917:    Collective on Mat

5919:    Input Parameters:
5920: +  mat - the matrix
5921: .  numRows - the number of rows to remove
5922: .  rows - the grid coordinates (and component number when dof > 1) for matrix rows
5923: .  diag - value put in all diagonals of eliminated rows (0.0 will even eliminate diagonal entry)
5924: .  x - optional vector of solutions for zeroed rows (other entries in vector are not used)
5925: -  b - optional vector of right hand side, that will be adjusted by provided solution

5927:    Notes:
5928:    For the AIJ and BAIJ matrix formats this removes the old nonzero structure,
5929:    but does not release memory.  For the dense and block diagonal
5930:    formats this does not alter the nonzero structure.

5932:    If the option MatSetOption(mat,MAT_KEEP_NONZERO_PATTERN,PETSC_TRUE) the nonzero structure
5933:    of the matrix is not changed (even for AIJ and BAIJ matrices) the values are
5934:    merely zeroed.

5936:    The user can set a value in the diagonal entry (or for the AIJ and
5937:    row formats can optionally remove the main diagonal entry from the
5938:    nonzero structure as well, by passing 0.0 as the final argument).

5940:    For the parallel case, all processes that share the matrix (i.e.,
5941:    those in the communicator used for matrix creation) MUST call this
5942:    routine, regardless of whether any rows being zeroed are owned by
5943:    them.

5945:    Each processor can indicate any rows in the entire matrix to be zeroed (i.e. each process does NOT have to
5946:    list only rows local to itself).

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

5950:    In Fortran idxm and idxn should be declared as
5951: $     MatStencil idxm(4,m)
5952:    and the values inserted using
5953: $    idxm(MatStencil_i,1) = i
5954: $    idxm(MatStencil_j,1) = j
5955: $    idxm(MatStencil_k,1) = k
5956: $    idxm(MatStencil_c,1) = c
5957:    etc

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

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

5967:    Level: intermediate

5969: .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsl(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
5970:           MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
5971: @*/
5972: PetscErrorCode MatZeroRowsStencil(Mat mat,PetscInt numRows,const MatStencil rows[],PetscScalar diag,Vec x,Vec b)
5973: {
5974:   PetscInt       dim     = mat->stencil.dim;
5975:   PetscInt       sdim    = dim - (1 - (PetscInt) mat->stencil.noc);
5976:   PetscInt       *dims   = mat->stencil.dims+1;
5977:   PetscInt       *starts = mat->stencil.starts;
5978:   PetscInt       *dxm    = (PetscInt*) rows;
5979:   PetscInt       *jdxm, i, j, tmp, numNewRows = 0;


5987:   PetscMalloc1(numRows, &jdxm);
5988:   for (i = 0; i < numRows; ++i) {
5989:     /* Skip unused dimensions (they are ordered k, j, i, c) */
5990:     for (j = 0; j < 3-sdim; ++j) dxm++;
5991:     /* Local index in X dir */
5992:     tmp = *dxm++ - starts[0];
5993:     /* Loop over remaining dimensions */
5994:     for (j = 0; j < dim-1; ++j) {
5995:       /* If nonlocal, set index to be negative */
5996:       if ((*dxm++ - starts[j+1]) < 0 || tmp < 0) tmp = PETSC_MIN_INT;
5997:       /* Update local index */
5998:       else tmp = tmp*dims[j] + *(dxm-1) - starts[j+1];
5999:     }
6000:     /* Skip component slot if necessary */
6001:     if (mat->stencil.noc) dxm++;
6002:     /* Local row number */
6003:     if (tmp >= 0) {
6004:       jdxm[numNewRows++] = tmp;
6005:     }
6006:   }
6007:   MatZeroRowsLocal(mat,numNewRows,jdxm,diag,x,b);
6008:   PetscFree(jdxm);
6009:   return(0);
6010: }

6012: /*@
6013:    MatZeroRowsColumnsStencil - Zeros all row and column entries (except possibly the main diagonal)
6014:    of a set of rows and columns of a matrix.

6016:    Collective on Mat

6018:    Input Parameters:
6019: +  mat - the matrix
6020: .  numRows - the number of rows/columns to remove
6021: .  rows - the grid coordinates (and component number when dof > 1) for matrix rows
6022: .  diag - value put in all diagonals of eliminated rows (0.0 will even eliminate diagonal entry)
6023: .  x - optional vector of solutions for zeroed rows (other entries in vector are not used)
6024: -  b - optional vector of right hand side, that will be adjusted by provided solution

6026:    Notes:
6027:    For the AIJ and BAIJ matrix formats this removes the old nonzero structure,
6028:    but does not release memory.  For the dense and block diagonal
6029:    formats this does not alter the nonzero structure.

6031:    If the option MatSetOption(mat,MAT_KEEP_NONZERO_PATTERN,PETSC_TRUE) the nonzero structure
6032:    of the matrix is not changed (even for AIJ and BAIJ matrices) the values are
6033:    merely zeroed.

6035:    The user can set a value in the diagonal entry (or for the AIJ and
6036:    row formats can optionally remove the main diagonal entry from the
6037:    nonzero structure as well, by passing 0.0 as the final argument).

6039:    For the parallel case, all processes that share the matrix (i.e.,
6040:    those in the communicator used for matrix creation) MUST call this
6041:    routine, regardless of whether any rows being zeroed are owned by
6042:    them.

6044:    Each processor can indicate any rows in the entire matrix to be zeroed (i.e. each process does NOT have to
6045:    list only rows local to itself, but the row/column numbers are given in local numbering).

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

6049:    In Fortran idxm and idxn should be declared as
6050: $     MatStencil idxm(4,m)
6051:    and the values inserted using
6052: $    idxm(MatStencil_i,1) = i
6053: $    idxm(MatStencil_j,1) = j
6054: $    idxm(MatStencil_k,1) = k
6055: $    idxm(MatStencil_c,1) = c
6056:    etc

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

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

6066:    Level: intermediate

6068: .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
6069:           MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRows()
6070: @*/
6071: PetscErrorCode MatZeroRowsColumnsStencil(Mat mat,PetscInt numRows,const MatStencil rows[],PetscScalar diag,Vec x,Vec b)
6072: {
6073:   PetscInt       dim     = mat->stencil.dim;
6074:   PetscInt       sdim    = dim - (1 - (PetscInt) mat->stencil.noc);
6075:   PetscInt       *dims   = mat->stencil.dims+1;
6076:   PetscInt       *starts = mat->stencil.starts;
6077:   PetscInt       *dxm    = (PetscInt*) rows;
6078:   PetscInt       *jdxm, i, j, tmp, numNewRows = 0;


6086:   PetscMalloc1(numRows, &jdxm);
6087:   for (i = 0; i < numRows; ++i) {
6088:     /* Skip unused dimensions (they are ordered k, j, i, c) */
6089:     for (j = 0; j < 3-sdim; ++j) dxm++;
6090:     /* Local index in X dir */
6091:     tmp = *dxm++ - starts[0];
6092:     /* Loop over remaining dimensions */
6093:     for (j = 0; j < dim-1; ++j) {
6094:       /* If nonlocal, set index to be negative */
6095:       if ((*dxm++ - starts[j+1]) < 0 || tmp < 0) tmp = PETSC_MIN_INT;
6096:       /* Update local index */
6097:       else tmp = tmp*dims[j] + *(dxm-1) - starts[j+1];
6098:     }
6099:     /* Skip component slot if necessary */
6100:     if (mat->stencil.noc) dxm++;
6101:     /* Local row number */
6102:     if (tmp >= 0) {
6103:       jdxm[numNewRows++] = tmp;
6104:     }
6105:   }
6106:   MatZeroRowsColumnsLocal(mat,numNewRows,jdxm,diag,x,b);
6107:   PetscFree(jdxm);
6108:   return(0);
6109: }

6111: /*@C
6112:    MatZeroRowsLocal - Zeros all entries (except possibly the main diagonal)
6113:    of a set of rows of a matrix; using local numbering of rows.

6115:    Collective on Mat

6117:    Input Parameters:
6118: +  mat - the matrix
6119: .  numRows - the number of rows to remove
6120: .  rows - the global row indices
6121: .  diag - value put in all diagonals of eliminated rows
6122: .  x - optional vector of solutions for zeroed rows (other entries in vector are not used)
6123: -  b - optional vector of right hand side, that will be adjusted by provided solution

6125:    Notes:
6126:    Before calling MatZeroRowsLocal(), the user must first set the
6127:    local-to-global mapping by calling MatSetLocalToGlobalMapping().

6129:    For the AIJ matrix formats this removes the old nonzero structure,
6130:    but does not release memory.  For the dense and block diagonal
6131:    formats this does not alter the nonzero structure.

6133:    If the option MatSetOption(mat,MAT_KEEP_NONZERO_PATTERN,PETSC_TRUE) the nonzero structure
6134:    of the matrix is not changed (even for AIJ and BAIJ matrices) the values are
6135:    merely zeroed.

6137:    The user can set a value in the diagonal entry (or for the AIJ and
6138:    row formats can optionally remove the main diagonal entry from the
6139:    nonzero structure as well, by passing 0.0 as the final argument).

6141:    You can call MatSetOption(mat,MAT_NO_OFF_PROC_ZERO_ROWS,PETSC_TRUE) if each process indicates only rows it
6142:    owns that are to be zeroed. This saves a global synchronization in the implementation.

6144:    Level: intermediate

6146: .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRows(), MatSetOption(),
6147:           MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
6148: @*/
6149: PetscErrorCode MatZeroRowsLocal(Mat mat,PetscInt numRows,const PetscInt rows[],PetscScalar diag,Vec x,Vec b)
6150: {

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

6161:   if (mat->ops->zerorowslocal) {
6162:     (*mat->ops->zerorowslocal)(mat,numRows,rows,diag,x,b);
6163:   } else {
6164:     IS             is, newis;
6165:     const PetscInt *newRows;

6167:     if (!mat->rmap->mapping) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Need to provide local to global mapping to matrix first");
6168:     ISCreateGeneral(PETSC_COMM_SELF,numRows,rows,PETSC_COPY_VALUES,&is);
6169:     ISLocalToGlobalMappingApplyIS(mat->rmap->mapping,is,&newis);
6170:     ISGetIndices(newis,&newRows);
6171:     (*mat->ops->zerorows)(mat,numRows,newRows,diag,x,b);
6172:     ISRestoreIndices(newis,&newRows);
6173:     ISDestroy(&newis);
6174:     ISDestroy(&is);
6175:   }
6176:   PetscObjectStateIncrease((PetscObject)mat);
6177:   return(0);
6178: }

6180: /*@
6181:    MatZeroRowsLocalIS - Zeros all entries (except possibly the main diagonal)
6182:    of a set of rows of a matrix; using local numbering of rows.

6184:    Collective on Mat

6186:    Input Parameters:
6187: +  mat - the matrix
6188: .  is - index set of rows to remove
6189: .  diag - value put in all diagonals of eliminated rows
6190: .  x - optional vector of solutions for zeroed rows (other entries in vector are not used)
6191: -  b - optional vector of right hand side, that will be adjusted by provided solution

6193:    Notes:
6194:    Before calling MatZeroRowsLocalIS(), the user must first set the
6195:    local-to-global mapping by calling MatSetLocalToGlobalMapping().

6197:    For the AIJ matrix formats this removes the old nonzero structure,
6198:    but does not release memory.  For the dense and block diagonal
6199:    formats this does not alter the nonzero structure.

6201:    If the option MatSetOption(mat,MAT_KEEP_NONZERO_PATTERN,PETSC_TRUE) the nonzero structure
6202:    of the matrix is not changed (even for AIJ and BAIJ matrices) the values are
6203:    merely zeroed.

6205:    The user can set a value in the diagonal entry (or for the AIJ and
6206:    row formats can optionally remove the main diagonal entry from the
6207:    nonzero structure as well, by passing 0.0 as the final argument).

6209:    You can call MatSetOption(mat,MAT_NO_OFF_PROC_ZERO_ROWS,PETSC_TRUE) if each process indicates only rows it
6210:    owns that are to be zeroed. This saves a global synchronization in the implementation.

6212:    Level: intermediate

6214: .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRows(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
6215:           MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
6216: @*/
6217: PetscErrorCode MatZeroRowsLocalIS(Mat mat,IS is,PetscScalar diag,Vec x,Vec b)
6218: {
6220:   PetscInt       numRows;
6221:   const PetscInt *rows;

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

6231:   ISGetLocalSize(is,&numRows);
6232:   ISGetIndices(is,&rows);
6233:   MatZeroRowsLocal(mat,numRows,rows,diag,x,b);
6234:   ISRestoreIndices(is,&rows);
6235:   return(0);
6236: }

6238: /*@
6239:    MatZeroRowsColumnsLocal - Zeros all entries (except possibly the main diagonal)
6240:    of a set of rows and columns of a matrix; using local numbering of rows.

6242:    Collective on Mat

6244:    Input Parameters:
6245: +  mat - the matrix
6246: .  numRows - the number of rows to remove
6247: .  rows - the global row indices
6248: .  diag - value put in all diagonals of eliminated rows
6249: .  x - optional vector of solutions for zeroed rows (other entries in vector are not used)
6250: -  b - optional vector of right hand side, that will be adjusted by provided solution

6252:    Notes:
6253:    Before calling MatZeroRowsColumnsLocal(), the user must first set the
6254:    local-to-global mapping by calling MatSetLocalToGlobalMapping().

6256:    The user can set a value in the diagonal entry (or for the AIJ and
6257:    row formats can optionally remove the main diagonal entry from the
6258:    nonzero structure as well, by passing 0.0 as the final argument).

6260:    Level: intermediate

6262: .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
6263:           MatZeroRows(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
6264: @*/
6265: PetscErrorCode MatZeroRowsColumnsLocal(Mat mat,PetscInt numRows,const PetscInt rows[],PetscScalar diag,Vec x,Vec b)
6266: {
6268:   IS             is, newis;
6269:   const PetscInt *newRows;

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

6279:   if (!mat->cmap->mapping) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Need to provide local to global mapping to matrix first");
6280:   ISCreateGeneral(PETSC_COMM_SELF,numRows,rows,PETSC_COPY_VALUES,&is);
6281:   ISLocalToGlobalMappingApplyIS(mat->cmap->mapping,is,&newis);
6282:   ISGetIndices(newis,&newRows);
6283:   (*mat->ops->zerorowscolumns)(mat,numRows,newRows,diag,x,b);
6284:   ISRestoreIndices(newis,&newRows);
6285:   ISDestroy(&newis);
6286:   ISDestroy(&is);
6287:   PetscObjectStateIncrease((PetscObject)mat);
6288:   return(0);
6289: }

6291: /*@
6292:    MatZeroRowsColumnsLocalIS - Zeros all entries (except possibly the main diagonal)
6293:    of a set of rows and columns of a matrix; using local numbering of rows.

6295:    Collective on Mat

6297:    Input Parameters:
6298: +  mat - the matrix
6299: .  is - index set of rows to remove
6300: .  diag - value put in all diagonals of eliminated rows
6301: .  x - optional vector of solutions for zeroed rows (other entries in vector are not used)
6302: -  b - optional vector of right hand side, that will be adjusted by provided solution

6304:    Notes:
6305:    Before calling MatZeroRowsColumnsLocalIS(), the user must first set the
6306:    local-to-global mapping by calling MatSetLocalToGlobalMapping().

6308:    The user can set a value in the diagonal entry (or for the AIJ and
6309:    row formats can optionally remove the main diagonal entry from the
6310:    nonzero structure as well, by passing 0.0 as the final argument).

6312:    Level: intermediate

6314: .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
6315:           MatZeroRowsColumnsLocal(), MatZeroRows(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
6316: @*/
6317: PetscErrorCode MatZeroRowsColumnsLocalIS(Mat mat,IS is,PetscScalar diag,Vec x,Vec b)
6318: {
6320:   PetscInt       numRows;
6321:   const PetscInt *rows;

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

6331:   ISGetLocalSize(is,&numRows);
6332:   ISGetIndices(is,&rows);
6333:   MatZeroRowsColumnsLocal(mat,numRows,rows,diag,x,b);
6334:   ISRestoreIndices(is,&rows);
6335:   return(0);
6336: }

6338: /*@C
6339:    MatGetSize - Returns the numbers of rows and columns in a matrix.

6341:    Not Collective

6343:    Input Parameter:
6344: .  mat - the matrix

6346:    Output Parameters:
6347: +  m - the number of global rows
6348: -  n - the number of global columns

6350:    Note: both output parameters can be NULL on input.

6352:    Level: beginner

6354: .seealso: MatGetLocalSize()
6355: @*/
6356: PetscErrorCode MatGetSize(Mat mat,PetscInt *m,PetscInt *n)
6357: {
6360:   if (m) *m = mat->rmap->N;
6361:   if (n) *n = mat->cmap->N;
6362:   return(0);
6363: }

6365: /*@C
6366:    MatGetLocalSize - Returns the number of rows and columns in a matrix
6367:    stored locally.  This information may be implementation dependent, so
6368:    use with care.

6370:    Not Collective

6372:    Input Parameters:
6373: .  mat - the matrix

6375:    Output Parameters:
6376: +  m - the number of local rows
6377: -  n - the number of local columns

6379:    Note: both output parameters can be NULL on input.

6381:    Level: beginner

6383: .seealso: MatGetSize()
6384: @*/
6385: PetscErrorCode MatGetLocalSize(Mat mat,PetscInt *m,PetscInt *n)
6386: {
6391:   if (m) *m = mat->rmap->n;
6392:   if (n) *n = mat->cmap->n;
6393:   return(0);
6394: }

6396: /*@C
6397:    MatGetOwnershipRangeColumn - Returns the range of matrix columns associated with rows of a vector one multiplies by that owned by
6398:    this processor. (The columns of the "diagonal block")

6400:    Not Collective, unless matrix has not been allocated, then collective on Mat

6402:    Input Parameters:
6403: .  mat - the matrix

6405:    Output Parameters:
6406: +  m - the global index of the first local column
6407: -  n - one more than the global index of the last local column

6409:    Notes:
6410:     both output parameters can be NULL on input.

6412:    Level: developer

6414: .seealso:  MatGetOwnershipRange(), MatGetOwnershipRanges(), MatGetOwnershipRangesColumn()

6416: @*/
6417: PetscErrorCode MatGetOwnershipRangeColumn(Mat mat,PetscInt *m,PetscInt *n)
6418: {
6424:   MatCheckPreallocated(mat,1);
6425:   if (m) *m = mat->cmap->rstart;
6426:   if (n) *n = mat->cmap->rend;
6427:   return(0);
6428: }

6430: /*@C
6431:    MatGetOwnershipRange - Returns the range of matrix rows owned by
6432:    this processor, assuming that the matrix is laid out with the first
6433:    n1 rows on the first processor, the next n2 rows on the second, etc.
6434:    For certain parallel layouts this range may not be well defined.

6436:    Not Collective

6438:    Input Parameters:
6439: .  mat - the matrix

6441:    Output Parameters:
6442: +  m - the global index of the first local row
6443: -  n - one more than the global index of the last local row

6445:    Note: Both output parameters can be NULL on input.
6446: $  This function requires that the matrix be preallocated. If you have not preallocated, consider using
6447: $    PetscSplitOwnership(MPI_Comm comm, PetscInt *n, PetscInt *N)
6448: $  and then MPI_Scan() to calculate prefix sums of the local sizes.

6450:    Level: beginner

6452: .seealso:   MatGetOwnershipRanges(), MatGetOwnershipRangeColumn(), MatGetOwnershipRangesColumn(), PetscSplitOwnership(), PetscSplitOwnershipBlock()

6454: @*/
6455: PetscErrorCode MatGetOwnershipRange(Mat mat,PetscInt *m,PetscInt *n)
6456: {
6462:   MatCheckPreallocated(mat,1);
6463:   if (m) *m = mat->rmap->rstart;
6464:   if (n) *n = mat->rmap->rend;
6465:   return(0);
6466: }

6468: /*@C
6469:    MatGetOwnershipRanges - Returns the range of matrix rows owned by
6470:    each process

6472:    Not Collective, unless matrix has not been allocated, then collective on Mat

6474:    Input Parameters:
6475: .  mat - the matrix

6477:    Output Parameters:
6478: .  ranges - start of each processors portion plus one more than the total length at the end

6480:    Level: beginner

6482: .seealso:   MatGetOwnershipRange(), MatGetOwnershipRangeColumn(), MatGetOwnershipRangesColumn()

6484: @*/
6485: PetscErrorCode MatGetOwnershipRanges(Mat mat,const PetscInt **ranges)
6486: {

6492:   MatCheckPreallocated(mat,1);
6493:   PetscLayoutGetRanges(mat->rmap,ranges);
6494:   return(0);
6495: }

6497: /*@C
6498:    MatGetOwnershipRangesColumn - Returns the range of matrix columns associated with rows of a vector one multiplies by that owned by
6499:    this processor. (The columns of the "diagonal blocks" for each process)

6501:    Not Collective, unless matrix has not been allocated, then collective on Mat

6503:    Input Parameters:
6504: .  mat - the matrix

6506:    Output Parameters:
6507: .  ranges - start of each processors portion plus one more then the total length at the end

6509:    Level: beginner

6511: .seealso:   MatGetOwnershipRange(), MatGetOwnershipRangeColumn(), MatGetOwnershipRanges()

6513: @*/
6514: PetscErrorCode MatGetOwnershipRangesColumn(Mat mat,const PetscInt **ranges)
6515: {

6521:   MatCheckPreallocated(mat,1);
6522:   PetscLayoutGetRanges(mat->cmap,ranges);
6523:   return(0);
6524: }

6526: /*@C
6527:    MatGetOwnershipIS - Get row and column ownership as index sets

6529:    Not Collective

6531:    Input Arguments:
6532: .  A - matrix of type Elemental

6534:    Output Arguments:
6535: +  rows - rows in which this process owns elements
6536: -  cols - columns in which this process owns elements

6538:    Level: intermediate

6540: .seealso: MatGetOwnershipRange(), MatGetOwnershipRangeColumn(), MatSetValues(), MATELEMENTAL
6541: @*/
6542: PetscErrorCode MatGetOwnershipIS(Mat A,IS *rows,IS *cols)
6543: {
6544:   PetscErrorCode ierr,(*f)(Mat,IS*,IS*);

6547:   MatCheckPreallocated(A,1);
6548:   PetscObjectQueryFunction((PetscObject)A,"MatGetOwnershipIS_C",&f);
6549:   if (f) {
6550:     (*f)(A,rows,cols);
6551:   } else {   /* Create a standard row-based partition, each process is responsible for ALL columns in their row block */
6552:     if (rows) {ISCreateStride(PETSC_COMM_SELF,A->rmap->n,A->rmap->rstart,1,rows);}
6553:     if (cols) {ISCreateStride(PETSC_COMM_SELF,A->cmap->N,0,1,cols);}
6554:   }
6555:   return(0);
6556: }

6558: /*@C
6559:    MatILUFactorSymbolic - Performs symbolic ILU factorization of a matrix.
6560:    Uses levels of fill only, not drop tolerance. Use MatLUFactorNumeric()
6561:    to complete the factorization.

6563:    Collective on Mat

6565:    Input Parameters:
6566: +  mat - the matrix
6567: .  row - row permutation
6568: .  column - column permutation
6569: -  info - structure containing
6570: $      levels - number of levels of fill.
6571: $      expected fill - as ratio of original fill.
6572: $      1 or 0 - indicating force fill on diagonal (improves robustness for matrices
6573:                 missing diagonal entries)

6575:    Output Parameters:
6576: .  fact - new matrix that has been symbolically factored

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

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

6585:    Level: developer

6587: .seealso: MatLUFactorSymbolic(), MatLUFactorNumeric(), MatCholeskyFactor()
6588:           MatGetOrdering(), MatFactorInfo

6590:     Note: this uses the definition of level of fill as in Y. Saad, 2003

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

6595:    References:
6596:      Y. Saad, Iterative methods for sparse linear systems Philadelphia: Society for Industrial and Applied Mathematics, 2003
6597: @*/
6598: PetscErrorCode MatILUFactorSymbolic(Mat fact,Mat mat,IS row,IS col,const MatFactorInfo *info)
6599: {

6609:   if (info->levels < 0) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_OUTOFRANGE,"Levels of fill negative %D",(PetscInt)info->levels);
6610:   if (info->fill < 1.0) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_OUTOFRANGE,"Expected fill less than 1.0 %g",(double)info->fill);
6611:   if (!(fact)->ops->ilufactorsymbolic) {
6612:     MatSolverType spackage;
6613:     MatFactorGetSolverType(fact,&spackage);
6614:     SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Matrix type %s symbolic ILU using solver package %s",((PetscObject)mat)->type_name,spackage);
6615:   }
6616:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6617:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6618:   MatCheckPreallocated(mat,2);

6620:   PetscLogEventBegin(MAT_ILUFactorSymbolic,mat,row,col,0);
6621:   (fact->ops->ilufactorsymbolic)(fact,mat,row,col,info);
6622:   PetscLogEventEnd(MAT_ILUFactorSymbolic,mat,row,col,0);
6623:   return(0);
6624: }

6626: /*@C
6627:    MatICCFactorSymbolic - Performs symbolic incomplete
6628:    Cholesky factorization for a symmetric matrix.  Use
6629:    MatCholeskyFactorNumeric() to complete the factorization.

6631:    Collective on Mat

6633:    Input Parameters:
6634: +  mat - the matrix
6635: .  perm - row and column permutation
6636: -  info - structure containing
6637: $      levels - number of levels of fill.
6638: $      expected fill - as ratio of original fill.

6640:    Output Parameter:
6641: .  fact - the factored matrix

6643:    Notes:
6644:    Most users should employ the KSP interface for linear solvers
6645:    instead of working directly with matrix algebra routines such as this.
6646:    See, e.g., KSPCreate().

6648:    Level: developer

6650: .seealso: MatCholeskyFactorNumeric(), MatCholeskyFactor(), MatFactorInfo

6652:     Note: this uses the definition of level of fill as in Y. Saad, 2003

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

6657:    References:
6658:      Y. Saad, Iterative methods for sparse linear systems Philadelphia: Society for Industrial and Applied Mathematics, 2003
6659: @*/
6660: PetscErrorCode MatICCFactorSymbolic(Mat fact,Mat mat,IS perm,const MatFactorInfo *info)
6661: {

6670:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6671:   if (info->levels < 0) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_OUTOFRANGE,"Levels negative %D",(PetscInt) info->levels);
6672:   if (info->fill < 1.0) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_OUTOFRANGE,"Expected fill less than 1.0 %g",(double)info->fill);
6673:   if (!(fact)->ops->iccfactorsymbolic) {
6674:     MatSolverType spackage;
6675:     MatFactorGetSolverType(fact,&spackage);
6676:     SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Matrix type %s symbolic ICC using solver package %s",((PetscObject)mat)->type_name,spackage);
6677:   }
6678:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6679:   MatCheckPreallocated(mat,2);

6681:   PetscLogEventBegin(MAT_ICCFactorSymbolic,mat,perm,0,0);
6682:   (fact->ops->iccfactorsymbolic)(fact,mat,perm,info);
6683:   PetscLogEventEnd(MAT_ICCFactorSymbolic,mat,perm,0,0);
6684:   return(0);
6685: }

6687: /*@C
6688:    MatCreateSubMatrices - Extracts several submatrices from a matrix. If submat
6689:    points to an array of valid matrices, they may be reused to store the new
6690:    submatrices.

6692:    Collective on Mat

6694:    Input Parameters:
6695: +  mat - the matrix
6696: .  n   - the number of submatrixes to be extracted (on this processor, may be zero)
6697: .  irow, icol - index sets of rows and columns to extract
6698: -  scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX

6700:    Output Parameter:
6701: .  submat - the array of submatrices

6703:    Notes:
6704:    MatCreateSubMatrices() can extract ONLY sequential submatrices
6705:    (from both sequential and parallel matrices). Use MatCreateSubMatrix()
6706:    to extract a parallel submatrix.

6708:    Some matrix types place restrictions on the row and column
6709:    indices, such as that they be sorted or that they be equal to each other.

6711:    The index sets may not have duplicate entries.

6713:    When extracting submatrices from a parallel matrix, each processor can
6714:    form a different submatrix by setting the rows and columns of its
6715:    individual index sets according to the local submatrix desired.

6717:    When finished using the submatrices, the user should destroy
6718:    them with MatDestroySubMatrices().

6720:    MAT_REUSE_MATRIX can only be used when the nonzero structure of the
6721:    original matrix has not changed from that last call to MatCreateSubMatrices().

6723:    This routine creates the matrices in submat; you should NOT create them before
6724:    calling it. It also allocates the array of matrix pointers submat.

6726:    For BAIJ matrices the index sets must respect the block structure, that is if they
6727:    request one row/column in a block, they must request all rows/columns that are in
6728:    that block. For example, if the block size is 2 you cannot request just row 0 and
6729:    column 0.

6731:    Fortran Note:
6732:    The Fortran interface is slightly different from that given below; it
6733:    requires one to pass in  as submat a Mat (integer) array of size at least n+1.

6735:    Level: advanced


6738: .seealso: MatDestroySubMatrices(), MatCreateSubMatrix(), MatGetRow(), MatGetDiagonal(), MatReuse
6739: @*/
6740: PetscErrorCode MatCreateSubMatrices(Mat mat,PetscInt n,const IS irow[],const IS icol[],MatReuse scall,Mat *submat[])
6741: {
6743:   PetscInt       i;
6744:   PetscBool      eq;

6749:   if (n) {
6754:   }
6756:   if (n && scall == MAT_REUSE_MATRIX) {
6759:   }
6760:   if (!mat->ops->createsubmatrices) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
6761:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6762:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6763:   MatCheckPreallocated(mat,1);

6765:   PetscLogEventBegin(MAT_CreateSubMats,mat,0,0,0);
6766:   (*mat->ops->createsubmatrices)(mat,n,irow,icol,scall,submat);
6767:   PetscLogEventEnd(MAT_CreateSubMats,mat,0,0,0);
6768:   for (i=0; i<n; i++) {
6769:     (*submat)[i]->factortype = MAT_FACTOR_NONE;  /* in case in place factorization was previously done on submatrix */
6770:     ISEqualUnsorted(irow[i],icol[i],&eq);
6771:     if (eq) {
6772:       MatPropagateSymmetryOptions(mat,(*submat)[i]);
6773:     }
6774:   }
6775:   return(0);
6776: }

6778: /*@C
6779:    MatCreateSubMatricesMPI - Extracts MPI submatrices across a sub communicator of mat (by pairs of IS that may live on subcomms).

6781:    Collective on Mat

6783:    Input Parameters:
6784: +  mat - the matrix
6785: .  n   - the number of submatrixes to be extracted
6786: .  irow, icol - index sets of rows and columns to extract
6787: -  scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX

6789:    Output Parameter:
6790: .  submat - the array of submatrices

6792:    Level: advanced


6795: .seealso: MatCreateSubMatrices(), MatCreateSubMatrix(), MatGetRow(), MatGetDiagonal(), MatReuse
6796: @*/
6797: PetscErrorCode MatCreateSubMatricesMPI(Mat mat,PetscInt n,const IS irow[],const IS icol[],MatReuse scall,Mat *submat[])
6798: {
6800:   PetscInt       i;
6801:   PetscBool      eq;

6806:   if (n) {
6811:   }
6813:   if (n && scall == MAT_REUSE_MATRIX) {
6816:   }
6817:   if (!mat->ops->createsubmatricesmpi) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
6818:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6819:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6820:   MatCheckPreallocated(mat,1);

6822:   PetscLogEventBegin(MAT_CreateSubMats,mat,0,0,0);
6823:   (*mat->ops->createsubmatricesmpi)(mat,n,irow,icol,scall,submat);
6824:   PetscLogEventEnd(MAT_CreateSubMats,mat,0,0,0);
6825:   for (i=0; i<n; i++) {
6826:     ISEqualUnsorted(irow[i],icol[i],&eq);
6827:     if (eq) {
6828:       MatPropagateSymmetryOptions(mat,(*submat)[i]);
6829:     }
6830:   }
6831:   return(0);
6832: }

6834: /*@C
6835:    MatDestroyMatrices - Destroys an array of matrices.

6837:    Collective on Mat

6839:    Input Parameters:
6840: +  n - the number of local matrices
6841: -  mat - the matrices (note that this is a pointer to the array of matrices)

6843:    Level: advanced

6845:     Notes:
6846:     Frees not only the matrices, but also the array that contains the matrices
6847:            In Fortran will not free the array.

6849: .seealso: MatCreateSubMatrices() MatDestroySubMatrices()
6850: @*/
6851: PetscErrorCode MatDestroyMatrices(PetscInt n,Mat *mat[])
6852: {
6854:   PetscInt       i;

6857:   if (!*mat) return(0);
6858:   if (n < 0) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Trying to destroy negative number of matrices %D",n);

6861:   for (i=0; i<n; i++) {
6862:     MatDestroy(&(*mat)[i]);
6863:   }

6865:   /* memory is allocated even if n = 0 */
6866:   PetscFree(*mat);
6867:   return(0);
6868: }

6870: /*@C
6871:    MatDestroySubMatrices - Destroys a set of matrices obtained with MatCreateSubMatrices().

6873:    Collective on Mat

6875:    Input Parameters:
6876: +  n - the number of local matrices
6877: -  mat - the matrices (note that this is a pointer to the array of matrices, just to match the calling
6878:                        sequence of MatCreateSubMatrices())

6880:    Level: advanced

6882:     Notes:
6883:     Frees not only the matrices, but also the array that contains the matrices
6884:            In Fortran will not free the array.

6886: .seealso: MatCreateSubMatrices()
6887: @*/
6888: PetscErrorCode MatDestroySubMatrices(PetscInt n,Mat *mat[])
6889: {
6891:   Mat            mat0;

6894:   if (!*mat) return(0);
6895:   /* mat[] is an array of length n+1, see MatCreateSubMatrices_xxx() */
6896:   if (n < 0) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Trying to destroy negative number of matrices %D",n);

6899:   mat0 = (*mat)[0];
6900:   if (mat0 && mat0->ops->destroysubmatrices) {
6901:     (mat0->ops->destroysubmatrices)(n,mat);
6902:   } else {
6903:     MatDestroyMatrices(n,mat);
6904:   }
6905:   return(0);
6906: }

6908: /*@C
6909:    MatGetSeqNonzeroStructure - Extracts the sequential nonzero structure from a matrix.

6911:    Collective on Mat

6913:    Input Parameters:
6914: .  mat - the matrix

6916:    Output Parameter:
6917: .  matstruct - the sequential matrix with the nonzero structure of mat

6919:   Level: intermediate

6921: .seealso: MatDestroySeqNonzeroStructure(), MatCreateSubMatrices(), MatDestroyMatrices()
6922: @*/
6923: PetscErrorCode MatGetSeqNonzeroStructure(Mat mat,Mat *matstruct)
6924: {


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

6935:   if (!mat->ops->getseqnonzerostructure) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Not for matrix type %s\n",((PetscObject)mat)->type_name);
6936:   PetscLogEventBegin(MAT_GetSeqNonzeroStructure,mat,0,0,0);
6937:   (*mat->ops->getseqnonzerostructure)(mat,matstruct);
6938:   PetscLogEventEnd(MAT_GetSeqNonzeroStructure,mat,0,0,0);
6939:   return(0);
6940: }

6942: /*@C
6943:    MatDestroySeqNonzeroStructure - Destroys matrix obtained with MatGetSeqNonzeroStructure().

6945:    Collective on Mat

6947:    Input Parameters:
6948: .  mat - the matrix (note that this is a pointer to the array of matrices, just to match the calling
6949:                        sequence of MatGetSequentialNonzeroStructure())

6951:    Level: advanced

6953:     Notes:
6954:     Frees not only the matrices, but also the array that contains the matrices

6956: .seealso: MatGetSeqNonzeroStructure()
6957: @*/
6958: PetscErrorCode MatDestroySeqNonzeroStructure(Mat *mat)
6959: {

6964:   MatDestroy(mat);
6965:   return(0);
6966: }

6968: /*@
6969:    MatIncreaseOverlap - Given a set of submatrices indicated by index sets,
6970:    replaces the index sets by larger ones that represent submatrices with
6971:    additional overlap.

6973:    Collective on Mat

6975:    Input Parameters:
6976: +  mat - the matrix
6977: .  n   - the number of index sets
6978: .  is  - the array of index sets (these index sets will changed during the call)
6979: -  ov  - the additional overlap requested

6981:    Options Database:
6982: .  -mat_increase_overlap_scalable - use a scalable algorithm to compute the overlap (supported by MPIAIJ matrix)

6984:    Level: developer


6987: .seealso: MatCreateSubMatrices()
6988: @*/
6989: PetscErrorCode MatIncreaseOverlap(Mat mat,PetscInt n,IS is[],PetscInt ov)
6990: {

6996:   if (n < 0) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Must have one or more domains, you have %D",n);
6997:   if (n) {
7000:   }
7001:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
7002:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
7003:   MatCheckPreallocated(mat,1);

7005:   if (!ov) return(0);
7006:   if (!mat->ops->increaseoverlap) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
7007:   PetscLogEventBegin(MAT_IncreaseOverlap,mat,0,0,0);
7008:   (*mat->ops->increaseoverlap)(mat,n,is,ov);
7009:   PetscLogEventEnd(MAT_IncreaseOverlap,mat,0,0,0);
7010:   return(0);
7011: }


7014: PetscErrorCode MatIncreaseOverlapSplit_Single(Mat,IS*,PetscInt);

7016: /*@
7017:    MatIncreaseOverlapSplit - Given a set of submatrices indicated by index sets across
7018:    a sub communicator, replaces the index sets by larger ones that represent submatrices with
7019:    additional overlap.

7021:    Collective on Mat

7023:    Input Parameters:
7024: +  mat - the matrix
7025: .  n   - the number of index sets
7026: .  is  - the array of index sets (these index sets will changed during the call)
7027: -  ov  - the additional overlap requested

7029:    Options Database:
7030: .  -mat_increase_overlap_scalable - use a scalable algorithm to compute the overlap (supported by MPIAIJ matrix)

7032:    Level: developer


7035: .seealso: MatCreateSubMatrices()
7036: @*/
7037: PetscErrorCode MatIncreaseOverlapSplit(Mat mat,PetscInt n,IS is[],PetscInt ov)
7038: {
7039:   PetscInt       i;

7045:   if (n < 0) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Must have one or more domains, you have %D",n);
7046:   if (n) {
7049:   }
7050:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
7051:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
7052:   MatCheckPreallocated(mat,1);
7053:   if (!ov) return(0);
7054:   PetscLogEventBegin(MAT_IncreaseOverlap,mat,0,0,0);
7055:   for(i=0; i<n; i++){
7056:          MatIncreaseOverlapSplit_Single(mat,&is[i],ov);
7057:   }
7058:   PetscLogEventEnd(MAT_IncreaseOverlap,mat,0,0,0);
7059:   return(0);
7060: }




7065: /*@
7066:    MatGetBlockSize - Returns the matrix block size.

7068:    Not Collective

7070:    Input Parameter:
7071: .  mat - the matrix

7073:    Output Parameter:
7074: .  bs - block size

7076:    Notes:
7077:     Block row formats are MATSEQBAIJ, MATMPIBAIJ, MATSEQSBAIJ, MATMPISBAIJ. These formats ALWAYS have square block storage in the matrix.

7079:    If the block size has not been set yet this routine returns 1.

7081:    Level: intermediate

7083: .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSizes()
7084: @*/
7085: PetscErrorCode MatGetBlockSize(Mat mat,PetscInt *bs)
7086: {
7090:   *bs = PetscAbs(mat->rmap->bs);
7091:   return(0);
7092: }

7094: /*@
7095:    MatGetBlockSizes - Returns the matrix block row and column sizes.

7097:    Not Collective

7099:    Input Parameter:
7100: .  mat - the matrix

7102:    Output Parameter:
7103: +  rbs - row block size
7104: -  cbs - column block size

7106:    Notes:
7107:     Block row formats are MATSEQBAIJ, MATMPIBAIJ, MATSEQSBAIJ, MATMPISBAIJ. These formats ALWAYS have square block storage in the matrix.
7108:     If you pass a different block size for the columns than the rows, the row block size determines the square block storage.

7110:    If a block size has not been set yet this routine returns 1.

7112:    Level: intermediate

7114: .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSize(), MatSetBlockSize(), MatSetBlockSizes()
7115: @*/
7116: PetscErrorCode MatGetBlockSizes(Mat mat,PetscInt *rbs, PetscInt *cbs)
7117: {
7122:   if (rbs) *rbs = PetscAbs(mat->rmap->bs);
7123:   if (cbs) *cbs = PetscAbs(mat->cmap->bs);
7124:   return(0);
7125: }

7127: /*@
7128:    MatSetBlockSize - Sets the matrix block size.

7130:    Logically Collective on Mat

7132:    Input Parameters:
7133: +  mat - the matrix
7134: -  bs - block size

7136:    Notes:
7137:     Block row formats are MATSEQBAIJ, MATMPIBAIJ, MATSEQSBAIJ, MATMPISBAIJ. These formats ALWAYS have square block storage in the matrix.
7138:     This must be called before MatSetUp() or MatXXXSetPreallocation() (or will default to 1) and the block size cannot be changed later.

7140:     For MATMPIAIJ and MATSEQAIJ matrix formats, this function can be called at a later stage, provided that the specified block size
7141:     is compatible with the matrix local sizes.

7143:    Level: intermediate

7145: .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSize(), MatSetBlockSizes(), MatGetBlockSizes()
7146: @*/
7147: PetscErrorCode MatSetBlockSize(Mat mat,PetscInt bs)
7148: {

7154:   MatSetBlockSizes(mat,bs,bs);
7155:   return(0);
7156: }

7158: /*@
7159:    MatSetVariableBlockSizes - Sets a diagonal blocks of the matrix that need not be of the same size

7161:    Logically Collective on Mat

7163:    Input Parameters:
7164: +  mat - the matrix
7165: .  nblocks - the number of blocks on this process
7166: -  bsizes - the block sizes

7168:    Notes:
7169:     Currently used by PCVPBJACOBI for SeqAIJ matrices

7171:    Level: intermediate

7173: .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSize(), MatSetBlockSizes(), MatGetBlockSizes(), MatGetVariableBlockSizes()
7174: @*/
7175: PetscErrorCode MatSetVariableBlockSizes(Mat mat,PetscInt nblocks,PetscInt *bsizes)
7176: {
7178:   PetscInt       i,ncnt = 0, nlocal;

7182:   if (nblocks < 0) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Number of local blocks must be great than or equal to zero");
7183:   MatGetLocalSize(mat,&nlocal,NULL);
7184:   for (i=0; i<nblocks; i++) ncnt += bsizes[i];
7185:   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);
7186:   PetscFree(mat->bsizes);
7187:   mat->nblocks = nblocks;
7188:   PetscMalloc1(nblocks,&mat->bsizes);
7189:   PetscArraycpy(mat->bsizes,bsizes,nblocks);
7190:   return(0);
7191: }

7193: /*@C
7194:    MatGetVariableBlockSizes - Gets a diagonal blocks of the matrix that need not be of the same size

7196:    Logically Collective on Mat

7198:    Input Parameters:
7199: .  mat - the matrix

7201:    Output Parameters:
7202: +  nblocks - the number of blocks on this process
7203: -  bsizes - the block sizes

7205:    Notes: Currently not supported from Fortran

7207:    Level: intermediate

7209: .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSize(), MatSetBlockSizes(), MatGetBlockSizes(), MatSetVariableBlockSizes()
7210: @*/
7211: PetscErrorCode MatGetVariableBlockSizes(Mat mat,PetscInt *nblocks,const PetscInt **bsizes)
7212: {
7215:   *nblocks = mat->nblocks;
7216:   *bsizes  = mat->bsizes;
7217:   return(0);
7218: }

7220: /*@
7221:    MatSetBlockSizes - Sets the matrix block row and column sizes.

7223:    Logically Collective on Mat

7225:    Input Parameters:
7226: +  mat - the matrix
7227: .  rbs - row block size
7228: -  cbs - column block size

7230:    Notes:
7231:     Block row formats are MATSEQBAIJ, MATMPIBAIJ, MATSEQSBAIJ, MATMPISBAIJ. These formats ALWAYS have square block storage in the matrix.
7232:     If you pass a different block size for the columns than the rows, the row block size determines the square block storage.
7233:     This must be called before MatSetUp() or MatXXXSetPreallocation() (or will default to 1) and the block size cannot be changed later.

7235:     For MATMPIAIJ and MATSEQAIJ matrix formats, this function can be called at a later stage, provided that the specified block sizes
7236:     are compatible with the matrix local sizes.

7238:     The row and column block size determine the blocksize of the "row" and "column" vectors returned by MatCreateVecs().

7240:    Level: intermediate

7242: .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSize(), MatSetBlockSize(), MatGetBlockSizes()
7243: @*/
7244: PetscErrorCode MatSetBlockSizes(Mat mat,PetscInt rbs,PetscInt cbs)
7245: {

7252:   if (mat->ops->setblocksizes) {
7253:     (*mat->ops->setblocksizes)(mat,rbs,cbs);
7254:   }
7255:   if (mat->rmap->refcnt) {
7256:     ISLocalToGlobalMapping l2g = NULL;
7257:     PetscLayout            nmap = NULL;

7259:     PetscLayoutDuplicate(mat->rmap,&nmap);
7260:     if (mat->rmap->mapping) {
7261:       ISLocalToGlobalMappingDuplicate(mat->rmap->mapping,&l2g);
7262:     }
7263:     PetscLayoutDestroy(&mat->rmap);
7264:     mat->rmap = nmap;
7265:     mat->rmap->mapping = l2g;
7266:   }
7267:   if (mat->cmap->refcnt) {
7268:     ISLocalToGlobalMapping l2g = NULL;
7269:     PetscLayout            nmap = NULL;

7271:     PetscLayoutDuplicate(mat->cmap,&nmap);
7272:     if (mat->cmap->mapping) {
7273:       ISLocalToGlobalMappingDuplicate(mat->cmap->mapping,&l2g);
7274:     }
7275:     PetscLayoutDestroy(&mat->cmap);
7276:     mat->cmap = nmap;
7277:     mat->cmap->mapping = l2g;
7278:   }
7279:   PetscLayoutSetBlockSize(mat->rmap,rbs);
7280:   PetscLayoutSetBlockSize(mat->cmap,cbs);
7281:   return(0);
7282: }

7284: /*@
7285:    MatSetBlockSizesFromMats - Sets the matrix block row and column sizes to match a pair of matrices

7287:    Logically Collective on Mat

7289:    Input Parameters:
7290: +  mat - the matrix
7291: .  fromRow - matrix from which to copy row block size
7292: -  fromCol - matrix from which to copy column block size (can be same as fromRow)

7294:    Level: developer

7296: .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSize(), MatSetBlockSizes()
7297: @*/
7298: PetscErrorCode MatSetBlockSizesFromMats(Mat mat,Mat fromRow,Mat fromCol)
7299: {

7306:   if (fromRow->rmap->bs > 0) {PetscLayoutSetBlockSize(mat->rmap,fromRow->rmap->bs);}
7307:   if (fromCol->cmap->bs > 0) {PetscLayoutSetBlockSize(mat->cmap,fromCol->cmap->bs);}
7308:   return(0);
7309: }

7311: /*@
7312:    MatResidual - Default routine to calculate the residual.

7314:    Collective on Mat

7316:    Input Parameters:
7317: +  mat - the matrix
7318: .  b   - the right-hand-side
7319: -  x   - the approximate solution

7321:    Output Parameter:
7322: .  r - location to store the residual

7324:    Level: developer

7326: .seealso: PCMGSetResidual()
7327: @*/
7328: PetscErrorCode MatResidual(Mat mat,Vec b,Vec x,Vec r)
7329: {

7338:   MatCheckPreallocated(mat,1);
7339:   PetscLogEventBegin(MAT_Residual,mat,0,0,0);
7340:   if (!mat->ops->residual) {
7341:     MatMult(mat,x,r);
7342:     VecAYPX(r,-1.0,b);
7343:   } else {
7344:     (*mat->ops->residual)(mat,b,x,r);
7345:   }
7346:   PetscLogEventEnd(MAT_Residual,mat,0,0,0);
7347:   return(0);
7348: }

7350: /*@C
7351:     MatGetRowIJ - Returns the compressed row storage i and j indices for sequential matrices.

7353:    Collective on Mat

7355:     Input Parameters:
7356: +   mat - the matrix
7357: .   shift -  0 or 1 indicating we want the indices starting at 0 or 1
7358: .   symmetric - PETSC_TRUE or PETSC_FALSE indicating the matrix data structure should be   symmetrized
7359: -   inodecompressed - PETSC_TRUE or PETSC_FALSE  indicating if the nonzero structure of the
7360:                  inodes or the nonzero elements is wanted. For BAIJ matrices the compressed version is
7361:                  always used.

7363:     Output Parameters:
7364: +   n - number of rows in the (possibly compressed) matrix
7365: .   ia - the row pointers; that is ia[0] = 0, ia[row] = ia[row-1] + number of elements in that row of the matrix
7366: .   ja - the column indices
7367: -   done - indicates if the routine actually worked and returned appropriate ia[] and ja[] arrays; callers
7368:            are responsible for handling the case when done == PETSC_FALSE and ia and ja are not set

7370:     Level: developer

7372:     Notes:
7373:     You CANNOT change any of the ia[] or ja[] values.

7375:     Use MatRestoreRowIJ() when you are finished accessing the ia[] and ja[] values.

7377:     Fortran Notes:
7378:     In Fortran use
7379: $
7380: $      PetscInt ia(1), ja(1)
7381: $      PetscOffset iia, jja
7382: $      call MatGetRowIJ(mat,shift,symmetric,inodecompressed,n,ia,iia,ja,jja,done,ierr)
7383: $      ! Access the ith and jth entries via ia(iia + i) and ja(jja + j)

7385:      or
7386: $
7387: $    PetscInt, pointer :: ia(:),ja(:)
7388: $    call MatGetRowIJF90(mat,shift,symmetric,inodecompressed,n,ia,ja,done,ierr)
7389: $    ! Access the ith and jth entries via ia(i) and ja(j)

7391: .seealso: MatGetColumnIJ(), MatRestoreRowIJ(), MatSeqAIJGetArray()
7392: @*/
7393: PetscErrorCode MatGetRowIJ(Mat mat,PetscInt shift,PetscBool symmetric,PetscBool inodecompressed,PetscInt *n,const PetscInt *ia[],const PetscInt *ja[],PetscBool  *done)
7394: {

7404:   MatCheckPreallocated(mat,1);
7405:   if (!mat->ops->getrowij) *done = PETSC_FALSE;
7406:   else {
7407:     *done = PETSC_TRUE;
7408:     PetscLogEventBegin(MAT_GetRowIJ,mat,0,0,0);
7409:     (*mat->ops->getrowij)(mat,shift,symmetric,inodecompressed,n,ia,ja,done);
7410:     PetscLogEventEnd(MAT_GetRowIJ,mat,0,0,0);
7411:   }
7412:   return(0);
7413: }

7415: /*@C
7416:     MatGetColumnIJ - Returns the compressed column storage i and j indices for sequential matrices.

7418:     Collective on Mat

7420:     Input Parameters:
7421: +   mat - the matrix
7422: .   shift - 1 or zero indicating we want the indices starting at 0 or 1
7423: .   symmetric - PETSC_TRUE or PETSC_FALSE indicating the matrix data structure should be
7424:                 symmetrized
7425: .   inodecompressed - PETSC_TRUE or PETSC_FALSE indicating if the nonzero structure of the
7426:                  inodes or the nonzero elements is wanted. For BAIJ matrices the compressed version is
7427:                  always used.
7428: .   n - number of columns in the (possibly compressed) matrix
7429: .   ia - the column pointers; that is ia[0] = 0, ia[col] = i[col-1] + number of elements in that col of the matrix
7430: -   ja - the row indices

7432:     Output Parameters:
7433: .   done - PETSC_TRUE or PETSC_FALSE, indicating whether the values have been returned

7435:     Level: developer

7437: .seealso: MatGetRowIJ(), MatRestoreColumnIJ()
7438: @*/
7439: PetscErrorCode MatGetColumnIJ(Mat mat,PetscInt shift,PetscBool symmetric,PetscBool inodecompressed,PetscInt *n,const PetscInt *ia[],const PetscInt *ja[],PetscBool  *done)
7440: {

7450:   MatCheckPreallocated(mat,1);
7451:   if (!mat->ops->getcolumnij) *done = PETSC_FALSE;
7452:   else {
7453:     *done = PETSC_TRUE;
7454:     (*mat->ops->getcolumnij)(mat,shift,symmetric,inodecompressed,n,ia,ja,done);
7455:   }
7456:   return(0);
7457: }

7459: /*@C
7460:     MatRestoreRowIJ - Call after you are completed with the ia,ja indices obtained with
7461:     MatGetRowIJ().

7463:     Collective on Mat

7465:     Input Parameters:
7466: +   mat - the matrix
7467: .   shift - 1 or zero indicating we want the indices starting at 0 or 1
7468: .   symmetric - PETSC_TRUE or PETSC_FALSE indicating the matrix data structure should be
7469:                 symmetrized
7470: .   inodecompressed -  PETSC_TRUE or PETSC_FALSE indicating if the nonzero structure of the
7471:                  inodes or the nonzero elements is wanted. For BAIJ matrices the compressed version is
7472:                  always used.
7473: .   n - size of (possibly compressed) matrix
7474: .   ia - the row pointers
7475: -   ja - the column indices

7477:     Output Parameters:
7478: .   done - PETSC_TRUE or PETSC_FALSE indicated that the values have been returned

7480:     Note:
7481:     This routine zeros out n, ia, and ja. This is to prevent accidental
7482:     us of the array after it has been restored. If you pass NULL, it will
7483:     not zero the pointers.  Use of ia or ja after MatRestoreRowIJ() is invalid.

7485:     Level: developer

7487: .seealso: MatGetRowIJ(), MatRestoreColumnIJ()
7488: @*/
7489: PetscErrorCode MatRestoreRowIJ(Mat mat,PetscInt shift,PetscBool symmetric,PetscBool inodecompressed,PetscInt *n,const PetscInt *ia[],const PetscInt *ja[],PetscBool  *done)
7490: {

7499:   MatCheckPreallocated(mat,1);

7501:   if (!mat->ops->restorerowij) *done = PETSC_FALSE;
7502:   else {
7503:     *done = PETSC_TRUE;
7504:     (*mat->ops->restorerowij)(mat,shift,symmetric,inodecompressed,n,ia,ja,done);
7505:     if (n)  *n = 0;
7506:     if (ia) *ia = NULL;
7507:     if (ja) *ja = NULL;
7508:   }
7509:   return(0);
7510: }

7512: /*@C
7513:     MatRestoreColumnIJ - Call after you are completed with the ia,ja indices obtained with
7514:     MatGetColumnIJ().

7516:     Collective on Mat

7518:     Input Parameters:
7519: +   mat - the matrix
7520: .   shift - 1 or zero indicating we want the indices starting at 0 or 1
7521: -   symmetric - PETSC_TRUE or PETSC_FALSE indicating the matrix data structure should be
7522:                 symmetrized
7523: -   inodecompressed - PETSC_TRUE or PETSC_FALSE indicating if the nonzero structure of the
7524:                  inodes or the nonzero elements is wanted. For BAIJ matrices the compressed version is
7525:                  always used.

7527:     Output Parameters:
7528: +   n - size of (possibly compressed) matrix
7529: .   ia - the column pointers
7530: .   ja - the row indices
7531: -   done - PETSC_TRUE or PETSC_FALSE indicated that the values have been returned

7533:     Level: developer

7535: .seealso: MatGetColumnIJ(), MatRestoreRowIJ()
7536: @*/
7537: PetscErrorCode MatRestoreColumnIJ(Mat mat,PetscInt shift,PetscBool symmetric,PetscBool inodecompressed,PetscInt *n,const PetscInt *ia[],const PetscInt *ja[],PetscBool  *done)
7538: {

7547:   MatCheckPreallocated(mat,1);

7549:   if (!mat->ops->restorecolumnij) *done = PETSC_FALSE;
7550:   else {
7551:     *done = PETSC_TRUE;
7552:     (*mat->ops->restorecolumnij)(mat,shift,symmetric,inodecompressed,n,ia,ja,done);
7553:     if (n)  *n = 0;
7554:     if (ia) *ia = NULL;
7555:     if (ja) *ja = NULL;
7556:   }
7557:   return(0);
7558: }

7560: /*@C
7561:     MatColoringPatch -Used inside matrix coloring routines that
7562:     use MatGetRowIJ() and/or MatGetColumnIJ().

7564:     Collective on Mat

7566:     Input Parameters:
7567: +   mat - the matrix
7568: .   ncolors - max color value
7569: .   n   - number of entries in colorarray
7570: -   colorarray - array indicating color for each column

7572:     Output Parameters:
7573: .   iscoloring - coloring generated using colorarray information

7575:     Level: developer

7577: .seealso: MatGetRowIJ(), MatGetColumnIJ()

7579: @*/
7580: PetscErrorCode MatColoringPatch(Mat mat,PetscInt ncolors,PetscInt n,ISColoringValue colorarray[],ISColoring *iscoloring)
7581: {

7589:   MatCheckPreallocated(mat,1);

7591:   if (!mat->ops->coloringpatch) {
7592:     ISColoringCreate(PetscObjectComm((PetscObject)mat),ncolors,n,colorarray,PETSC_OWN_POINTER,iscoloring);
7593:   } else {
7594:     (*mat->ops->coloringpatch)(mat,ncolors,n,colorarray,iscoloring);
7595:   }
7596:   return(0);
7597: }


7600: /*@
7601:    MatSetUnfactored - Resets a factored matrix to be treated as unfactored.

7603:    Logically Collective on Mat

7605:    Input Parameter:
7606: .  mat - the factored matrix to be reset

7608:    Notes:
7609:    This routine should be used only with factored matrices formed by in-place
7610:    factorization via ILU(0) (or by in-place LU factorization for the MATSEQDENSE
7611:    format).  This option can save memory, for example, when solving nonlinear
7612:    systems with a matrix-free Newton-Krylov method and a matrix-based, in-place
7613:    ILU(0) preconditioner.

7615:    Note that one can specify in-place ILU(0) factorization by calling
7616: .vb
7617:      PCType(pc,PCILU);
7618:      PCFactorSeUseInPlace(pc);
7619: .ve
7620:    or by using the options -pc_type ilu -pc_factor_in_place

7622:    In-place factorization ILU(0) can also be used as a local
7623:    solver for the blocks within the block Jacobi or additive Schwarz
7624:    methods (runtime option: -sub_pc_factor_in_place).  See Users-Manual: ch_pc
7625:    for details on setting local solver options.

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

7631:    Level: developer

7633: .seealso: PCFactorSetUseInPlace(), PCFactorGetUseInPlace()

7635: @*/
7636: PetscErrorCode MatSetUnfactored(Mat mat)
7637: {

7643:   MatCheckPreallocated(mat,1);
7644:   mat->factortype = MAT_FACTOR_NONE;
7645:   if (!mat->ops->setunfactored) return(0);
7646:   (*mat->ops->setunfactored)(mat);
7647:   return(0);
7648: }

7650: /*MC
7651:     MatDenseGetArrayF90 - Accesses a matrix array from Fortran90.

7653:     Synopsis:
7654:     MatDenseGetArrayF90(Mat x,{Scalar, pointer :: xx_v(:,:)},integer ierr)

7656:     Not collective

7658:     Input Parameter:
7659: .   x - matrix

7661:     Output Parameters:
7662: +   xx_v - the Fortran90 pointer to the array
7663: -   ierr - error code

7665:     Example of Usage:
7666: .vb
7667:       PetscScalar, pointer xx_v(:,:)
7668:       ....
7669:       call MatDenseGetArrayF90(x,xx_v,ierr)
7670:       a = xx_v(3)
7671:       call MatDenseRestoreArrayF90(x,xx_v,ierr)
7672: .ve

7674:     Level: advanced

7676: .seealso:  MatDenseRestoreArrayF90(), MatDenseGetArray(), MatDenseRestoreArray(), MatSeqAIJGetArrayF90()

7678: M*/

7680: /*MC
7681:     MatDenseRestoreArrayF90 - Restores a matrix array that has been
7682:     accessed with MatDenseGetArrayF90().

7684:     Synopsis:
7685:     MatDenseRestoreArrayF90(Mat x,{Scalar, pointer :: xx_v(:,:)},integer ierr)

7687:     Not collective

7689:     Input Parameters:
7690: +   x - matrix
7691: -   xx_v - the Fortran90 pointer to the array

7693:     Output Parameter:
7694: .   ierr - error code

7696:     Example of Usage:
7697: .vb
7698:        PetscScalar, pointer xx_v(:,:)
7699:        ....
7700:        call MatDenseGetArrayF90(x,xx_v,ierr)
7701:        a = xx_v(3)
7702:        call MatDenseRestoreArrayF90(x,xx_v,ierr)
7703: .ve

7705:     Level: advanced

7707: .seealso:  MatDenseGetArrayF90(), MatDenseGetArray(), MatDenseRestoreArray(), MatSeqAIJRestoreArrayF90()

7709: M*/


7712: /*MC
7713:     MatSeqAIJGetArrayF90 - Accesses a matrix array from Fortran90.

7715:     Synopsis:
7716:     MatSeqAIJGetArrayF90(Mat x,{Scalar, pointer :: xx_v(:)},integer ierr)

7718:     Not collective

7720:     Input Parameter:
7721: .   x - matrix

7723:     Output Parameters:
7724: +   xx_v - the Fortran90 pointer to the array
7725: -   ierr - error code

7727:     Example of Usage:
7728: .vb
7729:       PetscScalar, pointer xx_v(:)
7730:       ....
7731:       call MatSeqAIJGetArrayF90(x,xx_v,ierr)
7732:       a = xx_v(3)
7733:       call MatSeqAIJRestoreArrayF90(x,xx_v,ierr)
7734: .ve

7736:     Level: advanced

7738: .seealso:  MatSeqAIJRestoreArrayF90(), MatSeqAIJGetArray(), MatSeqAIJRestoreArray(), MatDenseGetArrayF90()

7740: M*/

7742: /*MC
7743:     MatSeqAIJRestoreArrayF90 - Restores a matrix array that has been
7744:     accessed with MatSeqAIJGetArrayF90().

7746:     Synopsis:
7747:     MatSeqAIJRestoreArrayF90(Mat x,{Scalar, pointer :: xx_v(:)},integer ierr)

7749:     Not collective

7751:     Input Parameters:
7752: +   x - matrix
7753: -   xx_v - the Fortran90 pointer to the array

7755:     Output Parameter:
7756: .   ierr - error code

7758:     Example of Usage:
7759: .vb
7760:        PetscScalar, pointer xx_v(:)
7761:        ....
7762:        call MatSeqAIJGetArrayF90(x,xx_v,ierr)
7763:        a = xx_v(3)
7764:        call MatSeqAIJRestoreArrayF90(x,xx_v,ierr)
7765: .ve

7767:     Level: advanced

7769: .seealso:  MatSeqAIJGetArrayF90(), MatSeqAIJGetArray(), MatSeqAIJRestoreArray(), MatDenseRestoreArrayF90()

7771: M*/


7774: /*@
7775:     MatCreateSubMatrix - Gets a single submatrix on the same number of processors
7776:                       as the original matrix.

7778:     Collective on Mat

7780:     Input Parameters:
7781: +   mat - the original matrix
7782: .   isrow - parallel IS containing the rows this processor should obtain
7783: .   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.
7784: -   cll - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX

7786:     Output Parameter:
7787: .   newmat - the new submatrix, of the same type as the old

7789:     Level: advanced

7791:     Notes:
7792:     The submatrix will be able to be multiplied with vectors using the same layout as iscol.

7794:     Some matrix types place restrictions on the row and column indices, such
7795:     as that they be sorted or that they be equal to each other.

7797:     The index sets may not have duplicate entries.

7799:       The first time this is called you should use a cll of MAT_INITIAL_MATRIX,
7800:    the MatCreateSubMatrix() routine will create the newmat for you. Any additional calls
7801:    to this routine with a mat of the same nonzero structure and with a call of MAT_REUSE_MATRIX
7802:    will reuse the matrix generated the first time.  You should call MatDestroy() on newmat when
7803:    you are finished using it.

7805:     The communicator of the newly obtained matrix is ALWAYS the same as the communicator of
7806:     the input matrix.

7808:     If iscol is NULL then all columns are obtained (not supported in Fortran).

7810:    Example usage:
7811:    Consider the following 8x8 matrix with 34 non-zero values, that is
7812:    assembled across 3 processors. Let's assume that proc0 owns 3 rows,
7813:    proc1 owns 3 rows, proc2 owns 2 rows. This division can be shown
7814:    as follows:

7816: .vb
7817:             1  2  0  |  0  3  0  |  0  4
7818:     Proc0   0  5  6  |  7  0  0  |  8  0
7819:             9  0 10  | 11  0  0  | 12  0
7820:     -------------------------------------
7821:            13  0 14  | 15 16 17  |  0  0
7822:     Proc1   0 18  0  | 19 20 21  |  0  0
7823:             0  0  0  | 22 23  0  | 24  0
7824:     -------------------------------------
7825:     Proc2  25 26 27  |  0  0 28  | 29  0
7826:            30  0  0  | 31 32 33  |  0 34
7827: .ve

7829:     Suppose isrow = [0 1 | 4 | 6 7] and iscol = [1 2 | 3 4 5 | 6].  The resulting submatrix is

7831: .vb
7832:             2  0  |  0  3  0  |  0
7833:     Proc0   5  6  |  7  0  0  |  8
7834:     -------------------------------
7835:     Proc1  18  0  | 19 20 21  |  0
7836:     -------------------------------
7837:     Proc2  26 27  |  0  0 28  | 29
7838:             0  0  | 31 32 33  |  0
7839: .ve


7842: .seealso: MatCreateSubMatrices(), MatCreateSubMatricesMPI(), MatCreateSubMatrixVirtual(), MatSubMatrixVirtualUpdate()
7843: @*/
7844: PetscErrorCode MatCreateSubMatrix(Mat mat,IS isrow,IS iscol,MatReuse cll,Mat *newmat)
7845: {
7847:   PetscMPIInt    size;
7848:   Mat            *local;
7849:   IS             iscoltmp;
7850:   PetscBool      flg;

7859:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
7860:   if (cll == MAT_IGNORE_MATRIX) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Cannot use MAT_IGNORE_MATRIX");

7862:   MatCheckPreallocated(mat,1);
7863:   MPI_Comm_size(PetscObjectComm((PetscObject)mat),&size);

7865:   if (!iscol || isrow == iscol) {
7866:     PetscBool   stride;
7867:     PetscMPIInt grabentirematrix = 0,grab;
7868:     PetscObjectTypeCompare((PetscObject)isrow,ISSTRIDE,&stride);
7869:     if (stride) {
7870:       PetscInt first,step,n,rstart,rend;
7871:       ISStrideGetInfo(isrow,&first,&step);
7872:       if (step == 1) {
7873:         MatGetOwnershipRange(mat,&rstart,&rend);
7874:         if (rstart == first) {
7875:           ISGetLocalSize(isrow,&n);
7876:           if (n == rend-rstart) {
7877:             grabentirematrix = 1;
7878:           }
7879:         }
7880:       }
7881:     }
7882:     MPIU_Allreduce(&grabentirematrix,&grab,1,MPI_INT,MPI_MIN,PetscObjectComm((PetscObject)mat));
7883:     if (grab) {
7884:       PetscInfo(mat,"Getting entire matrix as submatrix\n");
7885:       if (cll == MAT_INITIAL_MATRIX) {
7886:         *newmat = mat;
7887:         PetscObjectReference((PetscObject)mat);
7888:       }
7889:       return(0);
7890:     }
7891:   }

7893:   if (!iscol) {
7894:     ISCreateStride(PetscObjectComm((PetscObject)mat),mat->cmap->n,mat->cmap->rstart,1,&iscoltmp);
7895:   } else {
7896:     iscoltmp = iscol;
7897:   }

7899:   /* if original matrix is on just one processor then use submatrix generated */
7900:   if (mat->ops->createsubmatrices && !mat->ops->createsubmatrix && size == 1 && cll == MAT_REUSE_MATRIX) {
7901:     MatCreateSubMatrices(mat,1,&isrow,&iscoltmp,MAT_REUSE_MATRIX,&newmat);
7902:     goto setproperties;
7903:   } else if (mat->ops->createsubmatrices && !mat->ops->createsubmatrix && size == 1) {
7904:     MatCreateSubMatrices(mat,1,&isrow,&iscoltmp,MAT_INITIAL_MATRIX,&local);
7905:     *newmat = *local;
7906:     PetscFree(local);
7907:     goto setproperties;
7908:   } else if (!mat->ops->createsubmatrix) {
7909:     /* Create a new matrix type that implements the operation using the full matrix */
7910:     PetscLogEventBegin(MAT_CreateSubMat,mat,0,0,0);
7911:     switch (cll) {
7912:     case MAT_INITIAL_MATRIX:
7913:       MatCreateSubMatrixVirtual(mat,isrow,iscoltmp,newmat);
7914:       break;
7915:     case MAT_REUSE_MATRIX:
7916:       MatSubMatrixVirtualUpdate(*newmat,mat,isrow,iscoltmp);
7917:       break;
7918:     default: SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_OUTOFRANGE,"Invalid MatReuse, must be either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX");
7919:     }
7920:     PetscLogEventEnd(MAT_CreateSubMat,mat,0,0,0);
7921:     goto setproperties;
7922:   }

7924:   if (!mat->ops->createsubmatrix) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
7925:   PetscLogEventBegin(MAT_CreateSubMat,mat,0,0,0);
7926:   (*mat->ops->createsubmatrix)(mat,isrow,iscoltmp,cll,newmat);
7927:   PetscLogEventEnd(MAT_CreateSubMat,mat,0,0,0);

7929: setproperties:
7930:   ISEqualUnsorted(isrow,iscoltmp,&flg);
7931:   if (flg) {
7932:     MatPropagateSymmetryOptions(mat,*newmat);
7933:   }
7934:   if (!iscol) {ISDestroy(&iscoltmp);}
7935:   if (*newmat && cll == MAT_INITIAL_MATRIX) {PetscObjectStateIncrease((PetscObject)*newmat);}
7936:   return(0);
7937: }

7939: /*@
7940:    MatPropagateSymmetryOptions - Propagates symmetry options set on a matrix to another matrix

7942:    Not Collective

7944:    Input Parameters:
7945: +  A - the matrix we wish to propagate options from
7946: -  B - the matrix we wish to propagate options to

7948:    Level: beginner

7950:    Notes: Propagates the options associated to MAT_SYMMETRY_ETERNAL, MAT_STRUCTURALLY_SYMMETRIC, MAT_HERMITIAN, MAT_SPD and MAT_SYMMETRIC

7952: .seealso: MatSetOption()
7953: @*/
7954: PetscErrorCode MatPropagateSymmetryOptions(Mat A, Mat B)
7955: {

7961:   if (A->symmetric_eternal) { /* symmetric_eternal does not have a corresponding *set flag */
7962:     MatSetOption(B,MAT_SYMMETRY_ETERNAL,A->symmetric_eternal);
7963:   }
7964:   if (A->structurally_symmetric_set) {
7965:     MatSetOption(B,MAT_STRUCTURALLY_SYMMETRIC,A->structurally_symmetric);
7966:   }
7967:   if (A->hermitian_set) {
7968:     MatSetOption(B,MAT_HERMITIAN,A->hermitian);
7969:   }
7970:   if (A->spd_set) {
7971:     MatSetOption(B,MAT_SPD,A->spd);
7972:   }
7973:   if (A->symmetric_set) {
7974:     MatSetOption(B,MAT_SYMMETRIC,A->symmetric);
7975:   }
7976:   return(0);
7977: }

7979: /*@
7980:    MatStashSetInitialSize - sets the sizes of the matrix stash, that is
7981:    used during the assembly process to store values that belong to
7982:    other processors.

7984:    Not Collective

7986:    Input Parameters:
7987: +  mat   - the matrix
7988: .  size  - the initial size of the stash.
7989: -  bsize - the initial size of the block-stash(if used).

7991:    Options Database Keys:
7992: +   -matstash_initial_size <size> or <size0,size1,...sizep-1>
7993: -   -matstash_block_initial_size <bsize>  or <bsize0,bsize1,...bsizep-1>

7995:    Level: intermediate

7997:    Notes:
7998:      The block-stash is used for values set with MatSetValuesBlocked() while
7999:      the stash is used for values set with MatSetValues()

8001:      Run with the option -info and look for output of the form
8002:      MatAssemblyBegin_MPIXXX:Stash has MM entries, uses nn mallocs.
8003:      to determine the appropriate value, MM, to use for size and
8004:      MatAssemblyBegin_MPIXXX:Block-Stash has BMM entries, uses nn mallocs.
8005:      to determine the value, BMM to use for bsize


8008: .seealso: MatAssemblyBegin(), MatAssemblyEnd(), Mat, MatStashGetInfo()

8010: @*/
8011: PetscErrorCode MatStashSetInitialSize(Mat mat,PetscInt size, PetscInt bsize)
8012: {

8018:   MatStashSetInitialSize_Private(&mat->stash,size);
8019:   MatStashSetInitialSize_Private(&mat->bstash,bsize);
8020:   return(0);
8021: }

8023: /*@
8024:    MatInterpolateAdd - w = y + A*x or A'*x depending on the shape of
8025:      the matrix

8027:    Neighbor-wise Collective on Mat

8029:    Input Parameters:
8030: +  mat   - the matrix
8031: .  x,y - the vectors
8032: -  w - where the result is stored

8034:    Level: intermediate

8036:    Notes:
8037:     w may be the same vector as y.

8039:     This allows one to use either the restriction or interpolation (its transpose)
8040:     matrix to do the interpolation

8042: .seealso: MatMultAdd(), MatMultTransposeAdd(), MatRestrict()

8044: @*/
8045: PetscErrorCode MatInterpolateAdd(Mat A,Vec x,Vec y,Vec w)
8046: {
8048:   PetscInt       M,N,Ny;

8056:   MatCheckPreallocated(A,1);
8057:   MatGetSize(A,&M,&N);
8058:   VecGetSize(y,&Ny);
8059:   if (M == Ny) {
8060:     MatMultAdd(A,x,y,w);
8061:   } else {
8062:     MatMultTransposeAdd(A,x,y,w);
8063:   }
8064:   return(0);
8065: }

8067: /*@
8068:    MatInterpolate - y = A*x or A'*x depending on the shape of
8069:      the matrix

8071:    Neighbor-wise Collective on Mat

8073:    Input Parameters:
8074: +  mat   - the matrix
8075: -  x,y - the vectors

8077:    Level: intermediate

8079:    Notes:
8080:     This allows one to use either the restriction or interpolation (its transpose)
8081:     matrix to do the interpolation

8083: .seealso: MatMultAdd(), MatMultTransposeAdd(), MatRestrict()

8085: @*/
8086: PetscErrorCode MatInterpolate(Mat A,Vec x,Vec y)
8087: {
8089:   PetscInt       M,N,Ny;

8096:   MatCheckPreallocated(A,1);
8097:   MatGetSize(A,&M,&N);
8098:   VecGetSize(y,&Ny);
8099:   if (M == Ny) {
8100:     MatMult(A,x,y);
8101:   } else {
8102:     MatMultTranspose(A,x,y);
8103:   }
8104:   return(0);
8105: }

8107: /*@
8108:    MatRestrict - y = A*x or A'*x

8110:    Neighbor-wise Collective on Mat

8112:    Input Parameters:
8113: +  mat   - the matrix
8114: -  x,y - the vectors

8116:    Level: intermediate

8118:    Notes:
8119:     This allows one to use either the restriction or interpolation (its transpose)
8120:     matrix to do the restriction

8122: .seealso: MatMultAdd(), MatMultTransposeAdd(), MatInterpolate()

8124: @*/
8125: PetscErrorCode MatRestrict(Mat A,Vec x,Vec y)
8126: {
8128:   PetscInt       M,N,Ny;

8135:   MatCheckPreallocated(A,1);

8137:   MatGetSize(A,&M,&N);
8138:   VecGetSize(y,&Ny);
8139:   if (M == Ny) {
8140:     MatMult(A,x,y);
8141:   } else {
8142:     MatMultTranspose(A,x,y);
8143:   }
8144:   return(0);
8145: }

8147: /*@
8148:    MatGetNullSpace - retrieves the null space of a matrix.

8150:    Logically Collective on Mat

8152:    Input Parameters:
8153: +  mat - the matrix
8154: -  nullsp - the null space object

8156:    Level: developer

8158: .seealso: MatCreate(), MatNullSpaceCreate(), MatSetNearNullSpace(), MatSetNullSpace()
8159: @*/
8160: PetscErrorCode MatGetNullSpace(Mat mat, MatNullSpace *nullsp)
8161: {
8165:   *nullsp = (mat->symmetric_set && mat->symmetric && !mat->nullsp) ? mat->transnullsp : mat->nullsp;
8166:   return(0);
8167: }

8169: /*@
8170:    MatSetNullSpace - attaches a null space to a matrix.

8172:    Logically Collective on Mat

8174:    Input Parameters:
8175: +  mat - the matrix
8176: -  nullsp - the null space object

8178:    Level: advanced

8180:    Notes:
8181:       This null space is used by the linear solvers. Overwrites any previous null space that may have been attached

8183:       For inconsistent singular systems (linear systems where the right hand side is not in the range of the operator) you also likely should
8184:       call MatSetTransposeNullSpace(). This allows the linear system to be solved in a least squares sense.

8186:       You can remove the null space by calling this routine with an nullsp of NULL


8189:       The fundamental theorem of linear algebra (Gilbert Strang, Introduction to Applied Mathematics, page 72) states that
8190:    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).
8191:    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
8192:    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
8193:    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).

8195:       Krylov solvers can produce the minimal norm solution to the least squares problem by utilizing MatNullSpaceRemove().

8197:     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
8198:     routine also automatically calls MatSetTransposeNullSpace().

8200: .seealso: MatCreate(), MatNullSpaceCreate(), MatSetNearNullSpace(), MatGetNullSpace(), MatSetTransposeNullSpace(), MatGetTransposeNullSpace(), MatNullSpaceRemove()
8201: @*/
8202: PetscErrorCode MatSetNullSpace(Mat mat,MatNullSpace nullsp)
8203: {

8209:   if (nullsp) {PetscObjectReference((PetscObject)nullsp);}
8210:   MatNullSpaceDestroy(&mat->nullsp);
8211:   mat->nullsp = nullsp;
8212:   if (mat->symmetric_set && mat->symmetric) {
8213:     MatSetTransposeNullSpace(mat,nullsp);
8214:   }
8215:   return(0);
8216: }

8218: /*@
8219:    MatGetTransposeNullSpace - retrieves the null space of the transpose of a matrix.

8221:    Logically Collective on Mat

8223:    Input Parameters:
8224: +  mat - the matrix
8225: -  nullsp - the null space object

8227:    Level: developer

8229: .seealso: MatCreate(), MatNullSpaceCreate(), MatSetNearNullSpace(), MatSetTransposeNullSpace(), MatSetNullSpace(), MatGetNullSpace()
8230: @*/
8231: PetscErrorCode MatGetTransposeNullSpace(Mat mat, MatNullSpace *nullsp)
8232: {
8237:   *nullsp = (mat->symmetric_set && mat->symmetric && !mat->transnullsp) ? mat->nullsp : mat->transnullsp;
8238:   return(0);
8239: }

8241: /*@
8242:    MatSetTransposeNullSpace - attaches a null space to a matrix.

8244:    Logically Collective on Mat

8246:    Input Parameters:
8247: +  mat - the matrix
8248: -  nullsp - the null space object

8250:    Level: advanced

8252:    Notes:
8253:       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.
8254:       You must also call MatSetNullSpace()


8257:       The fundamental theorem of linear algebra (Gilbert Strang, Introduction to Applied Mathematics, page 72) states that
8258:    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).
8259:    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
8260:    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
8261:    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).

8263:       Krylov solvers can produce the minimal norm solution to the least squares problem by utilizing MatNullSpaceRemove().

8265: .seealso: MatCreate(), MatNullSpaceCreate(), MatSetNearNullSpace(), MatGetNullSpace(), MatSetNullSpace(), MatGetTransposeNullSpace(), MatNullSpaceRemove()
8266: @*/
8267: PetscErrorCode MatSetTransposeNullSpace(Mat mat,MatNullSpace nullsp)
8268: {

8274:   if (nullsp) {PetscObjectReference((PetscObject)nullsp);}
8275:   MatNullSpaceDestroy(&mat->transnullsp);
8276:   mat->transnullsp = nullsp;
8277:   return(0);
8278: }

8280: /*@
8281:    MatSetNearNullSpace - attaches a null space to a matrix, which is often the null space (rigid body modes) of the operator without boundary conditions
8282:         This null space will be used to provide near null space vectors to a multigrid preconditioner built from this matrix.

8284:    Logically Collective on Mat

8286:    Input Parameters:
8287: +  mat - the matrix
8288: -  nullsp - the null space object

8290:    Level: advanced

8292:    Notes:
8293:       Overwrites any previous near null space that may have been attached

8295:       You can remove the null space by calling this routine with an nullsp of NULL

8297: .seealso: MatCreate(), MatNullSpaceCreate(), MatSetNullSpace(), MatNullSpaceCreateRigidBody(), MatGetNearNullSpace()
8298: @*/
8299: PetscErrorCode MatSetNearNullSpace(Mat mat,MatNullSpace nullsp)
8300: {

8307:   MatCheckPreallocated(mat,1);
8308:   if (nullsp) {PetscObjectReference((PetscObject)nullsp);}
8309:   MatNullSpaceDestroy(&mat->nearnullsp);
8310:   mat->nearnullsp = nullsp;
8311:   return(0);
8312: }

8314: /*@
8315:    MatGetNearNullSpace - Get null space attached with MatSetNearNullSpace()

8317:    Not Collective

8319:    Input Parameter:
8320: .  mat - the matrix

8322:    Output Parameter:
8323: .  nullsp - the null space object, NULL if not set

8325:    Level: developer

8327: .seealso: MatSetNearNullSpace(), MatGetNullSpace(), MatNullSpaceCreate()
8328: @*/
8329: PetscErrorCode MatGetNearNullSpace(Mat mat,MatNullSpace *nullsp)
8330: {
8335:   MatCheckPreallocated(mat,1);
8336:   *nullsp = mat->nearnullsp;
8337:   return(0);
8338: }

8340: /*@C
8341:    MatICCFactor - Performs in-place incomplete Cholesky factorization of matrix.

8343:    Collective on Mat

8345:    Input Parameters:
8346: +  mat - the matrix
8347: .  row - row/column permutation
8348: .  fill - expected fill factor >= 1.0
8349: -  level - level of fill, for ICC(k)

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

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

8359:    Level: developer


8362: .seealso: MatICCFactorSymbolic(), MatLUFactorNumeric(), MatCholeskyFactor()

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

8367: @*/
8368: PetscErrorCode MatICCFactor(Mat mat,IS row,const MatFactorInfo *info)
8369: {

8377:   if (mat->rmap->N != mat->cmap->N) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONG,"matrix must be square");
8378:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
8379:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
8380:   if (!mat->ops->iccfactor) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
8381:   MatCheckPreallocated(mat,1);
8382:   (*mat->ops->iccfactor)(mat,row,info);
8383:   PetscObjectStateIncrease((PetscObject)mat);
8384:   return(0);
8385: }

8387: /*@
8388:    MatDiagonalScaleLocal - Scales columns of a matrix given the scaling values including the
8389:          ghosted ones.

8391:    Not Collective

8393:    Input Parameters:
8394: +  mat - the matrix
8395: -  diag = the diagonal values, including ghost ones

8397:    Level: developer

8399:    Notes:
8400:     Works only for MPIAIJ and MPIBAIJ matrices

8402: .seealso: MatDiagonalScale()
8403: @*/
8404: PetscErrorCode MatDiagonalScaleLocal(Mat mat,Vec diag)
8405: {
8407:   PetscMPIInt    size;


8414:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Matrix must be already assembled");
8415:   PetscLogEventBegin(MAT_Scale,mat,0,0,0);
8416:   MPI_Comm_size(PetscObjectComm((PetscObject)mat),&size);
8417:   if (size == 1) {
8418:     PetscInt n,m;
8419:     VecGetSize(diag,&n);
8420:     MatGetSize(mat,0,&m);
8421:     if (m == n) {
8422:       MatDiagonalScale(mat,0,diag);
8423:     } else SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"Only supported for sequential matrices when no ghost points/periodic conditions");
8424:   } else {
8425:     PetscUseMethod(mat,"MatDiagonalScaleLocal_C",(Mat,Vec),(mat,diag));
8426:   }
8427:   PetscLogEventEnd(MAT_Scale,mat,0,0,0);
8428:   PetscObjectStateIncrease((PetscObject)mat);
8429:   return(0);
8430: }

8432: /*@
8433:    MatGetInertia - Gets the inertia from a factored matrix

8435:    Collective on Mat

8437:    Input Parameter:
8438: .  mat - the matrix

8440:    Output Parameters:
8441: +   nneg - number of negative eigenvalues
8442: .   nzero - number of zero eigenvalues
8443: -   npos - number of positive eigenvalues

8445:    Level: advanced

8447:    Notes:
8448:     Matrix must have been factored by MatCholeskyFactor()


8451: @*/
8452: PetscErrorCode MatGetInertia(Mat mat,PetscInt *nneg,PetscInt *nzero,PetscInt *npos)
8453: {

8459:   if (!mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
8460:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Numeric factor mat is not assembled");
8461:   if (!mat->ops->getinertia) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
8462:   (*mat->ops->getinertia)(mat,nneg,nzero,npos);
8463:   return(0);
8464: }

8466: /* ----------------------------------------------------------------*/
8467: /*@C
8468:    MatSolves - Solves A x = b, given a factored matrix, for a collection of vectors

8470:    Neighbor-wise Collective on Mats

8472:    Input Parameters:
8473: +  mat - the factored matrix
8474: -  b - the right-hand-side vectors

8476:    Output Parameter:
8477: .  x - the result vectors

8479:    Notes:
8480:    The vectors b and x cannot be the same.  I.e., one cannot
8481:    call MatSolves(A,x,x).

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

8488:    Level: developer

8490: .seealso: MatSolveAdd(), MatSolveTranspose(), MatSolveTransposeAdd(), MatSolve()
8491: @*/
8492: PetscErrorCode MatSolves(Mat mat,Vecs b,Vecs x)
8493: {

8499:   if (x == b) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"x and b must be different vectors");
8500:   if (!mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
8501:   if (!mat->rmap->N && !mat->cmap->N) return(0);

8503:   if (!mat->ops->solves) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
8504:   MatCheckPreallocated(mat,1);
8505:   PetscLogEventBegin(MAT_Solves,mat,0,0,0);
8506:   (*mat->ops->solves)(mat,b,x);
8507:   PetscLogEventEnd(MAT_Solves,mat,0,0,0);
8508:   return(0);
8509: }

8511: /*@
8512:    MatIsSymmetric - Test whether a matrix is symmetric

8514:    Collective on Mat

8516:    Input Parameter:
8517: +  A - the matrix to test
8518: -  tol - difference between value and its transpose less than this amount counts as equal (use 0.0 for exact transpose)

8520:    Output Parameters:
8521: .  flg - the result

8523:    Notes:
8524:     For real numbers MatIsSymmetric() and MatIsHermitian() return identical results

8526:    Level: intermediate

8528: .seealso: MatTranspose(), MatIsTranspose(), MatIsHermitian(), MatIsStructurallySymmetric(), MatSetOption(), MatIsSymmetricKnown()
8529: @*/
8530: PetscErrorCode MatIsSymmetric(Mat A,PetscReal tol,PetscBool  *flg)
8531: {


8538:   if (!A->symmetric_set) {
8539:     if (!A->ops->issymmetric) {
8540:       MatType mattype;
8541:       MatGetType(A,&mattype);
8542:       SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Matrix of type %s does not support checking for symmetric",mattype);
8543:     }
8544:     (*A->ops->issymmetric)(A,tol,flg);
8545:     if (!tol) {
8546:       MatSetOption(A,MAT_SYMMETRIC,*flg);
8547:     }
8548:   } else if (A->symmetric) {
8549:     *flg = PETSC_TRUE;
8550:   } else if (!tol) {
8551:     *flg = PETSC_FALSE;
8552:   } else {
8553:     if (!A->ops->issymmetric) {
8554:       MatType mattype;
8555:       MatGetType(A,&mattype);
8556:       SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Matrix of type %s does not support checking for symmetric",mattype);
8557:     }
8558:     (*A->ops->issymmetric)(A,tol,flg);
8559:   }
8560:   return(0);
8561: }

8563: /*@
8564:    MatIsHermitian - Test whether a matrix is Hermitian

8566:    Collective on Mat

8568:    Input Parameter:
8569: +  A - the matrix to test
8570: -  tol - difference between value and its transpose less than this amount counts as equal (use 0.0 for exact Hermitian)

8572:    Output Parameters:
8573: .  flg - the result

8575:    Level: intermediate

8577: .seealso: MatTranspose(), MatIsTranspose(), MatIsHermitian(), MatIsStructurallySymmetric(), MatSetOption(),
8578:           MatIsSymmetricKnown(), MatIsSymmetric()
8579: @*/
8580: PetscErrorCode MatIsHermitian(Mat A,PetscReal tol,PetscBool  *flg)
8581: {


8588:   if (!A->hermitian_set) {
8589:     if (!A->ops->ishermitian) {
8590:       MatType mattype;
8591:       MatGetType(A,&mattype);
8592:       SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Matrix of type %s does not support checking for hermitian",mattype);
8593:     }
8594:     (*A->ops->ishermitian)(A,tol,flg);
8595:     if (!tol) {
8596:       MatSetOption(A,MAT_HERMITIAN,*flg);
8597:     }
8598:   } else if (A->hermitian) {
8599:     *flg = PETSC_TRUE;
8600:   } else if (!tol) {
8601:     *flg = PETSC_FALSE;
8602:   } else {
8603:     if (!A->ops->ishermitian) {
8604:       MatType mattype;
8605:       MatGetType(A,&mattype);
8606:       SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Matrix of type %s does not support checking for hermitian",mattype);
8607:     }
8608:     (*A->ops->ishermitian)(A,tol,flg);
8609:   }
8610:   return(0);
8611: }

8613: /*@
8614:    MatIsSymmetricKnown - Checks the flag on the matrix to see if it is symmetric.

8616:    Not Collective

8618:    Input Parameter:
8619: .  A - the matrix to check

8621:    Output Parameters:
8622: +  set - if the symmetric flag is set (this tells you if the next flag is valid)
8623: -  flg - the result

8625:    Level: advanced

8627:    Note: Does not check the matrix values directly, so this may return unknown (set = PETSC_FALSE). Use MatIsSymmetric()
8628:          if you want it explicitly checked

8630: .seealso: MatTranspose(), MatIsTranspose(), MatIsHermitian(), MatIsStructurallySymmetric(), MatSetOption(), MatIsSymmetric()
8631: @*/
8632: PetscErrorCode MatIsSymmetricKnown(Mat A,PetscBool  *set,PetscBool  *flg)
8633: {
8638:   if (A->symmetric_set) {
8639:     *set = PETSC_TRUE;
8640:     *flg = A->symmetric;
8641:   } else {
8642:     *set = PETSC_FALSE;
8643:   }
8644:   return(0);
8645: }

8647: /*@
8648:    MatIsHermitianKnown - Checks the flag on the matrix to see if it is hermitian.

8650:    Not Collective

8652:    Input Parameter:
8653: .  A - the matrix to check

8655:    Output Parameters:
8656: +  set - if the hermitian flag is set (this tells you if the next flag is valid)
8657: -  flg - the result

8659:    Level: advanced

8661:    Note: Does not check the matrix values directly, so this may return unknown (set = PETSC_FALSE). Use MatIsHermitian()
8662:          if you want it explicitly checked

8664: .seealso: MatTranspose(), MatIsTranspose(), MatIsHermitian(), MatIsStructurallySymmetric(), MatSetOption(), MatIsSymmetric()
8665: @*/
8666: PetscErrorCode MatIsHermitianKnown(Mat A,PetscBool *set,PetscBool *flg)
8667: {
8672:   if (A->hermitian_set) {
8673:     *set = PETSC_TRUE;
8674:     *flg = A->hermitian;
8675:   } else {
8676:     *set = PETSC_FALSE;
8677:   }
8678:   return(0);
8679: }

8681: /*@
8682:    MatIsStructurallySymmetric - Test whether a matrix is structurally symmetric

8684:    Collective on Mat

8686:    Input Parameter:
8687: .  A - the matrix to test

8689:    Output Parameters:
8690: .  flg - the result

8692:    Level: intermediate

8694: .seealso: MatTranspose(), MatIsTranspose(), MatIsHermitian(), MatIsSymmetric(), MatSetOption()
8695: @*/
8696: PetscErrorCode MatIsStructurallySymmetric(Mat A,PetscBool *flg)
8697: {

8703:   if (!A->structurally_symmetric_set) {
8704:     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);
8705:     (*A->ops->isstructurallysymmetric)(A,flg);
8706:     MatSetOption(A,MAT_STRUCTURALLY_SYMMETRIC,*flg);
8707:   } else *flg = A->structurally_symmetric;
8708:   return(0);
8709: }

8711: /*@
8712:    MatStashGetInfo - Gets how many values are currently in the matrix stash, i.e. need
8713:        to be communicated to other processors during the MatAssemblyBegin/End() process

8715:     Not collective

8717:    Input Parameter:
8718: .   vec - the vector

8720:    Output Parameters:
8721: +   nstash   - the size of the stash
8722: .   reallocs - the number of additional mallocs incurred.
8723: .   bnstash   - the size of the block stash
8724: -   breallocs - the number of additional mallocs incurred.in the block stash

8726:    Level: advanced

8728: .seealso: MatAssemblyBegin(), MatAssemblyEnd(), Mat, MatStashSetInitialSize()

8730: @*/
8731: PetscErrorCode MatStashGetInfo(Mat mat,PetscInt *nstash,PetscInt *reallocs,PetscInt *bnstash,PetscInt *breallocs)
8732: {

8736:   MatStashGetInfo_Private(&mat->stash,nstash,reallocs);
8737:   MatStashGetInfo_Private(&mat->bstash,bnstash,breallocs);
8738:   return(0);
8739: }

8741: /*@C
8742:    MatCreateVecs - Get vector(s) compatible with the matrix, i.e. with the same
8743:      parallel layout

8745:    Collective on Mat

8747:    Input Parameter:
8748: .  mat - the matrix

8750:    Output Parameter:
8751: +   right - (optional) vector that the matrix can be multiplied against
8752: -   left - (optional) vector that the matrix vector product can be stored in

8754:    Notes:
8755:     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().

8757:   Notes:
8758:     These are new vectors which are not owned by the Mat, they should be destroyed in VecDestroy() when no longer needed

8760:   Level: advanced

8762: .seealso: MatCreate(), VecDestroy()
8763: @*/
8764: PetscErrorCode MatCreateVecs(Mat mat,Vec *right,Vec *left)
8765: {

8771:   if (mat->ops->getvecs) {
8772:     (*mat->ops->getvecs)(mat,right,left);
8773:   } else {
8774:     PetscInt rbs,cbs;
8775:     MatGetBlockSizes(mat,&rbs,&cbs);
8776:     if (right) {
8777:       if (mat->cmap->n < 0) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"PetscLayout for columns not yet setup");
8778:       VecCreate(PetscObjectComm((PetscObject)mat),right);
8779:       VecSetSizes(*right,mat->cmap->n,PETSC_DETERMINE);
8780:       VecSetBlockSize(*right,cbs);
8781:       VecSetType(*right,mat->defaultvectype);
8782:       PetscLayoutReference(mat->cmap,&(*right)->map);
8783:     }
8784:     if (left) {
8785:       if (mat->rmap->n < 0) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"PetscLayout for rows not yet setup");
8786:       VecCreate(PetscObjectComm((PetscObject)mat),left);
8787:       VecSetSizes(*left,mat->rmap->n,PETSC_DETERMINE);
8788:       VecSetBlockSize(*left,rbs);
8789:       VecSetType(*left,mat->defaultvectype);
8790:       PetscLayoutReference(mat->rmap,&(*left)->map);
8791:     }
8792:   }
8793:   return(0);
8794: }

8796: /*@C
8797:    MatFactorInfoInitialize - Initializes a MatFactorInfo data structure
8798:      with default values.

8800:    Not Collective

8802:    Input Parameters:
8803: .    info - the MatFactorInfo data structure


8806:    Notes:
8807:     The solvers are generally used through the KSP and PC objects, for example
8808:           PCLU, PCILU, PCCHOLESKY, PCICC

8810:    Level: developer

8812: .seealso: MatFactorInfo

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

8817: @*/

8819: PetscErrorCode MatFactorInfoInitialize(MatFactorInfo *info)
8820: {

8824:   PetscMemzero(info,sizeof(MatFactorInfo));
8825:   return(0);
8826: }

8828: /*@
8829:    MatFactorSetSchurIS - Set indices corresponding to the Schur complement you wish to have computed

8831:    Collective on Mat

8833:    Input Parameters:
8834: +  mat - the factored matrix
8835: -  is - the index set defining the Schur indices (0-based)

8837:    Notes:
8838:     Call MatFactorSolveSchurComplement() or MatFactorSolveSchurComplementTranspose() after this call to solve a Schur complement system.

8840:    You can call MatFactorGetSchurComplement() or MatFactorCreateSchurComplement() after this call.

8842:    Level: developer

8844: .seealso: MatGetFactor(), MatFactorGetSchurComplement(), MatFactorRestoreSchurComplement(), MatFactorCreateSchurComplement(), MatFactorSolveSchurComplement(),
8845:           MatFactorSolveSchurComplementTranspose(), MatFactorSolveSchurComplement()

8847: @*/
8848: PetscErrorCode MatFactorSetSchurIS(Mat mat,IS is)
8849: {
8850:   PetscErrorCode ierr,(*f)(Mat,IS);

8858:   if (!mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Only for factored matrix");
8859:   PetscObjectQueryFunction((PetscObject)mat,"MatFactorSetSchurIS_C",&f);
8860:   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");
8861:   MatDestroy(&mat->schur);
8862:   (*f)(mat,is);
8863:   if (!mat->schur) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_PLIB,"Schur complement has not been created");
8864:   return(0);
8865: }

8867: /*@
8868:   MatFactorCreateSchurComplement - Create a Schur complement matrix object using Schur data computed during the factorization step

8870:    Logically Collective on Mat

8872:    Input Parameters:
8873: +  F - the factored matrix obtained by calling MatGetFactor() from PETSc-MUMPS interface
8874: .  S - location where to return the Schur complement, can be NULL
8875: -  status - the status of the Schur complement matrix, can be NULL

8877:    Notes:
8878:    You must call MatFactorSetSchurIS() before calling this routine.

8880:    The routine provides a copy of the Schur matrix stored within the solver data structures.
8881:    The caller must destroy the object when it is no longer needed.
8882:    If MatFactorInvertSchurComplement() has been called, the routine gets back the inverse.

8884:    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)

8886:    Developer Notes:
8887:     The reason this routine exists is because the representation of the Schur complement within the factor matrix may be different than a standard PETSc
8888:    matrix representation and we normally do not want to use the time or memory to make a copy as a regular PETSc matrix.

8890:    See MatCreateSchurComplement() or MatGetSchurComplement() for ways to create virtual or approximate Schur complements.

8892:    Level: advanced

8894:    References:

8896: .seealso: MatGetFactor(), MatFactorSetSchurIS(), MatFactorGetSchurComplement(), MatFactorSchurStatus
8897: @*/
8898: PetscErrorCode MatFactorCreateSchurComplement(Mat F,Mat* S,MatFactorSchurStatus* status)
8899: {

8906:   if (S) {
8907:     PetscErrorCode (*f)(Mat,Mat*);

8909:     PetscObjectQueryFunction((PetscObject)F,"MatFactorCreateSchurComplement_C",&f);
8910:     if (f) {
8911:       (*f)(F,S);
8912:     } else {
8913:       MatDuplicate(F->schur,MAT_COPY_VALUES,S);
8914:     }
8915:   }
8916:   if (status) *status = F->schur_status;
8917:   return(0);
8918: }

8920: /*@
8921:   MatFactorGetSchurComplement - Gets access to a Schur complement matrix using the current Schur data within a factored matrix

8923:    Logically Collective on Mat

8925:    Input Parameters:
8926: +  F - the factored matrix obtained by calling MatGetFactor()
8927: .  *S - location where to return the Schur complement, can be NULL
8928: -  status - the status of the Schur complement matrix, can be NULL

8930:    Notes:
8931:    You must call MatFactorSetSchurIS() before calling this routine.

8933:    Schur complement mode is currently implemented for sequential matrices.
8934:    The routine returns a the Schur Complement stored within the data strutures of the solver.
8935:    If MatFactorInvertSchurComplement() has previously been called, the returned matrix is actually the inverse of the Schur complement.
8936:    The returned matrix should not be destroyed; the caller should call MatFactorRestoreSchurComplement() when the object is no longer needed.

8938:    Use MatFactorCreateSchurComplement() to create a copy of the Schur complement matrix that is within a factored matrix

8940:    See MatCreateSchurComplement() or MatGetSchurComplement() for ways to create virtual or approximate Schur complements.

8942:    Level: advanced

8944:    References:

8946: .seealso: MatGetFactor(), MatFactorSetSchurIS(), MatFactorRestoreSchurComplement(), MatFactorCreateSchurComplement(), MatFactorSchurStatus
8947: @*/
8948: PetscErrorCode MatFactorGetSchurComplement(Mat F,Mat* S,MatFactorSchurStatus* status)
8949: {
8954:   if (S) *S = F->schur;
8955:   if (status) *status = F->schur_status;
8956:   return(0);
8957: }

8959: /*@
8960:   MatFactorRestoreSchurComplement - Restore the Schur complement matrix object obtained from a call to MatFactorGetSchurComplement

8962:    Logically Collective on Mat

8964:    Input Parameters:
8965: +  F - the factored matrix obtained by calling MatGetFactor()
8966: .  *S - location where the Schur complement is stored
8967: -  status - the status of the Schur complement matrix (see MatFactorSchurStatus)

8969:    Notes:

8971:    Level: advanced

8973:    References:

8975: .seealso: MatGetFactor(), MatFactorSetSchurIS(), MatFactorRestoreSchurComplement(), MatFactorCreateSchurComplement(), MatFactorSchurStatus
8976: @*/
8977: PetscErrorCode MatFactorRestoreSchurComplement(Mat F,Mat* S,MatFactorSchurStatus status)
8978: {

8983:   if (S) {
8985:     *S = NULL;
8986:   }
8987:   F->schur_status = status;
8988:   MatFactorUpdateSchurStatus_Private(F);
8989:   return(0);
8990: }

8992: /*@
8993:   MatFactorSolveSchurComplementTranspose - Solve the transpose of the Schur complement system computed during the factorization step

8995:    Logically Collective on Mat

8997:    Input Parameters:
8998: +  F - the factored matrix obtained by calling MatGetFactor()
8999: .  rhs - location where the right hand side of the Schur complement system is stored
9000: -  sol - location where the solution of the Schur complement system has to be returned

9002:    Notes:
9003:    The sizes of the vectors should match the size of the Schur complement

9005:    Must be called after MatFactorSetSchurIS()

9007:    Level: advanced

9009:    References:

9011: .seealso: MatGetFactor(), MatFactorSetSchurIS(), MatFactorSolveSchurComplement()
9012: @*/
9013: PetscErrorCode MatFactorSolveSchurComplementTranspose(Mat F, Vec rhs, Vec sol)
9014: {

9026:   MatFactorFactorizeSchurComplement(F);
9027:   switch (F->schur_status) {
9028:   case MAT_FACTOR_SCHUR_FACTORED:
9029:     MatSolveTranspose(F->schur,rhs,sol);
9030:     break;
9031:   case MAT_FACTOR_SCHUR_INVERTED:
9032:     MatMultTranspose(F->schur,rhs,sol);
9033:     break;
9034:   default:
9035:     SETERRQ1(PetscObjectComm((PetscObject)F),PETSC_ERR_SUP,"Unhandled MatFactorSchurStatus %D",F->schur_status);
9036:     break;
9037:   }
9038:   return(0);
9039: }

9041: /*@
9042:   MatFactorSolveSchurComplement - Solve the Schur complement system computed during the factorization step

9044:    Logically Collective on Mat

9046:    Input Parameters:
9047: +  F - the factored matrix obtained by calling MatGetFactor()
9048: .  rhs - location where the right hand side of the Schur complement system is stored
9049: -  sol - location where the solution of the Schur complement system has to be returned

9051:    Notes:
9052:    The sizes of the vectors should match the size of the Schur complement

9054:    Must be called after MatFactorSetSchurIS()

9056:    Level: advanced

9058:    References:

9060: .seealso: MatGetFactor(), MatFactorSetSchurIS(), MatFactorSolveSchurComplementTranspose()
9061: @*/
9062: PetscErrorCode MatFactorSolveSchurComplement(Mat F, Vec rhs, Vec sol)
9063: {

9075:   MatFactorFactorizeSchurComplement(F);
9076:   switch (F->schur_status) {
9077:   case MAT_FACTOR_SCHUR_FACTORED:
9078:     MatSolve(F->schur,rhs,sol);
9079:     break;
9080:   case MAT_FACTOR_SCHUR_INVERTED:
9081:     MatMult(F->schur,rhs,sol);
9082:     break;
9083:   default:
9084:     SETERRQ1(PetscObjectComm((PetscObject)F),PETSC_ERR_SUP,"Unhandled MatFactorSchurStatus %D",F->schur_status);
9085:     break;
9086:   }
9087:   return(0);
9088: }

9090: /*@
9091:   MatFactorInvertSchurComplement - Invert the Schur complement matrix computed during the factorization step

9093:    Logically Collective on Mat

9095:    Input Parameters:
9096: .  F - the factored matrix obtained by calling MatGetFactor()

9098:    Notes:
9099:     Must be called after MatFactorSetSchurIS().

9101:    Call MatFactorGetSchurComplement() or  MatFactorCreateSchurComplement() AFTER this call to actually compute the inverse and get access to it.

9103:    Level: advanced

9105:    References:

9107: .seealso: MatGetFactor(), MatFactorSetSchurIS(), MatFactorGetSchurComplement(), MatFactorCreateSchurComplement()
9108: @*/
9109: PetscErrorCode MatFactorInvertSchurComplement(Mat F)
9110: {

9116:   if (F->schur_status == MAT_FACTOR_SCHUR_INVERTED) return(0);
9117:   MatFactorFactorizeSchurComplement(F);
9118:   MatFactorInvertSchurComplement_Private(F);
9119:   F->schur_status = MAT_FACTOR_SCHUR_INVERTED;
9120:   return(0);
9121: }

9123: /*@
9124:   MatFactorFactorizeSchurComplement - Factorize the Schur complement matrix computed during the factorization step

9126:    Logically Collective on Mat

9128:    Input Parameters:
9129: .  F - the factored matrix obtained by calling MatGetFactor()

9131:    Notes:
9132:     Must be called after MatFactorSetSchurIS().

9134:    Level: advanced

9136:    References:

9138: .seealso: MatGetFactor(), MatFactorSetSchurIS(), MatFactorInvertSchurComplement()
9139: @*/
9140: PetscErrorCode MatFactorFactorizeSchurComplement(Mat F)
9141: {

9147:   if (F->schur_status == MAT_FACTOR_SCHUR_INVERTED || F->schur_status == MAT_FACTOR_SCHUR_FACTORED) return(0);
9148:   MatFactorFactorizeSchurComplement_Private(F);
9149:   F->schur_status = MAT_FACTOR_SCHUR_FACTORED;
9150:   return(0);
9151: }

9153: PetscErrorCode MatPtAP_Basic(Mat A,Mat P,MatReuse scall,PetscReal fill,Mat *C)
9154: {
9155:   Mat            AP;

9159:   PetscInfo2(A,"Mat types %s and %s using basic PtAP\n",((PetscObject)A)->type_name,((PetscObject)P)->type_name);
9160:   MatMatMult(A,P,MAT_INITIAL_MATRIX,PETSC_DEFAULT,&AP);
9161:   MatTransposeMatMult(P,AP,scall,fill,C);
9162:   MatDestroy(&AP);
9163:   return(0);
9164: }

9166: /*@
9167:    MatPtAP - Creates the matrix product C = P^T * A * P

9169:    Neighbor-wise Collective on Mat

9171:    Input Parameters:
9172: +  A - the matrix
9173: .  P - the projection matrix
9174: .  scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
9175: -  fill - expected fill as ratio of nnz(C)/(nnz(A) + nnz(P)), use PETSC_DEFAULT if you do not have a good estimate
9176:           if the result is a dense matrix this is irrelevent

9178:    Output Parameters:
9179: .  C - the product matrix

9181:    Notes:
9182:    C will be created and must be destroyed by the user with MatDestroy().

9184:    For matrix types without special implementation the function fallbacks to MatMatMult() followed by MatTransposeMatMult().

9186:    Level: intermediate

9188: .seealso: MatPtAPSymbolic(), MatPtAPNumeric(), MatMatMult(), MatRARt()
9189: @*/
9190: PetscErrorCode MatPtAP(Mat A,Mat P,MatReuse scall,PetscReal fill,Mat *C)
9191: {
9193:   PetscErrorCode (*fA)(Mat,Mat,MatReuse,PetscReal,Mat*);
9194:   PetscErrorCode (*fP)(Mat,Mat,MatReuse,PetscReal,Mat*);
9195:   PetscErrorCode (*ptap)(Mat,Mat,MatReuse,PetscReal,Mat*)=NULL;
9196:   PetscBool      sametype;

9201:   MatCheckPreallocated(A,1);
9202:   if (scall == MAT_INPLACE_MATRIX) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Inplace product not supported");
9203:   if (!A->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
9204:   if (A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
9207:   MatCheckPreallocated(P,2);
9208:   if (!P->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
9209:   if (P->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");

9211:   if (A->rmap->N != A->cmap->N) SETERRQ2(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Matrix A must be square, %D != %D",A->rmap->N,A->cmap->N);
9212:   if (P->rmap->N != A->cmap->N) SETERRQ2(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Matrix dimensions are incompatible, %D != %D",P->rmap->N,A->cmap->N);
9213:   if (fill == PETSC_DEFAULT || fill == PETSC_DECIDE) fill = 2.0;
9214:   if (fill < 1.0) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Expected fill=%g must be >= 1.0",(double)fill);

9216:   if (scall == MAT_REUSE_MATRIX) {

9220:     PetscLogEventBegin(MAT_PtAP,A,P,0,0);
9221:     PetscLogEventBegin(MAT_PtAPNumeric,A,P,0,0);
9222:     if ((*C)->ops->ptapnumeric) {
9223:       (*(*C)->ops->ptapnumeric)(A,P,*C);
9224:     } else {
9225:       MatPtAP_Basic(A,P,scall,fill,C);
9226:     }
9227:     PetscLogEventEnd(MAT_PtAPNumeric,A,P,0,0);
9228:     PetscLogEventEnd(MAT_PtAP,A,P,0,0);
9229:     return(0);
9230:   }

9232:   if (fill == PETSC_DEFAULT || fill == PETSC_DECIDE) fill = 2.0;
9233:   if (fill < 1.0) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Expected fill=%g must be >= 1.0",(double)fill);

9235:   fA = A->ops->ptap;
9236:   fP = P->ops->ptap;
9237:   PetscStrcmp(((PetscObject)A)->type_name,((PetscObject)P)->type_name,&sametype);
9238:   if (fP == fA && sametype) {
9239:     ptap = fA;
9240:   } else {
9241:     /* dispatch based on the type of A and P from their PetscObject's PetscFunctionLists. */
9242:     char ptapname[256];
9243:     PetscStrncpy(ptapname,"MatPtAP_",sizeof(ptapname));
9244:     PetscStrlcat(ptapname,((PetscObject)A)->type_name,sizeof(ptapname));
9245:     PetscStrlcat(ptapname,"_",sizeof(ptapname));
9246:     PetscStrlcat(ptapname,((PetscObject)P)->type_name,sizeof(ptapname));
9247:     PetscStrlcat(ptapname,"_C",sizeof(ptapname)); /* e.g., ptapname = "MatPtAP_seqdense_seqaij_C" */
9248:     PetscObjectQueryFunction((PetscObject)P,ptapname,&ptap);
9249:   }

9251:   if (!ptap) ptap = MatPtAP_Basic;
9252:   PetscLogEventBegin(MAT_PtAP,A,P,0,0);
9253:   (*ptap)(A,P,scall,fill,C);
9254:   PetscLogEventEnd(MAT_PtAP,A,P,0,0);
9255:   if (A->symmetric_set && A->symmetric) {
9256:     MatSetOption(*C,MAT_SYMMETRIC,PETSC_TRUE);
9257:   }
9258:   return(0);
9259: }

9261: /*@
9262:    MatPtAPNumeric - Computes the matrix product C = P^T * A * P

9264:    Neighbor-wise Collective on Mat

9266:    Input Parameters:
9267: +  A - the matrix
9268: -  P - the projection matrix

9270:    Output Parameters:
9271: .  C - the product matrix

9273:    Notes:
9274:    C must have been created by calling MatPtAPSymbolic and must be destroyed by
9275:    the user using MatDeatroy().

9277:    This routine is currently only implemented for pairs of AIJ matrices and classes
9278:    which inherit from AIJ.  C will be of type MATAIJ.

9280:    Level: intermediate

9282: .seealso: MatPtAP(), MatPtAPSymbolic(), MatMatMultNumeric()
9283: @*/
9284: PetscErrorCode MatPtAPNumeric(Mat A,Mat P,Mat C)
9285: {

9291:   if (!A->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
9292:   if (A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
9295:   MatCheckPreallocated(P,2);
9296:   if (!P->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
9297:   if (P->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
9300:   MatCheckPreallocated(C,3);
9301:   if (C->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
9302:   if (P->cmap->N!=C->rmap->N) SETERRQ2(PetscObjectComm((PetscObject)A),PETSC_E