Actual source code: matrix.c

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

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

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

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

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

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

 47:    Logically Collective on Mat

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

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

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

 64:    Level: intermediate


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


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

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

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

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

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

102:    Logically Collective on Mat

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

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

112:    Level: advanced

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

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

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

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

134:    Logically Collective on Mat

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

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

142:    Level: advanced

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

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

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

160:    Logically Collective on Mat

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

165:    Level: developer

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

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

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

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

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

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

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

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

240:   Level: intermediate

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

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

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

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

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

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

273:   Level: intermediate

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


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

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

302:    Not Collective

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

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

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

315:    Level: advanced

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

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

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

342:    Collective on Mat

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

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

350:    Level: advanced

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

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

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

369:    Logically Collective on Mat

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

374:    Level: advanced


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

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

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

397:    Collective on Mat

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

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

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

409:    Level: advanced

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

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


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

434:    Logically Collective on Mat

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

439:    Level: advanced


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

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

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

462:    Not Collective

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

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

471:    Level: advanced


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

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

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

496:    Not Collective

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

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

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

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

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

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

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

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


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

546:    Level: advanced

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

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

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

572:    Logically Collective on Mat

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

577:    Level: advanced

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

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

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

600:    Not Collective

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

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

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

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

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

630:    Level: advanced

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

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

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

654:    Not Collective

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

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

662:    Level: advanced

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

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

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

684:    Not Collective

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

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


693:    Level: advanced

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

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

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

716:    Logically Collective on Mat

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

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

726:    Level: advanced

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

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

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

744:    Logically Collective on Mat

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

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

754:    Level: advanced

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

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

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

772:    Not Collective

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

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

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

784:    Level: advanced

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

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

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

801:    Collective on Mat

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

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

810:    Level: beginner

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

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


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

829:    Collective on Mat

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

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

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

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

841:    Level: beginner

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

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

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

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

877:    Collective on Mat

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

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

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

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

900:    Collective on Mat

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1090:    Collective on PetscViewer

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

1097:    Options Database Keys:
1098:    Used with block matrix formats (MATSEQBAIJ,  ...) to specify
1099:    block size
1100: .    -matload_block_size <bs>

1102:    Level: beginner

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1187:    Corresponding MatView() is not yet implemented.

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

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

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

1200:  @*/
1201: PetscErrorCode MatLoad(Mat mat,PetscViewer viewer)
1202: {
1204:   PetscBool      flg;


1210:   if (!((PetscObject)mat)->type_name) {
1211:     MatSetType(mat,MATAIJ);
1212:   }

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

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

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

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

1256:     if (redund->subcomm) {
1257:       PetscCommDestroy(&redund->subcomm);
1258:     }
1259:     PetscFree(redund);
1260:   }
1261:   return(0);
1262: }

1264: /*@
1265:    MatDestroy - Frees space taken by a matrix.

1267:    Collective on Mat

1269:    Input Parameter:
1270: .  A - the matrix

1272:    Level: beginner

1274: @*/
1275: PetscErrorCode MatDestroy(Mat *A)
1276: {

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

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

1290:   PetscFree((*A)->defaultvectype);
1291:   PetscFree((*A)->bsizes);
1292:   PetscFree((*A)->solvertype);
1293:   MatDestroy_Redundant(&(*A)->redundant);
1294:   MatProductClear(*A);
1295:   MatNullSpaceDestroy(&(*A)->nullsp);
1296:   MatNullSpaceDestroy(&(*A)->transnullsp);
1297:   MatNullSpaceDestroy(&(*A)->nearnullsp);
1298:   MatDestroy(&(*A)->schur);
1299:   PetscLayoutDestroy(&(*A)->rmap);
1300:   PetscLayoutDestroy(&(*A)->cmap);
1301:   PetscHeaderDestroy(A);
1302:   return(0);
1303: }

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

1310:    Not Collective

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

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

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

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

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

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

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

1343:    Level: beginner

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

1349: .seealso: MatSetOption(), MatAssemblyBegin(), MatAssemblyEnd(), MatSetValuesBlocked(), MatSetValuesLocal(),
1350:           InsertMode, INSERT_VALUES, ADD_VALUES
1351: @*/
1352: PetscErrorCode MatSetValues(Mat mat,PetscInt m,const PetscInt idxm[],PetscInt n,const PetscInt idxn[],const PetscScalar v[],InsertMode addv)
1353: {

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

1364:   if (mat->insertmode == NOT_SET_VALUES) {
1365:     mat->insertmode = addv;
1366:   } else if (PetscUnlikely(mat->insertmode != addv)) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Cannot mix add values and insert values");
1367:   if (PetscDefined(USE_DEBUG)) {
1368:     PetscInt       i,j;

1370:     if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
1371:     if (!mat->ops->setvalues) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);

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

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


1396: /*@
1397:    MatSetValuesRowLocal - Inserts a row (block row for BAIJ matrices) of nonzero
1398:         values into a matrix

1400:    Not Collective

1402:    Input Parameters:
1403: +  mat - the matrix
1404: .  row - the (block) row to set
1405: -  v - a logically two-dimensional array of values

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

1410:    All the nonzeros in the row must be provided

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

1414:    The row must belong to this process

1416:    Level: intermediate

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

1430:   ISLocalToGlobalMappingApply(mat->rmap->mapping,1,&row,&globalrow);
1431:   MatSetValuesRow(mat,globalrow,v);
1432:   return(0);
1433: }

1435: /*@
1436:    MatSetValuesRow - Inserts a row (block row for BAIJ matrices) of nonzero
1437:         values into a matrix

1439:    Not Collective

1441:    Input Parameters:
1442: +  mat - the matrix
1443: .  row - the (block) row to set
1444: -  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

1446:    Notes:
1447:    The values, v, are column-oriented for the block version.

1449:    All the nonzeros in the row must be provided

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

1453:    The row must belong to this process

1455:    Level: advanced

1457: .seealso: MatSetOption(), MatAssemblyBegin(), MatAssemblyEnd(), MatSetValuesBlocked(), MatSetValuesLocal(),
1458:           InsertMode, INSERT_VALUES, ADD_VALUES, MatSetValues()
1459: @*/
1460: PetscErrorCode MatSetValuesRow(Mat mat,PetscInt row,const PetscScalar v[])
1461: {

1467:   MatCheckPreallocated(mat,1);
1469:   if (PetscUnlikely(mat->insertmode == ADD_VALUES)) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Cannot mix add and insert values");
1470:   if (PetscUnlikely(mat->factortype)) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
1471:   mat->insertmode = INSERT_VALUES;

1473:   if (mat->assembled) {
1474:     mat->was_assembled = PETSC_TRUE;
1475:     mat->assembled     = PETSC_FALSE;
1476:   }
1477:   PetscLogEventBegin(MAT_SetValues,mat,0,0,0);
1478:   if (!mat->ops->setvaluesrow) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
1479:   (*mat->ops->setvaluesrow)(mat,row,v);
1480:   PetscLogEventEnd(MAT_SetValues,mat,0,0,0);
1481:   return(0);
1482: }

1484: /*@
1485:    MatSetValuesStencil - Inserts or adds a block of values into a matrix.
1486:      Using structured grid indexing

1488:    Not Collective

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

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

1504:    Calls to MatSetValuesStencil() with the INSERT_VALUES and ADD_VALUES
1505:    options cannot be mixed without intervening calls to the assembly
1506:    routines.

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

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

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

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

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

1524:    In Fortran idxm and idxn should be declared as
1525: $     MatStencil idxm(4,m),idxn(4,n)
1526:    and the values inserted using
1527: $    idxm(MatStencil_i,1) = i
1528: $    idxm(MatStencil_j,1) = j
1529: $    idxm(MatStencil_k,1) = k
1530: $    idxm(MatStencil_c,1) = c
1531:    etc

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

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

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

1544:    Efficiency Alert:
1545:    The routine MatSetValuesBlockedStencil() may offer much better efficiency
1546:    for users of block sparse formats (MATSEQBAIJ and MATMPIBAIJ).

1548:    Level: beginner

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

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

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

1598: /*@
1599:    MatSetValuesBlockedStencil - Inserts or adds a block of values into a matrix.
1600:      Using structured grid indexing

1602:    Not Collective

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

1615:    Notes:
1616:    By default the values, v, are row-oriented and unsorted.
1617:    See MatSetOption() for other options.

1619:    Calls to MatSetValuesBlockedStencil() with the INSERT_VALUES and ADD_VALUES
1620:    options cannot be mixed without intervening calls to the assembly
1621:    routines.

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

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

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

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

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

1639:    In Fortran idxm and idxn should be declared as
1640: $     MatStencil idxm(4,m),idxn(4,n)
1641:    and the values inserted using
1642: $    idxm(MatStencil_i,1) = i
1643: $    idxm(MatStencil_j,1) = j
1644: $    idxm(MatStencil_k,1) = k
1645:    etc

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

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

1655:    Level: beginner

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

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

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

1707: /*@
1708:    MatSetStencil - Sets the grid information for setting values into a matrix via
1709:         MatSetValuesStencil()

1711:    Not Collective

1713:    Input Parameters:
1714: +  mat - the matrix
1715: .  dim - dimension of the grid 1, 2, or 3
1716: .  dims - number of grid points in x, y, and z direction, including ghost points on your processor
1717: .  starts - starting point of ghost nodes on your processor in x, y, and z direction
1718: -  dof - number of degrees of freedom per node


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

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

1727:    Level: beginner

1729: .seealso: MatSetOption(), MatAssemblyBegin(), MatAssemblyEnd(), MatSetValuesBlocked(), MatSetValuesLocal()
1730:           MatSetValues(), MatSetValuesBlockedStencil(), MatSetValuesStencil()
1731: @*/
1732: PetscErrorCode MatSetStencil(Mat mat,PetscInt dim,const PetscInt dims[],const PetscInt starts[],PetscInt dof)
1733: {
1734:   PetscInt i;


1741:   mat->stencil.dim = dim + (dof > 1);
1742:   for (i=0; i<dim; i++) {
1743:     mat->stencil.dims[i]   = dims[dim-i-1];      /* copy the values in backwards */
1744:     mat->stencil.starts[i] = starts[dim-i-1];
1745:   }
1746:   mat->stencil.dims[dim]   = dof;
1747:   mat->stencil.starts[dim] = 0;
1748:   mat->stencil.noc         = (PetscBool)(dof == 1);
1749:   return(0);
1750: }

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

1755:    Not Collective

1757:    Input Parameters:
1758: +  mat - the matrix
1759: .  v - a logically two-dimensional array of values
1760: .  m, idxm - the number of block rows and their global block indices
1761: .  n, idxn - the number of block columns and their global block indices
1762: -  addv - either ADD_VALUES or INSERT_VALUES, where
1763:    ADD_VALUES adds values to any existing entries, and
1764:    INSERT_VALUES replaces existing entries with new values

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

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

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

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

1782:    Calls to MatSetValuesBlocked() with the INSERT_VALUES and ADD_VALUES
1783:    options cannot be mixed without intervening calls to the assembly
1784:    routines.

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

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

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

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

1815:    Level: intermediate

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

1826:   if (!m || !n) return(0); /* no values to insert */
1830:   MatCheckPreallocated(mat,1);
1831:   if (mat->insertmode == NOT_SET_VALUES) {
1832:     mat->insertmode = addv;
1833:   } else if (PetscUnlikely(mat->insertmode != addv)) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Cannot mix add values and insert values");
1834:   if (PetscDefined(USE_DEBUG)) {
1835:     if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
1836:     if (!mat->ops->setvaluesblocked && !mat->ops->setvalues) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
1837:   }

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

1873: /*@C
1874:    MatGetValues - Gets a block of values from a matrix.

1876:    Not Collective; currently only returns a local block

1878:    Input Parameters:
1879: +  mat - the matrix
1880: .  v - a logically two-dimensional array for storing the values
1881: .  m, idxm - the number of rows and their global indices
1882: -  n, idxn - the number of columns and their global indices

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

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

1892:    MatGetValues() requires that the matrix has been assembled
1893:    with MatAssemblyBegin()/MatAssemblyEnd().  Thus, calls to
1894:    MatSetValues() and MatGetValues() CANNOT be made in succession
1895:    without intermediate matrix assembly.

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

1900:    Level: advanced

1902: .seealso: MatGetRow(), MatCreateSubMatrices(), MatSetValues()
1903: @*/
1904: PetscErrorCode MatGetValues(Mat mat,PetscInt m,const PetscInt idxm[],PetscInt n,const PetscInt idxn[],PetscScalar v[])
1905: {

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

1920:   PetscLogEventBegin(MAT_GetValues,mat,0,0,0);
1921:   (*mat->ops->getvalues)(mat,m,idxm,n,idxn,v);
1922:   PetscLogEventEnd(MAT_GetValues,mat,0,0,0);
1923:   return(0);
1924: }

1926: /*@C
1927:    MatGetValuesLocal - retrieves values into certain locations of a matrix,
1928:    using a local numbering of the nodes.

1930:    Not Collective

1932:    Input Parameters:
1933: +  mat - the matrix
1934: .  nrow, irow - number of rows and their local indices
1935: -  ncol, icol - number of columns and their local indices

1937:    Output Parameter:
1938: .  y -  a logically two-dimensional array of values

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

1943:    Level: advanced

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

1949: .seealso:  MatAssemblyBegin(), MatAssemblyEnd(), MatSetValues(), MatSetLocalToGlobalMapping(),
1950:            MatSetValuesLocal()
1951: @*/
1952: PetscErrorCode MatGetValuesLocal(Mat mat,PetscInt nrow,const PetscInt irow[],PetscInt ncol,const PetscInt icol[],PetscScalar y[])
1953: {

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

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

1994:   Not Collective

1996:   Input Parameters:
1997: + mat - the matrix
1998: . nb - the number of blocks
1999: . bs - the number of rows (and columns) in each block
2000: . rows - a concatenation of the rows for each block
2001: - v - a concatenation of logically two-dimensional arrays of values

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

2006:   Level: advanced

2008: .seealso: MatSetOption(), MatAssemblyBegin(), MatAssemblyEnd(), MatSetValuesBlocked(), MatSetValuesLocal(),
2009:           InsertMode, INSERT_VALUES, ADD_VALUES, MatSetValues()
2010: @*/
2011: PetscErrorCode MatSetValuesBatch(Mat mat, PetscInt nb, PetscInt bs, PetscInt rows[], const PetscScalar v[])
2012: {

2020:   if (PetscUnlikelyDebug(mat->factortype)) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");

2022:   PetscLogEventBegin(MAT_SetValuesBatch,mat,0,0,0);
2023:   if (mat->ops->setvaluesbatch) {
2024:     (*mat->ops->setvaluesbatch)(mat,nb,bs,rows,v);
2025:   } else {
2026:     PetscInt b;
2027:     for (b = 0; b < nb; ++b) {
2028:       MatSetValues(mat, bs, &rows[b*bs], bs, &rows[b*bs], &v[b*bs*bs], ADD_VALUES);
2029:     }
2030:   }
2031:   PetscLogEventEnd(MAT_SetValuesBatch,mat,0,0,0);
2032:   return(0);
2033: }

2035: /*@
2036:    MatSetLocalToGlobalMapping - Sets a local-to-global numbering for use by
2037:    the routine MatSetValuesLocal() to allow users to insert matrix entries
2038:    using a local (per-processor) numbering.

2040:    Not Collective

2042:    Input Parameters:
2043: +  x - the matrix
2044: .  rmapping - row mapping created with ISLocalToGlobalMappingCreate()   or ISLocalToGlobalMappingCreateIS()
2045: - cmapping - column mapping

2047:    Level: intermediate


2050: .seealso:  MatAssemblyBegin(), MatAssemblyEnd(), MatSetValues(), MatSetValuesLocal()
2051: @*/
2052: PetscErrorCode MatSetLocalToGlobalMapping(Mat x,ISLocalToGlobalMapping rmapping,ISLocalToGlobalMapping cmapping)
2053: {


2062:   if (x->ops->setlocaltoglobalmapping) {
2063:     (*x->ops->setlocaltoglobalmapping)(x,rmapping,cmapping);
2064:   } else {
2065:     PetscLayoutSetISLocalToGlobalMapping(x->rmap,rmapping);
2066:     PetscLayoutSetISLocalToGlobalMapping(x->cmap,cmapping);
2067:   }
2068:   return(0);
2069: }


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

2075:    Not Collective

2077:    Input Parameters:
2078: .  A - the matrix

2080:    Output Parameters:
2081: + rmapping - row mapping
2082: - cmapping - column mapping

2084:    Level: advanced


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

2101: /*@
2102:    MatGetLayouts - Gets the PetscLayout objects for rows and columns

2104:    Not Collective

2106:    Input Parameters:
2107: .  A - the matrix

2109:    Output Parameters:
2110: + rmap - row layout
2111: - cmap - column layout

2113:    Level: advanced

2115: .seealso:  MatCreateVecs(), MatGetLocalToGlobalMapping()
2116: @*/
2117: PetscErrorCode MatGetLayouts(Mat A,PetscLayout *rmap,PetscLayout *cmap)
2118: {
2124:   if (rmap) *rmap = A->rmap;
2125:   if (cmap) *cmap = A->cmap;
2126:   return(0);
2127: }

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

2133:    Not Collective

2135:    Input Parameters:
2136: +  mat - the matrix
2137: .  nrow, irow - number of rows and their local indices
2138: .  ncol, icol - number of columns and their local indices
2139: .  y -  a logically two-dimensional array of values
2140: -  addv - either INSERT_VALUES or ADD_VALUES, where
2141:    ADD_VALUES adds values to any existing entries, and
2142:    INSERT_VALUES replaces existing entries with new values

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

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

2150:    Calls to MatSetValuesLocal() with the INSERT_VALUES and ADD_VALUES
2151:    options cannot be mixed without intervening calls to the assembly
2152:    routines.

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

2157:    Level: intermediate

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

2163: .seealso:  MatAssemblyBegin(), MatAssemblyEnd(), MatSetValues(), MatSetLocalToGlobalMapping(),
2164:            MatSetValueLocal(), MatGetValuesLocal()
2165: @*/
2166: PetscErrorCode MatSetValuesLocal(Mat mat,PetscInt nrow,const PetscInt irow[],PetscInt ncol,const PetscInt icol[],const PetscScalar y[],InsertMode addv)
2167: {

2173:   MatCheckPreallocated(mat,1);
2174:   if (!nrow || !ncol) return(0); /* no values to insert */
2177:   if (mat->insertmode == NOT_SET_VALUES) {
2178:     mat->insertmode = addv;
2179:   }
2180:   else if (PetscUnlikely(mat->insertmode != addv)) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Cannot mix add values and insert values");
2181:   if (PetscDefined(USE_DEBUG)) {
2182:     if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2183:     if (!mat->ops->setvalueslocal && !mat->ops->setvalues) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
2184:   }

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

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

2216:    Not Collective

2218:    Input Parameters:
2219: +  x - the matrix
2220: .  nrow, irow - number of rows and their local indices
2221: .  ncol, icol - number of columns and their local indices
2222: .  y -  a logically two-dimensional array of values
2223: -  addv - either INSERT_VALUES or ADD_VALUES, where
2224:    ADD_VALUES adds values to any existing entries, and
2225:    INSERT_VALUES replaces existing entries with new values

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

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

2234:    Calls to MatSetValuesBlockedLocal() with the INSERT_VALUES and ADD_VALUES
2235:    options cannot be mixed without intervening calls to the assembly
2236:    routines.

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

2241:    Level: intermediate

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

2247: .seealso:  MatSetBlockSize(), MatSetLocalToGlobalMapping(), MatAssemblyBegin(), MatAssemblyEnd(),
2248:            MatSetValuesLocal(),  MatSetValuesBlocked()
2249: @*/
2250: PetscErrorCode MatSetValuesBlockedLocal(Mat mat,PetscInt nrow,const PetscInt irow[],PetscInt ncol,const PetscInt icol[],const PetscScalar y[],InsertMode addv)
2251: {

2257:   MatCheckPreallocated(mat,1);
2258:   if (!nrow || !ncol) return(0); /* no values to insert */
2262:   if (mat->insertmode == NOT_SET_VALUES) {
2263:     mat->insertmode = addv;
2264:   } else if (PetscUnlikely(mat->insertmode != addv)) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Cannot mix add values and insert values");
2265:   if (PetscDefined(USE_DEBUG)) {
2266:     if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2267:     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);
2268:   }

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

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

2309:    Collective on Mat

2311:    Input Parameters:
2312: +  mat - the matrix
2313: -  x   - the vector to be multiplied

2315:    Output Parameters:
2316: .  y - the result

2318:    Notes:
2319:    The vectors x and y cannot be the same.  I.e., one cannot
2320:    call MatMult(A,y,y).

2322:    Level: developer

2324: .seealso: MatMultTranspose(), MatMultAdd(), MatMultTransposeAdd()
2325: @*/
2326: PetscErrorCode MatMultDiagonalBlock(Mat mat,Vec x,Vec y)
2327: {


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

2341:   if (!mat->ops->multdiagonalblock) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Matrix type %s does not have a multiply defined",((PetscObject)mat)->type_name);
2342:   (*mat->ops->multdiagonalblock)(mat,x,y);
2343:   PetscObjectStateIncrease((PetscObject)y);
2344:   return(0);
2345: }

2347: /* --------------------------------------------------------*/
2348: /*@
2349:    MatMult - Computes the matrix-vector product, y = Ax.

2351:    Neighbor-wise Collective on Mat

2353:    Input Parameters:
2354: +  mat - the matrix
2355: -  x   - the vector to be multiplied

2357:    Output Parameters:
2358: .  y - the result

2360:    Notes:
2361:    The vectors x and y cannot be the same.  I.e., one cannot
2362:    call MatMult(A,y,y).

2364:    Level: beginner

2366: .seealso: MatMultTranspose(), MatMultAdd(), MatMultTransposeAdd()
2367: @*/
2368: PetscErrorCode MatMult(Mat mat,Vec x,Vec y)
2369: {

2377:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2378:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2379:   if (x == y) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"x and y must be different vectors");
2380: #if !defined(PETSC_HAVE_CONSTRAINTS)
2381:   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);
2382:   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);
2383:   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);
2384: #endif
2385:   VecSetErrorIfLocked(y,3);
2386:   if (mat->erroriffailure) {VecValidValues(x,2,PETSC_TRUE);}
2387:   MatCheckPreallocated(mat,1);

2389:   VecLockReadPush(x);
2390:   if (!mat->ops->mult) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Matrix type %s does not have a multiply defined",((PetscObject)mat)->type_name);
2391:   PetscLogEventBegin(MAT_Mult,mat,x,y,0);
2392:   (*mat->ops->mult)(mat,x,y);
2393:   PetscLogEventEnd(MAT_Mult,mat,x,y,0);
2394:   if (mat->erroriffailure) {VecValidValues(y,3,PETSC_FALSE);}
2395:   VecLockReadPop(x);
2396:   return(0);
2397: }

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

2402:    Neighbor-wise Collective on Mat

2404:    Input Parameters:
2405: +  mat - the matrix
2406: -  x   - the vector to be multiplied

2408:    Output Parameters:
2409: .  y - the result

2411:    Notes:
2412:    The vectors x and y cannot be the same.  I.e., one cannot
2413:    call MatMultTranspose(A,y,y).

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

2418:    Level: beginner

2420: .seealso: MatMult(), MatMultAdd(), MatMultTransposeAdd(), MatMultHermitianTranspose(), MatTranspose()
2421: @*/
2422: PetscErrorCode MatMultTranspose(Mat mat,Vec x,Vec y)
2423: {


2432:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2433:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2434:   if (x == y) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"x and y must be different vectors");
2435: #if !defined(PETSC_HAVE_CONSTRAINTS)
2436:   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);
2437:   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);
2438: #endif
2439:   if (mat->erroriffailure) {VecValidValues(x,2,PETSC_TRUE);}
2440:   MatCheckPreallocated(mat,1);

2442:   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);
2443:   PetscLogEventBegin(MAT_MultTranspose,mat,x,y,0);
2444:   VecLockReadPush(x);
2445:   (*mat->ops->multtranspose)(mat,x,y);
2446:   VecLockReadPop(x);
2447:   PetscLogEventEnd(MAT_MultTranspose,mat,x,y,0);
2448:   PetscObjectStateIncrease((PetscObject)y);
2449:   if (mat->erroriffailure) {VecValidValues(y,3,PETSC_FALSE);}
2450:   return(0);
2451: }

2453: /*@
2454:    MatMultHermitianTranspose - Computes matrix Hermitian transpose times a vector.

2456:    Neighbor-wise Collective on Mat

2458:    Input Parameters:
2459: +  mat - the matrix
2460: -  x   - the vector to be multilplied

2462:    Output Parameters:
2463: .  y - the result

2465:    Notes:
2466:    The vectors x and y cannot be the same.  I.e., one cannot
2467:    call MatMultHermitianTranspose(A,y,y).

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

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

2473:    Level: beginner

2475: .seealso: MatMult(), MatMultAdd(), MatMultHermitianTransposeAdd(), MatMultTranspose()
2476: @*/
2477: PetscErrorCode MatMultHermitianTranspose(Mat mat,Vec x,Vec y)
2478: {
2480:   Vec            w;


2488:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2489:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2490:   if (x == y) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"x and y must be different vectors");
2491: #if !defined(PETSC_HAVE_CONSTRAINTS)
2492:   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);
2493:   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);
2494: #endif
2495:   MatCheckPreallocated(mat,1);

2497:   PetscLogEventBegin(MAT_MultHermitianTranspose,mat,x,y,0);
2498:   if (mat->ops->multhermitiantranspose) {
2499:     VecLockReadPush(x);
2500:     (*mat->ops->multhermitiantranspose)(mat,x,y);
2501:     VecLockReadPop(x);
2502:   } else {
2503:     VecDuplicate(x,&w);
2504:     VecCopy(x,w);
2505:     VecConjugate(w);
2506:     MatMultTranspose(mat,w,y);
2507:     VecDestroy(&w);
2508:     VecConjugate(y);
2509:   }
2510:   PetscLogEventEnd(MAT_MultHermitianTranspose,mat,x,y,0);
2511:   PetscObjectStateIncrease((PetscObject)y);
2512:   return(0);
2513: }

2515: /*@
2516:     MatMultAdd -  Computes v3 = v2 + A * v1.

2518:     Neighbor-wise Collective on Mat

2520:     Input Parameters:
2521: +   mat - the matrix
2522: -   v1, v2 - the vectors

2524:     Output Parameters:
2525: .   v3 - the result

2527:     Notes:
2528:     The vectors v1 and v3 cannot be the same.  I.e., one cannot
2529:     call MatMultAdd(A,v1,v2,v1).

2531:     Level: beginner

2533: .seealso: MatMultTranspose(), MatMult(), MatMultTransposeAdd()
2534: @*/
2535: PetscErrorCode MatMultAdd(Mat mat,Vec v1,Vec v2,Vec v3)
2536: {


2546:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2547:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2548:   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);
2549:   /* 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);
2550:      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); */
2551:   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);
2552:   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);
2553:   if (v1 == v3) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"v1 and v3 must be different vectors");
2554:   MatCheckPreallocated(mat,1);

2556:   if (!mat->ops->multadd) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"No MatMultAdd() for matrix type %s",((PetscObject)mat)->type_name);
2557:   PetscLogEventBegin(MAT_MultAdd,mat,v1,v2,v3);
2558:   VecLockReadPush(v1);
2559:   (*mat->ops->multadd)(mat,v1,v2,v3);
2560:   VecLockReadPop(v1);
2561:   PetscLogEventEnd(MAT_MultAdd,mat,v1,v2,v3);
2562:   PetscObjectStateIncrease((PetscObject)v3);
2563:   return(0);
2564: }

2566: /*@
2567:    MatMultTransposeAdd - Computes v3 = v2 + A' * v1.

2569:    Neighbor-wise Collective on Mat

2571:    Input Parameters:
2572: +  mat - the matrix
2573: -  v1, v2 - the vectors

2575:    Output Parameters:
2576: .  v3 - the result

2578:    Notes:
2579:    The vectors v1 and v3 cannot be the same.  I.e., one cannot
2580:    call MatMultTransposeAdd(A,v1,v2,v1).

2582:    Level: beginner

2584: .seealso: MatMultTranspose(), MatMultAdd(), MatMult()
2585: @*/
2586: PetscErrorCode MatMultTransposeAdd(Mat mat,Vec v1,Vec v2,Vec v3)
2587: {


2597:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2598:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2599:   if (!mat->ops->multtransposeadd) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
2600:   if (v1 == v3) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"v1 and v3 must be different vectors");
2601:   if (mat->rmap->N != v1->map->N) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_SIZ,"Mat mat,Vec v1: global dim %D %D",mat->rmap->N,v1->map->N);
2602:   if (mat->cmap->N != v2->map->N) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_SIZ,"Mat mat,Vec v2: global dim %D %D",mat->cmap->N,v2->map->N);
2603:   if (mat->cmap->N != v3->map->N) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_SIZ,"Mat mat,Vec v3: global dim %D %D",mat->cmap->N,v3->map->N);
2604:   MatCheckPreallocated(mat,1);

2606:   PetscLogEventBegin(MAT_MultTransposeAdd,mat,v1,v2,v3);
2607:   VecLockReadPush(v1);
2608:   (*mat->ops->multtransposeadd)(mat,v1,v2,v3);
2609:   VecLockReadPop(v1);
2610:   PetscLogEventEnd(MAT_MultTransposeAdd,mat,v1,v2,v3);
2611:   PetscObjectStateIncrease((PetscObject)v3);
2612:   return(0);
2613: }

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

2618:    Neighbor-wise Collective on Mat

2620:    Input Parameters:
2621: +  mat - the matrix
2622: -  v1, v2 - the vectors

2624:    Output Parameters:
2625: .  v3 - the result

2627:    Notes:
2628:    The vectors v1 and v3 cannot be the same.  I.e., one cannot
2629:    call MatMultHermitianTransposeAdd(A,v1,v2,v1).

2631:    Level: beginner

2633: .seealso: MatMultHermitianTranspose(), MatMultTranspose(), MatMultAdd(), MatMult()
2634: @*/
2635: PetscErrorCode MatMultHermitianTransposeAdd(Mat mat,Vec v1,Vec v2,Vec v3)
2636: {


2646:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2647:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2648:   if (v1 == v3) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"v1 and v3 must be different vectors");
2649:   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);
2650:   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);
2651:   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);
2652:   MatCheckPreallocated(mat,1);

2654:   PetscLogEventBegin(MAT_MultHermitianTransposeAdd,mat,v1,v2,v3);
2655:   VecLockReadPush(v1);
2656:   if (mat->ops->multhermitiantransposeadd) {
2657:     (*mat->ops->multhermitiantransposeadd)(mat,v1,v2,v3);
2658:   } else {
2659:     Vec w,z;
2660:     VecDuplicate(v1,&w);
2661:     VecCopy(v1,w);
2662:     VecConjugate(w);
2663:     VecDuplicate(v3,&z);
2664:     MatMultTranspose(mat,w,z);
2665:     VecDestroy(&w);
2666:     VecConjugate(z);
2667:     if (v2 != v3) {
2668:       VecWAXPY(v3,1.0,v2,z);
2669:     } else {
2670:       VecAXPY(v3,1.0,z);
2671:     }
2672:     VecDestroy(&z);
2673:   }
2674:   VecLockReadPop(v1);
2675:   PetscLogEventEnd(MAT_MultHermitianTransposeAdd,mat,v1,v2,v3);
2676:   PetscObjectStateIncrease((PetscObject)v3);
2677:   return(0);
2678: }

2680: /*@
2681:    MatMultConstrained - The inner multiplication routine for a
2682:    constrained matrix P^T A P.

2684:    Neighbor-wise Collective on Mat

2686:    Input Parameters:
2687: +  mat - the matrix
2688: -  x   - the vector to be multilplied

2690:    Output Parameters:
2691: .  y - the result

2693:    Notes:
2694:    The vectors x and y cannot be the same.  I.e., one cannot
2695:    call MatMult(A,y,y).

2697:    Level: beginner

2699: .seealso: MatMult(), MatMultTranspose(), MatMultAdd(), MatMultTransposeAdd()
2700: @*/
2701: PetscErrorCode MatMultConstrained(Mat mat,Vec x,Vec y)
2702: {

2709:   if (!mat->assembled) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2710:   if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2711:   if (x == y) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"x and y must be different vectors");
2712:   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);
2713:   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);
2714:   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);

2716:   PetscLogEventBegin(MAT_MultConstrained,mat,x,y,0);
2717:   VecLockReadPush(x);
2718:   (*mat->ops->multconstrained)(mat,x,y);
2719:   VecLockReadPop(x);
2720:   PetscLogEventEnd(MAT_MultConstrained,mat,x,y,0);
2721:   PetscObjectStateIncrease((PetscObject)y);
2722:   return(0);
2723: }

2725: /*@
2726:    MatMultTransposeConstrained - The inner multiplication routine for a
2727:    constrained matrix P^T A^T P.

2729:    Neighbor-wise Collective on Mat

2731:    Input Parameters:
2732: +  mat - the matrix
2733: -  x   - the vector to be multilplied

2735:    Output Parameters:
2736: .  y - the result

2738:    Notes:
2739:    The vectors x and y cannot be the same.  I.e., one cannot
2740:    call MatMult(A,y,y).

2742:    Level: beginner

2744: .seealso: MatMult(), MatMultTranspose(), MatMultAdd(), MatMultTransposeAdd()
2745: @*/
2746: PetscErrorCode MatMultTransposeConstrained(Mat mat,Vec x,Vec y)
2747: {

2754:   if (!mat->assembled) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2755:   if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2756:   if (x == y) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"x and y must be different vectors");
2757:   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);
2758:   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);

2760:   PetscLogEventBegin(MAT_MultConstrained,mat,x,y,0);
2761:   (*mat->ops->multtransposeconstrained)(mat,x,y);
2762:   PetscLogEventEnd(MAT_MultConstrained,mat,x,y,0);
2763:   PetscObjectStateIncrease((PetscObject)y);
2764:   return(0);
2765: }

2767: /*@C
2768:    MatGetFactorType - gets the type of factorization it is

2770:    Not Collective

2772:    Input Parameters:
2773: .  mat - the matrix

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

2778:    Level: intermediate

2780: .seealso: MatFactorType, MatGetFactor(), MatSetFactorType()
2781: @*/
2782: PetscErrorCode MatGetFactorType(Mat mat,MatFactorType *t)
2783: {
2788:   *t = mat->factortype;
2789:   return(0);
2790: }

2792: /*@C
2793:    MatSetFactorType - sets the type of factorization it is

2795:    Logically Collective on Mat

2797:    Input Parameters:
2798: +  mat - the matrix
2799: -  t - the type, one of MAT_FACTOR_NONE, MAT_FACTOR_LU, MAT_FACTOR_CHOLESKY, MAT_FACTOR_ILU, MAT_FACTOR_ICC,MAT_FACTOR_ILUDT

2801:    Level: intermediate

2803: .seealso: MatFactorType, MatGetFactor(), MatGetFactorType()
2804: @*/
2805: PetscErrorCode MatSetFactorType(Mat mat, MatFactorType t)
2806: {
2810:   mat->factortype = t;
2811:   return(0);
2812: }

2814: /* ------------------------------------------------------------*/
2815: /*@C
2816:    MatGetInfo - Returns information about matrix storage (number of
2817:    nonzeros, memory, etc.).

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

2821:    Input Parameters:
2822: .  mat - the matrix

2824:    Output Parameters:
2825: +  flag - flag indicating the type of parameters to be returned
2826:    (MAT_LOCAL - local matrix, MAT_GLOBAL_MAX - maximum over all processors,
2827:    MAT_GLOBAL_SUM - sum over all processors)
2828: -  info - matrix information context

2830:    Notes:
2831:    The MatInfo context contains a variety of matrix data, including
2832:    number of nonzeros allocated and used, number of mallocs during
2833:    matrix assembly, etc.  Additional information for factored matrices
2834:    is provided (such as the fill ratio, number of mallocs during
2835:    factorization, etc.).  Much of this info is printed to PETSC_STDOUT
2836:    when using the runtime options
2837: $       -info -mat_view ::ascii_info

2839:    Example for C/C++ Users:
2840:    See the file ${PETSC_DIR}/include/petscmat.h for a complete list of
2841:    data within the MatInfo context.  For example,
2842: .vb
2843:       MatInfo info;
2844:       Mat     A;
2845:       double  mal, nz_a, nz_u;

2847:       MatGetInfo(A,MAT_LOCAL,&info);
2848:       mal  = info.mallocs;
2849:       nz_a = info.nz_allocated;
2850: .ve

2852:    Example for Fortran Users:
2853:    Fortran users should declare info as a double precision
2854:    array of dimension MAT_INFO_SIZE, and then extract the parameters
2855:    of interest.  See the file ${PETSC_DIR}/include/petsc/finclude/petscmat.h
2856:    a complete list of parameter names.
2857: .vb
2858:       double  precision info(MAT_INFO_SIZE)
2859:       double  precision mal, nz_a
2860:       Mat     A
2861:       integer ierr

2863:       call MatGetInfo(A,MAT_LOCAL,info,ierr)
2864:       mal = info(MAT_INFO_MALLOCS)
2865:       nz_a = info(MAT_INFO_NZ_ALLOCATED)
2866: .ve

2868:     Level: intermediate

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

2873: .seealso: MatStashGetInfo()

2875: @*/
2876: PetscErrorCode MatGetInfo(Mat mat,MatInfoType flag,MatInfo *info)
2877: {

2884:   if (!mat->ops->getinfo) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
2885:   MatCheckPreallocated(mat,1);
2886:   (*mat->ops->getinfo)(mat,flag,info);
2887:   return(0);
2888: }

2890: /*
2891:    This is used by external packages where it is not easy to get the info from the actual
2892:    matrix factorization.
2893: */
2894: PetscErrorCode MatGetInfo_External(Mat A,MatInfoType flag,MatInfo *info)
2895: {

2899:   PetscMemzero(info,sizeof(MatInfo));
2900:   return(0);
2901: }

2903: /* ----------------------------------------------------------*/

2905: /*@C
2906:    MatLUFactor - Performs in-place LU factorization of matrix.

2908:    Collective on Mat

2910:    Input Parameters:
2911: +  mat - the matrix
2912: .  row - row permutation
2913: .  col - column permutation
2914: -  info - options for factorization, includes
2915: $          fill - expected fill as ratio of original fill.
2916: $          dtcol - pivot tolerance (0 no pivot, 1 full column pivoting)
2917: $                   Run with the option -info to determine an optimal value to use

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

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

2927:    Level: developer

2929: .seealso: MatLUFactorSymbolic(), MatLUFactorNumeric(), MatCholeskyFactor(),
2930:           MatGetOrdering(), MatSetUnfactored(), MatFactorInfo, MatGetFactor()

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

2935: @*/
2936: PetscErrorCode MatLUFactor(Mat mat,IS row,IS col,const MatFactorInfo *info)
2937: {
2939:   MatFactorInfo  tinfo;

2947:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2948:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2949:   if (!mat->ops->lufactor) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
2950:   MatCheckPreallocated(mat,1);
2951:   if (!info) {
2952:     MatFactorInfoInitialize(&tinfo);
2953:     info = &tinfo;
2954:   }

2956:   PetscLogEventBegin(MAT_LUFactor,mat,row,col,0);
2957:   (*mat->ops->lufactor)(mat,row,col,info);
2958:   PetscLogEventEnd(MAT_LUFactor,mat,row,col,0);
2959:   PetscObjectStateIncrease((PetscObject)mat);
2960:   return(0);
2961: }

2963: /*@C
2964:    MatILUFactor - Performs in-place ILU factorization of matrix.

2966:    Collective on Mat

2968:    Input Parameters:
2969: +  mat - the matrix
2970: .  row - row permutation
2971: .  col - column permutation
2972: -  info - structure containing
2973: $      levels - number of levels of fill.
2974: $      expected fill - as ratio of original fill.
2975: $      1 or 0 - indicating force fill on diagonal (improves robustness for matrices
2976:                 missing diagonal entries)

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

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

2986:    Level: developer

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

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

2993: @*/
2994: PetscErrorCode MatILUFactor(Mat mat,IS row,IS col,const MatFactorInfo *info)
2995: {

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

3010:   PetscLogEventBegin(MAT_ILUFactor,mat,row,col,0);
3011:   (*mat->ops->ilufactor)(mat,row,col,info);
3012:   PetscLogEventEnd(MAT_ILUFactor,mat,row,col,0);
3013:   PetscObjectStateIncrease((PetscObject)mat);
3014:   return(0);
3015: }

3017: /*@C
3018:    MatLUFactorSymbolic - Performs symbolic LU factorization of matrix.
3019:    Call this routine before calling MatLUFactorNumeric().

3021:    Collective on Mat

3023:    Input Parameters:
3024: +  fact - the factor matrix obtained with MatGetFactor()
3025: .  mat - the matrix
3026: .  row, col - row and column permutations
3027: -  info - options for factorization, includes
3028: $          fill - expected fill as ratio of original fill.
3029: $          dtcol - pivot tolerance (0 no pivot, 1 full column pivoting)
3030: $                   Run with the option -info to determine an optimal value to use


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

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

3040:    Level: developer

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

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

3047: @*/
3048: PetscErrorCode MatLUFactorSymbolic(Mat fact,Mat mat,IS row,IS col,const MatFactorInfo *info)
3049: {
3051:   MatFactorInfo  tinfo;

3060:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
3061:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
3062:   if (!(fact)->ops->lufactorsymbolic) {
3063:     MatSolverType spackage;
3064:     MatFactorGetSolverType(fact,&spackage);
3065:     SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Matrix type %s symbolic LU using solver package %s",((PetscObject)mat)->type_name,spackage);
3066:   }
3067:   MatCheckPreallocated(mat,2);
3068:   if (!info) {
3069:     MatFactorInfoInitialize(&tinfo);
3070:     info = &tinfo;
3071:   }

3073:   PetscLogEventBegin(MAT_LUFactorSymbolic,mat,row,col,0);
3074:   (fact->ops->lufactorsymbolic)(fact,mat,row,col,info);
3075:   PetscLogEventEnd(MAT_LUFactorSymbolic,mat,row,col,0);
3076:   PetscObjectStateIncrease((PetscObject)fact);
3077:   return(0);
3078: }

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

3084:    Collective on Mat

3086:    Input Parameters:
3087: +  fact - the factor matrix obtained with MatGetFactor()
3088: .  mat - the matrix
3089: -  info - options for factorization

3091:    Notes:
3092:    See MatLUFactor() for in-place factorization.  See
3093:    MatCholeskyFactorNumeric() for the symmetric, positive definite case.

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

3099:    Level: developer

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

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

3106: @*/
3107: PetscErrorCode MatLUFactorNumeric(Mat fact,Mat mat,const MatFactorInfo *info)
3108: {
3109:   MatFactorInfo  tinfo;

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

3120:   if (!(fact)->ops->lufactornumeric) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s numeric LU",((PetscObject)mat)->type_name);
3121:   MatCheckPreallocated(mat,2);
3122:   if (!info) {
3123:     MatFactorInfoInitialize(&tinfo);
3124:     info = &tinfo;
3125:   }

3127:   PetscLogEventBegin(MAT_LUFactorNumeric,mat,fact,0,0);
3128:   (fact->ops->lufactornumeric)(fact,mat,info);
3129:   PetscLogEventEnd(MAT_LUFactorNumeric,mat,fact,0,0);
3130:   MatViewFromOptions(fact,NULL,"-mat_factor_view");
3131:   PetscObjectStateIncrease((PetscObject)fact);
3132:   return(0);
3133: }

3135: /*@C
3136:    MatCholeskyFactor - Performs in-place Cholesky factorization of a
3137:    symmetric matrix.

3139:    Collective on Mat

3141:    Input Parameters:
3142: +  mat - the matrix
3143: .  perm - row and column permutations
3144: -  f - expected fill as ratio of original fill

3146:    Notes:
3147:    See MatLUFactor() for the nonsymmetric case.  See also
3148:    MatCholeskyFactorSymbolic(), and MatCholeskyFactorNumeric().

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

3154:    Level: developer

3156: .seealso: MatLUFactor(), MatCholeskyFactorSymbolic(), MatCholeskyFactorNumeric()
3157:           MatGetOrdering()

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

3162: @*/
3163: PetscErrorCode MatCholeskyFactor(Mat mat,IS perm,const MatFactorInfo *info)
3164: {
3166:   MatFactorInfo  tinfo;

3173:   if (mat->rmap->N != mat->cmap->N) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONG,"Matrix must be square");
3174:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
3175:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
3176:   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);
3177:   MatCheckPreallocated(mat,1);
3178:   if (!info) {
3179:     MatFactorInfoInitialize(&tinfo);
3180:     info = &tinfo;
3181:   }

3183:   PetscLogEventBegin(MAT_CholeskyFactor,mat,perm,0,0);
3184:   (*mat->ops->choleskyfactor)(mat,perm,info);
3185:   PetscLogEventEnd(MAT_CholeskyFactor,mat,perm,0,0);
3186:   PetscObjectStateIncrease((PetscObject)mat);
3187:   return(0);
3188: }

3190: /*@C
3191:    MatCholeskyFactorSymbolic - Performs symbolic Cholesky factorization
3192:    of a symmetric matrix.

3194:    Collective on Mat

3196:    Input Parameters:
3197: +  fact - the factor matrix obtained with MatGetFactor()
3198: .  mat - the matrix
3199: .  perm - row and column permutations
3200: -  info - options for factorization, includes
3201: $          fill - expected fill as ratio of original fill.
3202: $          dtcol - pivot tolerance (0 no pivot, 1 full column pivoting)
3203: $                   Run with the option -info to determine an optimal value to use

3205:    Notes:
3206:    See MatLUFactorSymbolic() for the nonsymmetric case.  See also
3207:    MatCholeskyFactor() and MatCholeskyFactorNumeric().

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

3213:    Level: developer

3215: .seealso: MatLUFactorSymbolic(), MatCholeskyFactor(), MatCholeskyFactorNumeric()
3216:           MatGetOrdering()

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

3221: @*/
3222: PetscErrorCode MatCholeskyFactorSymbolic(Mat fact,Mat mat,IS perm,const MatFactorInfo *info)
3223: {
3225:   MatFactorInfo  tinfo;

3233:   if (mat->rmap->N != mat->cmap->N) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONG,"Matrix must be square");
3234:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
3235:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
3236:   if (!(fact)->ops->choleskyfactorsymbolic) {
3237:     MatSolverType spackage;
3238:     MatFactorGetSolverType(fact,&spackage);
3239:     SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s symbolic factor Cholesky using solver package %s",((PetscObject)mat)->type_name,spackage);
3240:   }
3241:   MatCheckPreallocated(mat,2);
3242:   if (!info) {
3243:     MatFactorInfoInitialize(&tinfo);
3244:     info = &tinfo;
3245:   }

3247:   PetscLogEventBegin(MAT_CholeskyFactorSymbolic,mat,perm,0,0);
3248:   (fact->ops->choleskyfactorsymbolic)(fact,mat,perm,info);
3249:   PetscLogEventEnd(MAT_CholeskyFactorSymbolic,mat,perm,0,0);
3250:   PetscObjectStateIncrease((PetscObject)fact);
3251:   return(0);
3252: }

3254: /*@C
3255:    MatCholeskyFactorNumeric - Performs numeric Cholesky factorization
3256:    of a symmetric matrix. Call this routine after first calling
3257:    MatCholeskyFactorSymbolic().

3259:    Collective on Mat

3261:    Input Parameters:
3262: +  fact - the factor matrix obtained with MatGetFactor()
3263: .  mat - the initial matrix
3264: .  info - options for factorization
3265: -  fact - the symbolic factor of mat


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

3273:    Level: developer

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

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

3280: @*/
3281: PetscErrorCode MatCholeskyFactorNumeric(Mat fact,Mat mat,const MatFactorInfo *info)
3282: {
3283:   MatFactorInfo  tinfo;

3291:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
3292:   if (!(fact)->ops->choleskyfactornumeric) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s numeric factor Cholesky",((PetscObject)mat)->type_name);
3293:   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);
3294:   MatCheckPreallocated(mat,2);
3295:   if (!info) {
3296:     MatFactorInfoInitialize(&tinfo);
3297:     info = &tinfo;
3298:   }

3300:   PetscLogEventBegin(MAT_CholeskyFactorNumeric,mat,fact,0,0);
3301:   (fact->ops->choleskyfactornumeric)(fact,mat,info);
3302:   PetscLogEventEnd(MAT_CholeskyFactorNumeric,mat,fact,0,0);
3303:   MatViewFromOptions(fact,NULL,"-mat_factor_view");
3304:   PetscObjectStateIncrease((PetscObject)fact);
3305:   return(0);
3306: }

3308: /* ----------------------------------------------------------------*/
3309: /*@
3310:    MatSolve - Solves A x = b, given a factored matrix.

3312:    Neighbor-wise Collective on Mat

3314:    Input Parameters:
3315: +  mat - the factored matrix
3316: -  b - the right-hand-side vector

3318:    Output Parameter:
3319: .  x - the result vector

3321:    Notes:
3322:    The vectors b and x cannot be the same.  I.e., one cannot
3323:    call MatSolve(A,x,x).

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

3330:    Level: developer

3332: .seealso: MatSolveAdd(), MatSolveTranspose(), MatSolveTransposeAdd()
3333: @*/
3334: PetscErrorCode MatSolve(Mat mat,Vec b,Vec x)
3335: {

3345:   if (x == b) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"x and b must be different vectors");
3346:   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);
3347:   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);
3348:   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);
3349:   if (!mat->rmap->N && !mat->cmap->N) return(0);
3350:   MatCheckPreallocated(mat,1);

3352:   PetscLogEventBegin(MAT_Solve,mat,b,x,0);
3353:   if (mat->factorerrortype) {
3354:     PetscInfo1(mat,"MatFactorError %D\n",mat->factorerrortype);
3355:     VecSetInf(x);
3356:   } else {
3357:     if (!mat->ops->solve) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
3358:     (*mat->ops->solve)(mat,b,x);
3359:   }
3360:   PetscLogEventEnd(MAT_Solve,mat,b,x,0);
3361:   PetscObjectStateIncrease((PetscObject)x);
3362:   return(0);
3363: }

3365: static PetscErrorCode MatMatSolve_Basic(Mat A,Mat B,Mat X,PetscBool trans)
3366: {
3368:   Vec            b,x;
3369:   PetscInt       m,N,i;
3370:   PetscScalar    *bb,*xx;

3373:   MatDenseGetArrayRead(B,(const PetscScalar**)&bb);
3374:   MatDenseGetArray(X,&xx);
3375:   MatGetLocalSize(B,&m,NULL);  /* number local rows */
3376:   MatGetSize(B,NULL,&N);       /* total columns in dense matrix */
3377:   MatCreateVecs(A,&x,&b);
3378:   for (i=0; i<N; i++) {
3379:     VecPlaceArray(b,bb + i*m);
3380:     VecPlaceArray(x,xx + i*m);
3381:     if (trans) {
3382:       MatSolveTranspose(A,b,x);
3383:     } else {
3384:       MatSolve(A,b,x);
3385:     }
3386:     VecResetArray(x);
3387:     VecResetArray(b);
3388:   }
3389:   VecDestroy(&b);
3390:   VecDestroy(&x);
3391:   MatDenseRestoreArrayRead(B,(const PetscScalar**)&bb);
3392:   MatDenseRestoreArray(X,&xx);
3393:   return(0);
3394: }

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

3399:    Neighbor-wise Collective on Mat

3401:    Input Parameters:
3402: +  A - the factored matrix
3403: -  B - the right-hand-side matrix MATDENSE (or sparse -- when using MUMPS)

3405:    Output Parameter:
3406: .  X - the result matrix (dense matrix)

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

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

3418:    Level: developer

3420: .seealso: MatMatSolveTranspose(), MatLUFactor(), MatCholeskyFactor()
3421: @*/
3422: PetscErrorCode MatMatSolve(Mat A,Mat B,Mat X)
3423: {

3433:   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);
3434:   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);
3435:   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");
3436:   if (!A->rmap->N && !A->cmap->N) return(0);
3437:   if (!A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
3438:   MatCheckPreallocated(A,1);

3440:   PetscLogEventBegin(MAT_MatSolve,A,B,X,0);
3441:   if (!A->ops->matsolve) {
3442:     PetscInfo1(A,"Mat type %s using basic MatMatSolve\n",((PetscObject)A)->type_name);
3443:     MatMatSolve_Basic(A,B,X,PETSC_FALSE);
3444:   } else {
3445:     (*A->ops->matsolve)(A,B,X);
3446:   }
3447:   PetscLogEventEnd(MAT_MatSolve,A,B,X,0);
3448:   PetscObjectStateIncrease((PetscObject)X);
3449:   return(0);
3450: }

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

3455:    Neighbor-wise Collective on Mat

3457:    Input Parameters:
3458: +  A - the factored matrix
3459: -  B - the right-hand-side matrix  (dense matrix)

3461:    Output Parameter:
3462: .  X - the result matrix (dense matrix)

3464:    Notes:
3465:    The matrices B and X cannot be the same.  I.e., one cannot
3466:    call MatMatSolveTranspose(A,X,X).

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

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

3476:    Level: developer

3478: .seealso: MatMatSolve(), MatLUFactor(), MatCholeskyFactor()
3479: @*/
3480: PetscErrorCode MatMatSolveTranspose(Mat A,Mat B,Mat X)
3481: {

3491:   if (X == B) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_IDN,"X and B must be different matrices");
3492:   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);
3493:   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);
3494:   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);
3495:   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");
3496:   if (!A->rmap->N && !A->cmap->N) return(0);
3497:   if (!A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
3498:   MatCheckPreallocated(A,1);

3500:   PetscLogEventBegin(MAT_MatSolve,A,B,X,0);
3501:   if (!A->ops->matsolvetranspose) {
3502:     PetscInfo1(A,"Mat type %s using basic MatMatSolveTranspose\n",((PetscObject)A)->type_name);
3503:     MatMatSolve_Basic(A,B,X,PETSC_TRUE);
3504:   } else {
3505:     (*A->ops->matsolvetranspose)(A,B,X);
3506:   }
3507:   PetscLogEventEnd(MAT_MatSolve,A,B,X,0);
3508:   PetscObjectStateIncrease((PetscObject)X);
3509:   return(0);
3510: }

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

3515:    Neighbor-wise Collective on Mat

3517:    Input Parameters:
3518: +  A - the factored matrix
3519: -  Bt - the transpose of right-hand-side matrix

3521:    Output Parameter:
3522: .  X - the result matrix (dense matrix)

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

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

3532:    Level: developer

3534: .seealso: MatMatSolve(), MatMatSolveTranspose(), MatLUFactor(), MatCholeskyFactor()
3535: @*/
3536: PetscErrorCode MatMatTransposeSolve(Mat A,Mat Bt,Mat X)
3537: {


3548:   if (X == Bt) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_IDN,"X and B must be different matrices");
3549:   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);
3550:   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);
3551:   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");
3552:   if (!A->rmap->N && !A->cmap->N) return(0);
3553:   if (!A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
3554:   MatCheckPreallocated(A,1);

3556:   if (!A->ops->mattransposesolve) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Mat type %s",((PetscObject)A)->type_name);
3557:   PetscLogEventBegin(MAT_MatTrSolve,A,Bt,X,0);
3558:   (*A->ops->mattransposesolve)(A,Bt,X);
3559:   PetscLogEventEnd(MAT_MatTrSolve,A,Bt,X,0);
3560:   PetscObjectStateIncrease((PetscObject)X);
3561:   return(0);
3562: }

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

3568:    Neighbor-wise Collective on Mat

3570:    Input Parameters:
3571: +  mat - the factored matrix
3572: -  b - the right-hand-side vector

3574:    Output Parameter:
3575: .  x - the result vector

3577:    Notes:
3578:    MatSolve() should be used for most applications, as it performs
3579:    a forward solve followed by a backward solve.

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

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

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

3594:    Level: developer

3596: .seealso: MatSolve(), MatBackwardSolve()
3597: @*/
3598: PetscErrorCode MatForwardSolve(Mat mat,Vec b,Vec x)
3599: {

3609:   if (x == b) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"x and b must be different vectors");
3610:   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);
3611:   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);
3612:   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);
3613:   if (!mat->rmap->N && !mat->cmap->N) return(0);
3614:   MatCheckPreallocated(mat,1);

3616:   if (!mat->ops->forwardsolve) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
3617:   PetscLogEventBegin(MAT_ForwardSolve,mat,b,x,0);
3618:   (*mat->ops->forwardsolve)(mat,b,x);
3619:   PetscLogEventEnd(MAT_ForwardSolve,mat,b,x,0);
3620:   PetscObjectStateIncrease((PetscObject)x);
3621:   return(0);
3622: }

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

3628:    Neighbor-wise Collective on Mat

3630:    Input Parameters:
3631: +  mat - the factored matrix
3632: -  b - the right-hand-side vector

3634:    Output Parameter:
3635: .  x - the result vector

3637:    Notes:
3638:    MatSolve() should be used for most applications, as it performs
3639:    a forward solve followed by a backward solve.

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

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

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

3654:    Level: developer

3656: .seealso: MatSolve(), MatForwardSolve()
3657: @*/
3658: PetscErrorCode MatBackwardSolve(Mat mat,Vec b,Vec x)
3659: {

3669:   if (x == b) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"x and b must be different vectors");
3670:   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);
3671:   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);
3672:   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);
3673:   if (!mat->rmap->N && !mat->cmap->N) return(0);
3674:   MatCheckPreallocated(mat,1);

3676:   if (!mat->ops->backwardsolve) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
3677:   PetscLogEventBegin(MAT_BackwardSolve,mat,b,x,0);
3678:   (*mat->ops->backwardsolve)(mat,b,x);
3679:   PetscLogEventEnd(MAT_BackwardSolve,mat,b,x,0);
3680:   PetscObjectStateIncrease((PetscObject)x);
3681:   return(0);
3682: }

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

3687:    Neighbor-wise Collective on Mat

3689:    Input Parameters:
3690: +  mat - the factored matrix
3691: .  b - the right-hand-side vector
3692: -  y - the vector to be added to

3694:    Output Parameter:
3695: .  x - the result vector

3697:    Notes:
3698:    The vectors b and x cannot be the same.  I.e., one cannot
3699:    call MatSolveAdd(A,x,y,x).

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

3705:    Level: developer

3707: .seealso: MatSolve(), MatSolveTranspose(), MatSolveTransposeAdd()
3708: @*/
3709: PetscErrorCode MatSolveAdd(Mat mat,Vec b,Vec y,Vec x)
3710: {
3711:   PetscScalar    one = 1.0;
3712:   Vec            tmp;

3724:   if (x == b) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"x and b must be different vectors");
3725:   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);
3726:   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);
3727:   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);
3728:   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);
3729:   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);
3730:   if (!mat->rmap->N && !mat->cmap->N) return(0);
3731:    MatCheckPreallocated(mat,1);

3733:   PetscLogEventBegin(MAT_SolveAdd,mat,b,x,y);
3734:   if (mat->factorerrortype) {
3735:     PetscInfo1(mat,"MatFactorError %D\n",mat->factorerrortype);
3736:     VecSetInf(x);
3737:   } else if (mat->ops->solveadd) {
3738:     (*mat->ops->solveadd)(mat,b,y,x);
3739:   } else {
3740:     /* do the solve then the add manually */
3741:     if (x != y) {
3742:       MatSolve(mat,b,x);
3743:       VecAXPY(x,one,y);
3744:     } else {
3745:       VecDuplicate(x,&tmp);
3746:       PetscLogObjectParent((PetscObject)mat,(PetscObject)tmp);
3747:       VecCopy(x,tmp);
3748:       MatSolve(mat,b,x);
3749:       VecAXPY(x,one,tmp);
3750:       VecDestroy(&tmp);
3751:     }
3752:   }
3753:   PetscLogEventEnd(MAT_SolveAdd,mat,b,x,y);
3754:   PetscObjectStateIncrease((PetscObject)x);
3755:   return(0);
3756: }

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

3761:    Neighbor-wise Collective on Mat

3763:    Input Parameters:
3764: +  mat - the factored matrix
3765: -  b - the right-hand-side vector

3767:    Output Parameter:
3768: .  x - the result vector

3770:    Notes:
3771:    The vectors b and x cannot be the same.  I.e., one cannot
3772:    call MatSolveTranspose(A,x,x).

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

3778:    Level: developer

3780: .seealso: MatSolve(), MatSolveAdd(), MatSolveTransposeAdd()
3781: @*/
3782: PetscErrorCode MatSolveTranspose(Mat mat,Vec b,Vec x)
3783: {

3793:   if (x == b) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"x and b must be different vectors");
3794:   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);
3795:   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);
3796:   if (!mat->rmap->N && !mat->cmap->N) return(0);
3797:   MatCheckPreallocated(mat,1);
3798:   PetscLogEventBegin(MAT_SolveTranspose,mat,b,x,0);
3799:   if (mat->factorerrortype) {
3800:     PetscInfo1(mat,"MatFactorError %D\n",mat->factorerrortype);
3801:     VecSetInf(x);
3802:   } else {
3803:     if (!mat->ops->solvetranspose) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Matrix type %s",((PetscObject)mat)->type_name);
3804:     (*mat->ops->solvetranspose)(mat,b,x);
3805:   }
3806:   PetscLogEventEnd(MAT_SolveTranspose,mat,b,x,0);
3807:   PetscObjectStateIncrease((PetscObject)x);
3808:   return(0);
3809: }

3811: /*@
3812:    MatSolveTransposeAdd - Computes x = y + inv(Transpose(A)) b, given a
3813:                       factored matrix.

3815:    Neighbor-wise Collective on Mat

3817:    Input Parameters:
3818: +  mat - the factored matrix
3819: .  b - the right-hand-side vector
3820: -  y - the vector to be added to

3822:    Output Parameter:
3823: .  x - the result vector

3825:    Notes:
3826:    The vectors b and x cannot be the same.  I.e., one cannot
3827:    call MatSolveTransposeAdd(A,x,y,x).

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

3833:    Level: developer

3835: .seealso: MatSolve(), MatSolveAdd(), MatSolveTranspose()
3836: @*/
3837: PetscErrorCode MatSolveTransposeAdd(Mat mat,Vec b,Vec y,Vec x)
3838: {
3839:   PetscScalar    one = 1.0;
3841:   Vec            tmp;

3852:   if (x == b) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"x and b must be different vectors");
3853:   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);
3854:   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);
3855:   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);
3856:   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);
3857:   if (!mat->rmap->N && !mat->cmap->N) return(0);
3858:    MatCheckPreallocated(mat,1);

3860:   PetscLogEventBegin(MAT_SolveTransposeAdd,mat,b,x,y);
3861:   if (mat->factorerrortype) {
3862:     PetscInfo1(mat,"MatFactorError %D\n",mat->factorerrortype);
3863:     VecSetInf(x);
3864:   } else if (mat->ops->solvetransposeadd){
3865:     (*mat->ops->solvetransposeadd)(mat,b,y,x);
3866:   } else {
3867:     /* do the solve then the add manually */
3868:     if (x != y) {
3869:       MatSolveTranspose(mat,b,x);
3870:       VecAXPY(x,one,y);
3871:     } else {
3872:       VecDuplicate(x,&tmp);
3873:       PetscLogObjectParent((PetscObject)mat,(PetscObject)tmp);
3874:       VecCopy(x,tmp);
3875:       MatSolveTranspose(mat,b,x);
3876:       VecAXPY(x,one,tmp);
3877:       VecDestroy(&tmp);
3878:     }
3879:   }
3880:   PetscLogEventEnd(MAT_SolveTransposeAdd,mat,b,x,y);
3881:   PetscObjectStateIncrease((PetscObject)x);
3882:   return(0);
3883: }
3884: /* ----------------------------------------------------------------*/

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

3889:    Neighbor-wise Collective on Mat

3891:    Input Parameters:
3892: +  mat - the matrix
3893: .  b - the right hand side
3894: .  omega - the relaxation factor
3895: .  flag - flag indicating the type of SOR (see below)
3896: .  shift -  diagonal shift
3897: .  its - the number of iterations
3898: -  lits - the number of local iterations

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

3903:    SOR Flags:
3904: +     SOR_FORWARD_SWEEP - forward SOR
3905: .     SOR_BACKWARD_SWEEP - backward SOR
3906: .     SOR_SYMMETRIC_SWEEP - SSOR (symmetric SOR)
3907: .     SOR_LOCAL_FORWARD_SWEEP - local forward SOR
3908: .     SOR_LOCAL_BACKWARD_SWEEP - local forward SOR
3909: .     SOR_LOCAL_SYMMETRIC_SWEEP - local SSOR
3910: .     SOR_APPLY_UPPER, SOR_APPLY_LOWER - applies
3911:          upper/lower triangular part of matrix to
3912:          vector (with omega)
3913: -     SOR_ZERO_INITIAL_GUESS - zero initial guess

3915:    Notes:
3916:    SOR_LOCAL_FORWARD_SWEEP, SOR_LOCAL_BACKWARD_SWEEP, and
3917:    SOR_LOCAL_SYMMETRIC_SWEEP perform separate independent smoothings
3918:    on each processor.

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

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

3926:    Notes for Advanced Users:
3927:    The flags are implemented as bitwise inclusive or operations.
3928:    For example, use (SOR_ZERO_INITIAL_GUESS | SOR_SYMMETRIC_SWEEP)
3929:    to specify a zero initial guess for SSOR.

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

3935:    Vectors x and b CANNOT be the same

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

3939:    Level: developer

3941: @*/
3942: PetscErrorCode MatSOR(Mat mat,Vec b,PetscReal omega,MatSORType flag,PetscReal shift,PetscInt its,PetscInt lits,Vec x)
3943: {

3953:   if (!mat->ops->sor) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
3954:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
3955:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
3956:   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);
3957:   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);
3958:   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);
3959:   if (its <= 0) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONG,"Relaxation requires global its %D positive",its);
3960:   if (lits <= 0) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONG,"Relaxation requires local its %D positive",lits);
3961:   if (b == x) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_IDN,"b and x vector cannot be the same");

3963:   MatCheckPreallocated(mat,1);
3964:   PetscLogEventBegin(MAT_SOR,mat,b,x,0);
3965:   ierr =(*mat->ops->sor)(mat,b,omega,flag,shift,its,lits,x);
3966:   PetscLogEventEnd(MAT_SOR,mat,b,x,0);
3967:   PetscObjectStateIncrease((PetscObject)x);
3968:   return(0);
3969: }

3971: /*
3972:       Default matrix copy routine.
3973: */
3974: PetscErrorCode MatCopy_Basic(Mat A,Mat B,MatStructure str)
3975: {
3976:   PetscErrorCode    ierr;
3977:   PetscInt          i,rstart = 0,rend = 0,nz;
3978:   const PetscInt    *cwork;
3979:   const PetscScalar *vwork;

3982:   if (B->assembled) {
3983:     MatZeroEntries(B);
3984:   }
3985:   if (str == SAME_NONZERO_PATTERN) {
3986:     MatGetOwnershipRange(A,&rstart,&rend);
3987:     for (i=rstart; i<rend; i++) {
3988:       MatGetRow(A,i,&nz,&cwork,&vwork);
3989:       MatSetValues(B,1,&i,nz,cwork,vwork,INSERT_VALUES);
3990:       MatRestoreRow(A,i,&nz,&cwork,&vwork);
3991:     }
3992:   } else {
3993:     MatAYPX(B,0.0,A,str);
3994:   }
3995:   MatAssemblyBegin(B,MAT_FINAL_ASSEMBLY);
3996:   MatAssemblyEnd(B,MAT_FINAL_ASSEMBLY);
3997:   return(0);
3998: }

4000: /*@
4001:    MatCopy - Copies a matrix to another matrix.

4003:    Collective on Mat

4005:    Input Parameters:
4006: +  A - the matrix
4007: -  str - SAME_NONZERO_PATTERN or DIFFERENT_NONZERO_PATTERN

4009:    Output Parameter:
4010: .  B - where the copy is put

4012:    Notes:
4013:    If you use SAME_NONZERO_PATTERN then the two matrices had better have the
4014:    same nonzero pattern or the routine will crash.

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

4020:    Level: intermediate

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

4024: @*/
4025: PetscErrorCode MatCopy(Mat A,Mat B,MatStructure str)
4026: {
4028:   PetscInt       i;

4036:   MatCheckPreallocated(B,2);
4037:   if (!A->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
4038:   if (A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
4039:   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);
4040:   MatCheckPreallocated(A,1);
4041:   if (A == B) return(0);

4043:   PetscLogEventBegin(MAT_Copy,A,B,0,0);
4044:   if (A->ops->copy) {
4045:     (*A->ops->copy)(A,B,str);
4046:   } else { /* generic conversion */
4047:     MatCopy_Basic(A,B,str);
4048:   }

4050:   B->stencil.dim = A->stencil.dim;
4051:   B->stencil.noc = A->stencil.noc;
4052:   for (i=0; i<=A->stencil.dim; i++) {
4053:     B->stencil.dims[i]   = A->stencil.dims[i];
4054:     B->stencil.starts[i] = A->stencil.starts[i];
4055:   }

4057:   PetscLogEventEnd(MAT_Copy,A,B,0,0);
4058:   PetscObjectStateIncrease((PetscObject)B);
4059:   return(0);
4060: }

4062: /*@C
4063:    MatConvert - Converts a matrix to another matrix, either of the same
4064:    or different type.

4066:    Collective on Mat

4068:    Input Parameters:
4069: +  mat - the matrix
4070: .  newtype - new matrix type.  Use MATSAME to create a new matrix of the
4071:    same type as the original matrix.
4072: -  reuse - denotes if the destination matrix is to be created or reused.
4073:    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
4074:    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).

4076:    Output Parameter:
4077: .  M - pointer to place new matrix

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

4084:    Cannot be used to convert a sequential matrix to parallel or parallel to sequential,
4085:    the MPI communicator of the generated matrix is always the same as the communicator
4086:    of the input matrix.

4088:    Level: intermediate

4090: .seealso: MatCopy(), MatDuplicate()
4091: @*/
4092: PetscErrorCode MatConvert(Mat mat, MatType newtype,MatReuse reuse,Mat *M)
4093: {
4095:   PetscBool      sametype,issame,flg,issymmetric,ishermitian;
4096:   char           convname[256],mtype[256];
4097:   Mat            B;

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

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

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

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

4120:   /* Cache Mat options because some converter use MatHeaderReplace  */
4121:   issymmetric = mat->symmetric;
4122:   ishermitian = mat->hermitian;

4124:   if ((sametype || issame) && (reuse==MAT_INITIAL_MATRIX) && mat->ops->duplicate) {
4125:     PetscInfo3(mat,"Calling duplicate for initial matrix %s %d %d\n",((PetscObject)mat)->type_name,sametype,issame);
4126:     (*mat->ops->duplicate)(mat,MAT_COPY_VALUES,M);
4127:   } else {
4128:     PetscErrorCode (*conv)(Mat, MatType,MatReuse,Mat*)=NULL;
4129:     const char     *prefix[3] = {"seq","mpi",""};
4130:     PetscInt       i;
4131:     /*
4132:        Order of precedence:
4133:        0) See if newtype is a superclass of the current matrix.
4134:        1) See if a specialized converter is known to the current matrix.
4135:        2) See if a specialized converter is known to the desired matrix class.
4136:        3) See if a good general converter is registered for the desired class
4137:           (as of 6/27/03 only MATMPIADJ falls into this category).
4138:        4) See if a good general converter is known for the current matrix.
4139:        5) Use a really basic converter.
4140:     */

4142:     /* 0) See if newtype is a superclass of the current matrix.
4143:           i.e mat is mpiaij and newtype is aij */
4144:     for (i=0; i<2; i++) {
4145:       PetscStrncpy(convname,prefix[i],sizeof(convname));
4146:       PetscStrlcat(convname,newtype,sizeof(convname));
4147:       PetscStrcmp(convname,((PetscObject)mat)->type_name,&flg);
4148:       PetscInfo3(mat,"Check superclass %s %s -> %d\n",convname,((PetscObject)mat)->type_name,flg);
4149:       if (flg) {
4150:         if (reuse == MAT_INPLACE_MATRIX) {
4151:           PetscInfo(mat,"Early return\n");
4152:           return(0);
4153:         } else if (reuse == MAT_INITIAL_MATRIX && mat->ops->duplicate) {
4154:           PetscInfo(mat,"Calling MatDuplicate\n");
4155:           (*mat->ops->duplicate)(mat,MAT_COPY_VALUES,M);
4156:           return(0);
4157:         } else if (reuse == MAT_REUSE_MATRIX && mat->ops->copy) {
4158:           PetscInfo(mat,"Calling MatCopy\n");
4159:           MatCopy(mat,*M,SAME_NONZERO_PATTERN);
4160:           return(0);
4161:         }
4162:       }
4163:     }
4164:     /* 1) See if a specialized converter is known to the current matrix and the desired class */
4165:     for (i=0; i<3; i++) {
4166:       PetscStrncpy(convname,"MatConvert_",sizeof(convname));
4167:       PetscStrlcat(convname,((PetscObject)mat)->type_name,sizeof(convname));
4168:       PetscStrlcat(convname,"_",sizeof(convname));
4169:       PetscStrlcat(convname,prefix[i],sizeof(convname));
4170:       PetscStrlcat(convname,issame ? ((PetscObject)mat)->type_name : newtype,sizeof(convname));
4171:       PetscStrlcat(convname,"_C",sizeof(convname));
4172:       PetscObjectQueryFunction((PetscObject)mat,convname,&conv);
4173:       PetscInfo3(mat,"Check specialized (1) %s (%s) -> %d\n",convname,((PetscObject)mat)->type_name,!!conv);
4174:       if (conv) goto foundconv;
4175:     }

4177:     /* 2)  See if a specialized converter is known to the desired matrix class. */
4178:     MatCreate(PetscObjectComm((PetscObject)mat),&B);
4179:     MatSetSizes(B,mat->rmap->n,mat->cmap->n,mat->rmap->N,mat->cmap->N);
4180:     MatSetType(B,newtype);
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,newtype,sizeof(convname));
4187:       PetscStrlcat(convname,"_C",sizeof(convname));
4188:       PetscObjectQueryFunction((PetscObject)B,convname,&conv);
4189:       PetscInfo3(mat,"Check specialized (2) %s (%s) -> %d\n",convname,((PetscObject)B)->type_name,!!conv);
4190:       if (conv) {
4191:         MatDestroy(&B);
4192:         goto foundconv;
4193:       }
4194:     }

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

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

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

4208:     /* 5) Use a really basic converter. */
4209:     PetscInfo(mat,"Using MatConvert_Basic\n");
4210:     conv = MatConvert_Basic;

4212: foundconv:
4213:     PetscLogEventBegin(MAT_Convert,mat,0,0,0);
4214:     (*conv)(mat,newtype,reuse,M);
4215:     if (mat->rmap->mapping && mat->cmap->mapping && !(*M)->rmap->mapping && !(*M)->cmap->mapping) {
4216:       /* the block sizes must be same if the mappings are copied over */
4217:       (*M)->rmap->bs = mat->rmap->bs;
4218:       (*M)->cmap->bs = mat->cmap->bs;
4219:       PetscObjectReference((PetscObject)mat->rmap->mapping);
4220:       PetscObjectReference((PetscObject)mat->cmap->mapping);
4221:       (*M)->rmap->mapping = mat->rmap->mapping;
4222:       (*M)->cmap->mapping = mat->cmap->mapping;
4223:     }
4224:     (*M)->stencil.dim = mat->stencil.dim;
4225:     (*M)->stencil.noc = mat->stencil.noc;
4226:     for (i=0; i<=mat->stencil.dim; i++) {
4227:       (*M)->stencil.dims[i]   = mat->stencil.dims[i];
4228:       (*M)->stencil.starts[i] = mat->stencil.starts[i];
4229:     }
4230:     PetscLogEventEnd(MAT_Convert,mat,0,0,0);
4231:   }
4232:   PetscObjectStateIncrease((PetscObject)*M);

4234:   /* Copy Mat options */
4235:   if (issymmetric) {
4236:     MatSetOption(*M,MAT_SYMMETRIC,PETSC_TRUE);
4237:   }
4238:   if (ishermitian) {
4239:     MatSetOption(*M,MAT_HERMITIAN,PETSC_TRUE);
4240:   }
4241:   return(0);
4242: }

4244: /*@C
4245:    MatFactorGetSolverType - Returns name of the package providing the factorization routines

4247:    Not Collective

4249:    Input Parameter:
4250: .  mat - the matrix, must be a factored matrix

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

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

4259:    Level: intermediate

4261: .seealso: MatCopy(), MatDuplicate(), MatGetFactorAvailable(), MatGetFactor()
4262: @*/
4263: PetscErrorCode MatFactorGetSolverType(Mat mat, MatSolverType *type)
4264: {
4265:   PetscErrorCode ierr, (*conv)(Mat,MatSolverType*);

4270:   if (!mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Only for factored matrix");
4271:   PetscObjectQueryFunction((PetscObject)mat,"MatFactorGetSolverType_C",&conv);
4272:   if (!conv) {
4273:     *type = MATSOLVERPETSC;
4274:   } else {
4275:     (*conv)(mat,type);
4276:   }
4277:   return(0);
4278: }

4280: typedef struct _MatSolverTypeForSpecifcType* MatSolverTypeForSpecifcType;
4281: struct _MatSolverTypeForSpecifcType {
4282:   MatType                        mtype;
4283:   PetscErrorCode                 (*getfactor[4])(Mat,MatFactorType,Mat*);
4284:   MatSolverTypeForSpecifcType next;
4285: };

4287: typedef struct _MatSolverTypeHolder* MatSolverTypeHolder;
4288: struct _MatSolverTypeHolder {
4289:   char                           *name;
4290:   MatSolverTypeForSpecifcType handlers;
4291:   MatSolverTypeHolder         next;
4292: };

4294: static MatSolverTypeHolder MatSolverTypeHolders = NULL;

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

4299:    Input Parameters:
4300: +    package - name of the package, for example petsc or superlu
4301: .    mtype - the matrix type that works with this package
4302: .    ftype - the type of factorization supported by the package
4303: -    getfactor - routine that will create the factored matrix ready to be used

4305:     Level: intermediate

4307: .seealso: MatCopy(), MatDuplicate(), MatGetFactorAvailable()
4308: @*/
4309: PetscErrorCode MatSolverTypeRegister(MatSolverType package,MatType mtype,MatFactorType ftype,PetscErrorCode (*getfactor)(Mat,MatFactorType,Mat*))
4310: {
4311:   PetscErrorCode              ierr;
4312:   MatSolverTypeHolder         next = MatSolverTypeHolders,prev = NULL;
4313:   PetscBool                   flg;
4314:   MatSolverTypeForSpecifcType inext,iprev = NULL;

4317:   MatInitializePackage();
4318:   if (!next) {
4319:     PetscNew(&MatSolverTypeHolders);
4320:     PetscStrallocpy(package,&MatSolverTypeHolders->name);
4321:     PetscNew(&MatSolverTypeHolders->handlers);
4322:     PetscStrallocpy(mtype,(char **)&MatSolverTypeHolders->handlers->mtype);
4323:     MatSolverTypeHolders->handlers->getfactor[(int)ftype-1] = getfactor;
4324:     return(0);
4325:   }
4326:   while (next) {
4327:     PetscStrcasecmp(package,next->name,&flg);
4328:     if (flg) {
4329:       if (!next->handlers) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_PLIB,"MatSolverTypeHolder is missing handlers");
4330:       inext = next->handlers;
4331:       while (inext) {
4332:         PetscStrcasecmp(mtype,inext->mtype,&flg);
4333:         if (flg) {
4334:           inext->getfactor[(int)ftype-1] = getfactor;
4335:           return(0);
4336:         }
4337:         iprev = inext;
4338:         inext = inext->next;
4339:       }
4340:       PetscNew(&iprev->next);
4341:       PetscStrallocpy(mtype,(char **)&iprev->next->mtype);
4342:       iprev->next->getfactor[(int)ftype-1] = getfactor;
4343:       return(0);
4344:     }
4345:     prev = next;
4346:     next = next->next;
4347:   }
4348:   PetscNew(&prev->next);
4349:   PetscStrallocpy(package,&prev->next->name);
4350:   PetscNew(&prev->next->handlers);
4351:   PetscStrallocpy(mtype,(char **)&prev->next->handlers->mtype);
4352:   prev->next->handlers->getfactor[(int)ftype-1] = getfactor;
4353:   return(0);
4354: }

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

4359:    Input Parameters:
4360: +    package - name of the package, for example petsc or superlu
4361: .    ftype - the type of factorization supported by the package
4362: -    mtype - the matrix type that works with this package

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

4369:     Level: intermediate

4371: .seealso: MatCopy(), MatDuplicate(), MatGetFactorAvailable()
4372: @*/
4373: PetscErrorCode MatSolverTypeGet(MatSolverType package,MatType mtype,MatFactorType ftype,PetscBool *foundpackage,PetscBool *foundmtype,PetscErrorCode (**getfactor)(Mat,MatFactorType,Mat*))
4374: {
4375:   PetscErrorCode              ierr;
4376:   MatSolverTypeHolder         next = MatSolverTypeHolders;
4377:   PetscBool                   flg;
4378:   MatSolverTypeForSpecifcType inext;

4381:   if (foundpackage) *foundpackage = PETSC_FALSE;
4382:   if (foundmtype)   *foundmtype   = PETSC_FALSE;
4383:   if (getfactor)    *getfactor    = NULL;

4385:   if (package) {
4386:     while (next) {
4387:       PetscStrcasecmp(package,next->name,&flg);
4388:       if (flg) {
4389:         if (foundpackage) *foundpackage = PETSC_TRUE;
4390:         inext = next->handlers;
4391:         while (inext) {
4392:           PetscStrbeginswith(mtype,inext->mtype,&flg);
4393:           if (flg) {
4394:             if (foundmtype) *foundmtype = PETSC_TRUE;
4395:             if (getfactor)  *getfactor  = inext->getfactor[(int)ftype-1];
4396:             return(0);
4397:           }
4398:           inext = inext->next;
4399:         }
4400:       }
4401:       next = next->next;
4402:     }
4403:   } else {
4404:     while (next) {
4405:       inext = next->handlers;
4406:       while (inext) {
4407:         PetscStrbeginswith(mtype,inext->mtype,&flg);
4408:         if (flg && inext->getfactor[(int)ftype-1]) {
4409:           if (foundpackage) *foundpackage = PETSC_TRUE;
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:       next = next->next;
4417:     }
4418:   }
4419:   return(0);
4420: }

4422: PetscErrorCode MatSolverTypeDestroy(void)
4423: {
4424:   PetscErrorCode              ierr;
4425:   MatSolverTypeHolder         next = MatSolverTypeHolders,prev;
4426:   MatSolverTypeForSpecifcType inext,iprev;

4429:   while (next) {
4430:     PetscFree(next->name);
4431:     inext = next->handlers;
4432:     while (inext) {
4433:       PetscFree(inext->mtype);
4434:       iprev = inext;
4435:       inext = inext->next;
4436:       PetscFree(iprev);
4437:     }
4438:     prev = next;
4439:     next = next->next;
4440:     PetscFree(prev);
4441:   }
4442:   MatSolverTypeHolders = NULL;
4443:   return(0);
4444: }

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

4449:    Collective on Mat

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

4456:    Output Parameters:
4457: .  f - the factor matrix used with MatXXFactorSymbolic() calls

4459:    Notes:
4460:       Some PETSc matrix formats have alternative solvers available that are contained in alternative packages
4461:      such as pastix, superlu, mumps etc.

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

4465:    Level: intermediate

4467: .seealso: MatCopy(), MatDuplicate(), MatGetFactorAvailable()
4468: @*/
4469: PetscErrorCode MatGetFactor(Mat mat, MatSolverType type,MatFactorType ftype,Mat *f)
4470: {
4471:   PetscErrorCode ierr,(*conv)(Mat,MatFactorType,Mat*);
4472:   PetscBool      foundpackage,foundmtype;


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

4481:   MatSolverTypeGet(type,((PetscObject)mat)->type_name,ftype,&foundpackage,&foundmtype,&conv);
4482:   if (!foundpackage) {
4483:     if (type) {
4484:       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);
4485:     } else {
4486:       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);
4487:     }
4488:   }
4489:   if (!foundmtype) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_MISSING_FACTOR,"MatSolverType %s does not support matrix type %s",type,((PetscObject)mat)->type_name);
4490:   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);

4492:   (*conv)(mat,ftype,f);
4493:   return(0);
4494: }

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

4499:    Not Collective

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

4506:    Output Parameter:
4507: .    flg - PETSC_TRUE if the factorization is available

4509:    Notes:
4510:       Some PETSc matrix formats have alternative solvers available that are contained in alternative packages
4511:      such as pastix, superlu, mumps etc.

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

4515:    Level: intermediate

4517: .seealso: MatCopy(), MatDuplicate(), MatGetFactor()
4518: @*/
4519: PetscErrorCode MatGetFactorAvailable(Mat mat, MatSolverType type,MatFactorType ftype,PetscBool  *flg)
4520: {
4521:   PetscErrorCode ierr, (*gconv)(Mat,MatFactorType,Mat*);


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

4530:   *flg = PETSC_FALSE;
4531:   MatSolverTypeGet(type,((PetscObject)mat)->type_name,ftype,NULL,NULL,&gconv);
4532:   if (gconv) {
4533:     *flg = PETSC_TRUE;
4534:   }
4535:   return(0);
4536: }

4538:  #include <petscdmtypes.h>

4540: /*@
4541:    MatDuplicate - Duplicates a matrix including the non-zero structure.

4543:    Collective on Mat

4545:    Input Parameters:
4546: +  mat - the matrix
4547: -  op - One of MAT_DO_NOT_COPY_VALUES, MAT_COPY_VALUES, or MAT_SHARE_NONZERO_PATTERN.
4548:         See the manual page for MatDuplicateOption for an explanation of these options.

4550:    Output Parameter:
4551: .  M - pointer to place new matrix

4553:    Level: intermediate

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

4559: .seealso: MatCopy(), MatConvert(), MatDuplicateOption
4560: @*/
4561: PetscErrorCode MatDuplicate(Mat mat,MatDuplicateOption op,Mat *M)
4562: {
4564:   Mat            B;
4565:   PetscInt       i;
4566:   DM             dm;
4567:   void           (*viewf)(void);

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

4577:   *M = 0;
4578:   if (!mat->ops->duplicate) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Not written for matrix type %s\n",((PetscObject)mat)->type_name);
4579:   PetscLogEventBegin(MAT_Convert,mat,0,0,0);
4580:   (*mat->ops->duplicate)(mat,op,M);
4581:   B    = *M;

4583:   MatGetOperation(mat,MATOP_VIEW,&viewf);
4584:   if (viewf) {
4585:     MatSetOperation(B,MATOP_VIEW,viewf);
4586:   }

4588:   B->stencil.dim = mat->stencil.dim;
4589:   B->stencil.noc = mat->stencil.noc;
4590:   for (i=0; i<=mat->stencil.dim; i++) {
4591:     B->stencil.dims[i]   = mat->stencil.dims[i];
4592:     B->stencil.starts[i] = mat->stencil.starts[i];
4593:   }

4595:   B->nooffproczerorows = mat->nooffproczerorows;
4596:   B->nooffprocentries  = mat->nooffprocentries;

4598:   PetscObjectQuery((PetscObject) mat, "__PETSc_dm", (PetscObject*) &dm);
4599:   if (dm) {
4600:     PetscObjectCompose((PetscObject) B, "__PETSc_dm", (PetscObject) dm);
4601:   }
4602:   PetscLogEventEnd(MAT_Convert,mat,0,0,0);
4603:   PetscObjectStateIncrease((PetscObject)B);
4604:   return(0);
4605: }

4607: /*@
4608:    MatGetDiagonal - Gets the diagonal of a matrix.

4610:    Logically Collective on Mat

4612:    Input Parameters:
4613: +  mat - the matrix
4614: -  v - the vector for storing the diagonal

4616:    Output Parameter:
4617: .  v - the diagonal of the matrix

4619:    Level: intermediate

4621:    Note:
4622:    Currently only correct in parallel for square matrices.

4624: .seealso: MatGetRow(), MatCreateSubMatrices(), MatCreateSubMatrix(), MatGetRowMaxAbs()
4625: @*/
4626: PetscErrorCode MatGetDiagonal(Mat mat,Vec v)
4627: {

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

4638:   (*mat->ops->getdiagonal)(mat,v);
4639:   PetscObjectStateIncrease((PetscObject)v);
4640:   return(0);
4641: }

4643: /*@C
4644:    MatGetRowMin - Gets the minimum value (of the real part) of each
4645:         row of the matrix

4647:    Logically Collective on Mat

4649:    Input Parameters:
4650: .  mat - the matrix

4652:    Output Parameter:
4653: +  v - the vector for storing the maximums
4654: -  idx - the indices of the column found for each row (optional)

4656:    Level: intermediate

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

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

4664: .seealso: MatGetDiagonal(), MatCreateSubMatrices(), MatCreateSubMatrix(), MatGetRowMaxAbs(),
4665:           MatGetRowMax()
4666: @*/
4667: PetscErrorCode MatGetRowMin(Mat mat,Vec v,PetscInt idx[])
4668: {

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

4679:   (*mat->ops->getrowmin)(mat,v,idx);
4680:   PetscObjectStateIncrease((PetscObject)v);
4681:   return(0);
4682: }

4684: /*@C
4685:    MatGetRowMinAbs - Gets the minimum value (in absolute value) of each
4686:         row of the matrix

4688:    Logically Collective on Mat

4690:    Input Parameters:
4691: .  mat - the matrix

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

4697:    Level: intermediate

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

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

4705: .seealso: MatGetDiagonal(), MatCreateSubMatrices(), MatCreateSubMatrix(), MatGetRowMax(), MatGetRowMaxAbs(), MatGetRowMin()
4706: @*/
4707: PetscErrorCode MatGetRowMinAbs(Mat mat,Vec v,PetscInt idx[])
4708: {

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

4720:   (*mat->ops->getrowminabs)(mat,v,idx);
4721:   PetscObjectStateIncrease((PetscObject)v);
4722:   return(0);
4723: }

4725: /*@C
4726:    MatGetRowMax - Gets the maximum value (of the real part) of each
4727:         row of the matrix

4729:    Logically Collective on Mat

4731:    Input Parameters:
4732: .  mat - the matrix

4734:    Output Parameter:
4735: +  v - the vector for storing the maximums
4736: -  idx - the indices of the column found for each row (optional)

4738:    Level: intermediate

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

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

4746: .seealso: MatGetDiagonal(), MatCreateSubMatrices(), MatCreateSubMatrix(), MatGetRowMaxAbs(), MatGetRowMin()
4747: @*/
4748: PetscErrorCode MatGetRowMax(Mat mat,Vec v,PetscInt idx[])
4749: {

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

4760:   (*mat->ops->getrowmax)(mat,v,idx);
4761:   PetscObjectStateIncrease((PetscObject)v);
4762:   return(0);
4763: }

4765: /*@C
4766:    MatGetRowMaxAbs - Gets the maximum value (in absolute value) of each
4767:         row of the matrix

4769:    Logically Collective on Mat

4771:    Input Parameters:
4772: .  mat - the matrix

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

4778:    Level: intermediate

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

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

4786: .seealso: MatGetDiagonal(), MatCreateSubMatrices(), MatCreateSubMatrix(), MatGetRowMax(), MatGetRowMin()
4787: @*/
4788: PetscErrorCode MatGetRowMaxAbs(Mat mat,Vec v,PetscInt idx[])
4789: {

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

4801:   (*mat->ops->getrowmaxabs)(mat,v,idx);
4802:   PetscObjectStateIncrease((PetscObject)v);
4803:   return(0);
4804: }

4806: /*@
4807:    MatGetRowSum - Gets the sum of each row of the matrix

4809:    Logically or Neighborhood Collective on Mat

4811:    Input Parameters:
4812: .  mat - the matrix

4814:    Output Parameter:
4815: .  v - the vector for storing the sum of rows

4817:    Level: intermediate

4819:    Notes:
4820:     This code is slow since it is not currently specialized for different formats

4822: .seealso: MatGetDiagonal(), MatCreateSubMatrices(), MatCreateSubMatrix(), MatGetRowMax(), MatGetRowMin()
4823: @*/
4824: PetscErrorCode MatGetRowSum(Mat mat, Vec v)
4825: {
4826:   Vec            ones;

4833:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
4834:   MatCheckPreallocated(mat,1);
4835:   MatCreateVecs(mat,&ones,NULL);
4836:   VecSet(ones,1.);
4837:   MatMult(mat,ones,v);
4838:   VecDestroy(&ones);
4839:   return(0);
4840: }

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

4845:    Collective on Mat

4847:    Input Parameter:
4848: +  mat - the matrix to transpose
4849: -  reuse - either MAT_INITIAL_MATRIX, MAT_REUSE_MATRIX, or MAT_INPLACE_MATRIX

4851:    Output Parameters:
4852: .  B - the transpose

4854:    Notes:
4855:      If you use MAT_INPLACE_MATRIX then you must pass in &mat for B

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

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

4861:    Level: intermediate

4863: .seealso: MatMultTranspose(), MatMultTransposeAdd(), MatIsTranspose(), MatReuse
4864: @*/
4865: PetscErrorCode MatTranspose(Mat mat,MatReuse reuse,Mat *B)
4866: {

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

4879:   PetscLogEventBegin(MAT_Transpose,mat,0,0,0);
4880:   (*mat->ops->transpose)(mat,reuse,B);
4881:   PetscLogEventEnd(MAT_Transpose,mat,0,0,0);
4882:   if (B) {PetscObjectStateIncrease((PetscObject)*B);}
4883:   return(0);
4884: }

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

4890:    Collective on Mat

4892:    Input Parameter:
4893: +  A - the matrix to test
4894: -  B - the matrix to test against, this can equal the first parameter

4896:    Output Parameters:
4897: .  flg - the result

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

4904:    Level: intermediate

4906: .seealso: MatTranspose(), MatIsSymmetric(), MatIsHermitian()
4907: @*/
4908: PetscErrorCode MatIsTranspose(Mat A,Mat B,PetscReal tol,PetscBool  *flg)
4909: {
4910:   PetscErrorCode ierr,(*f)(Mat,Mat,PetscReal,PetscBool*),(*g)(Mat,Mat,PetscReal,PetscBool*);

4916:   PetscObjectQueryFunction((PetscObject)A,"MatIsTranspose_C",&f);
4917:   PetscObjectQueryFunction((PetscObject)B,"MatIsTranspose_C",&g);
4918:   *flg = PETSC_FALSE;
4919:   if (f && g) {
4920:     if (f == g) {
4921:       (*f)(A,B,tol,flg);
4922:     } else SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_NOTSAMETYPE,"Matrices do not have the same comparator for symmetry test");
4923:   } else {
4924:     MatType mattype;
4925:     if (!f) {
4926:       MatGetType(A,&mattype);
4927:     } else {
4928:       MatGetType(B,&mattype);
4929:     }
4930:     SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Matrix of type %s does not support checking for transpose",mattype);
4931:   }
4932:   return(0);
4933: }

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

4938:    Collective on Mat

4940:    Input Parameter:
4941: +  mat - the matrix to transpose and complex conjugate
4942: -  reuse - MAT_INITIAL_MATRIX to create a new matrix, MAT_INPLACE_MATRIX to reuse the first argument to store the transpose

4944:    Output Parameters:
4945: .  B - the Hermitian

4947:    Level: intermediate

4949: .seealso: MatTranspose(), MatMultTranspose(), MatMultTransposeAdd(), MatIsTranspose(), MatReuse
4950: @*/
4951: PetscErrorCode MatHermitianTranspose(Mat mat,MatReuse reuse,Mat *B)
4952: {

4956:   MatTranspose(mat,reuse,B);
4957: #if defined(PETSC_USE_COMPLEX)
4958:   MatConjugate(*B);
4959: #endif
4960:   return(0);
4961: }

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

4966:    Collective on Mat

4968:    Input Parameter:
4969: +  A - the matrix to test
4970: -  B - the matrix to test against, this can equal the first parameter

4972:    Output Parameters:
4973: .  flg - the result

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

4980:    Level: intermediate

4982: .seealso: MatTranspose(), MatIsSymmetric(), MatIsHermitian(), MatIsTranspose()
4983: @*/
4984: PetscErrorCode MatIsHermitianTranspose(Mat A,Mat B,PetscReal tol,PetscBool  *flg)
4985: {
4986:   PetscErrorCode ierr,(*f)(Mat,Mat,PetscReal,PetscBool*),(*g)(Mat,Mat,PetscReal,PetscBool*);

4992:   PetscObjectQueryFunction((PetscObject)A,"MatIsHermitianTranspose_C",&f);
4993:   PetscObjectQueryFunction((PetscObject)B,"MatIsHermitianTranspose_C",&g);
4994:   if (f && g) {
4995:     if (f==g) {
4996:       (*f)(A,B,tol,flg);
4997:     } else SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_NOTSAMETYPE,"Matrices do not have the same comparator for Hermitian test");
4998:   }
4999:   return(0);
5000: }

5002: /*@
5003:    MatPermute - Creates a new matrix with rows and columns permuted from the
5004:    original.

5006:    Collective on Mat

5008:    Input Parameters:
5009: +  mat - the matrix to permute
5010: .  row - row permutation, each processor supplies only the permutation for its rows
5011: -  col - column permutation, each processor supplies only the permutation for its columns

5013:    Output Parameters:
5014: .  B - the permuted matrix

5016:    Level: advanced

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

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

5024: @*/
5025: PetscErrorCode MatPermute(Mat mat,IS row,IS col,Mat *B)
5026: {

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

5040:   (*mat->ops->permute)(mat,row,col,B);
5041:   PetscObjectStateIncrease((PetscObject)*B);
5042:   return(0);
5043: }

5045: /*@
5046:    MatEqual - Compares two matrices.

5048:    Collective on Mat

5050:    Input Parameters:
5051: +  A - the first matrix
5052: -  B - the second matrix

5054:    Output Parameter:
5055: .  flg - PETSC_TRUE if the matrices are equal; PETSC_FALSE otherwise.

5057:    Level: intermediate

5059: @*/
5060: PetscErrorCode MatEqual(Mat A,Mat B,PetscBool  *flg)
5061: {

5071:   MatCheckPreallocated(B,2);
5072:   if (!A->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
5073:   if (!B->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
5074:   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);
5075:   if (!A->ops->equal) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Mat type %s",((PetscObject)A)->type_name);
5076:   if (!B->ops->equal) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Mat type %s",((PetscObject)B)->type_name);
5077:   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);
5078:   MatCheckPreallocated(A,1);

5080:   (*A->ops->equal)(A,B,flg);
5081:   return(0);
5082: }

5084: /*@
5085:    MatDiagonalScale - Scales a matrix on the left and right by diagonal
5086:    matrices that are stored as vectors.  Either of the two scaling
5087:    matrices can be NULL.

5089:    Collective on Mat

5091:    Input Parameters:
5092: +  mat - the matrix to be scaled
5093: .  l - the left scaling vector (or NULL)
5094: -  r - the right scaling vector (or NULL)

5096:    Notes:
5097:    MatDiagonalScale() computes A = LAR, where
5098:    L = a diagonal matrix (stored as a vector), R = a diagonal matrix (stored as a vector)
5099:    The L scales the rows of the matrix, the R scales the columns of the matrix.

5101:    Level: intermediate


5104: .seealso: MatScale(), MatShift(), MatDiagonalSet()
5105: @*/
5106: PetscErrorCode MatDiagonalScale(Mat mat,Vec l,Vec r)
5107: {

5115:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
5116:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
5117:   MatCheckPreallocated(mat,1);
5118:   if (!l && !r) return(0);

5120:   if (!mat->ops->diagonalscale) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
5121:   PetscLogEventBegin(MAT_Scale,mat,0,0,0);
5122:   (*mat->ops->diagonalscale)(mat,l,r);
5123:   PetscLogEventEnd(MAT_Scale,mat,0,0,0);
5124:   PetscObjectStateIncrease((PetscObject)mat);
5125:   return(0);
5126: }

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

5131:     Logically Collective on Mat

5133:     Input Parameters:
5134: +   mat - the matrix to be scaled
5135: -   a  - the scaling value

5137:     Output Parameter:
5138: .   mat - the scaled matrix

5140:     Level: intermediate

5142: .seealso: MatDiagonalScale()
5143: @*/
5144: PetscErrorCode MatScale(Mat mat,PetscScalar a)
5145: {

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

5157:   PetscLogEventBegin(MAT_Scale,mat,0,0,0);
5158:   if (a != (PetscScalar)1.0) {
5159:     (*mat->ops->scale)(mat,a);
5160:     PetscObjectStateIncrease((PetscObject)mat);
5161:   }
5162:   PetscLogEventEnd(MAT_Scale,mat,0,0,0);
5163:   return(0);
5164: }

5166: /*@
5167:    MatNorm - Calculates various norms of a matrix.

5169:    Collective on Mat

5171:    Input Parameters:
5172: +  mat - the matrix
5173: -  type - the type of norm, NORM_1, NORM_FROBENIUS, NORM_INFINITY

5175:    Output Parameters:
5176: .  nrm - the resulting norm

5178:    Level: intermediate

5180: @*/
5181: PetscErrorCode MatNorm(Mat mat,NormType type,PetscReal *nrm)
5182: {


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

5195:   (*mat->ops->norm)(mat,type,nrm);
5196:   return(0);
5197: }

5199: /*
5200:      This variable is used to prevent counting of MatAssemblyBegin() that
5201:    are called from within a MatAssemblyEnd().
5202: */
5203: static PetscInt MatAssemblyEnd_InUse = 0;
5204: /*@
5205:    MatAssemblyBegin - Begins assembling the matrix.  This routine should
5206:    be called after completing all calls to MatSetValues().

5208:    Collective on Mat

5210:    Input Parameters:
5211: +  mat - the matrix
5212: -  type - type of assembly, either MAT_FLUSH_ASSEMBLY or MAT_FINAL_ASSEMBLY

5214:    Notes:
5215:    MatSetValues() generally caches the values.  The matrix is ready to
5216:    use only after MatAssemblyBegin() and MatAssemblyEnd() have been called.
5217:    Use MAT_FLUSH_ASSEMBLY when switching between ADD_VALUES and INSERT_VALUES
5218:    in MatSetValues(); use MAT_FINAL_ASSEMBLY for the final assembly before
5219:    using the matrix.

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

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

5229:    Level: beginner

5231: .seealso: MatAssemblyEnd(), MatSetValues(), MatAssembled()
5232: @*/
5233: PetscErrorCode MatAssemblyBegin(Mat mat,MatAssemblyType type)
5234: {

5240:   MatCheckPreallocated(mat,1);
5241:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix.\nDid you forget to call MatSetUnfactored()?");
5242:   if (mat->assembled) {
5243:     mat->was_assembled = PETSC_TRUE;
5244:     mat->assembled     = PETSC_FALSE;
5245:   }

5247:   if (!MatAssemblyEnd_InUse) {
5248:     PetscLogEventBegin(MAT_AssemblyBegin,mat,0,0,0);
5249:     if (mat->ops->assemblybegin) {(*mat->ops->assemblybegin)(mat,type);}
5250:     PetscLogEventEnd(MAT_AssemblyBegin,mat,0,0,0);
5251:   } else if (mat->ops->assemblybegin) {
5252:     (*mat->ops->assemblybegin)(mat,type);
5253:   }
5254:   return(0);
5255: }

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

5261:    Not Collective

5263:    Input Parameter:
5264: .  mat - the matrix

5266:    Output Parameter:
5267: .  assembled - PETSC_TRUE or PETSC_FALSE

5269:    Level: advanced

5271: .seealso: MatAssemblyEnd(), MatSetValues(), MatAssemblyBegin()
5272: @*/
5273: PetscErrorCode MatAssembled(Mat mat,PetscBool  *assembled)
5274: {
5278:   *assembled = mat->assembled;
5279:   return(0);
5280: }

5282: /*@
5283:    MatAssemblyEnd - Completes assembling the matrix.  This routine should
5284:    be called after MatAssemblyBegin().

5286:    Collective on Mat

5288:    Input Parameters:
5289: +  mat - the matrix
5290: -  type - type of assembly, either MAT_FLUSH_ASSEMBLY or MAT_FINAL_ASSEMBLY

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

5305:    Notes:
5306:    MatSetValues() generally caches the values.  The matrix is ready to
5307:    use only after MatAssemblyBegin() and MatAssemblyEnd() have been called.
5308:    Use MAT_FLUSH_ASSEMBLY when switching between ADD_VALUES and INSERT_VALUES
5309:    in MatSetValues(); use MAT_FINAL_ASSEMBLY for the final assembly before
5310:    using the matrix.

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

5316:    Level: beginner

5318: .seealso: MatAssemblyBegin(), MatSetValues(), PetscDrawOpenX(), PetscDrawCreate(), MatView(), MatAssembled(), PetscViewerSocketOpen()
5319: @*/
5320: PetscErrorCode MatAssemblyEnd(Mat mat,MatAssemblyType type)
5321: {
5322:   PetscErrorCode  ierr;
5323:   static PetscInt inassm = 0;
5324:   PetscBool       flg    = PETSC_FALSE;


5330:   inassm++;
5331:   MatAssemblyEnd_InUse++;
5332:   if (MatAssemblyEnd_InUse == 1) { /* Do the logging only the first time through */
5333:     PetscLogEventBegin(MAT_AssemblyEnd,mat,0,0,0);
5334:     if (mat->ops->assemblyend) {
5335:       (*mat->ops->assemblyend)(mat,type);
5336:     }
5337:     PetscLogEventEnd(MAT_AssemblyEnd,mat,0,0,0);
5338:   } else if (mat->ops->assemblyend) {
5339:     (*mat->ops->assemblyend)(mat,type);
5340:   }

5342:   /* Flush assembly is not a true assembly */
5343:   if (type != MAT_FLUSH_ASSEMBLY) {
5344:     mat->num_ass++;
5345:     mat->assembled        = PETSC_TRUE;
5346:     mat->ass_nonzerostate = mat->nonzerostate;
5347:   }

5349:   mat->insertmode = NOT_SET_VALUES;
5350:   MatAssemblyEnd_InUse--;
5351:   PetscObjectStateIncrease((PetscObject)mat);
5352:   if (!mat->symmetric_eternal) {
5353:     mat->symmetric_set              = PETSC_FALSE;
5354:     mat->hermitian_set              = PETSC_FALSE;
5355:     mat->structurally_symmetric_set = PETSC_FALSE;
5356:   }
5357:   if (inassm == 1 && type != MAT_FLUSH_ASSEMBLY) {
5358:     MatViewFromOptions(mat,NULL,"-mat_view");

5360:     if (mat->checksymmetryonassembly) {
5361:       MatIsSymmetric(mat,mat->checksymmetrytol,&flg);
5362:       if (flg) {
5363:         PetscPrintf(PetscObjectComm((PetscObject)mat),"Matrix is symmetric (tolerance %g)\n",(double)mat->checksymmetrytol);
5364:       } else {
5365:         PetscPrintf(PetscObjectComm((PetscObject)mat),"Matrix is not symmetric (tolerance %g)\n",(double)mat->checksymmetrytol);
5366:       }
5367:     }
5368:     if (mat->nullsp && mat->checknullspaceonassembly) {
5369:       MatNullSpaceTest(mat->nullsp,mat,NULL);
5370:     }
5371:   }
5372:   inassm--;
5373:   return(0);
5374: }

5376: /*@
5377:    MatSetOption - Sets a parameter option for a matrix. Some options
5378:    may be specific to certain storage formats.  Some options
5379:    determine how values will be inserted (or added). Sorted,
5380:    row-oriented input will generally assemble the fastest. The default
5381:    is row-oriented.

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

5385:    Input Parameters:
5386: +  mat - the matrix
5387: .  option - the option, one of those listed below (and possibly others),
5388: -  flg - turn the option on (PETSC_TRUE) or off (PETSC_FALSE)

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


5404:    Options For Use with MatSetValues():
5405:    Insert a logically dense subblock, which can be
5406: .    MAT_ROW_ORIENTED - row-oriented (default)

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

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

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

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

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

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

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

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

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

5460:    MAT_USE_HASH_TABLE indicates that a hash table be used to improve the
5461:    searches during matrix assembly. When this flag is set, the hash table
5462:    is created during the first Matrix Assembly. This hash table is
5463:    used the next time through, during MatSetVaules()/MatSetVaulesBlocked()
5464:    to improve the searching of indices. MAT_NEW_NONZERO_LOCATIONS flag
5465:    should be used with MAT_USE_HASH_TABLE flag. This option is currently
5466:    supported by MATMPIBAIJ format only.

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

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

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

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

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

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

5488:    Level: intermediate

5490: .seealso:  MatOption, Mat

5492: @*/
5493: PetscErrorCode MatSetOption(Mat mat,MatOption op,PetscBool flg)
5494: {

5500:   if (op > 0) {
5503:   }

5505:   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);
5506:   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()");

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

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

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

5583:    Input Parameters:
5584: +  mat - the matrix
5585: -  option - the option, this only responds to certain options, check the code for which ones

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

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

5593:    Level: intermediate

5595: .seealso:  MatOption, MatSetOption()

5597: @*/
5598: PetscErrorCode MatGetOption(Mat mat,MatOption op,PetscBool *flg)
5599: {

5604:   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);
5605:   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()");

5607:   switch (op) {
5608:   case MAT_NO_OFF_PROC_ENTRIES:
5609:     *flg = mat->nooffprocentries;
5610:     break;
5611:   case MAT_NO_OFF_PROC_ZERO_ROWS:
5612:     *flg = mat->nooffproczerorows;
5613:     break;
5614:   case MAT_SYMMETRIC:
5615:     *flg = mat->symmetric;
5616:     break;
5617:   case MAT_HERMITIAN:
5618:     *flg = mat->hermitian;
5619:     break;
5620:   case MAT_STRUCTURALLY_SYMMETRIC:
5621:     *flg = mat->structurally_symmetric;
5622:     break;
5623:   case MAT_SYMMETRY_ETERNAL:
5624:     *flg = mat->symmetric_eternal;
5625:     break;
5626:   case MAT_SPD:
5627:     *flg = mat->spd;
5628:     break;
5629:   default:
5630:     break;
5631:   }
5632:   return(0);
5633: }

5635: /*@
5636:    MatZeroEntries - Zeros all entries of a matrix.  For sparse matrices
5637:    this routine retains the old nonzero structure.

5639:    Logically Collective on Mat

5641:    Input Parameters:
5642: .  mat - the matrix

5644:    Level: intermediate

5646:    Notes:
5647:     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.
5648:    See the Performance chapter of the users manual for information on preallocating matrices.

5650: .seealso: MatZeroRows()
5651: @*/
5652: PetscErrorCode MatZeroEntries(Mat mat)
5653: {

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

5664:   PetscLogEventBegin(MAT_ZeroEntries,mat,0,0,0);
5665:   (*mat->ops->zeroentries)(mat);
5666:   PetscLogEventEnd(MAT_ZeroEntries,mat,0,0,0);
5667:   PetscObjectStateIncrease((PetscObject)mat);
5668:   return(0);
5669: }

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

5675:    Collective on Mat

5677:    Input Parameters:
5678: +  mat - the matrix
5679: .  numRows - the number of rows to remove
5680: .  rows - the global row indices
5681: .  diag - value put in all diagonals of eliminated rows (0.0 will even eliminate diagonal entry)
5682: .  x - optional vector of solutions for zeroed rows (other entries in vector are not used)
5683: -  b - optional vector of right hand side, that will be adjusted by provided solution

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

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

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

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

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

5702:    Level: intermediate

5704: .seealso: MatZeroRowsIS(), MatZeroRows(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
5705:           MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
5706: @*/
5707: PetscErrorCode MatZeroRowsColumns(Mat mat,PetscInt numRows,const PetscInt rows[],PetscScalar diag,Vec x,Vec b)
5708: {

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

5720:   (*mat->ops->zerorowscolumns)(mat,numRows,rows,diag,x,b);
5721:   MatViewFromOptions(mat,NULL,"-mat_view");
5722:   PetscObjectStateIncrease((PetscObject)mat);
5723:   return(0);
5724: }

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

5730:    Collective on Mat

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

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

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

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

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

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

5756:    Level: intermediate

5758: .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
5759:           MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRows(), MatZeroRowsColumnsStencil()
5760: @*/
5761: PetscErrorCode MatZeroRowsColumnsIS(Mat mat,IS is,PetscScalar diag,Vec x,Vec b)
5762: {
5764:   PetscInt       numRows;
5765:   const PetscInt *rows;

5772:   ISGetLocalSize(is,&numRows);
5773:   ISGetIndices(is,&rows);
5774:   MatZeroRowsColumns(mat,numRows,rows,diag,x,b);
5775:   ISRestoreIndices(is,&rows);
5776:   return(0);
5777: }

5779: /*@
5780:    MatZeroRows - Zeros all entries (except possibly the main diagonal)
5781:    of a set of rows of a matrix.

5783:    Collective on Mat

5785:    Input Parameters:
5786: +  mat - the matrix
5787: .  numRows - the number of rows to remove
5788: .  rows - the global row indices
5789: .  diag - value put in all diagonals of eliminated rows (0.0 will even eliminate diagonal entry)
5790: .  x - optional vector of solutions for zeroed rows (other entries in vector are not used)
5791: -  b - optional vector of right hand side, that will be adjusted by provided solution

5793:    Notes:
5794:    For the AIJ and BAIJ matrix formats this removes the old nonzero structure,
5795:    but does not release memory.  For the dense and block diagonal
5796:    formats this does not alter the nonzero structure.

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

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

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

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

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

5817:    Level: intermediate

5819: .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
5820:           MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
5821: @*/
5822: PetscErrorCode MatZeroRows(Mat mat,PetscInt numRows,const PetscInt rows[],PetscScalar diag,Vec x,Vec b)
5823: {

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

5835:   (*mat->ops->zerorows)(mat,numRows,rows,diag,x,b);
5836:   MatViewFromOptions(mat,NULL,"-mat_view");
5837:   PetscObjectStateIncrease((PetscObject)mat);
5838:   return(0);
5839: }

5841: /*@
5842:    MatZeroRowsIS - Zeros all entries (except possibly the main diagonal)
5843:    of a set of rows of a matrix.

5845:    Collective on Mat

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

5854:    Notes:
5855:    For the AIJ and BAIJ matrix formats this removes the old nonzero structure,
5856:    but does not release memory.  For the dense and block diagonal
5857:    formats this does not alter the nonzero structure.

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

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

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

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

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

5878:    Level: intermediate

5880: .seealso: MatZeroRows(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
5881:           MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
5882: @*/
5883: PetscErrorCode MatZeroRowsIS(Mat mat,IS is,PetscScalar diag,Vec x,Vec b)
5884: {
5885:   PetscInt       numRows;
5886:   const PetscInt *rows;

5893:   ISGetLocalSize(is,&numRows);
5894:   ISGetIndices(is,&rows);
5895:   MatZeroRows(mat,numRows,rows,diag,x,b);
5896:   ISRestoreIndices(is,&rows);
5897:   return(0);
5898: }

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

5904:    Collective on Mat

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

5914:    Notes:
5915:    For the AIJ and BAIJ matrix formats this removes the old nonzero structure,
5916:    but does not release memory.  For the dense and block diagonal
5917:    formats this does not alter the nonzero structure.

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

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

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

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

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

5937:    In Fortran idxm and idxn should be declared as
5938: $     MatStencil idxm(4,m)
5939:    and the values inserted using
5940: $    idxm(MatStencil_i,1) = i
5941: $    idxm(MatStencil_j,1) = j
5942: $    idxm(MatStencil_k,1) = k
5943: $    idxm(MatStencil_c,1) = c
5944:    etc

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

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

5954:    Level: intermediate

5956: .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsl(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
5957:           MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
5958: @*/
5959: PetscErrorCode MatZeroRowsStencil(Mat mat,PetscInt numRows,const MatStencil rows[],PetscScalar diag,Vec x,Vec b)
5960: {
5961:   PetscInt       dim     = mat->stencil.dim;
5962:   PetscInt       sdim    = dim - (1 - (PetscInt) mat->stencil.noc);
5963:   PetscInt       *dims   = mat->stencil.dims+1;
5964:   PetscInt       *starts = mat->stencil.starts;
5965:   PetscInt       *dxm    = (PetscInt*) rows;
5966:   PetscInt       *jdxm, i, j, tmp, numNewRows = 0;


5974:   PetscMalloc1(numRows, &jdxm);
5975:   for (i = 0; i < numRows; ++i) {
5976:     /* Skip unused dimensions (they are ordered k, j, i, c) */
5977:     for (j = 0; j < 3-sdim; ++j) dxm++;
5978:     /* Local index in X dir */
5979:     tmp = *dxm++ - starts[0];
5980:     /* Loop over remaining dimensions */
5981:     for (j = 0; j < dim-1; ++j) {
5982:       /* If nonlocal, set index to be negative */
5983:       if ((*dxm++ - starts[j+1]) < 0 || tmp < 0) tmp = PETSC_MIN_INT;
5984:       /* Update local index */
5985:       else tmp = tmp*dims[j] + *(dxm-1) - starts[j+1];
5986:     }
5987:     /* Skip component slot if necessary */
5988:     if (mat->stencil.noc) dxm++;
5989:     /* Local row number */
5990:     if (tmp >= 0) {
5991:       jdxm[numNewRows++] = tmp;
5992:     }
5993:   }
5994:   MatZeroRowsLocal(mat,numNewRows,jdxm,diag,x,b);
5995:   PetscFree(jdxm);
5996:   return(0);
5997: }

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

6003:    Collective on Mat

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

6013:    Notes:
6014:    For the AIJ and BAIJ matrix formats this removes the old nonzero structure,
6015:    but does not release memory.  For the dense and block diagonal
6016:    formats this does not alter the nonzero structure.

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

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

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

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

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

6036:    In Fortran idxm and idxn should be declared as
6037: $     MatStencil idxm(4,m)
6038:    and the values inserted using
6039: $    idxm(MatStencil_i,1) = i
6040: $    idxm(MatStencil_j,1) = j
6041: $    idxm(MatStencil_k,1) = k
6042: $    idxm(MatStencil_c,1) = c
6043:    etc

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

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

6053:    Level: intermediate

6055: .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
6056:           MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRows()
6057: @*/
6058: PetscErrorCode MatZeroRowsColumnsStencil(Mat mat,PetscInt numRows,const MatStencil rows[],PetscScalar diag,Vec x,Vec b)
6059: {
6060:   PetscInt       dim     = mat->stencil.dim;
6061:   PetscInt       sdim    = dim - (1 - (PetscInt) mat->stencil.noc);
6062:   PetscInt       *dims   = mat->stencil.dims+1;
6063:   PetscInt       *starts = mat->stencil.starts;
6064:   PetscInt       *dxm    = (PetscInt*) rows;
6065:   PetscInt       *jdxm, i, j, tmp, numNewRows = 0;


6073:   PetscMalloc1(numRows, &jdxm);
6074:   for (i = 0; i < numRows; ++i) {
6075:     /* Skip unused dimensions (they are ordered k, j, i, c) */
6076:     for (j = 0; j < 3-sdim; ++j) dxm++;
6077:     /* Local index in X dir */
6078:     tmp = *dxm++ - starts[0];
6079:     /* Loop over remaining dimensions */
6080:     for (j = 0; j < dim-1; ++j) {
6081:       /* If nonlocal, set index to be negative */
6082:       if ((*dxm++ - starts[j+1]) < 0 || tmp < 0) tmp = PETSC_MIN_INT;
6083:       /* Update local index */
6084:       else tmp = tmp*dims[j] + *(dxm-1) - starts[j+1];
6085:     }
6086:     /* Skip component slot if necessary */
6087:     if (mat->stencil.noc) dxm++;
6088:     /* Local row number */
6089:     if (tmp >= 0) {
6090:       jdxm[numNewRows++] = tmp;
6091:     }
6092:   }
6093:   MatZeroRowsColumnsLocal(mat,numNewRows,jdxm,diag,x,b);
6094:   PetscFree(jdxm);
6095:   return(0);
6096: }

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

6102:    Collective on Mat

6104:    Input Parameters:
6105: +  mat - the matrix
6106: .  numRows - the number of rows to remove
6107: .  rows - the global row indices
6108: .  diag - value put in all diagonals of eliminated rows
6109: .  x - optional vector of solutions for zeroed rows (other entries in vector are not used)
6110: -  b - optional vector of right hand side, that will be adjusted by provided solution

6112:    Notes:
6113:    Before calling MatZeroRowsLocal(), the user must first set the
6114:    local-to-global mapping by calling MatSetLocalToGlobalMapping().

6116:    For the AIJ matrix formats this removes the old nonzero structure,
6117:    but does not release memory.  For the dense and block diagonal
6118:    formats this does not alter the nonzero structure.

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

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

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

6131:    Level: intermediate

6133: .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRows(), MatSetOption(),
6134:           MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
6135: @*/
6136: PetscErrorCode MatZeroRowsLocal(Mat mat,PetscInt numRows,const PetscInt rows[],PetscScalar diag,Vec x,Vec b)
6137: {

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

6148:   if (mat->ops->zerorowslocal) {
6149:     (*mat->ops->zerorowslocal)(mat,numRows,rows,diag,x,b);
6150:   } else {
6151:     IS             is, newis;
6152:     const PetscInt *newRows;

6154:     if (!mat->rmap->mapping) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Need to provide local to global mapping to matrix first");
6155:     ISCreateGeneral(PETSC_COMM_SELF,numRows,rows,PETSC_COPY_VALUES,&is);
6156:     ISLocalToGlobalMappingApplyIS(mat->rmap->mapping,is,&newis);
6157:     ISGetIndices(newis,&newRows);
6158:     (*mat->ops->zerorows)(mat,numRows,newRows,diag,x,b);
6159:     ISRestoreIndices(newis,&newRows);
6160:     ISDestroy(&newis);
6161:     ISDestroy(&is);
6162:   }
6163:   PetscObjectStateIncrease((PetscObject)mat);
6164:   return(0);
6165: }

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

6171:    Collective on Mat

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

6180:    Notes:
6181:    Before calling MatZeroRowsLocalIS(), the user must first set the
6182:    local-to-global mapping by calling MatSetLocalToGlobalMapping().

6184:    For the AIJ matrix formats this removes the old nonzero structure,
6185:    but does not release memory.  For the dense and block diagonal
6186:    formats this does not alter the nonzero structure.

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

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

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

6199:    Level: intermediate

6201: .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRows(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
6202:           MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
6203: @*/
6204: PetscErrorCode MatZeroRowsLocalIS(Mat mat,IS is,PetscScalar diag,Vec x,Vec b)
6205: {
6207:   PetscInt       numRows;
6208:   const PetscInt *rows;

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

6218:   ISGetLocalSize(is,&numRows);
6219:   ISGetIndices(is,&rows);
6220:   MatZeroRowsLocal(mat,numRows,rows,diag,x,b);
6221:   ISRestoreIndices(is,&rows);
6222:   return(0);
6223: }

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

6229:    Collective on Mat

6231:    Input Parameters:
6232: +  mat - the matrix
6233: .  numRows - the number of rows to remove
6234: .  rows - the global row indices
6235: .  diag - value put in all diagonals of eliminated rows
6236: .  x - optional vector of solutions for zeroed rows (other entries in vector are not used)
6237: -  b - optional vector of right hand side, that will be adjusted by provided solution

6239:    Notes:
6240:    Before calling MatZeroRowsColumnsLocal(), the user must first set the
6241:    local-to-global mapping by calling MatSetLocalToGlobalMapping().

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

6247:    Level: intermediate

6249: .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
6250:           MatZeroRows(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
6251: @*/
6252: PetscErrorCode MatZeroRowsColumnsLocal(Mat mat,PetscInt numRows,const PetscInt rows[],PetscScalar diag,Vec x,Vec b)
6253: {
6255:   IS             is, newis;
6256:   const PetscInt *newRows;

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

6266:   if (!mat->cmap->mapping) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Need to provide local to global mapping to matrix first");
6267:   ISCreateGeneral(PETSC_COMM_SELF,numRows,rows,PETSC_COPY_VALUES,&is);
6268:   ISLocalToGlobalMappingApplyIS(mat->cmap->mapping,is,&newis);
6269:   ISGetIndices(newis,&newRows);
6270:   (*mat->ops->zerorowscolumns)(mat,numRows,newRows,diag,x,b);
6271:   ISRestoreIndices(newis,&newRows);
6272:   ISDestroy(&newis);
6273:   ISDestroy(&is);
6274:   PetscObjectStateIncrease((PetscObject)mat);
6275:   return(0);
6276: }

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

6282:    Collective on Mat

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

6291:    Notes:
6292:    Before calling MatZeroRowsColumnsLocalIS(), the user must first set the
6293:    local-to-global mapping by calling MatSetLocalToGlobalMapping().

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

6299:    Level: intermediate

6301: .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
6302:           MatZeroRowsColumnsLocal(), MatZeroRows(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
6303: @*/
6304: PetscErrorCode MatZeroRowsColumnsLocalIS(Mat mat,IS is,PetscScalar diag,Vec x,Vec b)
6305: {
6307:   PetscInt       numRows;
6308:   const PetscInt *rows;

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

6318:   ISGetLocalSize(is,&numRows);
6319:   ISGetIndices(is,&rows);
6320:   MatZeroRowsColumnsLocal(mat,numRows,rows,diag,x,b);
6321:   ISRestoreIndices(is,&rows);
6322:   return(0);
6323: }

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

6328:    Not Collective

6330:    Input Parameter:
6331: .  mat - the matrix

6333:    Output Parameters:
6334: +  m - the number of global rows
6335: -  n - the number of global columns

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

6339:    Level: beginner

6341: .seealso: MatGetLocalSize()
6342: @*/
6343: PetscErrorCode MatGetSize(Mat mat,PetscInt *m,PetscInt *n)
6344: {
6347:   if (m) *m = mat->rmap->N;
6348:   if (n) *n = mat->cmap->N;
6349:   return(0);
6350: }

6352: /*@C
6353:    MatGetLocalSize - Returns the number of rows and columns in a matrix
6354:    stored locally.  This information may be implementation dependent, so
6355:    use with care.

6357:    Not Collective

6359:    Input Parameters:
6360: .  mat - the matrix

6362:    Output Parameters:
6363: +  m - the number of local rows
6364: -  n - the number of local columns

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

6368:    Level: beginner

6370: .seealso: MatGetSize()
6371: @*/
6372: PetscErrorCode MatGetLocalSize(Mat mat,PetscInt *m,PetscInt *n)
6373: {
6378:   if (m) *m = mat->rmap->n;
6379:   if (n) *n = mat->cmap->n;
6380:   return(0);
6381: }

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

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

6389:    Input Parameters:
6390: .  mat - the matrix

6392:    Output Parameters:
6393: +  m - the global index of the first local column
6394: -  n - one more than the global index of the last local column

6396:    Notes:
6397:     both output parameters can be NULL on input.

6399:    Level: developer

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

6403: @*/
6404: PetscErrorCode MatGetOwnershipRangeColumn(Mat mat,PetscInt *m,PetscInt *n)
6405: {
6411:   MatCheckPreallocated(mat,1);
6412:   if (m) *m = mat->cmap->rstart;
6413:   if (n) *n = mat->cmap->rend;
6414:   return(0);
6415: }

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

6423:    Not Collective

6425:    Input Parameters:
6426: .  mat - the matrix

6428:    Output Parameters:
6429: +  m - the global index of the first local row
6430: -  n - one more than the global index of the last local row

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

6437:    Level: beginner

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

6441: @*/
6442: PetscErrorCode MatGetOwnershipRange(Mat mat,PetscInt *m,PetscInt *n)
6443: {
6449:   MatCheckPreallocated(mat,1);
6450:   if (m) *m = mat->rmap->rstart;
6451:   if (n) *n = mat->rmap->rend;
6452:   return(0);
6453: }

6455: /*@C
6456:    MatGetOwnershipRanges - Returns the range of matrix rows owned by
6457:    each process

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

6461:    Input Parameters:
6462: .  mat - the matrix

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

6467:    Level: beginner

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

6471: @*/
6472: PetscErrorCode MatGetOwnershipRanges(Mat mat,const PetscInt **ranges)
6473: {

6479:   MatCheckPreallocated(mat,1);
6480:   PetscLayoutGetRanges(mat->rmap,ranges);
6481:   return(0);
6482: }

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

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

6490:    Input Parameters:
6491: .  mat - the matrix

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

6496:    Level: beginner

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

6500: @*/
6501: PetscErrorCode MatGetOwnershipRangesColumn(Mat mat,const PetscInt **ranges)
6502: {

6508:   MatCheckPreallocated(mat,1);
6509:   PetscLayoutGetRanges(mat->cmap,ranges);
6510:   return(0);
6511: }

6513: /*@C
6514:    MatGetOwnershipIS - Get row and column ownership as index sets

6516:    Not Collective

6518:    Input Arguments:
6519: .  A - matrix of type Elemental

6521:    Output Arguments:
6522: +  rows - rows in which this process owns elements
6523: -  cols - columns in which this process owns elements

6525:    Level: intermediate

6527: .seealso: MatGetOwnershipRange(), MatGetOwnershipRangeColumn(), MatSetValues(), MATELEMENTAL
6528: @*/
6529: PetscErrorCode MatGetOwnershipIS(Mat A,IS *rows,IS *cols)
6530: {
6531:   PetscErrorCode ierr,(*f)(Mat,IS*,IS*);

6534:   MatCheckPreallocated(A,1);
6535:   PetscObjectQueryFunction((PetscObject)A,"MatGetOwnershipIS_C",&f);
6536:   if (f) {
6537:     (*f)(A,rows,cols);
6538:   } else {   /* Create a standard row-based partition, each process is responsible for ALL columns in their row block */
6539:     if (rows) {ISCreateStride(PETSC_COMM_SELF,A->rmap->n,A->rmap->rstart,1,rows);}
6540:     if (cols) {ISCreateStride(PETSC_COMM_SELF,A->cmap->N,0,1,cols);}
6541:   }
6542:   return(0);
6543: }

6545: /*@C
6546:    MatILUFactorSymbolic - Performs symbolic ILU factorization of a matrix.
6547:    Uses levels of fill only, not drop tolerance. Use MatLUFactorNumeric()
6548:    to complete the factorization.

6550:    Collective on Mat

6552:    Input Parameters:
6553: +  mat - the matrix
6554: .  row - row permutation
6555: .  column - column permutation
6556: -  info - structure containing
6557: $      levels - number of levels of fill.
6558: $      expected fill - as ratio of original fill.
6559: $      1 or 0 - indicating force fill on diagonal (improves robustness for matrices
6560:                 missing diagonal entries)

6562:    Output Parameters:
6563: .  fact - new matrix that has been symbolically factored

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

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

6572:    Level: developer

6574: .seealso: MatLUFactorSymbolic(), MatLUFactorNumeric(), MatCholeskyFactor()
6575:           MatGetOrdering(), MatFactorInfo

6577:     Note: this uses the definition of level of fill as in Y. Saad, 2003

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

6582:    References:
6583:      Y. Saad, Iterative methods for sparse linear systems Philadelphia: Society for Industrial and Applied Mathematics, 2003
6584: @*/
6585: PetscErrorCode MatILUFactorSymbolic(Mat fact,Mat mat,IS row,IS col,const MatFactorInfo *info)
6586: {

6596:   if (info->levels < 0) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_OUTOFRANGE,"Levels of fill negative %D",(PetscInt)info->levels);
6597:   if (info->fill < 1.0) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_OUTOFRANGE,"Expected fill less than 1.0 %g",(double)info->fill);
6598:   if (!(fact)->ops->ilufactorsymbolic) {
6599:     MatSolverType spackage;
6600:     MatFactorGetSolverType(fact,&spackage);
6601:     SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Matrix type %s symbolic ILU using solver package %s",((PetscObject)mat)->type_name,spackage);
6602:   }
6603:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6604:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6605:   MatCheckPreallocated(mat,2);

6607:   PetscLogEventBegin(MAT_ILUFactorSymbolic,mat,row,col,0);
6608:   (fact->ops->ilufactorsymbolic)(fact,mat,row,col,info);
6609:   PetscLogEventEnd(MAT_ILUFactorSymbolic,mat,row,col,0);
6610:   return(0);
6611: }

6613: /*@C
6614:    MatICCFactorSymbolic - Performs symbolic incomplete
6615:    Cholesky factorization for a symmetric matrix.  Use
6616:    MatCholeskyFactorNumeric() to complete the factorization.

6618:    Collective on Mat

6620:    Input Parameters:
6621: +  mat - the matrix
6622: .  perm - row and column permutation
6623: -  info - structure containing
6624: $      levels - number of levels of fill.
6625: $      expected fill - as ratio of original fill.

6627:    Output Parameter:
6628: .  fact - the factored matrix

6630:    Notes:
6631:    Most users should employ the KSP interface for linear solvers
6632:    instead of working directly with matrix algebra routines such as this.
6633:    See, e.g., KSPCreate().

6635:    Level: developer

6637: .seealso: MatCholeskyFactorNumeric(), MatCholeskyFactor(), MatFactorInfo

6639:     Note: this uses the definition of level of fill as in Y. Saad, 2003

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

6644:    References:
6645:      Y. Saad, Iterative methods for sparse linear systems Philadelphia: Society for Industrial and Applied Mathematics, 2003
6646: @*/
6647: PetscErrorCode MatICCFactorSymbolic(Mat fact,Mat mat,IS perm,const MatFactorInfo *info)
6648: {

6657:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6658:   if (info->levels < 0) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_OUTOFRANGE,"Levels negative %D",(PetscInt) info->levels);
6659:   if (info->fill < 1.0) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_OUTOFRANGE,"Expected fill less than 1.0 %g",(double)info->fill);
6660:   if (!(fact)->ops->iccfactorsymbolic) {
6661:     MatSolverType spackage;
6662:     MatFactorGetSolverType(fact,&spackage);
6663:     SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Matrix type %s symbolic ICC using solver package %s",((PetscObject)mat)->type_name,spackage);
6664:   }
6665:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6666:   MatCheckPreallocated(mat,2);

6668:   PetscLogEventBegin(MAT_ICCFactorSymbolic,mat,perm,0,0);
6669:   (fact->ops->iccfactorsymbolic)(fact,mat,perm,info);
6670:   PetscLogEventEnd(MAT_ICCFactorSymbolic,mat,perm,0,0);
6671:   return(0);
6672: }

6674: /*@C
6675:    MatCreateSubMatrices - Extracts several submatrices from a matrix. If submat
6676:    points to an array of valid matrices, they may be reused to store the new
6677:    submatrices.

6679:    Collective on Mat

6681:    Input Parameters:
6682: +  mat - the matrix
6683: .  n   - the number of submatrixes to be extracted (on this processor, may be zero)
6684: .  irow, icol - index sets of rows and columns to extract
6685: -  scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX

6687:    Output Parameter:
6688: .  submat - the array of submatrices

6690:    Notes:
6691:    MatCreateSubMatrices() can extract ONLY sequential submatrices
6692:    (from both sequential and parallel matrices). Use MatCreateSubMatrix()
6693:    to extract a parallel submatrix.

6695:    Some matrix types place restrictions on the row and column
6696:    indices, such as that they be sorted or that they be equal to each other.

6698:    The index sets may not have duplicate entries.

6700:    When extracting submatrices from a parallel matrix, each processor can
6701:    form a different submatrix by setting the rows and columns of its
6702:    individual index sets according to the local submatrix desired.

6704:    When finished using the submatrices, the user should destroy
6705:    them with MatDestroySubMatrices().

6707:    MAT_REUSE_MATRIX can only be used when the nonzero structure of the
6708:    original matrix has not changed from that last call to MatCreateSubMatrices().

6710:    This routine creates the matrices in submat; you should NOT create them before
6711:    calling it. It also allocates the array of matrix pointers submat.

6713:    For BAIJ matrices the index sets must respect the block structure, that is if they
6714:    request one row/column in a block, they must request all rows/columns that are in
6715:    that block. For example, if the block size is 2 you cannot request just row 0 and
6716:    column 0.

6718:    Fortran Note:
6719:    The Fortran interface is slightly different from that given below; it
6720:    requires one to pass in  as submat a Mat (integer) array of size at least n+1.

6722:    Level: advanced


6725: .seealso: MatDestroySubMatrices(), MatCreateSubMatrix(), MatGetRow(), MatGetDiagonal(), MatReuse
6726: @*/
6727: PetscErrorCode MatCreateSubMatrices(Mat mat,PetscInt n,const IS irow[],const IS icol[],MatReuse scall,Mat *submat[])
6728: {
6730:   PetscInt       i;
6731:   PetscBool      eq;

6736:   if (n) {
6741:   }
6743:   if (n && scall == MAT_REUSE_MATRIX) {
6746:   }
6747:   if (!mat->ops->createsubmatrices) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
6748:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6749:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6750:   MatCheckPreallocated(mat,1);

6752:   PetscLogEventBegin(MAT_CreateSubMats,mat,0,0,0);
6753:   (*mat->ops->createsubmatrices)(mat,n,irow,icol,scall,submat);
6754:   PetscLogEventEnd(MAT_CreateSubMats,mat,0,0,0);
6755:   for (i=0; i<n; i++) {
6756:     (*submat)[i]->factortype = MAT_FACTOR_NONE;  /* in case in place factorization was previously done on submatrix */
6757:     ISEqualUnsorted(irow[i],icol[i],&eq);
6758:     if (eq) {
6759:       MatPropagateSymmetryOptions(mat,(*submat)[i]);
6760:     }
6761:   }
6762:   return(0);
6763: }

6765: /*@C
6766:    MatCreateSubMatricesMPI - Extracts MPI submatrices across a sub communicator of mat (by pairs of IS that may live on subcomms).

6768:    Collective on Mat

6770:    Input Parameters:
6771: +  mat - the matrix
6772: .  n   - the number of submatrixes to be extracted
6773: .  irow, icol - index sets of rows and columns to extract
6774: -  scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX

6776:    Output Parameter:
6777: .  submat - the array of submatrices

6779:    Level: advanced


6782: .seealso: MatCreateSubMatrices(), MatCreateSubMatrix(), MatGetRow(), MatGetDiagonal(), MatReuse
6783: @*/
6784: PetscErrorCode MatCreateSubMatricesMPI(Mat mat,PetscInt n,const IS irow[],const IS icol[],MatReuse scall,Mat *submat[])
6785: {
6787:   PetscInt       i;
6788:   PetscBool      eq;

6793:   if (n) {
6798:   }
6800:   if (n && scall == MAT_REUSE_MATRIX) {
6803:   }
6804:   if (!mat->ops->createsubmatricesmpi) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
6805:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6806:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6807:   MatCheckPreallocated(mat,1);

6809:   PetscLogEventBegin(MAT_CreateSubMats,mat,0,0,0);
6810:   (*mat->ops->createsubmatricesmpi)(mat,n,irow,icol,scall,submat);
6811:   PetscLogEventEnd(MAT_CreateSubMats,mat,0,0,0);
6812:   for (i=0; i<n; i++) {
6813:     ISEqualUnsorted(irow[i],icol[i],&eq);
6814:     if (eq) {
6815:       MatPropagateSymmetryOptions(mat,(*submat)[i]);
6816:     }
6817:   }
6818:   return(0);
6819: }

6821: /*@C
6822:    MatDestroyMatrices - Destroys an array of matrices.

6824:    Collective on Mat

6826:    Input Parameters:
6827: +  n - the number of local matrices
6828: -  mat - the matrices (note that this is a pointer to the array of matrices)

6830:    Level: advanced

6832:     Notes:
6833:     Frees not only the matrices, but also the array that contains the matrices
6834:            In Fortran will not free the array.

6836: .seealso: MatCreateSubMatrices() MatDestroySubMatrices()
6837: @*/
6838: PetscErrorCode MatDestroyMatrices(PetscInt n,Mat *mat[])
6839: {
6841:   PetscInt       i;

6844:   if (!*mat) return(0);
6845:   if (n < 0) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Trying to destroy negative number of matrices %D",n);

6848:   for (i=0; i<n; i++) {
6849:     MatDestroy(&(*mat)[i]);
6850:   }

6852:   /* memory is allocated even if n = 0 */
6853:   PetscFree(*mat);
6854:   return(0);
6855: }

6857: /*@C
6858:    MatDestroySubMatrices - Destroys a set of matrices obtained with MatCreateSubMatrices().

6860:    Collective on Mat

6862:    Input Parameters:
6863: +  n - the number of local matrices
6864: -  mat - the matrices (note that this is a pointer to the array of matrices, just to match the calling
6865:                        sequence of MatCreateSubMatrices())

6867:    Level: advanced

6869:     Notes:
6870:     Frees not only the matrices, but also the array that contains the matrices
6871:            In Fortran will not free the array.

6873: .seealso: MatCreateSubMatrices()
6874: @*/
6875: PetscErrorCode MatDestroySubMatrices(PetscInt n,Mat *mat[])
6876: {
6878:   Mat            mat0;

6881:   if (!*mat) return(0);
6882:   /* mat[] is an array of length n+1, see MatCreateSubMatrices_xxx() */
6883:   if (n < 0) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Trying to destroy negative number of matrices %D",n);

6886:   mat0 = (*mat)[0];
6887:   if (mat0 && mat0->ops->destroysubmatrices) {
6888:     (mat0->ops->destroysubmatrices)(n,mat);
6889:   } else {
6890:     MatDestroyMatrices(n,mat);
6891:   }
6892:   return(0);
6893: }

6895: /*@C
6896:    MatGetSeqNonzeroStructure - Extracts the sequential nonzero structure from a matrix.

6898:    Collective on Mat

6900:    Input Parameters:
6901: .  mat - the matrix

6903:    Output Parameter:
6904: .  matstruct - the sequential matrix with the nonzero structure of mat

6906:   Level: intermediate

6908: .seealso: MatDestroySeqNonzeroStructure(), MatCreateSubMatrices(), MatDestroyMatrices()
6909: @*/
6910: PetscErrorCode MatGetSeqNonzeroStructure(Mat mat,Mat *matstruct)
6911: {


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

6922:   if (!mat->ops->getseqnonzerostructure) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Not for matrix type %s\n",((PetscObject)mat)->type_name);
6923:   PetscLogEventBegin(MAT_GetSeqNonzeroStructure,mat,0,0,0);
6924:   (*mat->ops->getseqnonzerostructure)(mat,matstruct);
6925:   PetscLogEventEnd(MAT_GetSeqNonzeroStructure,mat,0,0,0);
6926:   return(0);
6927: }

6929: /*@C
6930:    MatDestroySeqNonzeroStructure - Destroys matrix obtained with MatGetSeqNonzeroStructure().

6932:    Collective on Mat

6934:    Input Parameters:
6935: .  mat - the matrix (note that this is a pointer to the array of matrices, just to match the calling
6936:                        sequence of MatGetSequentialNonzeroStructure())

6938:    Level: advanced

6940:     Notes:
6941:     Frees not only the matrices, but also the array that contains the matrices

6943: .seealso: MatGetSeqNonzeroStructure()
6944: @*/
6945: PetscErrorCode MatDestroySeqNonzeroStructure(Mat *mat)
6946: {

6951:   MatDestroy(mat);
6952:   return(0);
6953: }

6955: /*@
6956:    MatIncreaseOverlap - Given a set of submatrices indicated by index sets,
6957:    replaces the index sets by larger ones that represent submatrices with
6958:    additional overlap.

6960:    Collective on Mat

6962:    Input Parameters:
6963: +  mat - the matrix
6964: .  n   - the number of index sets
6965: .  is  - the array of index sets (these index sets will changed during the call)
6966: -  ov  - the additional overlap requested

6968:    Options Database:
6969: .  -mat_increase_overlap_scalable - use a scalable algorithm to compute the overlap (supported by MPIAIJ matrix)

6971:    Level: developer


6974: .seealso: MatCreateSubMatrices()
6975: @*/
6976: PetscErrorCode MatIncreaseOverlap(Mat mat,PetscInt n,IS is[],PetscInt ov)
6977: {

6983:   if (n < 0) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Must have one or more domains, you have %D",n);
6984:   if (n) {
6987:   }
6988:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6989:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6990:   MatCheckPreallocated(mat,1);

6992:   if (!ov) return(0);
6993:   if (!mat->ops->increaseoverlap) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
6994:   PetscLogEventBegin(MAT_IncreaseOverlap,mat,0,0,0);
6995:   (*mat->ops->increaseoverlap)(mat,n,is,ov);
6996:   PetscLogEventEnd(MAT_IncreaseOverlap,mat,0,0,0);
6997:   return(0);
6998: }


7001: PetscErrorCode MatIncreaseOverlapSplit_Single(Mat,IS*,PetscInt);

7003: /*@
7004:    MatIncreaseOverlapSplit - Given a set of submatrices indicated by index sets across
7005:    a sub communicator, replaces the index sets by larger ones that represent submatrices with
7006:    additional overlap.

7008:    Collective on Mat

7010:    Input Parameters:
7011: +  mat - the matrix
7012: .  n   - the number of index sets
7013: .  is  - the array of index sets (these index sets will changed during the call)
7014: -  ov  - the additional overlap requested

7016:    Options Database:
7017: .  -mat_increase_overlap_scalable - use a scalable algorithm to compute the overlap (supported by MPIAIJ matrix)

7019:    Level: developer


7022: .seealso: MatCreateSubMatrices()
7023: @*/
7024: PetscErrorCode MatIncreaseOverlapSplit(Mat mat,PetscInt n,IS is[],PetscInt ov)
7025: {
7026:   PetscInt       i;

7032:   if (n < 0) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Must have one or more domains, you have %D",n);
7033:   if (n) {
7036:   }
7037:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
7038:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
7039:   MatCheckPreallocated(mat,1);
7040:   if (!ov) return(0);
7041:   PetscLogEventBegin(MAT_IncreaseOverlap,mat,0,0,0);
7042:   for(i=0; i<n; i++){
7043:          MatIncreaseOverlapSplit_Single(mat,&is[i],ov);
7044:   }
7045:   PetscLogEventEnd(MAT_IncreaseOverlap,mat,0,0,0);
7046:   return(0);
7047: }




7052: /*@
7053:    MatGetBlockSize - Returns the matrix block size.

7055:    Not Collective

7057:    Input Parameter:
7058: .  mat - the matrix

7060:    Output Parameter:
7061: .  bs - block size

7063:    Notes:
7064:     Block row formats are MATSEQBAIJ, MATMPIBAIJ, MATSEQSBAIJ, MATMPISBAIJ. These formats ALWAYS have square block storage in the matrix.

7066:    If the block size has not been set yet this routine returns 1.

7068:    Level: intermediate

7070: .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSizes()
7071: @*/
7072: PetscErrorCode MatGetBlockSize(Mat mat,PetscInt *bs)
7073: {
7077:   *bs = PetscAbs(mat->rmap->bs);
7078:   return(0);
7079: }

7081: /*@
7082:    MatGetBlockSizes - Returns the matrix block row and column sizes.

7084:    Not Collective

7086:    Input Parameter:
7087: .  mat - the matrix

7089:    Output Parameter:
7090: +  rbs - row block size
7091: -  cbs - column block size

7093:    Notes:
7094:     Block row formats are MATSEQBAIJ, MATMPIBAIJ, MATSEQSBAIJ, MATMPISBAIJ. These formats ALWAYS have square block storage in the matrix.
7095:     If you pass a different block size for the columns than the rows, the row block size determines the square block storage.

7097:    If a block size has not been set yet this routine returns 1.

7099:    Level: intermediate

7101: .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSize(), MatSetBlockSize(), MatSetBlockSizes()
7102: @*/
7103: PetscErrorCode MatGetBlockSizes(Mat mat,PetscInt *rbs, PetscInt *cbs)
7104: {
7109:   if (rbs) *rbs = PetscAbs(mat->rmap->bs);
7110:   if (cbs) *cbs = PetscAbs(mat->cmap->bs);
7111:   return(0);
7112: }

7114: /*@
7115:    MatSetBlockSize - Sets the matrix block size.

7117:    Logically Collective on Mat

7119:    Input Parameters:
7120: +  mat - the matrix
7121: -  bs - block size

7123:    Notes:
7124:     Block row formats are MATSEQBAIJ, MATMPIBAIJ, MATSEQSBAIJ, MATMPISBAIJ. These formats ALWAYS have square block storage in the matrix.
7125:     This must be called before MatSetUp() or MatXXXSetPreallocation() (or will default to 1) and the block size cannot be changed later.

7127:     For MATMPIAIJ and MATSEQAIJ matrix formats, this function can be called at a later stage, provided that the specified block size
7128:     is compatible with the matrix local sizes.

7130:    Level: intermediate

7132: .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSize(), MatSetBlockSizes(), MatGetBlockSizes()
7133: @*/
7134: PetscErrorCode MatSetBlockSize(Mat mat,PetscInt bs)
7135: {

7141:   MatSetBlockSizes(mat,bs,bs);
7142:   return(0);
7143: }

7145: /*@
7146:    MatSetVariableBlockSizes - Sets a diagonal blocks of the matrix that need not be of the same size

7148:    Logically Collective on Mat

7150:    Input Parameters:
7151: +  mat - the matrix
7152: .  nblocks - the number of blocks on this process
7153: -  bsizes - the block sizes

7155:    Notes:
7156:     Currently used by PCVPBJACOBI for SeqAIJ matrices

7158:    Level: intermediate

7160: .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSize(), MatSetBlockSizes(), MatGetBlockSizes(), MatGetVariableBlockSizes()
7161: @*/
7162: PetscErrorCode MatSetVariableBlockSizes(Mat mat,PetscInt nblocks,PetscInt *bsizes)
7163: {
7165:   PetscInt       i,ncnt = 0, nlocal;

7169:   if (nblocks < 0) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Number of local blocks must be great than or equal to zero");
7170:   MatGetLocalSize(mat,&nlocal,NULL);
7171:   for (i=0; i<nblocks; i++) ncnt += bsizes[i];
7172:   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);
7173:   PetscFree(mat->bsizes);
7174:   mat->nblocks = nblocks;
7175:   PetscMalloc1(nblocks,&mat->bsizes);
7176:   PetscArraycpy(mat->bsizes,bsizes,nblocks);
7177:   return(0);
7178: }

7180: /*@C
7181:    MatGetVariableBlockSizes - Gets a diagonal blocks of the matrix that need not be of the same size

7183:    Logically Collective on Mat

7185:    Input Parameters:
7186: .  mat - the matrix

7188:    Output Parameters:
7189: +  nblocks - the number of blocks on this process
7190: -  bsizes - the block sizes

7192:    Notes: Currently not supported from Fortran

7194:    Level: intermediate

7196: .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSize(), MatSetBlockSizes(), MatGetBlockSizes(), MatSetVariableBlockSizes()
7197: @*/
7198: PetscErrorCode MatGetVariableBlockSizes(Mat mat,PetscInt *nblocks,const PetscInt **bsizes)
7199: {
7202:   *nblocks = mat->nblocks;
7203:   *bsizes  = mat->bsizes;
7204:   return(0);
7205: }

7207: /*@
7208:    MatSetBlockSizes - Sets the matrix block row and column sizes.

7210:    Logically Collective on Mat

7212:    Input Parameters:
7213: +  mat - the matrix
7214: .  rbs - row block size
7215: -  cbs - column block size

7217:    Notes:
7218:     Block row formats are MATSEQBAIJ, MATMPIBAIJ, MATSEQSBAIJ, MATMPISBAIJ. These formats ALWAYS have square block storage in the matrix.
7219:     If you pass a different block size for the columns than the rows, the row block size determines the square block storage.
7220:     This must be called before MatSetUp() or MatXXXSetPreallocation() (or will default to 1) and the block size cannot be changed later.

7222:     For MATMPIAIJ and MATSEQAIJ matrix formats, this function can be called at a later stage, provided that the specified block sizes
7223:     are compatible with the matrix local sizes.

7225:     The row and column block size determine the blocksize of the "row" and "column" vectors returned by MatCreateVecs().

7227:    Level: intermediate

7229: .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSize(), MatSetBlockSize(), MatGetBlockSizes()
7230: @*/
7231: PetscErrorCode MatSetBlockSizes(Mat mat,PetscInt rbs,PetscInt cbs)
7232: {

7239:   if (mat->ops->setblocksizes) {
7240:     (*mat->ops->setblocksizes)(mat,rbs,cbs);
7241:   }
7242:   if (mat->rmap->refcnt) {
7243:     ISLocalToGlobalMapping l2g = NULL;
7244:     PetscLayout            nmap = NULL;

7246:     PetscLayoutDuplicate(mat->rmap,&nmap);
7247:     if (mat->rmap->mapping) {
7248:       ISLocalToGlobalMappingDuplicate(mat->rmap->mapping,&l2g);
7249:     }
7250:     PetscLayoutDestroy(&mat->rmap);
7251:     mat->rmap = nmap;
7252:     mat->rmap->mapping = l2g;
7253:   }
7254:   if (mat->cmap->refcnt) {
7255:     ISLocalToGlobalMapping l2g = NULL;
7256:     PetscLayout            nmap = NULL;

7258:     PetscLayoutDuplicate(mat->cmap,&nmap);
7259:     if (mat->cmap->mapping) {
7260:       ISLocalToGlobalMappingDuplicate(mat->cmap->mapping,&l2g);
7261:     }
7262:     PetscLayoutDestroy(&mat->cmap);
7263:     mat->cmap = nmap;
7264:     mat->cmap->mapping = l2g;
7265:   }
7266:   PetscLayoutSetBlockSize(mat->rmap,rbs);
7267:   PetscLayoutSetBlockSize(mat->cmap,cbs);
7268:   return(0);
7269: }

7271: /*@
7272:    MatSetBlockSizesFromMats - Sets the matrix block row and column sizes to match a pair of matrices

7274:    Logically Collective on Mat

7276:    Input Parameters:
7277: +  mat - the matrix
7278: .  fromRow - matrix from which to copy row block size
7279: -  fromCol - matrix from which to copy column block size (can be same as fromRow)

7281:    Level: developer

7283: .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSize(), MatSetBlockSizes()
7284: @*/
7285: PetscErrorCode MatSetBlockSizesFromMats(Mat mat,Mat fromRow,Mat fromCol)
7286: {

7293:   if (fromRow->rmap->bs > 0) {PetscLayoutSetBlockSize(mat->rmap,fromRow->rmap->bs);}
7294:   if (fromCol->cmap->bs > 0) {PetscLayoutSetBlockSize(mat->cmap,fromCol->cmap->bs);}
7295:   return(0);
7296: }

7298: /*@
7299:    MatResidual - Default routine to calculate the residual.

7301:    Collective on Mat

7303:    Input Parameters:
7304: +  mat - the matrix
7305: .  b   - the right-hand-side
7306: -  x   - the approximate solution

7308:    Output Parameter:
7309: .  r - location to store the residual

7311:    Level: developer

7313: .seealso: PCMGSetResidual()
7314: @*/
7315: PetscErrorCode MatResidual(Mat mat,Vec b,Vec x,Vec r)
7316: {

7325:   MatCheckPreallocated(mat,1);
7326:   PetscLogEventBegin(MAT_Residual,mat,0,0,0);
7327:   if (!mat->ops->residual) {
7328:     MatMult(mat,x,r);
7329:     VecAYPX(r,-1.0,b);
7330:   } else {
7331:     (*mat->ops->residual)(mat,b,x,r);
7332:   }
7333:   PetscLogEventEnd(MAT_Residual,mat,0,0,0);
7334:   return(0);
7335: }

7337: /*@C
7338:     MatGetRowIJ - Returns the compressed row storage i and j indices for sequential matrices.

7340:    Collective on Mat

7342:     Input Parameters:
7343: +   mat - the matrix
7344: .   shift -  0 or 1 indicating we want the indices starting at 0 or 1
7345: .   symmetric - PETSC_TRUE or PETSC_FALSE indicating the matrix data structure should be   symmetrized
7346: -   inodecompressed - PETSC_TRUE or PETSC_FALSE  indicating if the nonzero structure of the
7347:                  inodes or the nonzero elements is wanted. For BAIJ matrices the compressed version is
7348:                  always used.

7350:     Output Parameters:
7351: +   n - number of rows in the (possibly compressed) matrix
7352: .   ia - the row pointers; that is ia[0] = 0, ia[row] = ia[row-1] + number of elements in that row of the matrix
7353: .   ja - the column indices
7354: -   done - indicates if the routine actually worked and returned appropriate ia[] and ja[] arrays; callers
7355:            are responsible for handling the case when done == PETSC_FALSE and ia and ja are not set

7357:     Level: developer

7359:     Notes:
7360:     You CANNOT change any of the ia[] or ja[] values.

7362:     Use MatRestoreRowIJ() when you are finished accessing the ia[] and ja[] values.

7364:     Fortran Notes:
7365:     In Fortran use
7366: $
7367: $      PetscInt ia(1), ja(1)
7368: $      PetscOffset iia, jja
7369: $      call MatGetRowIJ(mat,shift,symmetric,inodecompressed,n,ia,iia,ja,jja,done,ierr)
7370: $      ! Access the ith and jth entries via ia(iia + i) and ja(jja + j)

7372:      or
7373: $
7374: $    PetscInt, pointer :: ia(:),ja(:)
7375: $    call MatGetRowIJF90(mat,shift,symmetric,inodecompressed,n,ia,ja,done,ierr)
7376: $    ! Access the ith and jth entries via ia(i) and ja(j)

7378: .seealso: MatGetColumnIJ(), MatRestoreRowIJ(), MatSeqAIJGetArray()
7379: @*/
7380: PetscErrorCode MatGetRowIJ(Mat mat,PetscInt shift,PetscBool symmetric,PetscBool inodecompressed,PetscInt *n,const PetscInt *ia[],const PetscInt *ja[],PetscBool  *done)
7381: {

7391:   MatCheckPreallocated(mat,1);
7392:   if (!mat->ops->getrowij) *done = PETSC_FALSE;
7393:   else {
7394:     *done = PETSC_TRUE;
7395:     PetscLogEventBegin(MAT_GetRowIJ,mat,0,0,0);
7396:     (*mat->ops->getrowij)(mat,shift,symmetric,inodecompressed,n,ia,ja,done);
7397:     PetscLogEventEnd(MAT_GetRowIJ,mat,0,0,0);
7398:   }
7399:   return(0);
7400: }

7402: /*@C
7403:     MatGetColumnIJ - Returns the compressed column storage i and j indices for sequential matrices.

7405:     Collective on Mat

7407:     Input Parameters:
7408: +   mat - the matrix
7409: .   shift - 1 or zero indicating we want the indices starting at 0 or 1
7410: .   symmetric - PETSC_TRUE or PETSC_FALSE indicating the matrix data structure should be
7411:                 symmetrized
7412: .   inodecompressed - PETSC_TRUE or PETSC_FALSE indicating if the nonzero structure of the
7413:                  inodes or the nonzero elements is wanted. For BAIJ matrices the compressed version is
7414:                  always used.
7415: .   n - number of columns in the (possibly compressed) matrix
7416: .   ia - the column pointers; that is ia[0] = 0, ia[col] = i[col-1] + number of elements in that col of the matrix
7417: -   ja - the row indices

7419:     Output Parameters:
7420: .   done - PETSC_TRUE or PETSC_FALSE, indicating whether the values have been returned

7422:     Level: developer

7424: .seealso: MatGetRowIJ(), MatRestoreColumnIJ()
7425: @*/
7426: PetscErrorCode MatGetColumnIJ(Mat mat,PetscInt shift,PetscBool symmetric,PetscBool inodecompressed,PetscInt *n,const PetscInt *ia[],const PetscInt *ja[],PetscBool  *done)
7427: {

7437:   MatCheckPreallocated(mat,1);
7438:   if (!mat->ops->getcolumnij) *done = PETSC_FALSE;
7439:   else {
7440:     *done = PETSC_TRUE;
7441:     (*mat->ops->getcolumnij)(mat,shift,symmetric,inodecompressed,n,ia,ja,done);
7442:   }
7443:   return(0);
7444: }

7446: /*@C
7447:     MatRestoreRowIJ - Call after you are completed with the ia,ja indices obtained with
7448:     MatGetRowIJ().

7450:     Collective on Mat

7452:     Input Parameters:
7453: +   mat - the matrix
7454: .   shift - 1 or zero indicating we want the indices starting at 0 or 1
7455: .   symmetric - PETSC_TRUE or PETSC_FALSE indicating the matrix data structure should be
7456:                 symmetrized
7457: .   inodecompressed -  PETSC_TRUE or PETSC_FALSE indicating if the nonzero structure of the
7458:                  inodes or the nonzero elements is wanted. For BAIJ matrices the compressed version is
7459:                  always used.
7460: .   n - size of (possibly compressed) matrix
7461: .   ia - the row pointers
7462: -   ja - the column indices

7464:     Output Parameters:
7465: .   done - PETSC_TRUE or PETSC_FALSE indicated that the values have been returned

7467:     Note:
7468:     This routine zeros out n, ia, and ja. This is to prevent accidental
7469:     us of the array after it has been restored. If you pass NULL, it will
7470:     not zero the pointers.  Use of ia or ja after MatRestoreRowIJ() is invalid.

7472:     Level: developer

7474: .seealso: MatGetRowIJ(), MatRestoreColumnIJ()
7475: @*/
7476: PetscErrorCode MatRestoreRowIJ(Mat mat,PetscInt shift,PetscBool symmetric,PetscBool inodecompressed,PetscInt *n,const PetscInt *ia[],const PetscInt *ja[],PetscBool  *done)
7477: {

7486:   MatCheckPreallocated(mat,1);

7488:   if (!mat->ops->restorerowij) *done = PETSC_FALSE;
7489:   else {
7490:     *done = PETSC_TRUE;
7491:     (*mat->ops->restorerowij)(mat,shift,symmetric,inodecompressed,n,ia,ja,done);
7492:     if (n)  *n = 0;
7493:     if (ia) *ia = NULL;
7494:     if (ja) *ja = NULL;
7495:   }
7496:   return(0);
7497: }

7499: /*@C
7500:     MatRestoreColumnIJ - Call after you are completed with the ia,ja indices obtained with
7501:     MatGetColumnIJ().

7503:     Collective on Mat

7505:     Input Parameters:
7506: +   mat - the matrix
7507: .   shift - 1 or zero indicating we want the indices starting at 0 or 1
7508: -   symmetric - PETSC_TRUE or PETSC_FALSE indicating the matrix data structure should be
7509:                 symmetrized
7510: -   inodecompressed - PETSC_TRUE or PETSC_FALSE indicating if the nonzero structure of the
7511:                  inodes or the nonzero elements is wanted. For BAIJ matrices the compressed version is
7512:                  always used.

7514:     Output Parameters:
7515: +   n - size of (possibly compressed) matrix
7516: .   ia - the column pointers
7517: .   ja - the row indices
7518: -   done - PETSC_TRUE or PETSC_FALSE indicated that the values have been returned

7520:     Level: developer

7522: .seealso: MatGetColumnIJ(), MatRestoreRowIJ()
7523: @*/
7524: PetscErrorCode MatRestoreColumnIJ(Mat mat,PetscInt shift,PetscBool symmetric,PetscBool inodecompressed,PetscInt *n,const PetscInt *ia[],const PetscInt *ja[],PetscBool  *done)
7525: {

7534:   MatCheckPreallocated(mat,1);

7536:   if (!mat->ops->restorecolumnij) *done = PETSC_FALSE;
7537:   else {
7538:     *done = PETSC_TRUE;
7539:     (*mat->ops->restorecolumnij)(mat,shift,symmetric,inodecompressed,n,ia,ja,done);
7540:     if (n)  *n = 0;
7541:     if (ia) *ia = NULL;
7542:     if (ja) *ja = NULL;
7543:   }
7544:   return(0);
7545: }

7547: /*@C
7548:     MatColoringPatch -Used inside matrix coloring routines that
7549:     use MatGetRowIJ() and/or MatGetColumnIJ().

7551:     Collective on Mat

7553:     Input Parameters:
7554: +   mat - the matrix
7555: .   ncolors - max color value
7556: .   n   - number of entries in colorarray
7557: -   colorarray - array indicating color for each column

7559:     Output Parameters:
7560: .   iscoloring - coloring generated using colorarray information

7562:     Level: developer

7564: .seealso: MatGetRowIJ(), MatGetColumnIJ()

7566: @*/
7567: PetscErrorCode MatColoringPatch(Mat mat,PetscInt ncolors,PetscInt n,ISColoringValue colorarray[],ISColoring *iscoloring)
7568: {

7576:   MatCheckPreallocated(mat,1);

7578:   if (!mat->ops->coloringpatch) {
7579:     ISColoringCreate(PetscObjectComm((PetscObject)mat),ncolors,n,colorarray,PETSC_OWN_POINTER,iscoloring);
7580:   } else {
7581:     (*mat->ops->coloringpatch)(mat,ncolors,n,colorarray,iscoloring);
7582:   }
7583:   return(0);
7584: }


7587: /*@
7588:    MatSetUnfactored - Resets a factored matrix to be treated as unfactored.

7590:    Logically Collective on Mat

7592:    Input Parameter:
7593: .  mat - the factored matrix to be reset

7595:    Notes:
7596:    This routine should be used only with factored matrices formed by in-place
7597:    factorization via ILU(0) (or by in-place LU factorization for the MATSEQDENSE
7598:    format).  This option can save memory, for example, when solving nonlinear
7599:    systems with a matrix-free Newton-Krylov method and a matrix-based, in-place
7600:    ILU(0) preconditioner.

7602:    Note that one can specify in-place ILU(0) factorization by calling
7603: .vb
7604:      PCType(pc,PCILU);
7605:      PCFactorSeUseInPlace(pc);
7606: .ve
7607:    or by using the options -pc_type ilu -pc_factor_in_place

7609:    In-place factorization ILU(0) can also be used as a local
7610:    solver for the blocks within the block Jacobi or additive Schwarz
7611:    methods (runtime option: -sub_pc_factor_in_place).  See Users-Manual: ch_pc
7612:    for details on setting local solver options.

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

7618:    Level: developer

7620: .seealso: PCFactorSetUseInPlace(), PCFactorGetUseInPlace()

7622: @*/
7623: PetscErrorCode MatSetUnfactored(Mat mat)
7624: {

7630:   MatCheckPreallocated(mat,1);
7631:   mat->factortype = MAT_FACTOR_NONE;
7632:   if (!mat->ops->setunfactored) return(0);
7633:   (*mat->ops->setunfactored)(mat);
7634:   return(0);
7635: }

7637: /*MC
7638:     MatDenseGetArrayF90 - Accesses a matrix array from Fortran90.

7640:     Synopsis:
7641:     MatDenseGetArrayF90(Mat x,{Scalar, pointer :: xx_v(:,:)},integer ierr)

7643:     Not collective

7645:     Input Parameter:
7646: .   x - matrix

7648:     Output Parameters:
7649: +   xx_v - the Fortran90 pointer to the array
7650: -   ierr - error code

7652:     Example of Usage:
7653: .vb
7654:       PetscScalar, pointer xx_v(:,:)
7655:       ....
7656:       call MatDenseGetArrayF90(x,xx_v,ierr)
7657:       a = xx_v(3)
7658:       call MatDenseRestoreArrayF90(x,xx_v,ierr)
7659: .ve

7661:     Level: advanced

7663: .seealso:  MatDenseRestoreArrayF90(), MatDenseGetArray(), MatDenseRestoreArray(), MatSeqAIJGetArrayF90()

7665: M*/

7667: /*MC
7668:     MatDenseRestoreArrayF90 - Restores a matrix array that has been
7669:     accessed with MatDenseGetArrayF90().

7671:     Synopsis:
7672:     MatDenseRestoreArrayF90(Mat x,{Scalar, pointer :: xx_v(:,:)},integer ierr)

7674:     Not collective

7676:     Input Parameters:
7677: +   x - matrix
7678: -   xx_v - the Fortran90 pointer to the array

7680:     Output Parameter:
7681: .   ierr - error code

7683:     Example of Usage:
7684: .vb
7685:        PetscScalar, pointer xx_v(:,:)
7686:        ....
7687:        call MatDenseGetArrayF90(x,xx_v,ierr)
7688:        a = xx_v(3)
7689:        call MatDenseRestoreArrayF90(x,xx_v,ierr)
7690: .ve

7692:     Level: advanced

7694: .seealso:  MatDenseGetArrayF90(), MatDenseGetArray(), MatDenseRestoreArray(), MatSeqAIJRestoreArrayF90()

7696: M*/


7699: /*MC
7700:     MatSeqAIJGetArrayF90 - Accesses a matrix array from Fortran90.

7702:     Synopsis:
7703:     MatSeqAIJGetArrayF90(Mat x,{Scalar, pointer :: xx_v(:)},integer ierr)

7705:     Not collective

7707:     Input Parameter:
7708: .   x - matrix

7710:     Output Parameters:
7711: +   xx_v - the Fortran90 pointer to the array
7712: -   ierr - error code

7714:     Example of Usage:
7715: .vb
7716:       PetscScalar, pointer xx_v(:)
7717:       ....
7718:       call MatSeqAIJGetArrayF90(x,xx_v,ierr)
7719:       a = xx_v(3)
7720:       call MatSeqAIJRestoreArrayF90(x,xx_v,ierr)
7721: .ve

7723:     Level: advanced

7725: .seealso:  MatSeqAIJRestoreArrayF90(), MatSeqAIJGetArray(), MatSeqAIJRestoreArray(), MatDenseGetArrayF90()

7727: M*/

7729: /*MC
7730:     MatSeqAIJRestoreArrayF90 - Restores a matrix array that has been
7731:     accessed with MatSeqAIJGetArrayF90().

7733:     Synopsis:
7734:     MatSeqAIJRestoreArrayF90(Mat x,{Scalar, pointer :: xx_v(:)},integer ierr)

7736:     Not collective

7738:     Input Parameters:
7739: +   x - matrix
7740: -   xx_v - the Fortran90 pointer to the array

7742:     Output Parameter:
7743: .   ierr - error code

7745:     Example of Usage:
7746: .vb
7747:        PetscScalar, pointer xx_v(:)
7748:        ....
7749:        call MatSeqAIJGetArrayF90(x,xx_v,ierr)
7750:        a = xx_v(3)
7751:        call MatSeqAIJRestoreArrayF90(x,xx_v,ierr)
7752: .ve

7754:     Level: advanced

7756: .seealso:  MatSeqAIJGetArrayF90(), MatSeqAIJGetArray(), MatSeqAIJRestoreArray(), MatDenseRestoreArrayF90()

7758: M*/


7761: /*@
7762:     MatCreateSubMatrix - Gets a single submatrix on the same number of processors
7763:                       as the original matrix.

7765:     Collective on Mat

7767:     Input Parameters:
7768: +   mat - the original matrix
7769: .   isrow - parallel IS containing the rows this processor should obtain
7770: .   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.
7771: -   cll - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX

7773:     Output Parameter:
7774: .   newmat - the new submatrix, of the same type as the old

7776:     Level: advanced

7778:     Notes:
7779:     The submatrix will be able to be multiplied with vectors using the same layout as iscol.

7781:     Some matrix types place restrictions on the row and column indices, such
7782:     as that they be sorted or that they be equal to each other.

7784:     The index sets may not have duplicate entries.

7786:       The first time this is called you should use a cll of MAT_INITIAL_MATRIX,
7787:    the MatCreateSubMatrix() routine will create the newmat for you. Any additional calls
7788:    to this routine with a mat of the same nonzero structure and with a call of MAT_REUSE_MATRIX
7789:    will reuse the matrix generated the first time.  You should call MatDestroy() on newmat when
7790:    you are finished using it.

7792:     The communicator of the newly obtained matrix is ALWAYS the same as the communicator of
7793:     the input matrix.

7795:     If iscol is NULL then all columns are obtained (not supported in Fortran).

7797:    Example usage:
7798:    Consider the following 8x8 matrix with 34 non-zero values, that is
7799:    assembled across 3 processors. Let's assume that proc0 owns 3 rows,
7800:    proc1 owns 3 rows, proc2 owns 2 rows. This division can be shown
7801:    as follows:

7803: .vb
7804:             1  2  0  |  0  3  0  |  0  4
7805:     Proc0   0  5  6  |  7  0  0  |  8  0
7806:             9  0 10  | 11  0  0  | 12  0
7807:     -------------------------------------
7808:            13  0 14  | 15 16 17  |  0  0
7809:     Proc1   0 18  0  | 19 20 21  |  0  0
7810:             0  0  0  | 22 23  0  | 24  0
7811:     -------------------------------------
7812:     Proc2  25 26 27  |  0  0 28  | 29  0
7813:            30  0  0  | 31 32 33  |  0 34
7814: .ve

7816:     Suppose isrow = [0 1 | 4 | 6 7] and iscol = [1 2 | 3 4 5 | 6].  The resulting submatrix is

7818: .vb
7819:             2  0  |  0  3  0  |  0
7820:     Proc0   5  6  |  7  0  0  |  8
7821:     -------------------------------
7822:     Proc1  18  0  | 19 20 21  |  0
7823:     -------------------------------
7824:     Proc2  26 27  |  0  0 28  | 29
7825:             0  0  | 31 32 33  |  0
7826: .ve


7829: .seealso: MatCreateSubMatrices(), MatCreateSubMatricesMPI(), MatCreateSubMatrixVirtual(), MatSubMatrixVirtualUpdate()
7830: @*/
7831: PetscErrorCode MatCreateSubMatrix(Mat mat,IS isrow,IS iscol,MatReuse cll,Mat *newmat)
7832: {
7834:   PetscMPIInt    size;
7835:   Mat            *local;
7836:   IS             iscoltmp;
7837:   PetscBool      flg;

7846:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
7847:   if (cll == MAT_IGNORE_MATRIX) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Cannot use MAT_IGNORE_MATRIX");

7849:   MatCheckPreallocated(mat,1);
7850:   MPI_Comm_size(PetscObjectComm((PetscObject)mat),&size);

7852:   if (!iscol || isrow == iscol) {
7853:     PetscBool   stride;
7854:     PetscMPIInt grabentirematrix = 0,grab;
7855:     PetscObjectTypeCompare((PetscObject)isrow,ISSTRIDE,&stride);
7856:     if (stride) {
7857:       PetscInt first,step,n,rstart,rend;
7858:       ISStrideGetInfo(isrow,&first,&step);
7859:       if (step == 1) {
7860:         MatGetOwnershipRange(mat,&rstart,&rend);
7861:         if (rstart == first) {
7862:           ISGetLocalSize(isrow,&n);
7863:           if (n == rend-rstart) {
7864:             grabentirematrix = 1;
7865:           }
7866:         }
7867:       }
7868:     }
7869:     MPIU_Allreduce(&grabentirematrix,&grab,1,MPI_INT,MPI_MIN,PetscObjectComm((PetscObject)mat));
7870:     if (grab) {
7871:       PetscInfo(mat,"Getting entire matrix as submatrix\n");
7872:       if (cll == MAT_INITIAL_MATRIX) {
7873:         *newmat = mat;
7874:         PetscObjectReference((PetscObject)mat);
7875:       }
7876:       return(0);
7877:     }
7878:   }

7880:   if (!iscol) {
7881:     ISCreateStride(PetscObjectComm((PetscObject)mat),mat->cmap->n,mat->cmap->rstart,1,&iscoltmp);
7882:   } else {
7883:     iscoltmp = iscol;
7884:   }

7886:   /* if original matrix is on just one processor then use submatrix generated */
7887:   if (mat->ops->createsubmatrices && !mat->ops->createsubmatrix && size == 1 && cll == MAT_REUSE_MATRIX) {
7888:     MatCreateSubMatrices(mat,1,&isrow,&iscoltmp,MAT_REUSE_MATRIX,&newmat);
7889:     goto setproperties;
7890:   } else if (mat->ops->createsubmatrices && !mat->ops->createsubmatrix && size == 1) {
7891:     MatCreateSubMatrices(mat,1,&isrow,&iscoltmp,MAT_INITIAL_MATRIX,&local);
7892:     *newmat = *local;
7893:     PetscFree(local);
7894:     goto setproperties;
7895:   } else if (!mat->ops->createsubmatrix) {
7896:     /* Create a new matrix type that implements the operation using the full matrix */
7897:     PetscLogEventBegin(MAT_CreateSubMat,mat,0,0,0);
7898:     switch (cll) {
7899:     case MAT_INITIAL_MATRIX:
7900:       MatCreateSubMatrixVirtual(mat,isrow,iscoltmp,newmat);
7901:       break;
7902:     case MAT_REUSE_MATRIX:
7903:       MatSubMatrixVirtualUpdate(*newmat,mat,isrow,iscoltmp);
7904:       break;
7905:     default: SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_OUTOFRANGE,"Invalid MatReuse, must be either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX");
7906:     }
7907:     PetscLogEventEnd(MAT_CreateSubMat,mat,0,0,0);
7908:     goto setproperties;
7909:   }

7911:   if (!mat->ops->createsubmatrix) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
7912:   PetscLogEventBegin(MAT_CreateSubMat,mat,0,0,0);
7913:   (*mat->ops->createsubmatrix)(mat,isrow,iscoltmp,cll,newmat);
7914:   PetscLogEventEnd(MAT_CreateSubMat,mat,0,0,0);

7916: setproperties:
7917:   ISEqualUnsorted(isrow,iscoltmp,&flg);
7918:   if (flg) {
7919:     MatPropagateSymmetryOptions(mat,*newmat);
7920:   }
7921:   if (!iscol) {ISDestroy(&iscoltmp);}
7922:   if (*newmat && cll == MAT_INITIAL_MATRIX) {PetscObjectStateIncrease((PetscObject)*newmat);}
7923:   return(0);
7924: }

7926: /*@
7927:    MatPropagateSymmetryOptions - Propagates symmetry options set on a matrix to another matrix

7929:    Not Collective

7931:    Input Parameters:
7932: +  A - the matrix we wish to propagate options from
7933: -  B - the matrix we wish to propagate options to

7935:    Level: beginner

7937:    Notes: Propagates the options associated to MAT_SYMMETRY_ETERNAL, MAT_STRUCTURALLY_SYMMETRIC, MAT_HERMITIAN, MAT_SPD and MAT_SYMMETRIC

7939: .seealso: MatSetOption()
7940: @*/
7941: PetscErrorCode MatPropagateSymmetryOptions(Mat A, Mat B)
7942: {

7948:   if (A->symmetric_eternal) { /* symmetric_eternal does not have a corresponding *set flag */
7949:     MatSetOption(B,MAT_SYMMETRY_ETERNAL,A->symmetric_eternal);
7950:   }
7951:   if (A->structurally_symmetric_set) {
7952:     MatSetOption(B,MAT_STRUCTURALLY_SYMMETRIC,A->structurally_symmetric);
7953:   }
7954:   if (A->hermitian_set) {
7955:     MatSetOption(B,MAT_HERMITIAN,A->hermitian);
7956:   }
7957:   if (A->spd_set) {
7958:     MatSetOption(B,MAT_SPD,A->spd);
7959:   }
7960:   if (A->symmetric_set) {
7961:     MatSetOption(B,MAT_SYMMETRIC,A->symmetric);
7962:   }
7963:   return(0);
7964: }

7966: /*@
7967:    MatStashSetInitialSize - sets the sizes of the matrix stash, that is
7968:    used during the assembly process to store values that belong to
7969:    other processors.

7971:    Not Collective

7973:    Input Parameters:
7974: +  mat   - the matrix
7975: .  size  - the initial size of the stash.
7976: -  bsize - the initial size of the block-stash(if used).

7978:    Options Database Keys:
7979: +   -matstash_initial_size <size> or <size0,size1,...sizep-1>
7980: -   -matstash_block_initial_size <bsize>  or <bsize0,bsize1,...bsizep-1>

7982:    Level: intermediate

7984:    Notes:
7985:      The block-stash is used for values set with MatSetValuesBlocked() while
7986:      the stash is used for values set with MatSetValues()

7988:      Run with the option -info and look for output of the form
7989:      MatAssemblyBegin_MPIXXX:Stash has MM entries, uses nn mallocs.
7990:      to determine the appropriate value, MM, to use for size and
7991:      MatAssemblyBegin_MPIXXX:Block-Stash has BMM entries, uses nn mallocs.
7992:      to determine the value, BMM to use for bsize


7995: .seealso: MatAssemblyBegin(), MatAssemblyEnd(), Mat, MatStashGetInfo()

7997: @*/
7998: PetscErrorCode MatStashSetInitialSize(Mat mat,PetscInt size, PetscInt bsize)
7999: {

8005:   MatStashSetInitialSize_Private(&mat->stash,size);
8006:   MatStashSetInitialSize_Private(&mat->bstash,bsize);
8007:   return(0);
8008: }

8010: /*@
8011:    MatInterpolateAdd - w = y + A*x or A'*x depending on the shape of
8012:      the matrix

8014:    Neighbor-wise Collective on Mat

8016:    Input Parameters:
8017: +  mat   - the matrix
8018: .  x,y - the vectors
8019: -  w - where the result is stored

8021:    Level: intermediate

8023:    Notes:
8024:     w may be the same vector as y.

8026:     This allows one to use either the restriction or interpolation (its transpose)
8027:     matrix to do the interpolation

8029: .seealso: MatMultAdd(), MatMultTransposeAdd(), MatRestrict()

8031: @*/
8032: PetscErrorCode MatInterpolateAdd(Mat A,Vec x,Vec y,Vec w)
8033: {
8035:   PetscInt       M,N,Ny;

8043:   MatCheckPreallocated(A,1);
8044:   MatGetSize(A,&M,&N);
8045:   VecGetSize(y,&Ny);
8046:   if (M == Ny) {
8047:     MatMultAdd(A,x,y,w);
8048:   } else {
8049:     MatMultTransposeAdd(A,x,y,w);
8050:   }
8051:   return(0);
8052: }

8054: /*@
8055:    MatInterpolate - y = A*x or A'*x depending on the shape of
8056:      the matrix

8058:    Neighbor-wise Collective on Mat

8060:    Input Parameters:
8061: +  mat   - the matrix
8062: -  x,y - the vectors

8064:    Level: intermediate

8066:    Notes:
8067:     This allows one to use either the restriction or interpolation (its transpose)
8068:     matrix to do the interpolation

8070: .seealso: MatMultAdd(), MatMultTransposeAdd(), MatRestrict()

8072: @*/
8073: PetscErrorCode MatInterpolate(Mat A,Vec x,Vec y)
8074: {
8076:   PetscInt       M,N,Ny;

8083:   MatCheckPreallocated(A,1);
8084:   MatGetSize(A,&M,&N);
8085:   VecGetSize(y,&Ny);
8086:   if (M == Ny) {
8087:     MatMult(A,x,y);
8088:   } else {
8089:     MatMultTranspose(A,x,y);
8090:   }
8091:   return(0);
8092: }

8094: /*@
8095:    MatRestrict - y = A*x or A'*x

8097:    Neighbor-wise Collective on Mat

8099:    Input Parameters:
8100: +  mat   - the matrix
8101: -  x,y - the vectors

8103:    Level: intermediate

8105:    Notes:
8106:     This allows one to use either the restriction or interpolation (its transpose)
8107:     matrix to do the restriction

8109: .seealso: MatMultAdd(), MatMultTransposeAdd(), MatInterpolate()

8111: @*/
8112: PetscErrorCode MatRestrict(Mat A,Vec x,Vec y)
8113: {
8115:   PetscInt       M,N,Ny;

8122:   MatCheckPreallocated(A,1);

8124:   MatGetSize(A,&M,&N);
8125:   VecGetSize(y,&Ny);
8126:   if (M == Ny) {
8127:     MatMult(A,x,y);
8128:   } else {
8129:     MatMultTranspose(A,x,y);
8130:   }
8131:   return(0);
8132: }

8134: /*@
8135:    MatGetNullSpace - retrieves the null space of a matrix.

8137:    Logically Collective on Mat

8139:    Input Parameters:
8140: +  mat - the matrix
8141: -  nullsp - the null space object

8143:    Level: developer

8145: .seealso: MatCreate(), MatNullSpaceCreate(), MatSetNearNullSpace(), MatSetNullSpace()
8146: @*/
8147: PetscErrorCode MatGetNullSpace(Mat mat, MatNullSpace *nullsp)
8148: {
8152:   *nullsp = (mat->symmetric_set && mat->symmetric && !mat->nullsp) ? mat->transnullsp : mat->nullsp;
8153:   return(0);
8154: }

8156: /*@
8157:    MatSetNullSpace - attaches a null space to a matrix.

8159:    Logically Collective on Mat

8161:    Input Parameters:
8162: +  mat - the matrix
8163: -  nullsp - the null space object

8165:    Level: advanced

8167:    Notes:
8168:       This null space is used by the linear solvers. Overwrites any previous null space that may have been attached

8170:       For inconsistent singular systems (linear systems where the right hand side is not in the range of the operator) you also likely should
8171:       call MatSetTransposeNullSpace(). This allows the linear system to be solved in a least squares sense.

8173:       You can remove the null space by calling this routine with an nullsp of NULL


8176:       The fundamental theorem of linear algebra (Gilbert Strang, Introduction to Applied Mathematics, page 72) states that
8177:    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).
8178:    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
8179:    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
8180:    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).

8182:       Krylov solvers can produce the minimal norm solution to the least squares problem by utilizing MatNullSpaceRemove().

8184:     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
8185:     routine also automatically calls MatSetTransposeNullSpace().

8187: .seealso: MatCreate(), MatNullSpaceCreate(), MatSetNearNullSpace(), MatGetNullSpace(), MatSetTransposeNullSpace(), MatGetTransposeNullSpace(), MatNullSpaceRemove()
8188: @*/
8189: PetscErrorCode MatSetNullSpace(Mat mat,MatNullSpace nullsp)
8190: {

8196:   if (nullsp) {PetscObjectReference((PetscObject)nullsp);}
8197:   MatNullSpaceDestroy(&mat->nullsp);
8198:   mat->nullsp = nullsp;
8199:   if (mat->symmetric_set && mat->symmetric) {
8200:     MatSetTransposeNullSpace(mat,nullsp);
8201:   }
8202:   return(0);
8203: }

8205: /*@
8206:    MatGetTransposeNullSpace - retrieves the null space of the transpose of a matrix.

8208:    Logically Collective on Mat

8210:    Input Parameters:
8211: +  mat - the matrix
8212: -  nullsp - the null space object

8214:    Level: developer

8216: .seealso: MatCreate(), MatNullSpaceCreate(), MatSetNearNullSpace(), MatSetTransposeNullSpace(), MatSetNullSpace(), MatGetNullSpace()
8217: @*/
8218: PetscErrorCode MatGetTransposeNullSpace(Mat mat, MatNullSpace *nullsp)
8219: {
8224:   *nullsp = (mat->symmetric_set && mat->symmetric && !mat->transnullsp) ? mat->nullsp : mat->transnullsp;
8225:   return(0);
8226: }

8228: /*@
8229:    MatSetTransposeNullSpace - attaches a null space to a matrix.

8231:    Logically Collective on Mat

8233:    Input Parameters:
8234: +  mat - the matrix
8235: -  nullsp - the null space object

8237:    Level: advanced

8239:    Notes:
8240:       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.
8241:       You must also call MatSetNullSpace()


8244:       The fundamental theorem of linear algebra (Gilbert Strang, Introduction to Applied Mathematics, page 72) states that
8245:    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).
8246:    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
8247:    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
8248:    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).

8250:       Krylov solvers can produce the minimal norm solution to the least squares problem by utilizing MatNullSpaceRemove().

8252: .seealso: MatCreate(), MatNullSpaceCreate(), MatSetNearNullSpace(), MatGetNullSpace(), MatSetNullSpace(), MatGetTransposeNullSpace(), MatNullSpaceRemove()
8253: @*/
8254: PetscErrorCode MatSetTransposeNullSpace(Mat mat,MatNullSpace nullsp)
8255: {

8261:   if (nullsp) {PetscObjectReference((PetscObject)nullsp);}
8262:   MatNullSpaceDestroy(&mat->transnullsp);
8263:   mat->transnullsp = nullsp;
8264:   return(0);
8265: }

8267: /*@
8268:    MatSetNearNullSpace - attaches a null space to a matrix, which is often the null space (rigid body modes) of the operator without boundary conditions
8269:         This null space will be used to provide near null space vectors to a multigrid preconditioner built from this matrix.

8271:    Logically Collective on Mat

8273:    Input Parameters:
8274: +  mat - the matrix
8275: -  nullsp - the null space object

8277:    Level: advanced

8279:    Notes:
8280:       Overwrites any previous near null space that may have been attached

8282:       You can remove the null space by calling this routine with an nullsp of NULL

8284: .seealso: MatCreate(), MatNullSpaceCreate(), MatSetNullSpace(), MatNullSpaceCreateRigidBody(), MatGetNearNullSpace()
8285: @*/
8286: PetscErrorCode MatSetNearNullSpace(Mat mat,MatNullSpace nullsp)
8287: {

8294:   MatCheckPreallocated(mat,1);
8295:   if (nullsp) {PetscObjectReference((PetscObject)nullsp);}
8296:   MatNullSpaceDestroy(&mat->nearnullsp);
8297:   mat->nearnullsp = nullsp;
8298:   return(0);
8299: }

8301: /*@
8302:    MatGetNearNullSpace - Get null space attached with MatSetNearNullSpace()

8304:    Not Collective

8306:    Input Parameter:
8307: .  mat - the matrix

8309:    Output Parameter:
8310: .  nullsp - the null space object, NULL if not set

8312:    Level: developer

8314: .seealso: MatSetNearNullSpace(), MatGetNullSpace(), MatNullSpaceCreate()
8315: @*/
8316: PetscErrorCode MatGetNearNullSpace(Mat mat,MatNullSpace *nullsp)
8317: {
8322:   MatCheckPreallocated(mat,1);
8323:   *nullsp = mat->nearnullsp;
8324:   return(0);
8325: }

8327: /*@C
8328:    MatICCFactor - Performs in-place incomplete Cholesky factorization of matrix.

8330:    Collective on Mat

8332:    Input Parameters:
8333: +  mat - the matrix
8334: .  row - row/column permutation
8335: .  fill - expected fill factor >= 1.0
8336: -  level - level of fill, for ICC(k)

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

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

8346:    Level: developer


8349: .seealso: MatICCFactorSymbolic(), MatLUFactorNumeric(), MatCholeskyFactor()

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

8354: @*/
8355: PetscErrorCode MatICCFactor(Mat mat,IS row,const MatFactorInfo *info)
8356: {

8364:   if (mat->rmap->N != mat->cmap->N) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONG,"matrix must be square");
8365:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
8366:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
8367:   if (!mat->ops->iccfactor) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
8368:   MatCheckPreallocated(mat,1);
8369:   (*mat->ops->iccfactor)(mat,row,info);
8370:   PetscObjectStateIncrease((PetscObject)mat);
8371:   return(0);
8372: }

8374: /*@
8375:    MatDiagonalScaleLocal - Scales columns of a matrix given the scaling values including the
8376:          ghosted ones.

8378:    Not Collective

8380:    Input Parameters:
8381: +  mat - the matrix
8382: -  diag = the diagonal values, including ghost ones

8384:    Level: developer

8386:    Notes:
8387:     Works only for MPIAIJ and MPIBAIJ matrices

8389: .seealso: MatDiagonalScale()
8390: @*/
8391: PetscErrorCode MatDiagonalScaleLocal(Mat mat,Vec diag)
8392: {
8394:   PetscMPIInt    size;


8401:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Matrix must be already assembled");
8402:   PetscLogEventBegin(MAT_Scale,mat,0,0,0);
8403:   MPI_Comm_size(PetscObjectComm((PetscObject)mat),&size);
8404:   if (size == 1) {
8405:     PetscInt n,m;
8406:     VecGetSize(diag,&n);
8407:     MatGetSize(mat,0,&m);
8408:     if (m == n) {
8409:       MatDiagonalScale(mat,0,diag);
8410:     } else SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"Only supported for sequential matrices when no ghost points/periodic conditions");
8411:   } else {
8412:     PetscUseMethod(mat,"MatDiagonalScaleLocal_C",(Mat,Vec),(mat,diag));
8413:   }
8414:   PetscLogEventEnd(MAT_Scale,mat,0,0,0);
8415:   PetscObjectStateIncrease((PetscObject)mat);
8416:   return(0);
8417: }

8419: /*@
8420:    MatGetInertia - Gets the inertia from a factored matrix

8422:    Collective on Mat

8424:    Input Parameter:
8425: .  mat - the matrix

8427:    Output Parameters:
8428: +   nneg - number of negative eigenvalues
8429: .   nzero - number of zero eigenvalues
8430: -   npos - number of positive eigenvalues

8432:    Level: advanced

8434:    Notes:
8435:     Matrix must have been factored by MatCholeskyFactor()


8438: @*/
8439: PetscErrorCode MatGetInertia(Mat mat,PetscInt *nneg,PetscInt *nzero,PetscInt *npos)
8440: {

8446:   if (!mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
8447:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Numeric factor mat is not assembled");
8448:   if (!mat->ops->getinertia) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
8449:   (*mat->ops->getinertia)(mat,nneg,nzero,npos);
8450:   return(0);
8451: }

8453: /* ----------------------------------------------------------------*/
8454: /*@C
8455:    MatSolves - Solves A x = b, given a factored matrix, for a collection of vectors

8457:    Neighbor-wise Collective on Mats

8459:    Input Parameters:
8460: +  mat - the factored matrix
8461: -  b - the right-hand-side vectors

8463:    Output Parameter:
8464: .  x - the result vectors

8466:    Notes:
8467:    The vectors b and x cannot be the same.  I.e., one cannot
8468:    call MatSolves(A,x,x).

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

8475:    Level: developer

8477: .seealso: MatSolveAdd(), MatSolveTranspose(), MatSolveTransposeAdd(), MatSolve()
8478: @*/
8479: PetscErrorCode MatSolves(Mat mat,Vecs b,Vecs x)
8480: {

8486:   if (x == b) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"x and b must be different vectors");
8487:   if (!mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
8488:   if (!mat->rmap->N && !mat->cmap->N) return(0);

8490:   if (!mat->ops->solves) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
8491:   MatCheckPreallocated(mat,1);
8492:   PetscLogEventBegin(MAT_Solves,mat,0,0,0);
8493:   (*mat->ops->solves)(mat,b,x);
8494:   PetscLogEventEnd(MAT_Solves,mat,0,0,0);
8495:   return(0);
8496: }

8498: /*@
8499:    MatIsSymmetric - Test whether a matrix is symmetric

8501:    Collective on Mat

8503:    Input Parameter:
8504: +  A - the matrix to test
8505: -  tol - difference between value and its transpose less than this amount counts as equal (use 0.0 for exact transpose)

8507:    Output Parameters:
8508: .  flg - the result

8510:    Notes:
8511:     For real numbers MatIsSymmetric() and MatIsHermitian() return identical results

8513:    Level: intermediate

8515: .seealso: MatTranspose(), MatIsTranspose(), MatIsHermitian(), MatIsStructurallySymmetric(), MatSetOption(), MatIsSymmetricKnown()
8516: @*/
8517: PetscErrorCode MatIsSymmetric(Mat A,PetscReal tol,PetscBool  *flg)
8518: {


8525:   if (!A->symmetric_set) {
8526:     if (!A->ops->issymmetric) {
8527:       MatType mattype;
8528:       MatGetType(A,&mattype);
8529:       SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Matrix of type %s does not support checking for symmetric",mattype);
8530:     }
8531:     (*A->ops->issymmetric)(A,tol,flg);
8532:     if (!tol) {
8533:       MatSetOption(A,MAT_SYMMETRIC,*flg);
8534:     }
8535:   } else if (A->symmetric) {
8536:     *flg = PETSC_TRUE;
8537:   } else if (!tol) {
8538:     *flg = PETSC_FALSE;
8539:   } else {
8540:     if (!A->ops->issymmetric) {
8541:       MatType mattype;
8542:       MatGetType(A,&mattype);
8543:       SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Matrix of type %s does not support checking for symmetric",mattype);
8544:     }
8545:     (*A->ops->issymmetric)(A,tol,flg);
8546:   }
8547:   return(0);
8548: }

8550: /*@
8551:    MatIsHermitian - Test whether a matrix is Hermitian

8553:    Collective on Mat

8555:    Input Parameter:
8556: +  A - the matrix to test
8557: -  tol - difference between value and its transpose less than this amount counts as equal (use 0.0 for exact Hermitian)

8559:    Output Parameters:
8560: .  flg - the result

8562:    Level: intermediate

8564: .seealso: MatTranspose(), MatIsTranspose(), MatIsHermitian(), MatIsStructurallySymmetric(), MatSetOption(),
8565:           MatIsSymmetricKnown(), MatIsSymmetric()
8566: @*/
8567: PetscErrorCode MatIsHermitian(Mat A,PetscReal tol,PetscBool  *flg)
8568: {


8575:   if (!A->hermitian_set) {
8576:     if (!A->ops->ishermitian) {
8577:       MatType mattype;
8578:       MatGetType(A,&mattype);
8579:       SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Matrix of type %s does not support checking for hermitian",mattype);
8580:     }
8581:     (*A->ops->ishermitian)(A,tol,flg);
8582:     if (!tol) {
8583:       MatSetOption(A,MAT_HERMITIAN,*flg);
8584:     }
8585:   } else if (A->hermitian) {
8586:     *flg = PETSC_TRUE;
8587:   } else if (!tol) {
8588:     *flg = PETSC_FALSE;
8589:   } else {
8590:     if (!A->ops->ishermitian) {
8591:       MatType mattype;
8592:       MatGetType(A,&mattype);
8593:       SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Matrix of type %s does not support checking for hermitian",mattype);
8594:     }
8595:     (*A->ops->ishermitian)(A,tol,flg);
8596:   }
8597:   return(0);
8598: }

8600: /*@
8601:    MatIsSymmetricKnown - Checks the flag on the matrix to see if it is symmetric.

8603:    Not Collective

8605:    Input Parameter:
8606: .  A - the matrix to check

8608:    Output Parameters:
8609: +  set - if the symmetric flag is set (this tells you if the next flag is valid)
8610: -  flg - the result

8612:    Level: advanced

8614:    Note: Does not check the matrix values directly, so this may return unknown (set = PETSC_FALSE). Use MatIsSymmetric()
8615:          if you want it explicitly checked

8617: .seealso: MatTranspose(), MatIsTranspose(), MatIsHermitian(), MatIsStructurallySymmetric(), MatSetOption(), MatIsSymmetric()
8618: @*/
8619: PetscErrorCode MatIsSymmetricKnown(Mat A,PetscBool *set,PetscBool *flg)
8620: {
8625:   if (A->symmetric_set) {
8626:     *set = PETSC_TRUE;
8627:     *flg = A->symmetric;
8628:   } else {
8629:     *set = PETSC_FALSE;
8630:   }
8631:   return(0);
8632: }

8634: /*@
8635:    MatIsHermitianKnown - Checks the flag on the matrix to see if it is hermitian.

8637:    Not Collective

8639:    Input Parameter:
8640: .  A - the matrix to check

8642:    Output Parameters:
8643: +  set - if the hermitian flag is set (this tells you if the next flag is valid)
8644: -  flg - the result

8646:    Level: advanced

8648:    Note: Does not check the matrix values directly, so this may return unknown (set = PETSC_FALSE). Use MatIsHermitian()
8649:          if you want it explicitly checked

8651: .seealso: MatTranspose(), MatIsTranspose(), MatIsHermitian(), MatIsStructurallySymmetric(), MatSetOption(), MatIsSymmetric()
8652: @*/
8653: PetscErrorCode MatIsHermitianKnown(Mat A,PetscBool *set,PetscBool *flg)
8654: {
8659:   if (A->hermitian_set) {
8660:     *set = PETSC_TRUE;
8661:     *flg = A->hermitian;
8662:   } else {
8663:     *set = PETSC_FALSE;
8664:   }
8665:   return(0);
8666: }

8668: /*@
8669:    MatIsStructurallySymmetric - Test whether a matrix is structurally symmetric

8671:    Collective on Mat

8673:    Input Parameter:
8674: .  A - the matrix to test

8676:    Output Parameters:
8677: .  flg - the result

8679:    Level: intermediate

8681: .seealso: MatTranspose(), MatIsTranspose(), MatIsHermitian(), MatIsSymmetric(), MatSetOption()
8682: @*/
8683: PetscErrorCode MatIsStructurallySymmetric(Mat A,PetscBool *flg)
8684: {

8690:   if (!A->structurally_symmetric_set) {
8691:     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);
8692:     (*A->ops->isstructurallysymmetric)(A,flg);
8693:     MatSetOption(A,MAT_STRUCTURALLY_SYMMETRIC,*flg);
8694:   } else *flg = A->structurally_symmetric;
8695:   return(0);
8696: }

8698: /*@
8699:    MatStashGetInfo - Gets how many values are currently in the matrix stash, i.e. need
8700:        to be communicated to other processors during the MatAssemblyBegin/End() process

8702:     Not collective

8704:    Input Parameter:
8705: .   vec - the vector

8707:    Output Parameters:
8708: +   nstash   - the size of the stash
8709: .   reallocs - the number of additional mallocs incurred.
8710: .   bnstash   - the size of the block stash
8711: -   breallocs - the number of additional mallocs incurred.in the block stash

8713:    Level: advanced

8715: .seealso: MatAssemblyBegin(), MatAssemblyEnd(), Mat, MatStashSetInitialSize()

8717: @*/
8718: PetscErrorCode MatStashGetInfo(Mat mat,PetscInt *nstash,PetscInt *reallocs,PetscInt *bnstash,PetscInt *breallocs)
8719: {

8723:   MatStashGetInfo_Private(&mat->stash,nstash,reallocs);
8724:   MatStashGetInfo_Private(&mat->bstash,bnstash,breallocs);
8725:   return(0);
8726: }

8728: /*@C
8729:    MatCreateVecs - Get vector(s) compatible with the matrix, i.e. with the same
8730:      parallel layout

8732:    Collective on Mat

8734:    Input Parameter:
8735: .  mat - the matrix

8737:    Output Parameter:
8738: +   right - (optional) vector that the matrix can be multiplied against
8739: -   left - (optional) vector that the matrix vector product can be stored in

8741:    Notes:
8742:     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().

8744:   Notes:
8745:     These are new vectors which are not owned by the Mat, they should be destroyed in VecDestroy() when no longer needed

8747:   Level: advanced

8749: .seealso: MatCreate(), VecDestroy()
8750: @*/
8751: PetscErrorCode MatCreateVecs(Mat mat,Vec *right,Vec *left)
8752: {

8758:   if (mat->ops->getvecs) {
8759:     (*mat->ops->getvecs)(mat,right,left);
8760:   } else {
8761:     PetscInt rbs,cbs;
8762:     MatGetBlockSizes(mat,&rbs,&cbs);
8763:     if (right) {
8764:       if (mat->cmap->n < 0) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"PetscLayout for columns not yet setup");
8765:       VecCreate(PetscObjectComm((PetscObject)mat),right);
8766:       VecSetSizes(*right,mat->cmap->n,PETSC_DETERMINE);
8767:       VecSetBlockSize(*right,cbs);
8768:       VecSetType(*right,mat->defaultvectype);
8769:       PetscLayoutReference(mat->cmap,&(*right)->map);
8770:     }
8771:     if (left) {
8772:       if (mat->rmap->n < 0) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"PetscLayout for rows not yet setup");
8773:       VecCreate(PetscObjectComm((PetscObject)mat),left);
8774:       VecSetSizes(*left,mat->rmap->n,PETSC_DETERMINE);
8775:       VecSetBlockSize(*left,rbs);
8776:       VecSetType(*left,mat->defaultvectype);
8777:       PetscLayoutReference(mat->rmap,&(*left)->map);
8778:     }
8779:   }
8780:   return(0);
8781: }

8783: /*@C
8784:    MatFactorInfoInitialize - Initializes a MatFactorInfo data structure
8785:      with default values.

8787:    Not Collective

8789:    Input Parameters:
8790: .    info - the MatFactorInfo data structure


8793:    Notes:
8794:     The solvers are generally used through the KSP and PC objects, for example
8795:           PCLU, PCILU, PCCHOLESKY, PCICC

8797:    Level: developer

8799: .seealso: MatFactorInfo

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

8804: @*/

8806: PetscErrorCode MatFactorInfoInitialize(MatFactorInfo *info)
8807: {

8811:   PetscMemzero(info,sizeof(MatFactorInfo));
8812:   return(0);
8813: }

8815: /*@
8816:    MatFactorSetSchurIS - Set indices corresponding to the Schur complement you wish to have computed

8818:    Collective on Mat

8820:    Input Parameters:
8821: +  mat - the factored matrix
8822: -  is - the index set defining the Schur indices (0-based)

8824:    Notes:
8825:     Call MatFactorSolveSchurComplement() or MatFactorSolveSchurComplementTranspose() after this call to solve a Schur complement system.

8827:    You can call MatFactorGetSchurComplement() or MatFactorCreateSchurComplement() after this call.

8829:    Level: developer

8831: .seealso: MatGetFactor(), MatFactorGetSchurComplement(), MatFactorRestoreSchurComplement(), MatFactorCreateSchurComplement(), MatFactorSolveSchurComplement(),
8832:           MatFactorSolveSchurComplementTranspose(), MatFactorSolveSchurComplement()

8834: @*/
8835: PetscErrorCode MatFactorSetSchurIS(Mat mat,IS is)
8836: {
8837:   PetscErrorCode ierr,(*f)(Mat,IS);

8845:   if (!mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Only for factored matrix");
8846:   PetscObjectQueryFunction((PetscObject)mat,"MatFactorSetSchurIS_C",&f);
8847:   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");
8848:   MatDestroy(&mat->schur);
8849:   (*f)(mat,is);
8850:   if (!mat->schur) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_PLIB,"Schur complement has not been created");
8851:   return(0);
8852: }

8854: /*@
8855:   MatFactorCreateSchurComplement - Create a Schur complement matrix object using Schur data computed during the factorization step

8857:    Logically Collective on Mat

8859:    Input Parameters:
8860: +  F - the factored matrix obtained by calling MatGetFactor() from PETSc-MUMPS interface
8861: .  S - location where to return the Schur complement, can be NULL
8862: -  status - the status of the Schur complement matrix, can be NULL

8864:    Notes:
8865:    You must call MatFactorSetSchurIS() before calling this routine.

8867:    The routine provides a copy of the Schur matrix stored within the solver data structures.
8868:    The caller must destroy the object when it is no longer needed.
8869:    If MatFactorInvertSchurComplement() has been called, the routine gets back the inverse.

8871:    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)

8873:    Developer Notes:
8874:     The reason this routine exists is because the representation of the Schur complement within the factor matrix may be different than a standard PETSc
8875:    matrix representation and we normally do not want to use the time or memory to make a copy as a regular PETSc matrix.

8877:    See MatCreateSchurComplement() or MatGetSchurComplement() for ways to create virtual or approximate Schur complements.

8879:    Level: advanced

8881:    References:

8883: .seealso: MatGetFactor(), MatFactorSetSchurIS(), MatFactorGetSchurComplement(), MatFactorSchurStatus
8884: @*/
8885: PetscErrorCode MatFactorCreateSchurComplement(Mat F,Mat* S,MatFactorSchurStatus* status)
8886: {

8893:   if (S) {
8894:     PetscErrorCode (*f)(Mat,Mat*);

8896:     PetscObjectQueryFunction((PetscObject)F,"MatFactorCreateSchurComplement_C",&f);
8897:     if (f) {
8898:       (*f)(F,S);
8899:     } else {
8900:       MatDuplicate(F->schur,MAT_COPY_VALUES,S);
8901:     }
8902:   }
8903:   if (status) *status = F->schur_status;
8904:   return(0);
8905: }

8907: /*@
8908:   MatFactorGetSchurComplement - Gets access to a Schur complement matrix using the current Schur data within a factored matrix

8910:    Logically Collective on Mat

8912:    Input Parameters:
8913: +  F - the factored matrix obtained by calling MatGetFactor()
8914: .  *S - location where to return the Schur complement, can be NULL
8915: -  status - the status of the Schur complement matrix, can be NULL

8917:    Notes:
8918:    You must call MatFactorSetSchurIS() before calling this routine.

8920:    Schur complement mode is currently implemented for sequential matrices.
8921:    The routine returns a the Schur Complement stored within the data strutures of the solver.
8922:    If MatFactorInvertSchurComplement() has previously been called, the returned matrix is actually the inverse of the Schur complement.
8923:    The returned matrix should not be destroyed; the caller should call MatFactorRestoreSchurComplement() when the object is no longer needed.

8925:    Use MatFactorCreateSchurComplement() to create a copy of the Schur complement matrix that is within a factored matrix

8927:    See MatCreateSchurComplement() or MatGetSchurComplement() for ways to create virtual or approximate Schur complements.

8929:    Level: advanced

8931:    References:

8933: .seealso: MatGetFactor(), MatFactorSetSchurIS(), MatFactorRestoreSchurComplement(), MatFactorCreateSchurComplement(), MatFactorSchurStatus
8934: @*/
8935: PetscErrorCode MatFactorGetSchurComplement(Mat F,Mat* S,MatFactorSchurStatus* status)
8936: {
8941:   if (S) *S = F->schur;
8942:   if (status) *status = F->schur_status;
8943:   return(0);
8944: }

8946: /*@
8947:   MatFactorRestoreSchurComplement - Restore the Schur complement matrix object obtained from a call to MatFactorGetSchurComplement

8949:    Logically Collective on Mat

8951:    Input Parameters:
8952: +  F - the factored matrix obtained by calling MatGetFactor()
8953: .  *S - location where the Schur complement is stored
8954: -  status - the status of the Schur complement matrix (see MatFactorSchurStatus)

8956:    Notes:

8958:    Level: advanced

8960:    References:

8962: .seealso: MatGetFactor(), MatFactorSetSchurIS(), MatFactorRestoreSchurComplement(), MatFactorCreateSchurComplement(), MatFactorSchurStatus
8963: @*/
8964: PetscErrorCode MatFactorRestoreSchurComplement(Mat F,Mat* S,MatFactorSchurStatus status)
8965: {

8970:   if (S) {
8972:     *S = NULL;
8973:   }
8974:   F->schur_status = status;
8975:   MatFactorUpdateSchurStatus_Private(F);
8976:   return(0);
8977: }

8979: /*@
8980:   MatFactorSolveSchurComplementTranspose - Solve the transpose of the Schur complement system computed during the factorization step

8982:    Logically Collective on Mat

8984:    Input Parameters:
8985: +  F - the factored matrix obtained by calling MatGetFactor()
8986: .  rhs - location where the right hand side of the Schur complement system is stored
8987: -  sol - location where the solution of the Schur complement system has to be returned

8989:    Notes:
8990:    The sizes of the vectors should match the size of the Schur complement

8992:    Must be called after MatFactorSetSchurIS()

8994:    Level: advanced

8996:    References:

8998: .seealso: MatGetFactor(), MatFactorSetSchurIS(), MatFactorSolveSchurComplement()
8999: @*/
9000: PetscErrorCode MatFactorSolveSchurComplementTranspose(Mat F, Vec rhs, Vec sol)
9001: {

9013:   MatFactorFactorizeSchurComplement(F);
9014:   switch (F->schur_status) {
9015:   case MAT_FACTOR_SCHUR_FACTORED:
9016:     MatSolveTranspose(F->schur,rhs,sol);
9017:     break;
9018:   case MAT_FACTOR_SCHUR_INVERTED:
9019:     MatMultTranspose(F->schur,rhs,sol);
9020:     break;
9021:   default:
9022:     SETERRQ1(PetscObjectComm((PetscObject)F),PETSC_ERR_SUP,"Unhandled MatFactorSchurStatus %D",F->schur_status);
9023:     break;
9024:   }
9025:   return(0);
9026: }

9028: /*@
9029:   MatFactorSolveSchurComplement - Solve the Schur complement system computed during the factorization step

9031:    Logically Collective on Mat

9033:    Input Parameters:
9034: +  F - the factored matrix obtained by calling MatGetFactor()
9035: .  rhs - location where the right hand side of the Schur complement system is stored
9036: -  sol - location where the solution of the Schur complement system has to be returned

9038:    Notes:
9039:    The sizes of the vectors should match the size of the Schur complement

9041:    Must be called after MatFactorSetSchurIS()

9043:    Level: advanced

9045:    References:

9047: .seealso: MatGetFactor(), MatFactorSetSchurIS(), MatFactorSolveSchurComplementTranspose()
9048: @*/
9049: PetscErrorCode MatFactorSolveSchurComplement(Mat F, Vec rhs, Vec sol)
9050: {

9062:   MatFactorFactorizeSchurComplement(F);
9063:   switch (F->schur_status) {
9064:   case MAT_FACTOR_SCHUR_FACTORED:
9065:     MatSolve(F->schur,rhs,sol);
9066:     break;
9067:   case MAT_FACTOR_SCHUR_INVERTED:
9068:     MatMult(F->schur,rhs,sol);
9069:     break;
9070:   default:
9071:     SETERRQ1(PetscObjectComm((PetscObject)F),PETSC_ERR_SUP,"Unhandled MatFactorSchurStatus %D",F->schur_status);
9072:     break;
9073:   }
9074:   return(0);
9075: }

9077: /*@
9078:   MatFactorInvertSchurComplement - Invert the Schur complement matrix computed during the factorization step

9080:    Logically Collective on Mat

9082:    Input Parameters:
9083: .  F - the factored matrix obtained by calling MatGetFactor()

9085:    Notes:
9086:     Must be called after MatFactorSetSchurIS().

9088:    Call MatFactorGetSchurComplement() or  MatFactorCreateSchurComplement() AFTER this call to actually compute the inverse and get access to it.

9090:    Level: advanced

9092:    References:

9094: .seealso: MatGetFactor(), MatFactorSetSchurIS(), MatFactorGetSchurComplement(), MatFactorCreateSchurComplement()
9095: @*/
9096: PetscErrorCode MatFactorInvertSchurComplement(Mat F)
9097: {

9103:   if (F->schur_status == MAT_FACTOR_SCHUR_INVERTED) return(0);
9104:   MatFactorFactorizeSchurComplement(F);
9105:   MatFactorInvertSchurComplement_Private(F);
9106:   F->schur_status = MAT_FACTOR_SCHUR_INVERTED;
9107:   return(0);
9108: }

9110: /*@
9111:   MatFactorFactorizeSchurComplement - Factorize the Schur complement matrix computed during the factorization step

9113:    Logically Collective on Mat

9115:    Input Parameters:
9116: .  F - the factored matrix obtained by calling MatGetFactor()

9118:    Notes:
9119:     Must be called after MatFactorSetSchurIS().

9121:    Level: advanced

9123:    References:

9125: .seealso: MatGetFactor(), MatFactorSetSchurIS(), MatFactorInvertSchurComplement()
9126: @*/
9127: PetscErrorCode MatFactorFactorizeSchurComplement(Mat F)
9128: {

9134:   if (F->schur_status == MAT_FACTOR_SCHUR_INVERTED || F->schur_status == MAT_FACTOR_SCHUR_FACTORED) return(0);
9135:   MatFactorFactorizeSchurComplement_Private(F);
9136:   F->schur_status = MAT_FACTOR_SCHUR_FACTORED;
9137:   return(0);
9138: }

9140: /*@
9141:    MatPtAP - Creates the matrix product C = P^T * A * P

9143:    Neighbor-wise Collective on Mat

9145:    Input Parameters:
9146: +  A - the matrix
9147: .  P - the projection matrix
9148: .  scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
9149: -  fill - expected fill as ratio of nnz(C)/(nnz(A) + nnz(P)), use PETSC_DEFAULT if you do not have a good estimate
9150:           if the result is a dense matrix this is irrelevent

9152:    Output Parameters:
9153: .  C - the product matrix

9155:    Notes:
9156:    C will be created and must be destroyed by the user with MatDestroy().

9158:    For matrix types without special implementation the function fallbacks to MatMatMult() followed by MatTransposeMatMult().

9160:    Level: intermediate

9162: .seealso: MatMatMult(), MatRARt()
9163: @*/
9164: PetscErrorCode MatPtAP(Mat A,Mat P,MatReuse scall,PetscReal fill,Mat *C)
9165: {

9169:   if (scall == MAT_REUSE_MATRIX) MatCheckProduct(*C,5);
9170:   if (scall == MAT_INPLACE_MATRIX) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Inplace product not supported");

9172:   if (scall == MAT_INITIAL_MATRIX) {
9173:     MatProductCreate(A,P,NULL,C);
9174:     MatProductSetType(*C,MATPRODUCT_PtAP);
9175:     MatProductSetAlgorithm(*C,"default");
9176:     MatProductSetFill(*C,fill);

9178:     (*C)->product->api_user = PETSC_TRUE;
9179:     MatProductSetFromOptions(*C);
9180:     if (!(*C)->ops->productsymbolic) SETERRQ3(PetscObjectComm((PetscObject)(*C)),PETSC_ERR_SUP,"MatProduct %s not supported for A %s and P %s",MatProductTypes[MATPRODUCT_PtAP],((PetscObject)A)->type_name,((PetscObject)P)->type_name);
9181:     MatProductSymbolic(*C);
9182:   } else { /* scall == MAT_REUSE_MATRIX */
9183:     MatProductReplaceMats(A,P,NULL,*C);
9184:   }

9186:   MatProductNumeric(*C);
9187:   if (A->symmetric_set && A->symmetric) {
9188:     MatSetOption(*C,MAT_SYMMETRIC,PETSC_TRUE);
9189:   }
9190:   return(0);
9191: }

9193: /*@
9194:    MatRARt - Creates the matrix product C = R * A * R^T

9196:    Neighbor-wise Collective on Mat

9198:    Input Parameters:
9199: +  A - the matrix
9200: .  R - the projection matrix
9201: .  scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
9202: -  fill - expected fill as ratio of nnz(C)/nnz(A), use PETSC_DEFAULT if you do not have a good estimate
9203:           if the result is a dense matrix this is irrelevent

9205:    Output Parameters:
9206: .  C - the product matrix

9208:    Notes:
9209:    C will be created and must be destroyed by the user with MatDestroy().

9211:    This routine is currently only implemented for pairs of AIJ matrices and classes
9212:    which inherit from AIJ. Due to PETSc sparse matrix block row distribution among processes,
9213:    parallel MatRARt is implemented via explicit transpose of R, which could be very expensive.
9214:    We recommend using MatPtAP().

9216:    Level: intermediate

9218: .seealso: MatMatMult(), MatPtAP()
9219: @*/
9220: PetscErrorCode MatRARt(Mat A,Mat R,MatReuse scall,PetscReal fill,Mat *C)
9221: {

9225:   if (scall == MAT_REUSE_MATRIX) MatCheckProduct(*C,5);
9226:   if (scall == MAT_INPLACE_MATRIX) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Inplace product not supported");

9228:   if (scall == MAT_INITIAL_MATRIX) {
9229:     MatProductCreate(A,R,NULL,C);
9230:     MatProductSetType(*C,MATPRODUCT_RARt);
9231:     MatProductSetAlgorithm(*C,"default");
9232:     MatProductSetFill(*C,fill);

9234:     (*C)->product->api_user = PETSC_TRUE;
9235:     MatProductSetFromOptions(*C);
9236:     if (!(*C)->ops->productsymbolic) SETERRQ3(PetscObjectComm((PetscObject)(*C)),PETSC_ERR_SUP,"MatProduct %s not supported for A %s and R %s",MatProductTypes[MATPRODUCT_RARt],((PetscObject)A)->type_name,((PetscObject)R)->type_name);
9237:     MatProductSymbolic(*C);
9238:   } else { /* scall == MAT_REUSE_MATRIX */
9239:     MatProductReplaceMats(A,R,NULL,*C);
9240:   }

9242:   MatProductNumeric(*C);
9243:   if (A->symmetric_set && A->symmetric) {
9244:     MatSetOption(*C,MAT_SYMMETRIC,PETSC_TRUE);
9245:   }
9246:   return(0);
9247: }


9250: static PetscErrorCode MatProduct_Private(Mat A,Mat B,MatReuse scall,PetscReal fill,MatProductType ptype, Mat *C)
9251: {

9255:   if (scall == MAT_INPLACE_MATRIX) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Inplace product not supported");

9257:   if (scall == MAT_INITIAL_MATRIX) {
9258:     PetscInfo1(A,"Calling MatProduct API with MAT_INITIAL_MATRIX and product type %s\n",MatProductTypes[ptype]);
9259:     MatProductCreate(A,B,NULL,C);
9260:     MatProductSetType(*C,ptype);
9261:     MatProductSetAlgorithm(*C,MATPRODUCTALGORITHM_DEFAULT);
9262:     MatProductSetFill(*C,fill);

9264:     (*C)->product->api_user = PETSC_TRUE;
9265:     MatProductSetFromOptions(*C);
9266:     MatProductSymbolic(*C);
9267:   } else { /* scall == MAT_REUSE_MATRIX */
9268:     Mat_Product *product = (*C)->product;

9270:     PetscInfo2(A,"Calling MatProduct API with MAT_REUSE_MATRIX %s product present and product type %s\n",product ? "with" : "without",MatProductTypes[ptype]);
9271:     if (!product) {
9272:       /* user provide the dense matrix *C without calling MatProductCreate() */
9273:       PetscBool isdense;

9275:       PetscObjectBaseTypeCompareAny((PetscObject)(*C),&isdense,MATSEQDENSE,MATMPIDENSE,"");
9276:       if (isdense) {
9277:         /* user wants to reuse an assembled dense matrix */
9278:         /* Create product -- see MatCreateProduct() */
9279:         MatProductCreate_Private(A,B,NULL,*C);
9280:         product = (*C)->product;
9281:         product->fill     = fill;
9282:         product->api_user = PETSC_TRUE;
9283:         product->clear    = PETSC_TRUE;

9285:         MatProductSetType(*C,ptype);
9286:         MatProductSetFromOptions(*C);
9287:         if (!(*C)->ops->productsymbolic) SETERRQ3(PetscObjectComm((PetscObject)(*C)),PETSC_ERR_SUP,"MatProduct %s not supported for %s and %s",MatProductTypes[ptype],((PetscObject)A)->type_name,((PetscObject)B)->type_name);
9288:         MatProductSymbolic(*C);
9289:       } else SETERRQ(PetscObjectComm((PetscObject)(*C)),PETSC_ERR_SUP,"Call MatProductCreate() first");
9290:     }