Actual source code: matrix.c

petsc-master 2020-08-04
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_CUSPARSEGenerateTranspose, 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(), MatLUFactorSymbolic(), MatCholeskyFactorSymbolic(), 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(), MatLUFactorSymbolic(), MatCholeskyFactorSymbolic(), 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(), MatLUFactorSymbolic(), MatCholeskyFactorSymbolic(), 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 Section 1.5 Writing Application Codes with PETSc 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:         if (!mat->factortype) {
1025:           PetscViewerASCIIPrintf(viewer,"total number of mallocs used during MatSetValues calls=%D\n",(PetscInt)info.mallocs);
1026:         }
1027:       }
1028:       MatGetNullSpace(mat,&nullsp);
1029:       MatGetTransposeNullSpace(mat,&transnullsp);
1030:       if (nullsp) {PetscViewerASCIIPrintf(viewer,"  has attached null space\n");}
1031:       if (transnullsp && transnullsp != nullsp) {PetscViewerASCIIPrintf(viewer,"  has attached transposed null space\n");}
1032:       MatGetNearNullSpace(mat,&nullsp);
1033:       if (nullsp) {PetscViewerASCIIPrintf(viewer,"  has attached near null space\n");}
1034:       PetscViewerASCIIPushTab(viewer);
1035:       MatProductView(mat,viewer);
1036:       PetscViewerASCIIPopTab(viewer);
1037:     }
1038:   } else if (issaws) {
1039: #if defined(PETSC_HAVE_SAWS)
1040:     PetscMPIInt rank;

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

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

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

1092:    Collective on PetscViewer

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

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

1104:    Level: beginner

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1189:    Corresponding MatView() is not yet implemented.

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

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

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

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


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

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

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

1235: static PetscErrorCode MatDestroy_Redundant(Mat_Redundant **redundant)
1236: {
1238:   Mat_Redundant  *redund = *redundant;
1239:   PetscInt       i;

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

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

1266: /*@
1267:    MatDestroy - Frees space taken by a matrix.

1269:    Collective on Mat

1271:    Input Parameter:
1272: .  A - the matrix

1274:    Level: beginner

1276: @*/
1277: PetscErrorCode MatDestroy(Mat *A)
1278: {

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

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

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

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

1312:    Not Collective

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

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

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

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

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

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

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

1345:    Level: beginner

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

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

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

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

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

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

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


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

1402:    Not Collective

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

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

1412:    All the nonzeros in the row must be provided

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

1416:    The row must belong to this process

1418:    Level: intermediate

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

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

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

1441:    Not Collective

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

1448:    Notes:
1449:    The values, v, are column-oriented for the block version.

1451:    All the nonzeros in the row must be provided

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

1455:    The row must belong to this process

1457:    Level: advanced

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

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

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

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

1490:    Not Collective

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

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

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

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

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

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

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

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

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

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

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

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

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

1550:    Level: beginner

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

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

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

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

1604:    Not Collective

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

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

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

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

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

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

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

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

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

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

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

1657:    Level: beginner

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

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

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

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

1713:    Not Collective

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


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

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

1729:    Level: beginner

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


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

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

1757:    Not Collective

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

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

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

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

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

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

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

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

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

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

1817:    Level: intermediate

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

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

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

1875: /*@C
1876:    MatGetValues - Gets a block of values from a matrix.

1878:    Not Collective; currently only returns a local block

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

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

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

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

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

1902:    Level: advanced

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

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

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

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

1932:    Not Collective

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

1939:    Output Parameter:
1940: .  y -  a logically two-dimensional array of values

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

1945:    Level: advanced

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

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

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

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

1996:   Not Collective

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

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

2008:   Level: advanced

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

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

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

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

2042:    Not Collective

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

2049:    Level: intermediate


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


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


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

2077:    Not Collective

2079:    Input Parameters:
2080: .  A - the matrix

2082:    Output Parameters:
2083: + rmapping - row mapping
2084: - cmapping - column mapping

2086:    Level: advanced


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

2103: /*@
2104:    MatGetLayouts - Gets the PetscLayout objects for rows and columns

2106:    Not Collective

2108:    Input Parameters:
2109: .  A - the matrix

2111:    Output Parameters:
2112: + rmap - row layout
2113: - cmap - column layout

2115:    Level: advanced

2117: .seealso:  MatCreateVecs(), MatGetLocalToGlobalMapping()
2118: @*/
2119: PetscErrorCode MatGetLayouts(Mat A,PetscLayout *rmap,PetscLayout *cmap)
2120: {
2126:   if (rmap) *rmap = A->rmap;
2127:   if (cmap) *cmap = A->cmap;
2128:   return(0);
2129: }

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

2135:    Not Collective

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

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

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

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

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

2159:    Level: intermediate

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

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

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

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

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

2218:    Not Collective

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

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

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

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

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

2243:    Level: intermediate

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

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

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

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

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

2311:    Collective on Mat

2313:    Input Parameters:
2314: +  mat - the matrix
2315: -  x   - the vector to be multiplied

2317:    Output Parameters:
2318: .  y - the result

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

2324:    Level: developer

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


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

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

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

2353:    Neighbor-wise Collective on Mat

2355:    Input Parameters:
2356: +  mat - the matrix
2357: -  x   - the vector to be multiplied

2359:    Output Parameters:
2360: .  y - the result

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

2366:    Level: beginner

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

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

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

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

2404:    Neighbor-wise Collective on Mat

2406:    Input Parameters:
2407: +  mat - the matrix
2408: -  x   - the vector to be multiplied

2410:    Output Parameters:
2411: .  y - the result

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

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

2420:    Level: beginner

2422: .seealso: MatMult(), MatMultAdd(), MatMultTransposeAdd(), MatMultHermitianTranspose(), MatTranspose()
2423: @*/
2424: PetscErrorCode MatMultTranspose(Mat mat,Vec x,Vec y)
2425: {
2426:   PetscErrorCode (*op)(Mat,Vec,Vec)=NULL,ierr;


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

2444:   if (!mat->ops->multtranspose) {
2445:     if (mat->symmetric && mat->ops->mult) op = mat->ops->mult;
2446:     if (!op) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Matrix type %s does not have a multiply transpose defined or is symmetric and does not have a multiply defined",((PetscObject)mat)->type_name);
2447:   } else op = mat->ops->multtranspose;
2448:   PetscLogEventBegin(MAT_MultTranspose,mat,x,y,0);
2449:   VecLockReadPush(x);
2450:   (*op)(mat,x,y);
2451:   VecLockReadPop(x);
2452:   PetscLogEventEnd(MAT_MultTranspose,mat,x,y,0);
2453:   PetscObjectStateIncrease((PetscObject)y);
2454:   if (mat->erroriffailure) {VecValidValues(y,3,PETSC_FALSE);}
2455:   return(0);
2456: }

2458: /*@
2459:    MatMultHermitianTranspose - Computes matrix Hermitian transpose times a vector.

2461:    Neighbor-wise Collective on Mat

2463:    Input Parameters:
2464: +  mat - the matrix
2465: -  x   - the vector to be multilplied

2467:    Output Parameters:
2468: .  y - the result

2470:    Notes:
2471:    The vectors x and y cannot be the same.  I.e., one cannot
2472:    call MatMultHermitianTranspose(A,y,y).

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

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

2478:    Level: beginner

2480: .seealso: MatMult(), MatMultAdd(), MatMultHermitianTransposeAdd(), MatMultTranspose()
2481: @*/
2482: PetscErrorCode MatMultHermitianTranspose(Mat mat,Vec x,Vec y)
2483: {


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

2501:   PetscLogEventBegin(MAT_MultHermitianTranspose,mat,x,y,0);
2502: #if defined(PETSC_USE_COMPLEX)
2503:   if (mat->ops->multhermitiantranspose || (mat->hermitian && mat->ops->mult)) {
2504:     VecLockReadPush(x);
2505:     if (mat->ops->multhermitiantranspose) {
2506:       (*mat->ops->multhermitiantranspose)(mat,x,y);
2507:     } else {
2508:       (*mat->ops->mult)(mat,x,y);
2509:     }
2510:     VecLockReadPop(x);
2511:   } else {
2512:     Vec w;
2513:     VecDuplicate(x,&w);
2514:     VecCopy(x,w);
2515:     VecConjugate(w);
2516:     MatMultTranspose(mat,w,y);
2517:     VecDestroy(&w);
2518:     VecConjugate(y);
2519:   }
2520:   PetscObjectStateIncrease((PetscObject)y);
2521: #else
2522:   MatMultTranspose(mat,x,y);
2523: #endif
2524:   PetscLogEventEnd(MAT_MultHermitianTranspose,mat,x,y,0);
2525:   return(0);
2526: }

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

2531:     Neighbor-wise Collective on Mat

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

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

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

2544:     Level: beginner

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


2559:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2560:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2561:   if (mat->cmap->N != v1->map->N) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_SIZ,"Mat mat,Vec v1: global dim %D %D",mat->cmap->N,v1->map->N);
2562:   /* if (mat->rmap->N != v2->map->N) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Mat mat,Vec v2: global dim %D %D",mat->rmap->N,v2->map->N);
2563:      if (mat->rmap->N != v3->map->N) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Mat mat,Vec v3: global dim %D %D",mat->rmap->N,v3->map->N); */
2564:   if (mat->rmap->n != v3->map->n) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Mat mat,Vec v3: local dim %D %D",mat->rmap->n,v3->map->n);
2565:   if (mat->rmap->n != v2->map->n) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Mat mat,Vec v2: local dim %D %D",mat->rmap->n,v2->map->n);
2566:   if (v1 == v3) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"v1 and v3 must be different vectors");
2567:   MatCheckPreallocated(mat,1);

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

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

2582:    Neighbor-wise Collective on Mat

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

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

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

2595:    Level: beginner

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


2610:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2611:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2612:   if (!mat->ops->multtransposeadd) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
2613:   if (v1 == v3) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"v1 and v3 must be different vectors");
2614:   if (mat->rmap->N != v1->map->N) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_SIZ,"Mat mat,Vec v1: global dim %D %D",mat->rmap->N,v1->map->N);
2615:   if (mat->cmap->N != v2->map->N) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_SIZ,"Mat mat,Vec v2: global dim %D %D",mat->cmap->N,v2->map->N);
2616:   if (mat->cmap->N != v3->map->N) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_SIZ,"Mat mat,Vec v3: global dim %D %D",mat->cmap->N,v3->map->N);
2617:   MatCheckPreallocated(mat,1);

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

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

2631:    Neighbor-wise Collective on Mat

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

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

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

2644:    Level: beginner

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


2659:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2660:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2661:   if (v1 == v3) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"v1 and v3 must be different vectors");
2662:   if (mat->rmap->N != v1->map->N) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_SIZ,"Mat mat,Vec v1: global dim %D %D",mat->rmap->N,v1->map->N);
2663:   if (mat->cmap->N != v2->map->N) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_SIZ,"Mat mat,Vec v2: global dim %D %D",mat->cmap->N,v2->map->N);
2664:   if (mat->cmap->N != v3->map->N) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_SIZ,"Mat mat,Vec v3: global dim %D %D",mat->cmap->N,v3->map->N);
2665:   MatCheckPreallocated(mat,1);

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

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

2697:    Neighbor-wise Collective on Mat

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

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

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

2710:    Level: beginner

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

2722:   if (!mat->assembled) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2723:   if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2724:   if (x == y) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"x and y must be different vectors");
2725:   if (mat->cmap->N != x->map->N) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Mat mat,Vec x: global dim %D %D",mat->cmap->N,x->map->N);
2726:   if (mat->rmap->N != y->map->N) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Mat mat,Vec y: global dim %D %D",mat->rmap->N,y->map->N);
2727:   if (mat->rmap->n != y->map->n) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Mat mat,Vec y: local dim %D %D",mat->rmap->n,y->map->n);

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

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

2742:    Neighbor-wise Collective on Mat

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

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

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

2755:    Level: beginner

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

2767:   if (!mat->assembled) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
2768:   if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
2769:   if (x == y) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"x and y must be different vectors");
2770:   if (mat->rmap->N != x->map->N) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Mat mat,Vec x: global dim %D %D",mat->cmap->N,x->map->N);
2771:   if (mat->cmap->N != y->map->N) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Mat mat,Vec y: global dim %D %D",mat->rmap->N,y->map->N);

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

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

2783:    Not Collective

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

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

2791:    Level: intermediate

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

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

2808:    Logically Collective on Mat

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

2814:    Level: intermediate

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

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

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

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

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

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

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

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

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

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

2881:     Level: intermediate

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

2886: .seealso: MatStashGetInfo()

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

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

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

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

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

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

2921:    Collective on Mat

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

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

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

2940:    Level: developer

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

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

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

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

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

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

2979:    Collective on Mat

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

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

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

2999:    Level: developer

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

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

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

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

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

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

3034:    Collective on Mat

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


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

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

3053:    Level: developer

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

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

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

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

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

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

3097:    Collective on Mat

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

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

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

3112:    Level: developer

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

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

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

3130:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
3131:   if (mat->rmap->N != (fact)->rmap->N || mat->cmap->N != (fact)->cmap->N) SETERRQ4(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_SIZ,"Mat mat,Mat fact: global dimensions are different %D should = %D %D should = %D",mat->rmap->N,(fact)->rmap->N,mat->cmap->N,(fact)->cmap->N);

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

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

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

3152:    Collective on Mat

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

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

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

3167:    Level: developer

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

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

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

3186:   if (mat->rmap->N != mat->cmap->N) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONG,"Matrix must be square");
3187:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
3188:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
3189:   if (!mat->ops->choleskyfactor) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"In-place factorization for Mat type %s is not supported, try out-of-place factorization. See MatCholeskyFactorSymbolic/Numeric",((PetscObject)mat)->type_name);
3190:   MatCheckPreallocated(mat,1);
3191:   if (!info) {
3192:     MatFactorInfoInitialize(&tinfo);
3193:     info = &tinfo;
3194:   }

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

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

3207:    Collective on Mat

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

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

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

3226:    Level: developer

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

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

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

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

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

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

3272:    Collective on Mat

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


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

3286:    Level: developer

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

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

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

3304:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
3305:   if (!(fact)->ops->choleskyfactornumeric) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s numeric factor Cholesky",((PetscObject)mat)->type_name);
3306:   if (mat->rmap->N != (fact)->rmap->N || mat->cmap->N != (fact)->cmap->N) SETERRQ4(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_SIZ,"Mat mat,Mat fact: global dim %D should = %D %D should = %D",mat->rmap->N,(fact)->rmap->N,mat->cmap->N,(fact)->cmap->N);
3307:   MatCheckPreallocated(mat,2);
3308:   if (!info) {
3309:     MatFactorInfoInitialize(&tinfo);
3310:     info = &tinfo;
3311:   }

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

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

3325:    Neighbor-wise Collective on Mat

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

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

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

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

3343:    Level: developer

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

3358:   if (x == b) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"x and b must be different vectors");
3359:   if (mat->cmap->N != x->map->N) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_SIZ,"Mat mat,Vec x: global dim %D %D",mat->cmap->N,x->map->N);
3360:   if (mat->rmap->N != b->map->N) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_SIZ,"Mat mat,Vec b: global dim %D %D",mat->rmap->N,b->map->N);
3361:   if (mat->rmap->n != b->map->n) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Mat mat,Vec b: local dim %D %D",mat->rmap->n,b->map->n);
3362:   if (!mat->rmap->N && !mat->cmap->N) return(0);
3363:   MatCheckPreallocated(mat,1);

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

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

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

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

3412:    Neighbor-wise Collective on Mat

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

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

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

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

3431:    Level: developer

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

3446:   if (A->cmap->N != X->rmap->N) SETERRQ2(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Mat A,Mat X: global dim %D %D",A->cmap->N,X->rmap->N);
3447:   if (A->rmap->N != B->rmap->N) SETERRQ2(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Mat A,Mat B: global dim %D %D",A->rmap->N,B->rmap->N);
3448:   if (X->cmap->N != B->cmap->N) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Solution matrix must have same number of columns as rhs matrix");
3449:   if (!A->rmap->N && !A->cmap->N) return(0);
3450:   if (!A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
3451:   MatCheckPreallocated(A,1);

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

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

3468:    Neighbor-wise Collective on Mat

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

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

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

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

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

3489:    Level: developer

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

3504:   if (X == B) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_IDN,"X and B must be different matrices");
3505:   if (A->cmap->N != X->rmap->N) SETERRQ2(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Mat A,Mat X: global dim %D %D",A->cmap->N,X->rmap->N);
3506:   if (A->rmap->N != B->rmap->N) SETERRQ2(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Mat A,Mat B: global dim %D %D",A->rmap->N,B->rmap->N);
3507:   if (A->rmap->n != B->rmap->n) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Mat A,Mat B: local dim %D %D",A->rmap->n,B->rmap->n);
3508:   if (X->cmap->N < B->cmap->N) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Solution matrix must have same number of columns as rhs matrix");
3509:   if (!A->rmap->N && !A->cmap->N) return(0);
3510:   if (!A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
3511:   MatCheckPreallocated(A,1);

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

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

3528:    Neighbor-wise Collective on Mat

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

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

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

3543:    For MUMPS, it only supports centralized sparse compressed column format on the host processor for right hand side matrix. User must create B^T in sparse compressed row format on the host processor and call MatMatTransposeSolve() to implement MUMPS' MatMatSolve().

3545:    Level: developer

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


3561:   if (X == Bt) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_IDN,"X and B must be different matrices");
3562:   if (A->cmap->N != X->rmap->N) SETERRQ2(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Mat A,Mat X: global dim %D %D",A->cmap->N,X->rmap->N);
3563:   if (A->rmap->N != Bt->cmap->N) SETERRQ2(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Mat A,Mat Bt: global dim %D %D",A->rmap->N,Bt->cmap->N);
3564:   if (X->cmap->N < Bt->rmap->N) SETERRQ(PetscObjectComm((PetscObject)X),PETSC_ERR_ARG_SIZ,"Solution matrix must have same number of columns as row number of the rhs matrix");
3565:   if (!A->rmap->N && !A->cmap->N) return(0);
3566:   if (!A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
3567:   MatCheckPreallocated(A,1);

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

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

3581:    Neighbor-wise Collective on Mat

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

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

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

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

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

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

3607:    Level: developer

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

3622:   if (x == b) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"x and b must be different vectors");
3623:   if (mat->cmap->N != x->map->N) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_SIZ,"Mat mat,Vec x: global dim %D %D",mat->cmap->N,x->map->N);
3624:   if (mat->rmap->N != b->map->N) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_SIZ,"Mat mat,Vec b: global dim %D %D",mat->rmap->N,b->map->N);
3625:   if (mat->rmap->n != b->map->n) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Mat mat,Vec b: local dim %D %D",mat->rmap->n,b->map->n);
3626:   if (!mat->rmap->N && !mat->cmap->N) return(0);
3627:   MatCheckPreallocated(mat,1);

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

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

3641:    Neighbor-wise Collective on Mat

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

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

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

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

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

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

3667:    Level: developer

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

3682:   if (x == b) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"x and b must be different vectors");
3683:   if (mat->cmap->N != x->map->N) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_SIZ,"Mat mat,Vec x: global dim %D %D",mat->cmap->N,x->map->N);
3684:   if (mat->rmap->N != b->map->N) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_SIZ,"Mat mat,Vec b: global dim %D %D",mat->rmap->N,b->map->N);
3685:   if (mat->rmap->n != b->map->n) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Mat mat,Vec b: local dim %D %D",mat->rmap->n,b->map->n);
3686:   if (!mat->rmap->N && !mat->cmap->N) return(0);
3687:   MatCheckPreallocated(mat,1);

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

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

3700:    Neighbor-wise Collective on Mat

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

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

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

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

3718:    Level: developer

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

3737:   if (x == b) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"x and b must be different vectors");
3738:   if (mat->cmap->N != x->map->N) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_SIZ,"Mat mat,Vec x: global dim %D %D",mat->cmap->N,x->map->N);
3739:   if (mat->rmap->N != b->map->N) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_SIZ,"Mat mat,Vec b: global dim %D %D",mat->rmap->N,b->map->N);
3740:   if (mat->rmap->N != y->map->N) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_SIZ,"Mat mat,Vec y: global dim %D %D",mat->rmap->N,y->map->N);
3741:   if (mat->rmap->n != b->map->n) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Mat mat,Vec b: local dim %D %D",mat->rmap->n,b->map->n);
3742:   if (x->map->n != y->map->n) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Vec x,Vec y: local dim %D %D",x->map->n,y->map->n);
3743:   if (!mat->rmap->N && !mat->cmap->N) return(0);
3744:    MatCheckPreallocated(mat,1);

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

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

3774:    Neighbor-wise Collective on Mat

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

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

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

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

3791:    Level: developer

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

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

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

3828:    Neighbor-wise Collective on Mat

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

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

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

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

3846:    Level: developer

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

3865:   if (x == b) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"x and b must be different vectors");
3866:   if (mat->rmap->N != x->map->N) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_SIZ,"Mat mat,Vec x: global dim %D %D",mat->rmap->N,x->map->N);
3867:   if (mat->cmap->N != b->map->N) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_SIZ,"Mat mat,Vec b: global dim %D %D",mat->cmap->N,b->map->N);
3868:   if (mat->cmap->N != y->map->N) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_SIZ,"Mat mat,Vec y: global dim %D %D",mat->cmap->N,y->map->N);
3869:   if (x->map->n != y->map->n) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Vec x,Vec y: local dim %D %D",x->map->n,y->map->n);
3870:   if (!mat->rmap->N && !mat->cmap->N) return(0);
3871:    MatCheckPreallocated(mat,1);

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

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

3902:    Neighbor-wise Collective on Mat

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

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

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

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

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

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

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

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

3948:    Vectors x and b CANNOT be the same

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

3952:    Level: developer

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

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

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

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

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

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

4016:    Collective on Mat

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

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

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

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

4033:    Level: intermediate

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

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

4049:   MatCheckPreallocated(B,2);
4050:   if (!A->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
4051:   if (A->factortype) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
4052:   if (A->rmap->N != B->rmap->N || A->cmap->N != B->cmap->N) SETERRQ4(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Mat A,Mat B: global dim (%D,%D) (%D,%D)",A->rmap->N,B->rmap->N,A->cmap->N,B->cmap->N);
4053:   MatCheckPreallocated(A,1);
4054:   if (A == B) return(0);

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

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

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

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

4079:    Collective on Mat

4081:    Input Parameters:
4082: +  mat - the matrix
4083: .  newtype - new matrix type.  Use MATSAME to create a new matrix of the
4084:    same type as the original matrix.
4085: -  reuse - denotes if the destination matrix is to be created or reused.
4086:    Use MAT_INPLACE_MATRIX for inplace conversion (that is when you want the input mat to be changed to contain the matrix in the new format), otherwise use
4087:    MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX (can only be used after the first call was made with MAT_INITIAL_MATRIX, causes the matrix space in M to be reused).

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

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

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

4101:    Level: intermediate

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

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

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

4123:   PetscObjectTypeCompare((PetscObject)mat,newtype,&sametype);
4124:   PetscStrcmp(newtype,"same",&issame);
4125:   if ((reuse == MAT_INPLACE_MATRIX) && (mat != *M)) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"MAT_INPLACE_MATRIX requires same input and output matrix");
4126:   if ((reuse == MAT_REUSE_MATRIX) && (mat == *M)) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"MAT_REUSE_MATRIX means reuse matrix in final argument, perhaps you mean MAT_INPLACE_MATRIX");

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

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

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

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

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

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

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

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

4221:     /* 5) Use a really basic converter. */
4222:     PetscInfo(mat,"Using MatConvert_Basic\n");
4223:     conv = MatConvert_Basic;

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

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

4257: /*@C
4258:    MatFactorGetSolverType - Returns name of the package providing the factorization routines

4260:    Not Collective

4262:    Input Parameter:
4263: .  mat - the matrix, must be a factored matrix

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

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

4272:    Level: intermediate

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

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

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

4300: typedef struct _MatSolverTypeHolder* MatSolverTypeHolder;
4301: struct _MatSolverTypeHolder {
4302:   char                           *name;
4303:   MatSolverTypeForSpecifcType handlers;
4304:   MatSolverTypeHolder         next;
4305: };

4307: static MatSolverTypeHolder MatSolverTypeHolders = NULL;

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

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

4318:     Level: intermediate

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

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

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

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

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

4382:     Level: intermediate

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

4394:   if (foundpackage) *foundpackage = PETSC_FALSE;
4395:   if (foundmtype)   *foundmtype   = PETSC_FALSE;
4396:   if (getfactor)    *getfactor    = NULL;

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

4435: PetscErrorCode MatSolverTypeDestroy(void)
4436: {
4437:   PetscErrorCode              ierr;
4438:   MatSolverTypeHolder         next = MatSolverTypeHolders,prev;
4439:   MatSolverTypeForSpecifcType inext,iprev;

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

4459: /*@C
4460:    MatFactorGetUseOrdering - Indicates if the factorization uses the ordering provided in MatLUFactorSymbolic(), MatCholeskyFactorSymbolic()

4462:    Logically Collective on Mat

4464:    Input Parameters:
4465: .  mat - the matrix

4467:    Output Parameters:
4468: .  flg - PETSC_TRUE if uses the ordering

4470:    Notes:
4471:       Most internal PETSc factorizations use the ordering past to the factorization routine but external 
4472:       packages do no, thus we want to skip the ordering when it is not needed.

4474:    Level: developer

4476: .seealso: MatCopy(), MatDuplicate(), MatGetFactorAvailable(), MatGetFactor(), MatLUFactorSymbolic(), MatCholeskyFactorSymbolic()
4477: @*/
4478: PetscErrorCode MatFactorGetUseOrdering(Mat mat, PetscBool *flg)
4479: {
4481:   *flg = mat->useordering;
4482:   return(0);
4483: }

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

4488:    Collective on Mat

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

4495:    Output Parameters:
4496: .  f - the factor matrix used with MatXXFactorSymbolic() calls

4498:    Notes:
4499:       Some PETSc matrix formats have alternative solvers available that are contained in alternative packages
4500:      such as pastix, superlu, mumps etc.

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

4504:    Level: intermediate

4506: .seealso: MatCopy(), MatDuplicate(), MatGetFactorAvailable(), MatFactorGetUseOrdering()
4507: @*/
4508: PetscErrorCode MatGetFactor(Mat mat, MatSolverType type,MatFactorType ftype,Mat *f)
4509: {
4510:   PetscErrorCode ierr,(*conv)(Mat,MatFactorType,Mat*);
4511:   PetscBool      foundpackage,foundmtype;


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

4520:   MatSolverTypeGet(type,((PetscObject)mat)->type_name,ftype,&foundpackage,&foundmtype,&conv);
4521:   if (!foundpackage) {
4522:     if (type) {
4523:       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);
4524:     } else {
4525:       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);
4526:     }
4527:   }
4528:   if (!foundmtype) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_MISSING_FACTOR,"MatSolverType %s does not support matrix type %s",type,((PetscObject)mat)->type_name);
4529:   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);

4531:   (*conv)(mat,ftype,f);
4532:   return(0);
4533: }

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

4538:    Not Collective

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

4545:    Output Parameter:
4546: .    flg - PETSC_TRUE if the factorization is available

4548:    Notes:
4549:       Some PETSc matrix formats have alternative solvers available that are contained in alternative packages
4550:      such as pastix, superlu, mumps etc.

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

4554:    Level: intermediate

4556: .seealso: MatCopy(), MatDuplicate(), MatGetFactor()
4557: @*/
4558: PetscErrorCode MatGetFactorAvailable(Mat mat, MatSolverType type,MatFactorType ftype,PetscBool  *flg)
4559: {
4560:   PetscErrorCode ierr, (*gconv)(Mat,MatFactorType,Mat*);


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

4569:   *flg = PETSC_FALSE;
4570:   MatSolverTypeGet(type,((PetscObject)mat)->type_name,ftype,NULL,NULL,&gconv);
4571:   if (gconv) {
4572:     *flg = PETSC_TRUE;
4573:   }
4574:   return(0);
4575: }

4577:  #include <petscdmtypes.h>

4579: /*@
4580:    MatDuplicate - Duplicates a matrix including the non-zero structure.

4582:    Collective on Mat

4584:    Input Parameters:
4585: +  mat - the matrix
4586: -  op - One of MAT_DO_NOT_COPY_VALUES, MAT_COPY_VALUES, or MAT_SHARE_NONZERO_PATTERN.
4587:         See the manual page for MatDuplicateOption for an explanation of these options.

4589:    Output Parameter:
4590: .  M - pointer to place new matrix

4592:    Level: intermediate

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

4598: .seealso: MatCopy(), MatConvert(), MatDuplicateOption
4599: @*/
4600: PetscErrorCode MatDuplicate(Mat mat,MatDuplicateOption op,Mat *M)
4601: {
4603:   Mat            B;
4604:   PetscInt       i;
4605:   DM             dm;
4606:   void           (*viewf)(void);

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

4616:   *M = 0;
4617:   if (!mat->ops->duplicate) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Not written for matrix type %s\n",((PetscObject)mat)->type_name);
4618:   PetscLogEventBegin(MAT_Convert,mat,0,0,0);
4619:   (*mat->ops->duplicate)(mat,op,M);
4620:   B    = *M;

4622:   MatGetOperation(mat,MATOP_VIEW,&viewf);
4623:   if (viewf) {
4624:     MatSetOperation(B,MATOP_VIEW,viewf);
4625:   }

4627:   B->stencil.dim = mat->stencil.dim;
4628:   B->stencil.noc = mat->stencil.noc;
4629:   for (i=0; i<=mat->stencil.dim; i++) {
4630:     B->stencil.dims[i]   = mat->stencil.dims[i];
4631:     B->stencil.starts[i] = mat->stencil.starts[i];
4632:   }

4634:   B->nooffproczerorows = mat->nooffproczerorows;
4635:   B->nooffprocentries  = mat->nooffprocentries;

4637:   PetscObjectQuery((PetscObject) mat, "__PETSc_dm", (PetscObject*) &dm);
4638:   if (dm) {
4639:     PetscObjectCompose((PetscObject) B, "__PETSc_dm", (PetscObject) dm);
4640:   }
4641:   PetscLogEventEnd(MAT_Convert,mat,0,0,0);
4642:   PetscObjectStateIncrease((PetscObject)B);
4643:   return(0);
4644: }

4646: /*@
4647:    MatGetDiagonal - Gets the diagonal of a matrix.

4649:    Logically Collective on Mat

4651:    Input Parameters:
4652: +  mat - the matrix
4653: -  v - the vector for storing the diagonal

4655:    Output Parameter:
4656: .  v - the diagonal of the matrix

4658:    Level: intermediate

4660:    Note:
4661:    Currently only correct in parallel for square matrices.

4663: .seealso: MatGetRow(), MatCreateSubMatrices(), MatCreateSubMatrix(), MatGetRowMaxAbs()
4664: @*/
4665: PetscErrorCode MatGetDiagonal(Mat mat,Vec v)
4666: {

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

4677:   (*mat->ops->getdiagonal)(mat,v);
4678:   PetscObjectStateIncrease((PetscObject)v);
4679:   return(0);
4680: }

4682: /*@C
4683:    MatGetRowMin - Gets the minimum value (of the real part) of each
4684:         row of the matrix

4686:    Logically Collective on Mat

4688:    Input Parameters:
4689: .  mat - the matrix

4691:    Output Parameter:
4692: +  v - the vector for storing the maximums
4693: -  idx - the indices of the column found for each row (optional)

4695:    Level: intermediate

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

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

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

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

4718:   (*mat->ops->getrowmin)(mat,v,idx);
4719:   PetscObjectStateIncrease((PetscObject)v);
4720:   return(0);
4721: }

4723: /*@C
4724:    MatGetRowMinAbs - Gets the minimum value (in absolute value) of each
4725:         row of the matrix

4727:    Logically Collective on Mat

4729:    Input Parameters:
4730: .  mat - the matrix

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

4736:    Level: intermediate

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

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

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

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

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

4764: /*@C
4765:    MatGetRowMax - Gets the maximum value (of the real part) of each
4766:         row of the matrix

4768:    Logically Collective on Mat

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

4773:    Output Parameter:
4774: +  v - the vector for storing the maximums
4775: -  idx - the indices of the column found for each row (optional)

4777:    Level: intermediate

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

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

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

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

4799:   (*mat->ops->getrowmax)(mat,v,idx);
4800:   PetscObjectStateIncrease((PetscObject)v);
4801:   return(0);
4802: }

4804: /*@C
4805:    MatGetRowMaxAbs - Gets the maximum value (in absolute value) of each
4806:         row of the matrix

4808:    Logically Collective on Mat

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

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

4817:    Level: intermediate

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

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

4825: .seealso: MatGetDiagonal(), MatCreateSubMatrices(), MatCreateSubMatrix(), MatGetRowMax(), MatGetRowMin()
4826: @*/
4827: PetscErrorCode MatGetRowMaxAbs(Mat mat,Vec v,PetscInt idx[])
4828: {

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

4840:   (*mat->ops->getrowmaxabs)(mat,v,idx);
4841:   PetscObjectStateIncrease((PetscObject)v);
4842:   return(0);
4843: }

4845: /*@
4846:    MatGetRowSum - Gets the sum of each row of the matrix

4848:    Logically or Neighborhood Collective on Mat

4850:    Input Parameters:
4851: .  mat - the matrix

4853:    Output Parameter:
4854: .  v - the vector for storing the sum of rows

4856:    Level: intermediate

4858:    Notes:
4859:     This code is slow since it is not currently specialized for different formats

4861: .seealso: MatGetDiagonal(), MatCreateSubMatrices(), MatCreateSubMatrix(), MatGetRowMax(), MatGetRowMin()
4862: @*/
4863: PetscErrorCode MatGetRowSum(Mat mat, Vec v)
4864: {
4865:   Vec            ones;

4872:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
4873:   MatCheckPreallocated(mat,1);
4874:   MatCreateVecs(mat,&ones,NULL);
4875:   VecSet(ones,1.);
4876:   MatMult(mat,ones,v);
4877:   VecDestroy(&ones);
4878:   return(0);
4879: }

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

4884:    Collective on Mat

4886:    Input Parameter:
4887: +  mat - the matrix to transpose
4888: -  reuse - either MAT_INITIAL_MATRIX, MAT_REUSE_MATRIX, or MAT_INPLACE_MATRIX

4890:    Output Parameters:
4891: .  B - the transpose

4893:    Notes:
4894:      If you use MAT_INPLACE_MATRIX then you must pass in &mat for B

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

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

4900:    Level: intermediate

4902: .seealso: MatMultTranspose(), MatMultTransposeAdd(), MatIsTranspose(), MatReuse
4903: @*/
4904: PetscErrorCode MatTranspose(Mat mat,MatReuse reuse,Mat *B)
4905: {

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

4918:   PetscLogEventBegin(MAT_Transpose,mat,0,0,0);
4919:   (*mat->ops->transpose)(mat,reuse,B);
4920:   PetscLogEventEnd(MAT_Transpose,mat,0,0,0);
4921:   if (B) {PetscObjectStateIncrease((PetscObject)*B);}
4922:   return(0);
4923: }

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

4929:    Collective on Mat

4931:    Input Parameter:
4932: +  A - the matrix to test
4933: -  B - the matrix to test against, this can equal the first parameter

4935:    Output Parameters:
4936: .  flg - the result

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

4943:    Level: intermediate

4945: .seealso: MatTranspose(), MatIsSymmetric(), MatIsHermitian()
4946: @*/
4947: PetscErrorCode MatIsTranspose(Mat A,Mat B,PetscReal tol,PetscBool  *flg)
4948: {
4949:   PetscErrorCode ierr,(*f)(Mat,Mat,PetscReal,PetscBool*),(*g)(Mat,Mat,PetscReal,PetscBool*);

4955:   PetscObjectQueryFunction((PetscObject)A,"MatIsTranspose_C",&f);
4956:   PetscObjectQueryFunction((PetscObject)B,"MatIsTranspose_C",&g);
4957:   *flg = PETSC_FALSE;
4958:   if (f && g) {
4959:     if (f == g) {
4960:       (*f)(A,B,tol,flg);
4961:     } else SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_NOTSAMETYPE,"Matrices do not have the same comparator for symmetry test");
4962:   } else {
4963:     MatType mattype;
4964:     if (!f) {
4965:       MatGetType(A,&mattype);
4966:     } else {
4967:       MatGetType(B,&mattype);
4968:     }
4969:     SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Matrix of type %s does not support checking for transpose",mattype);
4970:   }
4971:   return(0);
4972: }

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

4977:    Collective on Mat

4979:    Input Parameter:
4980: +  mat - the matrix to transpose and complex conjugate
4981: -  reuse - MAT_INITIAL_MATRIX to create a new matrix, MAT_INPLACE_MATRIX to reuse the first argument to store the transpose

4983:    Output Parameters:
4984: .  B - the Hermitian

4986:    Level: intermediate

4988: .seealso: MatTranspose(), MatMultTranspose(), MatMultTransposeAdd(), MatIsTranspose(), MatReuse
4989: @*/
4990: PetscErrorCode MatHermitianTranspose(Mat mat,MatReuse reuse,Mat *B)
4991: {

4995:   MatTranspose(mat,reuse,B);
4996: #if defined(PETSC_USE_COMPLEX)
4997:   MatConjugate(*B);
4998: #endif
4999:   return(0);
5000: }

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

5005:    Collective on Mat

5007:    Input Parameter:
5008: +  A - the matrix to test
5009: -  B - the matrix to test against, this can equal the first parameter

5011:    Output Parameters:
5012: .  flg - the result

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

5019:    Level: intermediate

5021: .seealso: MatTranspose(), MatIsSymmetric(), MatIsHermitian(), MatIsTranspose()
5022: @*/
5023: PetscErrorCode MatIsHermitianTranspose(Mat A,Mat B,PetscReal tol,PetscBool  *flg)
5024: {
5025:   PetscErrorCode ierr,(*f)(Mat,Mat,PetscReal,PetscBool*),(*g)(Mat,Mat,PetscReal,PetscBool*);

5031:   PetscObjectQueryFunction((PetscObject)A,"MatIsHermitianTranspose_C",&f);
5032:   PetscObjectQueryFunction((PetscObject)B,"MatIsHermitianTranspose_C",&g);
5033:   if (f && g) {
5034:     if (f==g) {
5035:       (*f)(A,B,tol,flg);
5036:     } else SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_NOTSAMETYPE,"Matrices do not have the same comparator for Hermitian test");
5037:   }
5038:   return(0);
5039: }

5041: /*@
5042:    MatPermute - Creates a new matrix with rows and columns permuted from the
5043:    original.

5045:    Collective on Mat

5047:    Input Parameters:
5048: +  mat - the matrix to permute
5049: .  row - row permutation, each processor supplies only the permutation for its rows
5050: -  col - column permutation, each processor supplies only the permutation for its columns

5052:    Output Parameters:
5053: .  B - the permuted matrix

5055:    Level: advanced

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

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

5063: @*/
5064: PetscErrorCode MatPermute(Mat mat,IS row,IS col,Mat *B)
5065: {

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

5079:   (*mat->ops->permute)(mat,row,col,B);
5080:   PetscObjectStateIncrease((PetscObject)*B);
5081:   return(0);
5082: }

5084: /*@
5085:    MatEqual - Compares two matrices.

5087:    Collective on Mat

5089:    Input Parameters:
5090: +  A - the first matrix
5091: -  B - the second matrix

5093:    Output Parameter:
5094: .  flg - PETSC_TRUE if the matrices are equal; PETSC_FALSE otherwise.

5096:    Level: intermediate

5098: @*/
5099: PetscErrorCode MatEqual(Mat A,Mat B,PetscBool  *flg)
5100: {

5110:   MatCheckPreallocated(B,2);
5111:   if (!A->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
5112:   if (!B->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
5113:   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);
5114:   if (!A->ops->equal) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Mat type %s",((PetscObject)A)->type_name);
5115:   if (!B->ops->equal) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Mat type %s",((PetscObject)B)->type_name);
5116:   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);
5117:   MatCheckPreallocated(A,1);

5119:   (*A->ops->equal)(A,B,flg);
5120:   return(0);
5121: }

5123: /*@
5124:    MatDiagonalScale - Scales a matrix on the left and right by diagonal
5125:    matrices that are stored as vectors.  Either of the two scaling
5126:    matrices can be NULL.

5128:    Collective on Mat

5130:    Input Parameters:
5131: +  mat - the matrix to be scaled
5132: .  l - the left scaling vector (or NULL)
5133: -  r - the right scaling vector (or NULL)

5135:    Notes:
5136:    MatDiagonalScale() computes A = LAR, where
5137:    L = a diagonal matrix (stored as a vector), R = a diagonal matrix (stored as a vector)
5138:    The L scales the rows of the matrix, the R scales the columns of the matrix.

5140:    Level: intermediate


5143: .seealso: MatScale(), MatShift(), MatDiagonalSet()
5144: @*/
5145: PetscErrorCode MatDiagonalScale(Mat mat,Vec l,Vec r)
5146: {

5154:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
5155:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
5156:   MatCheckPreallocated(mat,1);
5157:   if (!l && !r) return(0);

5159:   if (!mat->ops->diagonalscale) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
5160:   PetscLogEventBegin(MAT_Scale,mat,0,0,0);
5161:   (*mat->ops->diagonalscale)(mat,l,r);
5162:   PetscLogEventEnd(MAT_Scale,mat,0,0,0);
5163:   PetscObjectStateIncrease((PetscObject)mat);
5164:   return(0);
5165: }

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

5170:     Logically Collective on Mat

5172:     Input Parameters:
5173: +   mat - the matrix to be scaled
5174: -   a  - the scaling value

5176:     Output Parameter:
5177: .   mat - the scaled matrix

5179:     Level: intermediate

5181: .seealso: MatDiagonalScale()
5182: @*/
5183: PetscErrorCode MatScale(Mat mat,PetscScalar a)
5184: {

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

5196:   PetscLogEventBegin(MAT_Scale,mat,0,0,0);
5197:   if (a != (PetscScalar)1.0) {
5198:     (*mat->ops->scale)(mat,a);
5199:     PetscObjectStateIncrease((PetscObject)mat);
5200:   }
5201:   PetscLogEventEnd(MAT_Scale,mat,0,0,0);
5202:   return(0);
5203: }

5205: /*@
5206:    MatNorm - Calculates various norms of a matrix.

5208:    Collective on Mat

5210:    Input Parameters:
5211: +  mat - the matrix
5212: -  type - the type of norm, NORM_1, NORM_FROBENIUS, NORM_INFINITY

5214:    Output Parameters:
5215: .  nrm - the resulting norm

5217:    Level: intermediate

5219: @*/
5220: PetscErrorCode MatNorm(Mat mat,NormType type,PetscReal *nrm)
5221: {


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

5234:   (*mat->ops->norm)(mat,type,nrm);
5235:   return(0);
5236: }

5238: /*
5239:      This variable is used to prevent counting of MatAssemblyBegin() that
5240:    are called from within a MatAssemblyEnd().
5241: */
5242: static PetscInt MatAssemblyEnd_InUse = 0;
5243: /*@
5244:    MatAssemblyBegin - Begins assembling the matrix.  This routine should
5245:    be called after completing all calls to MatSetValues().

5247:    Collective on Mat

5249:    Input Parameters:
5250: +  mat - the matrix
5251: -  type - type of assembly, either MAT_FLUSH_ASSEMBLY or MAT_FINAL_ASSEMBLY

5253:    Notes:
5254:    MatSetValues() generally caches the values.  The matrix is ready to
5255:    use only after MatAssemblyBegin() and MatAssemblyEnd() have been called.
5256:    Use MAT_FLUSH_ASSEMBLY when switching between ADD_VALUES and INSERT_VALUES
5257:    in MatSetValues(); use MAT_FINAL_ASSEMBLY for the final assembly before
5258:    using the matrix.

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

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

5268:    Level: beginner

5270: .seealso: MatAssemblyEnd(), MatSetValues(), MatAssembled()
5271: @*/
5272: PetscErrorCode MatAssemblyBegin(Mat mat,MatAssemblyType type)
5273: {

5279:   MatCheckPreallocated(mat,1);
5280:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix.\nDid you forget to call MatSetUnfactored()?");
5281:   if (mat->assembled) {
5282:     mat->was_assembled = PETSC_TRUE;
5283:     mat->assembled     = PETSC_FALSE;
5284:   }

5286:   if (!MatAssemblyEnd_InUse) {
5287:     PetscLogEventBegin(MAT_AssemblyBegin,mat,0,0,0);
5288:     if (mat->ops->assemblybegin) {(*mat->ops->assemblybegin)(mat,type);}
5289:     PetscLogEventEnd(MAT_AssemblyBegin,mat,0,0,0);
5290:   } else if (mat->ops->assemblybegin) {
5291:     (*mat->ops->assemblybegin)(mat,type);
5292:   }
5293:   return(0);
5294: }

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

5300:    Not Collective

5302:    Input Parameter:
5303: .  mat - the matrix

5305:    Output Parameter:
5306: .  assembled - PETSC_TRUE or PETSC_FALSE

5308:    Level: advanced

5310: .seealso: MatAssemblyEnd(), MatSetValues(), MatAssemblyBegin()
5311: @*/
5312: PetscErrorCode MatAssembled(Mat mat,PetscBool  *assembled)
5313: {
5317:   *assembled = mat->assembled;
5318:   return(0);
5319: }

5321: /*@
5322:    MatAssemblyEnd - Completes assembling the matrix.  This routine should
5323:    be called after MatAssemblyBegin().

5325:    Collective on Mat

5327:    Input Parameters:
5328: +  mat - the matrix
5329: -  type - type of assembly, either MAT_FLUSH_ASSEMBLY or MAT_FINAL_ASSEMBLY

5331:    Options Database Keys:
5332: +  -mat_view ::ascii_info - Prints info on matrix at conclusion of MatEndAssembly()
5333: .  -mat_view ::ascii_info_detail - Prints more detailed info
5334: .  -mat_view - Prints matrix in ASCII format
5335: .  -mat_view ::ascii_matlab - Prints matrix in Matlab format
5336: .  -mat_view draw - PetscDraws nonzero structure of matrix, using MatView() and PetscDrawOpenX().
5337: .  -display <name> - Sets display name (default is host)
5338: .  -draw_pause <sec> - Sets number of seconds to pause after display
5339: .  -mat_view socket - Sends matrix to socket, can be accessed from Matlab (See Users-Manual: Chapter 12 Using MATLAB with PETSc )
5340: .  -viewer_socket_machine <machine> - Machine to use for socket
5341: .  -viewer_socket_port <port> - Port number to use for socket
5342: -  -mat_view binary:filename[:append] - Save matrix to file in binary format

5344:    Notes:
5345:    MatSetValues() generally caches the values.  The matrix is ready to
5346:    use only after MatAssemblyBegin() and MatAssemblyEnd() have been called.
5347:    Use MAT_FLUSH_ASSEMBLY when switching between ADD_VALUES and INSERT_VALUES
5348:    in MatSetValues(); use MAT_FINAL_ASSEMBLY for the final assembly before
5349:    using the matrix.

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

5355:    Level: beginner

5357: .seealso: MatAssemblyBegin(), MatSetValues(), PetscDrawOpenX(), PetscDrawCreate(), MatView(), MatAssembled(), PetscViewerSocketOpen()
5358: @*/
5359: PetscErrorCode MatAssemblyEnd(Mat mat,MatAssemblyType type)
5360: {
5361:   PetscErrorCode  ierr;
5362:   static PetscInt inassm = 0;
5363:   PetscBool       flg    = PETSC_FALSE;


5369:   inassm++;
5370:   MatAssemblyEnd_InUse++;
5371:   if (MatAssemblyEnd_InUse == 1) { /* Do the logging only the first time through */
5372:     PetscLogEventBegin(MAT_AssemblyEnd,mat,0,0,0);
5373:     if (mat->ops->assemblyend) {
5374:       (*mat->ops->assemblyend)(mat,type);
5375:     }
5376:     PetscLogEventEnd(MAT_AssemblyEnd,mat,0,0,0);
5377:   } else if (mat->ops->assemblyend) {
5378:     (*mat->ops->assemblyend)(mat,type);
5379:   }

5381:   /* Flush assembly is not a true assembly */
5382:   if (type != MAT_FLUSH_ASSEMBLY) {
5383:     mat->num_ass++;
5384:     mat->assembled        = PETSC_TRUE;
5385:     mat->ass_nonzerostate = mat->nonzerostate;
5386:   }

5388:   mat->insertmode = NOT_SET_VALUES;
5389:   MatAssemblyEnd_InUse--;
5390:   PetscObjectStateIncrease((PetscObject)mat);
5391:   if (!mat->symmetric_eternal) {
5392:     mat->symmetric_set              = PETSC_FALSE;
5393:     mat->hermitian_set              = PETSC_FALSE;
5394:     mat->structurally_symmetric_set = PETSC_FALSE;
5395:   }
5396:   if (inassm == 1 && type != MAT_FLUSH_ASSEMBLY) {
5397:     MatViewFromOptions(mat,NULL,"-mat_view");

5399:     if (mat->checksymmetryonassembly) {
5400:       MatIsSymmetric(mat,mat->checksymmetrytol,&flg);
5401:       if (flg) {
5402:         PetscPrintf(PetscObjectComm((PetscObject)mat),"Matrix is symmetric (tolerance %g)\n",(double)mat->checksymmetrytol);
5403:       } else {
5404:         PetscPrintf(PetscObjectComm((PetscObject)mat),"Matrix is not symmetric (tolerance %g)\n",(double)mat->checksymmetrytol);
5405:       }
5406:     }
5407:     if (mat->nullsp && mat->checknullspaceonassembly) {
5408:       MatNullSpaceTest(mat->nullsp,mat,NULL);
5409:     }
5410:   }
5411:   inassm--;
5412:   return(0);
5413: }

5415: /*@
5416:    MatSetOption - Sets a parameter option for a matrix. Some options
5417:    may be specific to certain storage formats.  Some options
5418:    determine how values will be inserted (or added). Sorted,
5419:    row-oriented input will generally assemble the fastest. The default
5420:    is row-oriented.

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

5424:    Input Parameters:
5425: +  mat - the matrix
5426: .  option - the option, one of those listed below (and possibly others),
5427: -  flg - turn the option on (PETSC_TRUE) or off (PETSC_FALSE)

5429:   Options Describing Matrix Structure:
5430: +    MAT_SPD - symmetric positive definite
5431: .    MAT_SYMMETRIC - symmetric in terms of both structure and value
5432: .    MAT_HERMITIAN - transpose is the complex conjugation
5433: .    MAT_STRUCTURALLY_SYMMETRIC - symmetric nonzero structure
5434: -    MAT_SYMMETRY_ETERNAL - if you would like the symmetry/Hermitian flag
5435:                             you set to be kept with all future use of the matrix
5436:                             including after MatAssemblyBegin/End() which could
5437:                             potentially change the symmetry structure, i.e. you
5438:                             KNOW the matrix will ALWAYS have the property you set.
5439:                             Note that setting this flag alone implies nothing about whether the matrix is symmetric/Hermitian;
5440:                             the relevant flags must be set independently.


5443:    Options For Use with MatSetValues():
5444:    Insert a logically dense subblock, which can be
5445: .    MAT_ROW_ORIENTED - row-oriented (default)

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

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

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

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

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

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

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

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

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

5499:    MAT_USE_HASH_TABLE indicates that a hash table be used to improve the
5500:    searches during matrix assembly. When this flag is set, the hash table
5501:    is created during the first Matrix Assembly. This hash table is
5502:    used the next time through, during MatSetVaules()/MatSetVaulesBlocked()
5503:    to improve the searching of indices. MAT_NEW_NONZERO_LOCATIONS flag
5504:    should be used with MAT_USE_HASH_TABLE flag. This option is currently
5505:    supported by MATMPIBAIJ format only.

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

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

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

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

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

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

5527:    Level: intermediate

5529: .seealso:  MatOption, Mat

5531: @*/
5532: PetscErrorCode MatSetOption(Mat mat,MatOption op,PetscBool flg)
5533: {

5539:   if (op > 0) {
5542:   }

5544:   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);
5545:   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()");

5547:   switch (op) {
5548:   case MAT_NO_OFF_PROC_ENTRIES:
5549:     mat->nooffprocentries = flg;
5550:     return(0);
5551:     break;
5552:   case MAT_SUBSET_OFF_PROC_ENTRIES:
5553:     mat->assembly_subset = flg;
5554:     if (!mat->assembly_subset) { /* See the same logic in VecAssembly wrt VEC_SUBSET_OFF_PROC_ENTRIES */
5555: #if !defined(PETSC_HAVE_MPIUNI)
5556:       MatStashScatterDestroy_BTS(&mat->stash);
5557: #endif
5558:       mat->stash.first_assembly_done = PETSC_FALSE;
5559:     }
5560:     return(0);
5561:   case MAT_NO_OFF_PROC_ZERO_ROWS:
5562:     mat->nooffproczerorows = flg;
5563:     return(0);
5564:     break;
5565:   case MAT_SPD:
5566:     mat->spd_set = PETSC_TRUE;
5567:     mat->spd     = flg;
5568:     if (flg) {
5569:       mat->symmetric                  = PETSC_TRUE;
5570:       mat->structurally_symmetric     = PETSC_TRUE;
5571:       mat->symmetric_set              = PETSC_TRUE;
5572:       mat->structurally_symmetric_set = PETSC_TRUE;
5573:     }
5574:     break;
5575:   case MAT_SYMMETRIC:
5576:     mat->symmetric = flg;
5577:     if (flg) mat->structurally_symmetric = PETSC_TRUE;
5578:     mat->symmetric_set              = PETSC_TRUE;
5579:     mat->structurally_symmetric_set = flg;
5580: #if !defined(PETSC_USE_COMPLEX)
5581:     mat->hermitian     = flg;
5582:     mat->hermitian_set = PETSC_TRUE;
5583: #endif
5584:     break;
5585:   case MAT_HERMITIAN:
5586:     mat->hermitian = flg;
5587:     if (flg) mat->structurally_symmetric = PETSC_TRUE;
5588:     mat->hermitian_set              = PETSC_TRUE;
5589:     mat->structurally_symmetric_set = flg;
5590: #if !defined(PETSC_USE_COMPLEX)
5591:     mat->symmetric     = flg;
5592:     mat->symmetric_set = PETSC_TRUE;
5593: #endif
5594:     break;
5595:   case MAT_STRUCTURALLY_SYMMETRIC:
5596:     mat->structurally_symmetric     = flg;
5597:     mat->structurally_symmetric_set = PETSC_TRUE;
5598:     break;
5599:   case MAT_SYMMETRY_ETERNAL:
5600:     mat->symmetric_eternal = flg;
5601:     break;
5602:   case MAT_STRUCTURE_ONLY:
5603:     mat->structure_only = flg;
5604:     break;
5605:   case MAT_SORTED_FULL:
5606:     mat->sortedfull = flg;
5607:     break;
5608:   default:
5609:     break;
5610:   }
5611:   if (mat->ops->setoption) {
5612:     (*mat->ops->setoption)(mat,op,flg);
5613:   }
5614:   return(0);
5615: }

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

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

5622:    Input Parameters:
5623: +  mat - the matrix
5624: -  option - the option, this only responds to certain options, check the code for which ones

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

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

5632:    Level: intermediate

5634: .seealso:  MatOption, MatSetOption()

5636: @*/
5637: PetscErrorCode MatGetOption(Mat mat,MatOption op,PetscBool *flg)
5638: {

5643:   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);
5644:   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()");

5646:   switch (op) {
5647:   case MAT_NO_OFF_PROC_ENTRIES:
5648:     *flg = mat->nooffprocentries;
5649:     break;
5650:   case MAT_NO_OFF_PROC_ZERO_ROWS:
5651:     *flg = mat->nooffproczerorows;
5652:     break;
5653:   case MAT_SYMMETRIC:
5654:     *flg = mat->symmetric;
5655:     break;
5656:   case MAT_HERMITIAN:
5657:     *flg = mat->hermitian;
5658:     break;
5659:   case MAT_STRUCTURALLY_SYMMETRIC:
5660:     *flg = mat->structurally_symmetric;
5661:     break;
5662:   case MAT_SYMMETRY_ETERNAL:
5663:     *flg = mat->symmetric_eternal;
5664:     break;
5665:   case MAT_SPD:
5666:     *flg = mat->spd;
5667:     break;
5668:   default:
5669:     break;
5670:   }
5671:   return(0);
5672: }

5674: /*@
5675:    MatZeroEntries - Zeros all entries of a matrix.  For sparse matrices
5676:    this routine retains the old nonzero structure.

5678:    Logically Collective on Mat

5680:    Input Parameters:
5681: .  mat - the matrix

5683:    Level: intermediate

5685:    Notes:
5686:     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.
5687:    See the Performance chapter of the users manual for information on preallocating matrices.

5689: .seealso: MatZeroRows()
5690: @*/
5691: PetscErrorCode MatZeroEntries(Mat mat)
5692: {

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

5703:   PetscLogEventBegin(MAT_ZeroEntries,mat,0,0,0);
5704:   (*mat->ops->zeroentries)(mat);
5705:   PetscLogEventEnd(MAT_ZeroEntries,mat,0,0,0);
5706:   PetscObjectStateIncrease((PetscObject)mat);
5707:   return(0);
5708: }

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

5714:    Collective on Mat

5716:    Input Parameters:
5717: +  mat - the matrix
5718: .  numRows - the number of rows to remove
5719: .  rows - the global row indices
5720: .  diag - value put in all diagonals of eliminated rows (0.0 will even eliminate diagonal entry)
5721: .  x - optional vector of solutions for zeroed rows (other entries in vector are not used)
5722: -  b - optional vector of right hand side, that will be adjusted by provided solution

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

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

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

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

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

5741:    Level: intermediate

5743: .seealso: MatZeroRowsIS(), MatZeroRows(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
5744:           MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
5745: @*/
5746: PetscErrorCode MatZeroRowsColumns(Mat mat,PetscInt numRows,const PetscInt rows[],PetscScalar diag,Vec x,Vec b)
5747: {

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

5759:   (*mat->ops->zerorowscolumns)(mat,numRows,rows,diag,x,b);
5760:   MatViewFromOptions(mat,NULL,"-mat_view");
5761:   PetscObjectStateIncrease((PetscObject)mat);
5762:   return(0);
5763: }

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

5769:    Collective on Mat

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

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

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

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

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

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

5795:    Level: intermediate

5797: .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
5798:           MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRows(), MatZeroRowsColumnsStencil()
5799: @*/
5800: PetscErrorCode MatZeroRowsColumnsIS(Mat mat,IS is,PetscScalar diag,Vec x,Vec b)
5801: {
5803:   PetscInt       numRows;
5804:   const PetscInt *rows;

5811:   ISGetLocalSize(is,&numRows);
5812:   ISGetIndices(is,&rows);
5813:   MatZeroRowsColumns(mat,numRows,rows,diag,x,b);
5814:   ISRestoreIndices(is,&rows);
5815:   return(0);
5816: }

5818: /*@
5819:    MatZeroRows - Zeros all entries (except possibly the main diagonal)
5820:    of a set of rows of a matrix.

5822:    Collective on Mat

5824:    Input Parameters:
5825: +  mat - the matrix
5826: .  numRows - the number of rows to remove
5827: .  rows - the global row indices
5828: .  diag - value put in all diagonals of eliminated rows (0.0 will even eliminate diagonal entry)
5829: .  x - optional vector of solutions for zeroed rows (other entries in vector are not used)
5830: -  b - optional vector of right hand side, that will be adjusted by provided solution

5832:    Notes:
5833:    For the AIJ and BAIJ matrix formats this removes the old nonzero structure,
5834:    but does not release memory.  For the dense and block diagonal
5835:    formats this does not alter the nonzero structure.

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

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

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

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

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

5856:    Level: intermediate

5858: .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
5859:           MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
5860: @*/
5861: PetscErrorCode MatZeroRows(Mat mat,PetscInt numRows,const PetscInt rows[],PetscScalar diag,Vec x,Vec b)
5862: {

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

5874:   (*mat->ops->zerorows)(mat,numRows,rows,diag,x,b);
5875:   MatViewFromOptions(mat,NULL,"-mat_view");
5876:   PetscObjectStateIncrease((PetscObject)mat);
5877:   return(0);
5878: }

5880: /*@
5881:    MatZeroRowsIS - Zeros all entries (except possibly the main diagonal)
5882:    of a set of rows of a matrix.

5884:    Collective on Mat

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

5893:    Notes:
5894:    For the AIJ and BAIJ matrix formats this removes the old nonzero structure,
5895:    but does not release memory.  For the dense and block diagonal
5896:    formats this does not alter the nonzero structure.

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

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

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

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

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

5917:    Level: intermediate

5919: .seealso: MatZeroRows(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
5920:           MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
5921: @*/
5922: PetscErrorCode MatZeroRowsIS(Mat mat,IS is,PetscScalar diag,Vec x,Vec b)
5923: {
5924:   PetscInt       numRows;
5925:   const PetscInt *rows;

5932:   ISGetLocalSize(is,&numRows);
5933:   ISGetIndices(is,&rows);
5934:   MatZeroRows(mat,numRows,rows,diag,x,b);
5935:   ISRestoreIndices(is,&rows);
5936:   return(0);
5937: }

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

5943:    Collective on Mat

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

5953:    Notes:
5954:    For the AIJ and BAIJ matrix formats this removes the old nonzero structure,
5955:    but does not release memory.  For the dense and block diagonal
5956:    formats this does not alter the nonzero structure.

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

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

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

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

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

5976:    In Fortran idxm and idxn should be declared as
5977: $     MatStencil idxm(4,m)
5978:    and the values inserted using
5979: $    idxm(MatStencil_i,1) = i
5980: $    idxm(MatStencil_j,1) = j
5981: $    idxm(MatStencil_k,1) = k
5982: $    idxm(MatStencil_c,1) = c
5983:    etc

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

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

5993:    Level: intermediate

5995: .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsl(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
5996:           MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
5997: @*/
5998: PetscErrorCode MatZeroRowsStencil(Mat mat,PetscInt numRows,const MatStencil rows[],PetscScalar diag,Vec x,Vec b)
5999: {
6000:   PetscInt       dim     = mat->stencil.dim;
6001:   PetscInt       sdim    = dim - (1 - (PetscInt) mat->stencil.noc);
6002:   PetscInt       *dims   = mat->stencil.dims+1;
6003:   PetscInt       *starts = mat->stencil.starts;
6004:   PetscInt       *dxm    = (PetscInt*) rows;
6005:   PetscInt       *jdxm, i, j, tmp, numNewRows = 0;


6013:   PetscMalloc1(numRows, &jdxm);
6014:   for (i = 0; i < numRows; ++i) {
6015:     /* Skip unused dimensions (they are ordered k, j, i, c) */
6016:     for (j = 0; j < 3-sdim; ++j) dxm++;
6017:     /* Local index in X dir */
6018:     tmp = *dxm++ - starts[0];
6019:     /* Loop over remaining dimensions */
6020:     for (j = 0; j < dim-1; ++j) {
6021:       /* If nonlocal, set index to be negative */
6022:       if ((*dxm++ - starts[j+1]) < 0 || tmp < 0) tmp = PETSC_MIN_INT;
6023:       /* Update local index */
6024:       else tmp = tmp*dims[j] + *(dxm-1) - starts[j+1];
6025:     }
6026:     /* Skip component slot if necessary */
6027:     if (mat->stencil.noc) dxm++;
6028:     /* Local row number */
6029:     if (tmp >= 0) {
6030:       jdxm[numNewRows++] = tmp;
6031:     }
6032:   }
6033:   MatZeroRowsLocal(mat,numNewRows,jdxm,diag,x,b);
6034:   PetscFree(jdxm);
6035:   return(0);
6036: }

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

6042:    Collective on Mat

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

6052:    Notes:
6053:    For the AIJ and BAIJ matrix formats this removes the old nonzero structure,
6054:    but does not release memory.  For the dense and block diagonal
6055:    formats this does not alter the nonzero structure.

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

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

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

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

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

6075:    In Fortran idxm and idxn should be declared as
6076: $     MatStencil idxm(4,m)
6077:    and the values inserted using
6078: $    idxm(MatStencil_i,1) = i
6079: $    idxm(MatStencil_j,1) = j
6080: $    idxm(MatStencil_k,1) = k
6081: $    idxm(MatStencil_c,1) = c
6082:    etc

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

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

6092:    Level: intermediate

6094: .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
6095:           MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRows()
6096: @*/
6097: PetscErrorCode MatZeroRowsColumnsStencil(Mat mat,PetscInt numRows,const MatStencil rows[],PetscScalar diag,Vec x,Vec b)
6098: {
6099:   PetscInt       dim     = mat->stencil.dim;
6100:   PetscInt       sdim    = dim - (1 - (PetscInt) mat->stencil.noc);
6101:   PetscInt       *dims   = mat->stencil.dims+1;
6102:   PetscInt       *starts = mat->stencil.starts;
6103:   PetscInt       *dxm    = (PetscInt*) rows;
6104:   PetscInt       *jdxm, i, j, tmp, numNewRows = 0;


6112:   PetscMalloc1(numRows, &jdxm);
6113:   for (i = 0; i < numRows; ++i) {
6114:     /* Skip unused dimensions (they are ordered k, j, i, c) */
6115:     for (j = 0; j < 3-sdim; ++j) dxm++;
6116:     /* Local index in X dir */
6117:     tmp = *dxm++ - starts[0];
6118:     /* Loop over remaining dimensions */
6119:     for (j = 0; j < dim-1; ++j) {
6120:       /* If nonlocal, set index to be negative */
6121:       if ((*dxm++ - starts[j+1]) < 0 || tmp < 0) tmp = PETSC_MIN_INT;
6122:       /* Update local index */
6123:       else tmp = tmp*dims[j] + *(dxm-1) - starts[j+1];
6124:     }
6125:     /* Skip component slot if necessary */
6126:     if (mat->stencil.noc) dxm++;
6127:     /* Local row number */
6128:     if (tmp >= 0) {
6129:       jdxm[numNewRows++] = tmp;
6130:     }
6131:   }
6132:   MatZeroRowsColumnsLocal(mat,numNewRows,jdxm,diag,x,b);
6133:   PetscFree(jdxm);
6134:   return(0);
6135: }

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

6141:    Collective on Mat

6143:    Input Parameters:
6144: +  mat - the matrix
6145: .  numRows - the number of rows to remove
6146: .  rows - the global row indices
6147: .  diag - value put in all diagonals of eliminated rows
6148: .  x - optional vector of solutions for zeroed rows (other entries in vector are not used)
6149: -  b - optional vector of right hand side, that will be adjusted by provided solution

6151:    Notes:
6152:    Before calling MatZeroRowsLocal(), the user must first set the
6153:    local-to-global mapping by calling MatSetLocalToGlobalMapping().

6155:    For the AIJ matrix formats this removes the old nonzero structure,
6156:    but does not release memory.  For the dense and block diagonal
6157:    formats this does not alter the nonzero structure.

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

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

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

6170:    Level: intermediate

6172: .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRows(), MatSetOption(),
6173:           MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
6174: @*/
6175: PetscErrorCode MatZeroRowsLocal(Mat mat,PetscInt numRows,const PetscInt rows[],PetscScalar diag,Vec x,Vec b)
6176: {

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

6187:   if (mat->ops->zerorowslocal) {
6188:     (*mat->ops->zerorowslocal)(mat,numRows,rows,diag,x,b);
6189:   } else {
6190:     IS             is, newis;
6191:     const PetscInt *newRows;

6193:     if (!mat->rmap->mapping) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Need to provide local to global mapping to matrix first");
6194:     ISCreateGeneral(PETSC_COMM_SELF,numRows,rows,PETSC_COPY_VALUES,&is);
6195:     ISLocalToGlobalMappingApplyIS(mat->rmap->mapping,is,&newis);
6196:     ISGetIndices(newis,&newRows);
6197:     (*mat->ops->zerorows)(mat,numRows,newRows,diag,x,b);
6198:     ISRestoreIndices(newis,&newRows);
6199:     ISDestroy(&newis);
6200:     ISDestroy(&is);
6201:   }
6202:   PetscObjectStateIncrease((PetscObject)mat);
6203:   return(0);
6204: }

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

6210:    Collective on Mat

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

6219:    Notes:
6220:    Before calling MatZeroRowsLocalIS(), the user must first set the
6221:    local-to-global mapping by calling MatSetLocalToGlobalMapping().

6223:    For the AIJ matrix formats this removes the old nonzero structure,
6224:    but does not release memory.  For the dense and block diagonal
6225:    formats this does not alter the nonzero structure.

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

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

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

6238:    Level: intermediate

6240: .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRows(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
6241:           MatZeroRowsColumnsLocal(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
6242: @*/
6243: PetscErrorCode MatZeroRowsLocalIS(Mat mat,IS is,PetscScalar diag,Vec x,Vec b)
6244: {
6246:   PetscInt       numRows;
6247:   const PetscInt *rows;

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

6257:   ISGetLocalSize(is,&numRows);
6258:   ISGetIndices(is,&rows);
6259:   MatZeroRowsLocal(mat,numRows,rows,diag,x,b);
6260:   ISRestoreIndices(is,&rows);
6261:   return(0);
6262: }

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

6268:    Collective on Mat

6270:    Input Parameters:
6271: +  mat - the matrix
6272: .  numRows - the number of rows to remove
6273: .  rows - the global row indices
6274: .  diag - value put in all diagonals of eliminated rows
6275: .  x - optional vector of solutions for zeroed rows (other entries in vector are not used)
6276: -  b - optional vector of right hand side, that will be adjusted by provided solution

6278:    Notes:
6279:    Before calling MatZeroRowsColumnsLocal(), the user must first set the
6280:    local-to-global mapping by calling MatSetLocalToGlobalMapping().

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

6286:    Level: intermediate

6288: .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
6289:           MatZeroRows(), MatZeroRowsColumnsLocalIS(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
6290: @*/
6291: PetscErrorCode MatZeroRowsColumnsLocal(Mat mat,PetscInt numRows,const PetscInt rows[],PetscScalar diag,Vec x,Vec b)
6292: {
6294:   IS             is, newis;
6295:   const PetscInt *newRows;

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

6305:   if (!mat->cmap->mapping) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Need to provide local to global mapping to matrix first");
6306:   ISCreateGeneral(PETSC_COMM_SELF,numRows,rows,PETSC_COPY_VALUES,&is);
6307:   ISLocalToGlobalMappingApplyIS(mat->cmap->mapping,is,&newis);
6308:   ISGetIndices(newis,&newRows);
6309:   (*mat->ops->zerorowscolumns)(mat,numRows,newRows,diag,x,b);
6310:   ISRestoreIndices(newis,&newRows);
6311:   ISDestroy(&newis);
6312:   ISDestroy(&is);
6313:   PetscObjectStateIncrease((PetscObject)mat);
6314:   return(0);
6315: }

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

6321:    Collective on Mat

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

6330:    Notes:
6331:    Before calling MatZeroRowsColumnsLocalIS(), the user must first set the
6332:    local-to-global mapping by calling MatSetLocalToGlobalMapping().

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

6338:    Level: intermediate

6340: .seealso: MatZeroRowsIS(), MatZeroRowsColumns(), MatZeroRowsLocalIS(), MatZeroRowsStencil(), MatZeroEntries(), MatZeroRowsLocal(), MatSetOption(),
6341:           MatZeroRowsColumnsLocal(), MatZeroRows(), MatZeroRowsColumnsIS(), MatZeroRowsColumnsStencil()
6342: @*/
6343: PetscErrorCode MatZeroRowsColumnsLocalIS(Mat mat,IS is,PetscScalar diag,Vec x,Vec b)
6344: {
6346:   PetscInt       numRows;
6347:   const PetscInt *rows;

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

6357:   ISGetLocalSize(is,&numRows);
6358:   ISGetIndices(is,&rows);
6359:   MatZeroRowsColumnsLocal(mat,numRows,rows,diag,x,b);
6360:   ISRestoreIndices(is,&rows);
6361:   return(0);
6362: }

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

6367:    Not Collective

6369:    Input Parameter:
6370: .  mat - the matrix

6372:    Output Parameters:
6373: +  m - the number of global rows
6374: -  n - the number of global columns

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

6378:    Level: beginner

6380: .seealso: MatGetLocalSize()
6381: @*/
6382: PetscErrorCode MatGetSize(Mat mat,PetscInt *m,PetscInt *n)
6383: {
6386:   if (m) *m = mat->rmap->N;
6387:   if (n) *n = mat->cmap->N;
6388:   return(0);
6389: }

6391: /*@C
6392:    MatGetLocalSize - Returns the number of local rows and local columns
6393:    of a matrix, that is the local size of the left and right vectors as returned by MatCreateVecs().

6395:    Not Collective

6397:    Input Parameters:
6398: .  mat - the matrix

6400:    Output Parameters:
6401: +  m - the number of local rows
6402: -  n - the number of local columns

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

6406:    Level: beginner

6408: .seealso: MatGetSize()
6409: @*/
6410: PetscErrorCode MatGetLocalSize(Mat mat,PetscInt *m,PetscInt *n)
6411: {
6416:   if (m) *m = mat->rmap->n;
6417:   if (n) *n = mat->cmap->n;
6418:   return(0);
6419: }

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

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

6427:    Input Parameters:
6428: .  mat - the matrix

6430:    Output Parameters:
6431: +  m - the global index of the first local column
6432: -  n - one more than the global index of the last local column

6434:    Notes:
6435:     both output parameters can be NULL on input.

6437:    Level: developer

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

6441: @*/
6442: PetscErrorCode MatGetOwnershipRangeColumn(Mat mat,PetscInt *m,PetscInt *n)
6443: {
6449:   MatCheckPreallocated(mat,1);
6450:   if (m) *m = mat->cmap->rstart;
6451:   if (n) *n = mat->cmap->rend;
6452:   return(0);
6453: }

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

6461:    Not Collective

6463:    Input Parameters:
6464: .  mat - the matrix

6466:    Output Parameters:
6467: +  m - the global index of the first local row
6468: -  n - one more than the global index of the last local row

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

6475:    Level: beginner

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

6479: @*/
6480: PetscErrorCode MatGetOwnershipRange(Mat mat,PetscInt *m,PetscInt *n)
6481: {
6487:   MatCheckPreallocated(mat,1);
6488:   if (m) *m = mat->rmap->rstart;
6489:   if (n) *n = mat->rmap->rend;
6490:   return(0);
6491: }

6493: /*@C
6494:    MatGetOwnershipRanges - Returns the range of matrix rows owned by
6495:    each process

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

6499:    Input Parameters:
6500: .  mat - the matrix

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

6505:    Level: beginner

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

6509: @*/
6510: PetscErrorCode MatGetOwnershipRanges(Mat mat,const PetscInt **ranges)
6511: {

6517:   MatCheckPreallocated(mat,1);
6518:   PetscLayoutGetRanges(mat->rmap,ranges);
6519:   return(0);
6520: }

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

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

6528:    Input Parameters:
6529: .  mat - the matrix

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

6534:    Level: beginner

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

6538: @*/
6539: PetscErrorCode MatGetOwnershipRangesColumn(Mat mat,const PetscInt **ranges)
6540: {

6546:   MatCheckPreallocated(mat,1);
6547:   PetscLayoutGetRanges(mat->cmap,ranges);
6548:   return(0);
6549: }

6551: /*@C
6552:    MatGetOwnershipIS - Get row and column ownership as index sets

6554:    Not Collective

6556:    Input Arguments:
6557: .  A - matrix of type Elemental or ScaLAPACK

6559:    Output Arguments:
6560: +  rows - rows in which this process owns elements
6561: -  cols - columns in which this process owns elements

6563:    Level: intermediate

6565: .seealso: MatGetOwnershipRange(), MatGetOwnershipRangeColumn(), MatSetValues(), MATELEMENTAL
6566: @*/
6567: PetscErrorCode MatGetOwnershipIS(Mat A,IS *rows,IS *cols)
6568: {
6569:   PetscErrorCode ierr,(*f)(Mat,IS*,IS*);

6572:   MatCheckPreallocated(A,1);
6573:   PetscObjectQueryFunction((PetscObject)A,"MatGetOwnershipIS_C",&f);
6574:   if (f) {
6575:     (*f)(A,rows,cols);
6576:   } else {   /* Create a standard row-based partition, each process is responsible for ALL columns in their row block */
6577:     if (rows) {ISCreateStride(PETSC_COMM_SELF,A->rmap->n,A->rmap->rstart,1,rows);}
6578:     if (cols) {ISCreateStride(PETSC_COMM_SELF,A->cmap->N,0,1,cols);}
6579:   }
6580:   return(0);
6581: }

6583: /*@C
6584:    MatILUFactorSymbolic - Performs symbolic ILU factorization of a matrix.
6585:    Uses levels of fill only, not drop tolerance. Use MatLUFactorNumeric()
6586:    to complete the factorization.

6588:    Collective on Mat

6590:    Input Parameters:
6591: +  mat - the matrix
6592: .  row - row permutation
6593: .  column - column permutation
6594: -  info - structure containing
6595: $      levels - number of levels of fill.
6596: $      expected fill - as ratio of original fill.
6597: $      1 or 0 - indicating force fill on diagonal (improves robustness for matrices
6598:                 missing diagonal entries)

6600:    Output Parameters:
6601: .  fact - new matrix that has been symbolically factored

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

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

6610:    Level: developer

6612: .seealso: MatLUFactorSymbolic(), MatLUFactorNumeric(), MatCholeskyFactor()
6613:           MatGetOrdering(), MatFactorInfo

6615:     Note: this uses the definition of level of fill as in Y. Saad, 2003

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

6620:    References:
6621:      Y. Saad, Iterative methods for sparse linear systems Philadelphia: Society for Industrial and Applied Mathematics, 2003
6622: @*/
6623: PetscErrorCode MatILUFactorSymbolic(Mat fact,Mat mat,IS row,IS col,const MatFactorInfo *info)
6624: {

6634:   if (info->levels < 0) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_OUTOFRANGE,"Levels of fill negative %D",(PetscInt)info->levels);
6635:   if (info->fill < 1.0) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_OUTOFRANGE,"Expected fill less than 1.0 %g",(double)info->fill);
6636:   if (!(fact)->ops->ilufactorsymbolic) {
6637:     MatSolverType spackage;
6638:     MatFactorGetSolverType(fact,&spackage);
6639:     SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Matrix type %s symbolic ILU using solver package %s",((PetscObject)mat)->type_name,spackage);
6640:   }
6641:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6642:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6643:   MatCheckPreallocated(mat,2);

6645:   PetscLogEventBegin(MAT_ILUFactorSymbolic,mat,row,col,0);
6646:   (fact->ops->ilufactorsymbolic)(fact,mat,row,col,info);
6647:   PetscLogEventEnd(MAT_ILUFactorSymbolic,mat,row,col,0);
6648:   return(0);
6649: }

6651: /*@C
6652:    MatICCFactorSymbolic - Performs symbolic incomplete
6653:    Cholesky factorization for a symmetric matrix.  Use
6654:    MatCholeskyFactorNumeric() to complete the factorization.

6656:    Collective on Mat

6658:    Input Parameters:
6659: +  mat - the matrix
6660: .  perm - row and column permutation
6661: -  info - structure containing
6662: $      levels - number of levels of fill.
6663: $      expected fill - as ratio of original fill.

6665:    Output Parameter:
6666: .  fact - the factored matrix

6668:    Notes:
6669:    Most users should employ the KSP interface for linear solvers
6670:    instead of working directly with matrix algebra routines such as this.
6671:    See, e.g., KSPCreate().

6673:    Level: developer

6675: .seealso: MatCholeskyFactorNumeric(), MatCholeskyFactor(), MatFactorInfo

6677:     Note: this uses the definition of level of fill as in Y. Saad, 2003

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

6682:    References:
6683:      Y. Saad, Iterative methods for sparse linear systems Philadelphia: Society for Industrial and Applied Mathematics, 2003
6684: @*/
6685: PetscErrorCode MatICCFactorSymbolic(Mat fact,Mat mat,IS perm,const MatFactorInfo *info)
6686: {

6695:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6696:   if (info->levels < 0) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_OUTOFRANGE,"Levels negative %D",(PetscInt) info->levels);
6697:   if (info->fill < 1.0) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_OUTOFRANGE,"Expected fill less than 1.0 %g",(double)info->fill);
6698:   if (!(fact)->ops->iccfactorsymbolic) {
6699:     MatSolverType spackage;
6700:     MatFactorGetSolverType(fact,&spackage);
6701:     SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Matrix type %s symbolic ICC using solver package %s",((PetscObject)mat)->type_name,spackage);
6702:   }
6703:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6704:   MatCheckPreallocated(mat,2);

6706:   PetscLogEventBegin(MAT_ICCFactorSymbolic,mat,perm,0,0);
6707:   (fact->ops->iccfactorsymbolic)(fact,mat,perm,info);
6708:   PetscLogEventEnd(MAT_ICCFactorSymbolic,mat,perm,0,0);
6709:   return(0);
6710: }

6712: /*@C
6713:    MatCreateSubMatrices - Extracts several submatrices from a matrix. If submat
6714:    points to an array of valid matrices, they may be reused to store the new
6715:    submatrices.

6717:    Collective on Mat

6719:    Input Parameters:
6720: +  mat - the matrix
6721: .  n   - the number of submatrixes to be extracted (on this processor, may be zero)
6722: .  irow, icol - index sets of rows and columns to extract
6723: -  scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX

6725:    Output Parameter:
6726: .  submat - the array of submatrices

6728:    Notes:
6729:    MatCreateSubMatrices() can extract ONLY sequential submatrices
6730:    (from both sequential and parallel matrices). Use MatCreateSubMatrix()
6731:    to extract a parallel submatrix.

6733:    Some matrix types place restrictions on the row and column
6734:    indices, such as that they be sorted or that they be equal to each other.

6736:    The index sets may not have duplicate entries.

6738:    When extracting submatrices from a parallel matrix, each processor can
6739:    form a different submatrix by setting the rows and columns of its
6740:    individual index sets according to the local submatrix desired.

6742:    When finished using the submatrices, the user should destroy
6743:    them with MatDestroySubMatrices().

6745:    MAT_REUSE_MATRIX can only be used when the nonzero structure of the
6746:    original matrix has not changed from that last call to MatCreateSubMatrices().

6748:    This routine creates the matrices in submat; you should NOT create them before
6749:    calling it. It also allocates the array of matrix pointers submat.

6751:    For BAIJ matrices the index sets must respect the block structure, that is if they
6752:    request one row/column in a block, they must request all rows/columns that are in
6753:    that block. For example, if the block size is 2 you cannot request just row 0 and
6754:    column 0.

6756:    Fortran Note:
6757:    The Fortran interface is slightly different from that given below; it
6758:    requires one to pass in  as submat a Mat (integer) array of size at least n+1.

6760:    Level: advanced


6763: .seealso: MatDestroySubMatrices(), MatCreateSubMatrix(), MatGetRow(), MatGetDiagonal(), MatReuse
6764: @*/
6765: PetscErrorCode MatCreateSubMatrices(Mat mat,PetscInt n,const IS irow[],const IS icol[],MatReuse scall,Mat *submat[])
6766: {
6768:   PetscInt       i;
6769:   PetscBool      eq;

6774:   if (n) {
6779:   }
6781:   if (n && scall == MAT_REUSE_MATRIX) {
6784:   }
6785:   if (!mat->ops->createsubmatrices) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
6786:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6787:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6788:   MatCheckPreallocated(mat,1);

6790:   PetscLogEventBegin(MAT_CreateSubMats,mat,0,0,0);
6791:   (*mat->ops->createsubmatrices)(mat,n,irow,icol,scall,submat);
6792:   PetscLogEventEnd(MAT_CreateSubMats,mat,0,0,0);
6793:   for (i=0; i<n; i++) {
6794:     (*submat)[i]->factortype = MAT_FACTOR_NONE;  /* in case in place factorization was previously done on submatrix */
6795:     ISEqualUnsorted(irow[i],icol[i],&eq);
6796:     if (eq) {
6797:       MatPropagateSymmetryOptions(mat,(*submat)[i]);
6798:     }
6799:   }
6800:   return(0);
6801: }

6803: /*@C
6804:    MatCreateSubMatricesMPI - Extracts MPI submatrices across a sub communicator of mat (by pairs of IS that may live on subcomms).

6806:    Collective on Mat

6808:    Input Parameters:
6809: +  mat - the matrix
6810: .  n   - the number of submatrixes to be extracted
6811: .  irow, icol - index sets of rows and columns to extract
6812: -  scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX

6814:    Output Parameter:
6815: .  submat - the array of submatrices

6817:    Level: advanced


6820: .seealso: MatCreateSubMatrices(), MatCreateSubMatrix(), MatGetRow(), MatGetDiagonal(), MatReuse
6821: @*/
6822: PetscErrorCode MatCreateSubMatricesMPI(Mat mat,PetscInt n,const IS irow[],const IS icol[],MatReuse scall,Mat *submat[])
6823: {
6825:   PetscInt       i;
6826:   PetscBool      eq;

6831:   if (n) {
6836:   }
6838:   if (n && scall == MAT_REUSE_MATRIX) {
6841:   }
6842:   if (!mat->ops->createsubmatricesmpi) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
6843:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
6844:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
6845:   MatCheckPreallocated(mat,1);

6847:   PetscLogEventBegin(MAT_CreateSubMats,mat,0,0,0);
6848:   (*mat->ops->createsubmatricesmpi)(mat,n,irow,icol,scall,submat);
6849:   PetscLogEventEnd(MAT_CreateSubMats,mat,0,0,0);
6850:   for (i=0; i<n; i++) {
6851:     ISEqualUnsorted(irow[i],icol[i],&eq);
6852:     if (eq) {
6853:       MatPropagateSymmetryOptions(mat,(*submat)[i]);
6854:     }
6855:   }
6856:   return(0);
6857: }

6859: /*@C
6860:    MatDestroyMatrices - Destroys an array of matrices.

6862:    Collective on Mat

6864:    Input Parameters:
6865: +  n - the number of local matrices
6866: -  mat - the matrices (note that this is a pointer to the array of matrices)

6868:    Level: advanced

6870:     Notes:
6871:     Frees not only the matrices, but also the array that contains the matrices
6872:            In Fortran will not free the array.

6874: .seealso: MatCreateSubMatrices() MatDestroySubMatrices()
6875: @*/
6876: PetscErrorCode MatDestroyMatrices(PetscInt n,Mat *mat[])
6877: {
6879:   PetscInt       i;

6882:   if (!*mat) return(0);
6883:   if (n < 0) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Trying to destroy negative number of matrices %D",n);

6886:   for (i=0; i<n; i++) {
6887:     MatDestroy(&(*mat)[i]);
6888:   }

6890:   /* memory is allocated even if n = 0 */
6891:   PetscFree(*mat);
6892:   return(0);
6893: }

6895: /*@C
6896:    MatDestroySubMatrices - Destroys a set of matrices obtained with MatCreateSubMatrices().

6898:    Collective on Mat

6900:    Input Parameters:
6901: +  n - the number of local matrices
6902: -  mat - the matrices (note that this is a pointer to the array of matrices, just to match the calling
6903:                        sequence of MatCreateSubMatrices())

6905:    Level: advanced

6907:     Notes:
6908:     Frees not only the matrices, but also the array that contains the matrices
6909:            In Fortran will not free the array.

6911: .seealso: MatCreateSubMatrices()
6912: @*/
6913: PetscErrorCode MatDestroySubMatrices(PetscInt n,Mat *mat[])
6914: {
6916:   Mat            mat0;

6919:   if (!*mat) return(0);
6920:   /* mat[] is an array of length n+1, see MatCreateSubMatrices_xxx() */
6921:   if (n < 0) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Trying to destroy negative number of matrices %D",n);

6924:   mat0 = (*mat)[0];
6925:   if (mat0 && mat0->ops->destroysubmatrices) {
6926:     (mat0->ops->destroysubmatrices)(n,mat);
6927:   } else {
6928:     MatDestroyMatrices(n,mat);
6929:   }
6930:   return(0);
6931: }

6933: /*@C
6934:    MatGetSeqNonzeroStructure - Extracts the sequential nonzero structure from a matrix.

6936:    Collective on Mat

6938:    Input Parameters:
6939: .  mat - the matrix

6941:    Output Parameter:
6942: .  matstruct - the sequential matrix with the nonzero structure of mat

6944:   Level: intermediate

6946: .seealso: MatDestroySeqNonzeroStructure(), MatCreateSubMatrices(), MatDestroyMatrices()
6947: @*/
6948: PetscErrorCode MatGetSeqNonzeroStructure(Mat mat,Mat *matstruct)
6949: {


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

6960:   if (!mat->ops->getseqnonzerostructure) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Not for matrix type %s\n",((PetscObject)mat)->type_name);
6961:   PetscLogEventBegin(MAT_GetSeqNonzeroStructure,mat,0,0,0);
6962:   (*mat->ops->getseqnonzerostructure)(mat,matstruct);
6963:   PetscLogEventEnd(MAT_GetSeqNonzeroStructure,mat,0,0,0);
6964:   return(0);
6965: }

6967: /*@C
6968:    MatDestroySeqNonzeroStructure - Destroys matrix obtained with MatGetSeqNonzeroStructure().

6970:    Collective on Mat

6972:    Input Parameters:
6973: .  mat - the matrix (note that this is a pointer to the array of matrices, just to match the calling
6974:                        sequence of MatGetSequentialNonzeroStructure())

6976:    Level: advanced

6978:     Notes:
6979:     Frees not only the matrices, but also the array that contains the matrices

6981: .seealso: MatGetSeqNonzeroStructure()
6982: @*/
6983: PetscErrorCode MatDestroySeqNonzeroStructure(Mat *mat)
6984: {

6989:   MatDestroy(mat);
6990:   return(0);
6991: }

6993: /*@
6994:    MatIncreaseOverlap - Given a set of submatrices indicated by index sets,
6995:    replaces the index sets by larger ones that represent submatrices with
6996:    additional overlap.

6998:    Collective on Mat

7000:    Input Parameters:
7001: +  mat - the matrix
7002: .  n   - the number of index sets
7003: .  is  - the array of index sets (these index sets will changed during the call)
7004: -  ov  - the additional overlap requested

7006:    Options Database:
7007: .  -mat_increase_overlap_scalable - use a scalable algorithm to compute the overlap (supported by MPIAIJ matrix)

7009:    Level: developer


7012: .seealso: MatCreateSubMatrices()
7013: @*/
7014: PetscErrorCode MatIncreaseOverlap(Mat mat,PetscInt n,IS is[],PetscInt ov)
7015: {

7021:   if (n < 0) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Must have one or more domains, you have %D",n);
7022:   if (n) {
7025:   }
7026:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
7027:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
7028:   MatCheckPreallocated(mat,1);

7030:   if (!ov) return(0);
7031:   if (!mat->ops->increaseoverlap) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
7032:   PetscLogEventBegin(MAT_IncreaseOverlap,mat,0,0,0);
7033:   (*mat->ops->increaseoverlap)(mat,n,is,ov);
7034:   PetscLogEventEnd(MAT_IncreaseOverlap,mat,0,0,0);
7035:   return(0);
7036: }


7039: PetscErrorCode MatIncreaseOverlapSplit_Single(Mat,IS*,PetscInt);

7041: /*@
7042:    MatIncreaseOverlapSplit - Given a set of submatrices indicated by index sets across
7043:    a sub communicator, replaces the index sets by larger ones that represent submatrices with
7044:    additional overlap.

7046:    Collective on Mat

7048:    Input Parameters:
7049: +  mat - the matrix
7050: .  n   - the number of index sets
7051: .  is  - the array of index sets (these index sets will changed during the call)
7052: -  ov  - the additional overlap requested

7054:    Options Database:
7055: .  -mat_increase_overlap_scalable - use a scalable algorithm to compute the overlap (supported by MPIAIJ matrix)

7057:    Level: developer


7060: .seealso: MatCreateSubMatrices()
7061: @*/
7062: PetscErrorCode MatIncreaseOverlapSplit(Mat mat,PetscInt n,IS is[],PetscInt ov)
7063: {
7064:   PetscInt       i;

7070:   if (n < 0) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Must have one or more domains, you have %D",n);
7071:   if (n) {
7074:   }
7075:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
7076:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
7077:   MatCheckPreallocated(mat,1);
7078:   if (!ov) return(0);
7079:   PetscLogEventBegin(MAT_IncreaseOverlap,mat,0,0,0);
7080:   for(i=0; i<n; i++){
7081:          MatIncreaseOverlapSplit_Single(mat,&is[i],ov);
7082:   }
7083:   PetscLogEventEnd(MAT_IncreaseOverlap,mat,0,0,0);
7084:   return(0);
7085: }




7090: /*@
7091:    MatGetBlockSize - Returns the matrix block size.

7093:    Not Collective

7095:    Input Parameter:
7096: .  mat - the matrix

7098:    Output Parameter:
7099: .  bs - block size

7101:    Notes:
7102:     Block row formats are MATSEQBAIJ, MATMPIBAIJ, MATSEQSBAIJ, MATMPISBAIJ. These formats ALWAYS have square block storage in the matrix.

7104:    If the block size has not been set yet this routine returns 1.

7106:    Level: intermediate

7108: .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSizes()
7109: @*/
7110: PetscErrorCode MatGetBlockSize(Mat mat,PetscInt *bs)
7111: {
7115:   *bs = PetscAbs(mat->rmap->bs);
7116:   return(0);
7117: }

7119: /*@
7120:    MatGetBlockSizes - Returns the matrix block row and column sizes.

7122:    Not Collective

7124:    Input Parameter:
7125: .  mat - the matrix

7127:    Output Parameter:
7128: +  rbs - row block size
7129: -  cbs - column block size

7131:    Notes:
7132:     Block row formats are MATSEQBAIJ, MATMPIBAIJ, MATSEQSBAIJ, MATMPISBAIJ. These formats ALWAYS have square block storage in the matrix.
7133:     If you pass a different block size for the columns than the rows, the row block size determines the square block storage.

7135:    If a block size has not been set yet this routine returns 1.

7137:    Level: intermediate

7139: .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSize(), MatSetBlockSize(), MatSetBlockSizes()
7140: @*/
7141: PetscErrorCode MatGetBlockSizes(Mat mat,PetscInt *rbs, PetscInt *cbs)
7142: {
7147:   if (rbs) *rbs = PetscAbs(mat->rmap->bs);
7148:   if (cbs) *cbs = PetscAbs(mat->cmap->bs);
7149:   return(0);
7150: }

7152: /*@
7153:    MatSetBlockSize - Sets the matrix block size.

7155:    Logically Collective on Mat

7157:    Input Parameters:
7158: +  mat - the matrix
7159: -  bs - block size

7161:    Notes:
7162:     Block row formats are MATSEQBAIJ, MATMPIBAIJ, MATSEQSBAIJ, MATMPISBAIJ. These formats ALWAYS have square block storage in the matrix.
7163:     This must be called before MatSetUp() or MatXXXSetPreallocation() (or will default to 1) and the block size cannot be changed later.

7165:     For MATMPIAIJ and MATSEQAIJ matrix formats, this function can be called at a later stage, provided that the specified block size
7166:     is compatible with the matrix local sizes.

7168:    Level: intermediate

7170: .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSize(), MatSetBlockSizes(), MatGetBlockSizes()
7171: @*/
7172: PetscErrorCode MatSetBlockSize(Mat mat,PetscInt bs)
7173: {

7179:   MatSetBlockSizes(mat,bs,bs);
7180:   return(0);
7181: }

7183: /*@
7184:    MatSetVariableBlockSizes - Sets a diagonal blocks of the matrix that need not be of the same size

7186:    Logically Collective on Mat

7188:    Input Parameters:
7189: +  mat - the matrix
7190: .  nblocks - the number of blocks on this process
7191: -  bsizes - the block sizes

7193:    Notes:
7194:     Currently used by PCVPBJACOBI for SeqAIJ matrices

7196:    Level: intermediate

7198: .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSize(), MatSetBlockSizes(), MatGetBlockSizes(), MatGetVariableBlockSizes()
7199: @*/
7200: PetscErrorCode MatSetVariableBlockSizes(Mat mat,PetscInt nblocks,PetscInt *bsizes)
7201: {
7203:   PetscInt       i,ncnt = 0, nlocal;

7207:   if (nblocks < 0) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Number of local blocks must be great than or equal to zero");
7208:   MatGetLocalSize(mat,&nlocal,NULL);
7209:   for (i=0; i<nblocks; i++) ncnt += bsizes[i];
7210:   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);
7211:   PetscFree(mat->bsizes);
7212:   mat->nblocks = nblocks;
7213:   PetscMalloc1(nblocks,&mat->bsizes);
7214:   PetscArraycpy(mat->bsizes,bsizes,nblocks);
7215:   return(0);
7216: }

7218: /*@C
7219:    MatGetVariableBlockSizes - Gets a diagonal blocks of the matrix that need not be of the same size

7221:    Logically Collective on Mat

7223:    Input Parameters:
7224: .  mat - the matrix

7226:    Output Parameters:
7227: +  nblocks - the number of blocks on this process
7228: -  bsizes - the block sizes

7230:    Notes: Currently not supported from Fortran

7232:    Level: intermediate

7234: .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSize(), MatSetBlockSizes(), MatGetBlockSizes(), MatSetVariableBlockSizes()
7235: @*/
7236: PetscErrorCode MatGetVariableBlockSizes(Mat mat,PetscInt *nblocks,const PetscInt **bsizes)
7237: {
7240:   *nblocks = mat->nblocks;
7241:   *bsizes  = mat->bsizes;
7242:   return(0);
7243: }

7245: /*@
7246:    MatSetBlockSizes - Sets the matrix block row and column sizes.

7248:    Logically Collective on Mat

7250:    Input Parameters:
7251: +  mat - the matrix
7252: .  rbs - row block size
7253: -  cbs - column block size

7255:    Notes:
7256:     Block row formats are MATSEQBAIJ, MATMPIBAIJ, MATSEQSBAIJ, MATMPISBAIJ. These formats ALWAYS have square block storage in the matrix.
7257:     If you pass a different block size for the columns than the rows, the row block size determines the square block storage.
7258:     This must be called before MatSetUp() or MatXXXSetPreallocation() (or will default to 1) and the block size cannot be changed later.

7260:     For MATMPIAIJ and MATSEQAIJ matrix formats, this function can be called at a later stage, provided that the specified block sizes
7261:     are compatible with the matrix local sizes.

7263:     The row and column block size determine the blocksize of the "row" and "column" vectors returned by MatCreateVecs().

7265:    Level: intermediate

7267: .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSize(), MatSetBlockSize(), MatGetBlockSizes()
7268: @*/
7269: PetscErrorCode MatSetBlockSizes(Mat mat,PetscInt rbs,PetscInt cbs)
7270: {

7277:   if (mat->ops->setblocksizes) {
7278:     (*mat->ops->setblocksizes)(mat,rbs,cbs);
7279:   }
7280:   if (mat->rmap->refcnt) {
7281:     ISLocalToGlobalMapping l2g = NULL;
7282:     PetscLayout            nmap = NULL;

7284:     PetscLayoutDuplicate(mat->rmap,&nmap);
7285:     if (mat->rmap->mapping) {
7286:       ISLocalToGlobalMappingDuplicate(mat->rmap->mapping,&l2g);
7287:     }
7288:     PetscLayoutDestroy(&mat->rmap);
7289:     mat->rmap = nmap;
7290:     mat->rmap->mapping = l2g;
7291:   }
7292:   if (mat->cmap->refcnt) {
7293:     ISLocalToGlobalMapping l2g = NULL;
7294:     PetscLayout            nmap = NULL;

7296:     PetscLayoutDuplicate(mat->cmap,&nmap);
7297:     if (mat->cmap->mapping) {
7298:       ISLocalToGlobalMappingDuplicate(mat->cmap->mapping,&l2g);
7299:     }
7300:     PetscLayoutDestroy(&mat->cmap);
7301:     mat->cmap = nmap;
7302:     mat->cmap->mapping = l2g;
7303:   }
7304:   PetscLayoutSetBlockSize(mat->rmap,rbs);
7305:   PetscLayoutSetBlockSize(mat->cmap,cbs);
7306:   return(0);
7307: }

7309: /*@
7310:    MatSetBlockSizesFromMats - Sets the matrix block row and column sizes to match a pair of matrices

7312:    Logically Collective on Mat

7314:    Input Parameters:
7315: +  mat - the matrix
7316: .  fromRow - matrix from which to copy row block size
7317: -  fromCol - matrix from which to copy column block size (can be same as fromRow)

7319:    Level: developer

7321: .seealso: MatCreateSeqBAIJ(), MatCreateBAIJ(), MatGetBlockSize(), MatSetBlockSizes()
7322: @*/
7323: PetscErrorCode MatSetBlockSizesFromMats(Mat mat,Mat fromRow,Mat fromCol)
7324: {

7331:   if (fromRow->rmap->bs > 0) {PetscLayoutSetBlockSize(mat->rmap,fromRow->rmap->bs);}
7332:   if (fromCol->cmap->bs > 0) {PetscLayoutSetBlockSize(mat->cmap,fromCol->cmap->bs);}
7333:   return(0);
7334: }

7336: /*@
7337:    MatResidual - Default routine to calculate the residual.

7339:    Collective on Mat

7341:    Input Parameters:
7342: +  mat - the matrix
7343: .  b   - the right-hand-side
7344: -  x   - the approximate solution

7346:    Output Parameter:
7347: .  r - location to store the residual

7349:    Level: developer

7351: .seealso: PCMGSetResidual()
7352: @*/
7353: PetscErrorCode MatResidual(Mat mat,Vec b,Vec x,Vec r)
7354: {

7363:   MatCheckPreallocated(mat,1);
7364:   PetscLogEventBegin(MAT_Residual,mat,0,0,0);
7365:   if (!mat->ops->residual) {
7366:     MatMult(mat,x,r);
7367:     VecAYPX(r,-1.0,b);
7368:   } else {
7369:     (*mat->ops->residual)(mat,b,x,r);
7370:   }
7371:   PetscLogEventEnd(MAT_Residual,mat,0,0,0);
7372:   return(0);
7373: }

7375: /*@C
7376:     MatGetRowIJ - Returns the compressed row storage i and j indices for sequential matrices.

7378:    Collective on Mat

7380:     Input Parameters:
7381: +   mat - the matrix
7382: .   shift -  0 or 1 indicating we want the indices starting at 0 or 1
7383: .   symmetric - PETSC_TRUE or PETSC_FALSE indicating the matrix data structure should be   symmetrized
7384: -   inodecompressed - PETSC_TRUE or PETSC_FALSE  indicating if the nonzero structure of the
7385:                  inodes or the nonzero elements is wanted. For BAIJ matrices the compressed version is
7386:                  always used.

7388:     Output Parameters:
7389: +   n - number of rows in the (possibly compressed) matrix
7390: .   ia - the row pointers; that is ia[0] = 0, ia[row] = ia[row-1] + number of elements in that row of the matrix
7391: .   ja - the column indices
7392: -   done - indicates if the routine actually worked and returned appropriate ia[] and ja[] arrays; callers
7393:            are responsible for handling the case when done == PETSC_FALSE and ia and ja are not set

7395:     Level: developer

7397:     Notes:
7398:     You CANNOT change any of the ia[] or ja[] values.

7400:     Use MatRestoreRowIJ() when you are finished accessing the ia[] and ja[] values.

7402:     Fortran Notes:
7403:     In Fortran use
7404: $
7405: $      PetscInt ia(1), ja(1)
7406: $      PetscOffset iia, jja
7407: $      call MatGetRowIJ(mat,shift,symmetric,inodecompressed,n,ia,iia,ja,jja,done,ierr)
7408: $      ! Access the ith and jth entries via ia(iia + i) and ja(jja + j)

7410:      or
7411: $
7412: $    PetscInt, pointer :: ia(:),ja(:)
7413: $    call MatGetRowIJF90(mat,shift,symmetric,inodecompressed,n,ia,ja,done,ierr)
7414: $    ! Access the ith and jth entries via ia(i) and ja(j)

7416: .seealso: MatGetColumnIJ(), MatRestoreRowIJ(), MatSeqAIJGetArray()
7417: @*/
7418: PetscErrorCode MatGetRowIJ(Mat mat,PetscInt shift,PetscBool symmetric,PetscBool inodecompressed,PetscInt *n,const PetscInt *ia[],const PetscInt *ja[],PetscBool  *done)
7419: {

7429:   MatCheckPreallocated(mat,1);
7430:   if (!mat->ops->getrowij) *done = PETSC_FALSE;
7431:   else {
7432:     *done = PETSC_TRUE;
7433:     PetscLogEventBegin(MAT_GetRowIJ,mat,0,0,0);
7434:     (*mat->ops->getrowij)(mat,shift,symmetric,inodecompressed,n,ia,ja,done);
7435:     PetscLogEventEnd(MAT_GetRowIJ,mat,0,0,0);
7436:   }
7437:   return(0);
7438: }

7440: /*@C
7441:     MatGetColumnIJ - Returns the compressed column storage i and j indices for sequential matrices.

7443:     Collective on Mat

7445:     Input Parameters:
7446: +   mat - the matrix
7447: .   shift - 1 or zero indicating we want the indices starting at 0 or 1
7448: .   symmetric - PETSC_TRUE or PETSC_FALSE indicating the matrix data structure should be
7449:                 symmetrized
7450: .   inodecompressed - PETSC_TRUE or PETSC_FALSE indicating if the nonzero structure of the
7451:                  inodes or the nonzero elements is wanted. For BAIJ matrices the compressed version is
7452:                  always used.
7453: .   n - number of columns in the (possibly compressed) matrix
7454: .   ia - the column pointers; that is ia[0] = 0, ia[col] = i[col-1] + number of elements in that col of the matrix
7455: -   ja - the row indices

7457:     Output Parameters:
7458: .   done - PETSC_TRUE or PETSC_FALSE, indicating whether the values have been returned

7460:     Level: developer

7462: .seealso: MatGetRowIJ(), MatRestoreColumnIJ()
7463: @*/
7464: PetscErrorCode MatGetColumnIJ(Mat mat,PetscInt shift,PetscBool symmetric,PetscBool inodecompressed,PetscInt *n,const PetscInt *ia[],const PetscInt *ja[],PetscBool  *done)
7465: {

7475:   MatCheckPreallocated(mat,1);
7476:   if (!mat->ops->getcolumnij) *done = PETSC_FALSE;
7477:   else {
7478:     *done = PETSC_TRUE;
7479:     (*mat->ops->getcolumnij)(mat,shift,symmetric,inodecompressed,n,ia,ja,done);
7480:   }
7481:   return(0);
7482: }

7484: /*@C
7485:     MatRestoreRowIJ - Call after you are completed with the ia,ja indices obtained with
7486:     MatGetRowIJ().

7488:     Collective on Mat

7490:     Input Parameters:
7491: +   mat - the matrix
7492: .   shift - 1 or zero indicating we want the indices starting at 0 or 1
7493: .   symmetric - PETSC_TRUE or PETSC_FALSE indicating the matrix data structure should be
7494:                 symmetrized
7495: .   inodecompressed -  PETSC_TRUE or PETSC_FALSE indicating if the nonzero structure of the
7496:                  inodes or the nonzero elements is wanted. For BAIJ matrices the compressed version is
7497:                  always used.
7498: .   n - size of (possibly compressed) matrix
7499: .   ia - the row pointers
7500: -   ja - the column indices

7502:     Output Parameters:
7503: .   done - PETSC_TRUE or PETSC_FALSE indicated that the values have been returned

7505:     Note:
7506:     This routine zeros out n, ia, and ja. This is to prevent accidental
7507:     us of the array after it has been restored. If you pass NULL, it will
7508:     not zero the pointers.  Use of ia or ja after MatRestoreRowIJ() is invalid.

7510:     Level: developer

7512: .seealso: MatGetRowIJ(), MatRestoreColumnIJ()
7513: @*/
7514: PetscErrorCode MatRestoreRowIJ(Mat mat,PetscInt shift,PetscBool symmetric,PetscBool inodecompressed,PetscInt *n,const PetscInt *ia[],const PetscInt *ja[],PetscBool  *done)
7515: {

7524:   MatCheckPreallocated(mat,1);

7526:   if (!mat->ops->restorerowij) *done = PETSC_FALSE;
7527:   else {
7528:     *done = PETSC_TRUE;
7529:     (*mat->ops->restorerowij)(mat,shift,symmetric,inodecompressed,n,ia,ja,done);
7530:     if (n)  *n = 0;
7531:     if (ia) *ia = NULL;
7532:     if (ja) *ja = NULL;
7533:   }
7534:   return(0);
7535: }

7537: /*@C
7538:     MatRestoreColumnIJ - Call after you are completed with the ia,ja indices obtained with
7539:     MatGetColumnIJ().

7541:     Collective on Mat

7543:     Input Parameters:
7544: +   mat - the matrix
7545: .   shift - 1 or zero indicating we want the indices starting at 0 or 1
7546: -   symmetric - PETSC_TRUE or PETSC_FALSE indicating the matrix data structure should be
7547:                 symmetrized
7548: -   inodecompressed - PETSC_TRUE or PETSC_FALSE indicating if the nonzero structure of the
7549:                  inodes or the nonzero elements is wanted. For BAIJ matrices the compressed version is
7550:                  always used.

7552:     Output Parameters:
7553: +   n - size of (possibly compressed) matrix
7554: .   ia - the column pointers
7555: .   ja - the row indices
7556: -   done - PETSC_TRUE or PETSC_FALSE indicated that the values have been returned

7558:     Level: developer

7560: .seealso: MatGetColumnIJ(), MatRestoreRowIJ()
7561: @*/
7562: PetscErrorCode MatRestoreColumnIJ(Mat mat,PetscInt shift,PetscBool symmetric,PetscBool inodecompressed,PetscInt *n,const PetscInt *ia[],const PetscInt *ja[],PetscBool  *done)
7563: {

7572:   MatCheckPreallocated(mat,1);

7574:   if (!mat->ops->restorecolumnij) *done = PETSC_FALSE;
7575:   else {
7576:     *done = PETSC_TRUE;
7577:     (*mat->ops->restorecolumnij)(mat,shift,symmetric,inodecompressed,n,ia,ja,done);
7578:     if (n)  *n = 0;
7579:     if (ia) *ia = NULL;
7580:     if (ja) *ja = NULL;
7581:   }
7582:   return(0);
7583: }

7585: /*@C
7586:     MatColoringPatch -Used inside matrix coloring routines that
7587:     use MatGetRowIJ() and/or MatGetColumnIJ().

7589:     Collective on Mat

7591:     Input Parameters:
7592: +   mat - the matrix
7593: .   ncolors - max color value
7594: .   n   - number of entries in colorarray
7595: -   colorarray - array indicating color for each column

7597:     Output Parameters:
7598: .   iscoloring - coloring generated using colorarray information

7600:     Level: developer

7602: .seealso: MatGetRowIJ(), MatGetColumnIJ()

7604: @*/
7605: PetscErrorCode MatColoringPatch(Mat mat,PetscInt ncolors,PetscInt n,ISColoringValue colorarray[],ISColoring *iscoloring)
7606: {

7614:   MatCheckPreallocated(mat,1);

7616:   if (!mat->ops->coloringpatch) {
7617:     ISColoringCreate(PetscObjectComm((PetscObject)mat),ncolors,n,colorarray,PETSC_OWN_POINTER,iscoloring);
7618:   } else {
7619:     (*mat->ops->coloringpatch)(mat,ncolors,n,colorarray,iscoloring);
7620:   }
7621:   return(0);
7622: }


7625: /*@
7626:    MatSetUnfactored - Resets a factored matrix to be treated as unfactored.

7628:    Logically Collective on Mat

7630:    Input Parameter:
7631: .  mat - the factored matrix to be reset

7633:    Notes:
7634:    This routine should be used only with factored matrices formed by in-place
7635:    factorization via ILU(0) (or by in-place LU factorization for the MATSEQDENSE
7636:    format).  This option can save memory, for example, when solving nonlinear
7637:    systems with a matrix-free Newton-Krylov method and a matrix-based, in-place
7638:    ILU(0) preconditioner.

7640:    Note that one can specify in-place ILU(0) factorization by calling
7641: .vb
7642:      PCType(pc,PCILU);
7643:      PCFactorSeUseInPlace(pc);
7644: .ve
7645:    or by using the options -pc_type ilu -pc_factor_in_place

7647:    In-place factorization ILU(0) can also be used as a local
7648:    solver for the blocks within the block Jacobi or additive Schwarz
7649:    methods (runtime option: -sub_pc_factor_in_place).  See Users-Manual: ch_pc
7650:    for details on setting local solver options.

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

7656:    Level: developer

7658: .seealso: PCFactorSetUseInPlace(), PCFactorGetUseInPlace()

7660: @*/
7661: PetscErrorCode MatSetUnfactored(Mat mat)
7662: {

7668:   MatCheckPreallocated(mat,1);
7669:   mat->factortype = MAT_FACTOR_NONE;
7670:   if (!mat->ops->setunfactored) return(0);
7671:   (*mat->ops->setunfactored)(mat);
7672:   return(0);
7673: }

7675: /*MC
7676:     MatDenseGetArrayF90 - Accesses a matrix array from Fortran90.

7678:     Synopsis:
7679:     MatDenseGetArrayF90(Mat x,{Scalar, pointer :: xx_v(:,:)},integer ierr)

7681:     Not collective

7683:     Input Parameter:
7684: .   x - matrix

7686:     Output Parameters:
7687: +   xx_v - the Fortran90 pointer to the array
7688: -   ierr - error code

7690:     Example of Usage:
7691: .vb
7692:       PetscScalar, pointer xx_v(:,:)
7693:       ....
7694:       call MatDenseGetArrayF90(x,xx_v,ierr)
7695:       a = xx_v(3)
7696:       call MatDenseRestoreArrayF90(x,xx_v,ierr)
7697: .ve

7699:     Level: advanced

7701: .seealso:  MatDenseRestoreArrayF90(), MatDenseGetArray(), MatDenseRestoreArray(), MatSeqAIJGetArrayF90()

7703: M*/

7705: /*MC
7706:     MatDenseRestoreArrayF90 - Restores a matrix array that has been
7707:     accessed with MatDenseGetArrayF90().

7709:     Synopsis:
7710:     MatDenseRestoreArrayF90(Mat x,{Scalar, pointer :: xx_v(:,:)},integer ierr)

7712:     Not collective

7714:     Input Parameters:
7715: +   x - matrix
7716: -   xx_v - the Fortran90 pointer to the array

7718:     Output Parameter:
7719: .   ierr - error code

7721:     Example of Usage:
7722: .vb
7723:        PetscScalar, pointer xx_v(:,:)
7724:        ....
7725:        call MatDenseGetArrayF90(x,xx_v,ierr)
7726:        a = xx_v(3)
7727:        call MatDenseRestoreArrayF90(x,xx_v,ierr)
7728: .ve

7730:     Level: advanced

7732: .seealso:  MatDenseGetArrayF90(), MatDenseGetArray(), MatDenseRestoreArray(), MatSeqAIJRestoreArrayF90()

7734: M*/


7737: /*MC
7738:     MatSeqAIJGetArrayF90 - Accesses a matrix array from Fortran90.

7740:     Synopsis:
7741:     MatSeqAIJGetArrayF90(Mat x,{Scalar, pointer :: xx_v(:)},integer ierr)

7743:     Not collective

7745:     Input Parameter:
7746: .   x - matrix

7748:     Output Parameters:
7749: +   xx_v - the Fortran90 pointer to the array
7750: -   ierr - error code

7752:     Example of Usage:
7753: .vb
7754:       PetscScalar, pointer xx_v(:)
7755:       ....
7756:       call MatSeqAIJGetArrayF90(x,xx_v,ierr)
7757:       a = xx_v(3)
7758:       call MatSeqAIJRestoreArrayF90(x,xx_v,ierr)
7759: .ve

7761:     Level: advanced

7763: .seealso:  MatSeqAIJRestoreArrayF90(), MatSeqAIJGetArray(), MatSeqAIJRestoreArray(), MatDenseGetArrayF90()

7765: M*/

7767: /*MC
7768:     MatSeqAIJRestoreArrayF90 - Restores a matrix array that has been
7769:     accessed with MatSeqAIJGetArrayF90().

7771:     Synopsis:
7772:     MatSeqAIJRestoreArrayF90(Mat x,{Scalar, pointer :: xx_v(:)},integer ierr)

7774:     Not collective

7776:     Input Parameters:
7777: +   x - matrix
7778: -   xx_v - the Fortran90 pointer to the array

7780:     Output Parameter:
7781: .   ierr - error code

7783:     Example of Usage:
7784: .vb
7785:        PetscScalar, pointer xx_v(:)
7786:        ....
7787:        call MatSeqAIJGetArrayF90(x,xx_v,ierr)
7788:        a = xx_v(3)
7789:        call MatSeqAIJRestoreArrayF90(x,xx_v,ierr)
7790: .ve

7792:     Level: advanced

7794: .seealso:  MatSeqAIJGetArrayF90(), MatSeqAIJGetArray(), MatSeqAIJRestoreArray(), MatDenseRestoreArrayF90()

7796: M*/


7799: /*@
7800:     MatCreateSubMatrix - Gets a single submatrix on the same number of processors
7801:                       as the original matrix.

7803:     Collective on Mat

7805:     Input Parameters:
7806: +   mat - the original matrix
7807: .   isrow - parallel IS containing the rows this processor should obtain
7808: .   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.
7809: -   cll - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX

7811:     Output Parameter:
7812: .   newmat - the new submatrix, of the same type as the old

7814:     Level: advanced

7816:     Notes:
7817:     The submatrix will be able to be multiplied with vectors using the same layout as iscol.

7819:     Some matrix types place restrictions on the row and column indices, such
7820:     as that they be sorted or that they be equal to each other.

7822:     The index sets may not have duplicate entries.

7824:       The first time this is called you should use a cll of MAT_INITIAL_MATRIX,
7825:    the MatCreateSubMatrix() routine will create the newmat for you. Any additional calls
7826:    to this routine with a mat of the same nonzero structure and with a call of MAT_REUSE_MATRIX
7827:    will reuse the matrix generated the first time.  You should call MatDestroy() on newmat when
7828:    you are finished using it.

7830:     The communicator of the newly obtained matrix is ALWAYS the same as the communicator of
7831:     the input matrix.

7833:     If iscol is NULL then all columns are obtained (not supported in Fortran).

7835:    Example usage:
7836:    Consider the following 8x8 matrix with 34 non-zero values, that is
7837:    assembled across 3 processors. Let's assume that proc0 owns 3 rows,
7838:    proc1 owns 3 rows, proc2 owns 2 rows. This division can be shown
7839:    as follows:

7841: .vb
7842:             1  2  0  |  0  3  0  |  0  4
7843:     Proc0   0  5  6  |  7  0  0  |  8  0
7844:             9  0 10  | 11  0  0  | 12  0
7845:     -------------------------------------
7846:            13  0 14  | 15 16 17  |  0  0
7847:     Proc1   0 18  0  | 19 20 21  |  0  0
7848:             0  0  0  | 22 23  0  | 24  0
7849:     -------------------------------------
7850:     Proc2  25 26 27  |  0  0 28  | 29  0
7851:            30  0  0  | 31 32 33  |  0 34
7852: .ve

7854:     Suppose isrow = [0 1 | 4 | 6 7] and iscol = [1 2 | 3 4 5 | 6].  The resulting submatrix is

7856: .vb
7857:             2  0  |  0  3  0  |  0
7858:     Proc0   5  6  |  7  0  0  |  8
7859:     -------------------------------
7860:     Proc1  18  0  | 19 20 21  |  0
7861:     -------------------------------
7862:     Proc2  26 27  |  0  0 28  | 29
7863:             0  0  | 31 32 33  |  0
7864: .ve


7867: .seealso: MatCreateSubMatrices(), MatCreateSubMatricesMPI(), MatCreateSubMatrixVirtual(), MatSubMatrixVirtualUpdate()
7868: @*/
7869: PetscErrorCode MatCreateSubMatrix(Mat mat,IS isrow,IS iscol,MatReuse cll,Mat *newmat)
7870: {
7872:   PetscMPIInt    size;
7873:   Mat            *local;
7874:   IS             iscoltmp;
7875:   PetscBool      flg;

7884:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
7885:   if (cll == MAT_IGNORE_MATRIX) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Cannot use MAT_IGNORE_MATRIX");

7887:   MatCheckPreallocated(mat,1);
7888:   MPI_Comm_size(PetscObjectComm((PetscObject)mat),&size);

7890:   if (!iscol || isrow == iscol) {
7891:     PetscBool   stride;
7892:     PetscMPIInt grabentirematrix = 0,grab;
7893:     PetscObjectTypeCompare((PetscObject)isrow,ISSTRIDE,&stride);
7894:     if (stride) {
7895:       PetscInt first,step,n,rstart,rend;
7896:       ISStrideGetInfo(isrow,&first,&step);
7897:       if (step == 1) {
7898:         MatGetOwnershipRange(mat,&rstart,&rend);
7899:         if (rstart == first) {
7900:           ISGetLocalSize(isrow,&n);
7901:           if (n == rend-rstart) {
7902:             grabentirematrix = 1;
7903:           }
7904:         }
7905:       }
7906:     }
7907:     MPIU_Allreduce(&grabentirematrix,&grab,1,MPI_INT,MPI_MIN,PetscObjectComm((PetscObject)mat));
7908:     if (grab) {
7909:       PetscInfo(mat,"Getting entire matrix as submatrix\n");
7910:       if (cll == MAT_INITIAL_MATRIX) {
7911:         *newmat = mat;
7912:         PetscObjectReference((PetscObject)mat);
7913:       }
7914:       return(0);
7915:     }
7916:   }

7918:   if (!iscol) {
7919:     ISCreateStride(PetscObjectComm((PetscObject)mat),mat->cmap->n,mat->cmap->rstart,1,&iscoltmp);
7920:   } else {
7921:     iscoltmp = iscol;
7922:   }

7924:   /* if original matrix is on just one processor then use submatrix generated */
7925:   if (mat->ops->createsubmatrices && !mat->ops->createsubmatrix && size == 1 && cll == MAT_REUSE_MATRIX) {
7926:     MatCreateSubMatrices(mat,1,&isrow,&iscoltmp,MAT_REUSE_MATRIX,&newmat);
7927:     goto setproperties;
7928:   } else if (mat->ops->createsubmatrices && !mat->ops->createsubmatrix && size == 1) {
7929:     MatCreateSubMatrices(mat,1,&isrow,&iscoltmp,MAT_INITIAL_MATRIX,&local);
7930:     *newmat = *local;
7931:     PetscFree(local);
7932:     goto setproperties;
7933:   } else if (!mat->ops->createsubmatrix) {
7934:     /* Create a new matrix type that implements the operation using the full matrix */
7935:     PetscLogEventBegin(MAT_CreateSubMat,mat,0,0,0);
7936:     switch (cll) {
7937:     case MAT_INITIAL_MATRIX:
7938:       MatCreateSubMatrixVirtual(mat,isrow,iscoltmp,newmat);
7939:       break;
7940:     case MAT_REUSE_MATRIX:
7941:       MatSubMatrixVirtualUpdate(*newmat,mat,isrow,iscoltmp);
7942:       break;
7943:     default: SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_OUTOFRANGE,"Invalid MatReuse, must be either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX");
7944:     }
7945:     PetscLogEventEnd(MAT_CreateSubMat,mat,0,0,0);
7946:     goto setproperties;
7947:   }

7949:   if (!mat->ops->createsubmatrix) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
7950:   PetscLogEventBegin(MAT_CreateSubMat,mat,0,0,0);
7951:   (*mat->ops->createsubmatrix)(mat,isrow,iscoltmp,cll,newmat);
7952:   PetscLogEventEnd(MAT_CreateSubMat,mat,0,0,0);

7954: setproperties:
7955:   ISEqualUnsorted(isrow,iscoltmp,&flg);
7956:   if (flg) {
7957:     MatPropagateSymmetryOptions(mat,*newmat);
7958:   }
7959:   if (!iscol) {ISDestroy(&iscoltmp);}
7960:   if (*newmat && cll == MAT_INITIAL_MATRIX) {PetscObjectStateIncrease((PetscObject)*newmat);}
7961:   return(0);
7962: }

7964: /*@
7965:    MatPropagateSymmetryOptions - Propagates symmetry options set on a matrix to another matrix

7967:    Not Collective

7969:    Input Parameters:
7970: +  A - the matrix we wish to propagate options from
7971: -  B - the matrix we wish to propagate options to

7973:    Level: beginner

7975:    Notes: Propagates the options associated to MAT_SYMMETRY_ETERNAL, MAT_STRUCTURALLY_SYMMETRIC, MAT_HERMITIAN, MAT_SPD and MAT_SYMMETRIC

7977: .seealso: MatSetOption()
7978: @*/
7979: PetscErrorCode MatPropagateSymmetryOptions(Mat A, Mat B)
7980: {

7986:   if (A->symmetric_eternal) { /* symmetric_eternal does not have a corresponding *set flag */
7987:     MatSetOption(B,MAT_SYMMETRY_ETERNAL,A->symmetric_eternal);
7988:   }
7989:   if (A->structurally_symmetric_set) {
7990:     MatSetOption(B,MAT_STRUCTURALLY_SYMMETRIC,A->structurally_symmetric);
7991:   }
7992:   if (A->hermitian_set) {
7993:     MatSetOption(B,MAT_HERMITIAN,A->hermitian);
7994:   }
7995:   if (A->spd_set) {
7996:     MatSetOption(B,MAT_SPD,A->spd);
7997:   }
7998:   if (A->symmetric_set) {
7999:     MatSetOption(B,MAT_SYMMETRIC,A->symmetric);
8000:   }
8001:   return(0);
8002: }

8004: /*@
8005:    MatStashSetInitialSize - sets the sizes of the matrix stash, that is
8006:    used during the assembly process to store values that belong to
8007:    other processors.

8009:    Not Collective

8011:    Input Parameters:
8012: +  mat   - the matrix
8013: .  size  - the initial size of the stash.
8014: -  bsize - the initial size of the block-stash(if used).

8016:    Options Database Keys:
8017: +   -matstash_initial_size <size> or <size0,size1,...sizep-1>
8018: -   -matstash_block_initial_size <bsize>  or <bsize0,bsize1,...bsizep-1>

8020:    Level: intermediate

8022:    Notes:
8023:      The block-stash is used for values set with MatSetValuesBlocked() while
8024:      the stash is used for values set with MatSetValues()

8026:      Run with the option -info and look for output of the form
8027:      MatAssemblyBegin_MPIXXX:Stash has MM entries, uses nn mallocs.
8028:      to determine the appropriate value, MM, to use for size and
8029:      MatAssemblyBegin_MPIXXX:Block-Stash has BMM entries, uses nn mallocs.
8030:      to determine the value, BMM to use for bsize


8033: .seealso: MatAssemblyBegin(), MatAssemblyEnd(), Mat, MatStashGetInfo()

8035: @*/
8036: PetscErrorCode MatStashSetInitialSize(Mat mat,PetscInt size, PetscInt bsize)
8037: {

8043:   MatStashSetInitialSize_Private(&mat->stash,size);
8044:   MatStashSetInitialSize_Private(&mat->bstash,bsize);
8045:   return(0);
8046: }

8048: /*@
8049:    MatInterpolateAdd - w = y + A*x or A'*x depending on the shape of
8050:      the matrix

8052:    Neighbor-wise Collective on Mat

8054:    Input Parameters:
8055: +  mat   - the matrix
8056: .  x,y - the vectors
8057: -  w - where the result is stored

8059:    Level: intermediate

8061:    Notes:
8062:     w may be the same vector as y.

8064:     This allows one to use either the restriction or interpolation (its transpose)
8065:     matrix to do the interpolation

8067: .seealso: MatMultAdd(), MatMultTransposeAdd(), MatRestrict()

8069: @*/
8070: PetscErrorCode MatInterpolateAdd(Mat A,Vec x,Vec y,Vec w)
8071: {
8073:   PetscInt       M,N,Ny;

8081:   MatCheckPreallocated(A,1);
8082:   MatGetSize(A,&M,&N);
8083:   VecGetSize(y,&Ny);
8084:   if (M == Ny) {
8085:     MatMultAdd(A,x,y,w);
8086:   } else {
8087:     MatMultTransposeAdd(A,x,y,w);
8088:   }
8089:   return(0);
8090: }

8092: /*@
8093:    MatInterpolate - y = A*x or A'*x depending on the shape of
8094:      the matrix

8096:    Neighbor-wise Collective on Mat

8098:    Input Parameters:
8099: +  mat   - the matrix
8100: -  x,y - the vectors

8102:    Level: intermediate

8104:    Notes:
8105:     This allows one to use either the restriction or interpolation (its transpose)
8106:     matrix to do the interpolation

8108: .seealso: MatMultAdd(), MatMultTransposeAdd(), MatRestrict()

8110: @*/
8111: PetscErrorCode MatInterpolate(Mat A,Vec x,Vec y)
8112: {
8114:   PetscInt       M,N,Ny;

8121:   MatCheckPreallocated(A,1);
8122:   MatGetSize(A,&M,&N);
8123:   VecGetSize(y,&Ny);
8124:   if (M == Ny) {
8125:     MatMult(A,x,y);
8126:   } else {
8127:     MatMultTranspose(A,x,y);
8128:   }
8129:   return(0);
8130: }

8132: /*@
8133:    MatRestrict - y = A*x or A'*x

8135:    Neighbor-wise Collective on Mat

8137:    Input Parameters:
8138: +  mat   - the matrix
8139: -  x,y - the vectors

8141:    Level: intermediate

8143:    Notes:
8144:     This allows one to use either the restriction or interpolation (its transpose)
8145:     matrix to do the restriction

8147: .seealso: MatMultAdd(), MatMultTransposeAdd(), MatInterpolate()

8149: @*/
8150: PetscErrorCode MatRestrict(Mat A,Vec x,Vec y)
8151: {
8153:   PetscInt       M,N,Ny;

8160:   MatCheckPreallocated(A,1);

8162:   MatGetSize(A,&M,&N);
8163:   VecGetSize(y,&Ny);
8164:   if (M == Ny) {
8165:     MatMult(A,x,y);
8166:   } else {
8167:     MatMultTranspose(A,x,y);
8168:   }
8169:   return(0);
8170: }

8172: /*@
8173:    MatGetNullSpace - retrieves the null space of a matrix.

8175:    Logically Collective on Mat

8177:    Input Parameters:
8178: +  mat - the matrix
8179: -  nullsp - the null space object

8181:    Level: developer

8183: .seealso: MatCreate(), MatNullSpaceCreate(), MatSetNearNullSpace(), MatSetNullSpace()
8184: @*/
8185: PetscErrorCode MatGetNullSpace(Mat mat, MatNullSpace *nullsp)
8186: {
8190:   *nullsp = (mat->symmetric_set && mat->symmetric && !mat->nullsp) ? mat->transnullsp : mat->nullsp;
8191:   return(0);
8192: }

8194: /*@
8195:    MatSetNullSpace - attaches a null space to a matrix.

8197:    Logically Collective on Mat

8199:    Input Parameters:
8200: +  mat - the matrix
8201: -  nullsp - the null space object

8203:    Level: advanced

8205:    Notes:
8206:       This null space is used by the linear solvers. Overwrites any previous null space that may have been attached

8208:       For inconsistent singular systems (linear systems where the right hand side is not in the range of the operator) you also likely should
8209:       call MatSetTransposeNullSpace(). This allows the linear system to be solved in a least squares sense.

8211:       You can remove the null space by calling this routine with an nullsp of NULL


8214:       The fundamental theorem of linear algebra (Gilbert Strang, Introduction to Applied Mathematics, page 72) states that
8215:    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).
8216:    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
8217:    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
8218:    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).

8220:       Krylov solvers can produce the minimal norm solution to the least squares problem by utilizing MatNullSpaceRemove().

8222:     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
8223:     routine also automatically calls MatSetTransposeNullSpace().

8225: .seealso: MatCreate(), MatNullSpaceCreate(), MatSetNearNullSpace(), MatGetNullSpace(), MatSetTransposeNullSpace(), MatGetTransposeNullSpace(), MatNullSpaceRemove()
8226: @*/
8227: PetscErrorCode MatSetNullSpace(Mat mat,MatNullSpace nullsp)
8228: {

8234:   if (nullsp) {PetscObjectReference((PetscObject)nullsp);}
8235:   MatNullSpaceDestroy(&mat->nullsp);
8236:   mat->nullsp = nullsp;
8237:   if (mat->symmetric_set && mat->symmetric) {
8238:     MatSetTransposeNullSpace(mat,nullsp);
8239:   }
8240:   return(0);
8241: }

8243: /*@
8244:    MatGetTransposeNullSpace - retrieves the null space of the transpose of a matrix.

8246:    Logically Collective on Mat

8248:    Input Parameters:
8249: +  mat - the matrix
8250: -  nullsp - the null space object

8252:    Level: developer

8254: .seealso: MatCreate(), MatNullSpaceCreate(), MatSetNearNullSpace(), MatSetTransposeNullSpace(), MatSetNullSpace(), MatGetNullSpace()
8255: @*/
8256: PetscErrorCode MatGetTransposeNullSpace(Mat mat, MatNullSpace *nullsp)
8257: {
8262:   *nullsp = (mat->symmetric_set && mat->symmetric && !mat->transnullsp) ? mat->nullsp : mat->transnullsp;
8263:   return(0);
8264: }

8266: /*@
8267:    MatSetTransposeNullSpace - attaches a null space to a matrix.

8269:    Logically Collective on Mat

8271:    Input Parameters:
8272: +  mat - the matrix
8273: -  nullsp - the null space object

8275:    Level: advanced

8277:    Notes:
8278:       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.
8279:       You must also call MatSetNullSpace()


8282:       The fundamental theorem of linear algebra (Gilbert Strang, Introduction to Applied Mathematics, page 72) states that
8283:    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).
8284:    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
8285:    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
8286:    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).

8288:       Krylov solvers can produce the minimal norm solution to the least squares problem by utilizing MatNullSpaceRemove().

8290: .seealso: MatCreate(), MatNullSpaceCreate(), MatSetNearNullSpace(), MatGetNullSpace(), MatSetNullSpace(), MatGetTransposeNullSpace(), MatNullSpaceRemove()
8291: @*/
8292: PetscErrorCode MatSetTransposeNullSpace(Mat mat,MatNullSpace nullsp)
8293: {

8299:   if (nullsp) {PetscObjectReference((PetscObject)nullsp);}
8300:   MatNullSpaceDestroy(&mat->transnullsp);
8301:   mat->transnullsp = nullsp;
8302:   return(0);
8303: }

8305: /*@
8306:    MatSetNearNullSpace - attaches a null space to a matrix, which is often the null space (rigid body modes) of the operator without boundary conditions
8307:         This null space will be used to provide near null space vectors to a multigrid preconditioner built from this matrix.

8309:    Logically Collective on Mat

8311:    Input Parameters:
8312: +  mat - the matrix
8313: -  nullsp - the null space object

8315:    Level: advanced

8317:    Notes:
8318:       Overwrites any previous near null space that may have been attached

8320:       You can remove the null space by calling this routine with an nullsp of NULL

8322: .seealso: MatCreate(), MatNullSpaceCreate(), MatSetNullSpace(), MatNullSpaceCreateRigidBody(), MatGetNearNullSpace()
8323: @*/
8324: PetscErrorCode MatSetNearNullSpace(Mat mat,MatNullSpace nullsp)
8325: {

8332:   MatCheckPreallocated(mat,1);
8333:   if (nullsp) {PetscObjectReference((PetscObject)nullsp);}
8334:   MatNullSpaceDestroy(&mat->nearnullsp);
8335:   mat->nearnullsp = nullsp;
8336:   return(0);
8337: }

8339: /*@
8340:    MatGetNearNullSpace - Get null space attached with MatSetNearNullSpace()

8342:    Not Collective

8344:    Input Parameter:
8345: .  mat - the matrix

8347:    Output Parameter:
8348: .  nullsp - the null space object, NULL if not set

8350:    Level: developer

8352: .seealso: MatSetNearNullSpace(), MatGetNullSpace(), MatNullSpaceCreate()
8353: @*/
8354: PetscErrorCode MatGetNearNullSpace(Mat mat,MatNullSpace *nullsp)
8355: {
8360:   MatCheckPreallocated(mat,1);
8361:   *nullsp = mat->nearnullsp;
8362:   return(0);
8363: }

8365: /*@C
8366:    MatICCFactor - Performs in-place incomplete Cholesky factorization of matrix.

8368:    Collective on Mat

8370:    Input Parameters:
8371: +  mat - the matrix
8372: .  row - row/column permutation
8373: .  fill - expected fill factor >= 1.0
8374: -  level - level of fill, for ICC(k)

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

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

8384:    Level: developer


8387: .seealso: MatICCFactorSymbolic(), MatLUFactorNumeric(), MatCholeskyFactor()

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

8392: @*/
8393: PetscErrorCode MatICCFactor(Mat mat,IS row,const MatFactorInfo *info)
8394: {

8402:   if (mat->rmap->N != mat->cmap->N) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONG,"matrix must be square");
8403:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for unassembled matrix");
8404:   if (mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
8405:   if (!mat->ops->iccfactor) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
8406:   MatCheckPreallocated(mat,1);
8407:   (*mat->ops->iccfactor)(mat,row,info);
8408:   PetscObjectStateIncrease((PetscObject)mat);
8409:   return(0);
8410: }

8412: /*@
8413:    MatDiagonalScaleLocal - Scales columns of a matrix given the scaling values including the
8414:          ghosted ones.

8416:    Not Collective

8418:    Input Parameters:
8419: +  mat - the matrix
8420: -  diag = the diagonal values, including ghost ones

8422:    Level: developer

8424:    Notes:
8425:     Works only for MPIAIJ and MPIBAIJ matrices

8427: .seealso: MatDiagonalScale()
8428: @*/
8429: PetscErrorCode MatDiagonalScaleLocal(Mat mat,Vec diag)
8430: {
8432:   PetscMPIInt    size;


8439:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Matrix must be already assembled");
8440:   PetscLogEventBegin(MAT_Scale,mat,0,0,0);
8441:   MPI_Comm_size(PetscObjectComm((PetscObject)mat),&size);
8442:   if (size == 1) {
8443:     PetscInt n,m;
8444:     VecGetSize(diag,&n);
8445:     MatGetSize(mat,0,&m);
8446:     if (m == n) {
8447:       MatDiagonalScale(mat,0,diag);
8448:     } else SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"Only supported for sequential matrices when no ghost points/periodic conditions");
8449:   } else {
8450:     PetscUseMethod(mat,"MatDiagonalScaleLocal_C",(Mat,Vec),(mat,diag));
8451:   }
8452:   PetscLogEventEnd(MAT_Scale,mat,0,0,0);
8453:   PetscObjectStateIncrease((PetscObject)mat);
8454:   return(0);
8455: }

8457: /*@
8458:    MatGetInertia - Gets the inertia from a factored matrix

8460:    Collective on Mat

8462:    Input Parameter:
8463: .  mat - the matrix

8465:    Output Parameters:
8466: +   nneg - number of negative eigenvalues
8467: .   nzero - number of zero eigenvalues
8468: -   npos - number of positive eigenvalues

8470:    Level: advanced

8472:    Notes:
8473:     Matrix must have been factored by MatCholeskyFactor()


8476: @*/
8477: PetscErrorCode MatGetInertia(Mat mat,PetscInt *nneg,PetscInt *nzero,PetscInt *npos)
8478: {

8484:   if (!mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
8485:   if (!mat->assembled) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Numeric factor mat is not assembled");
8486:   if (!mat->ops->getinertia) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
8487:   (*mat->ops->getinertia)(mat,nneg,nzero,npos);
8488:   return(0);
8489: }

8491: /* ----------------------------------------------------------------*/
8492: /*@C
8493:    MatSolves - Solves A x = b, given a factored matrix, for a collection of vectors

8495:    Neighbor-wise Collective on Mats

8497:    Input Parameters:
8498: +  mat - the factored matrix
8499: -  b - the right-hand-side vectors

8501:    Output Parameter:
8502: .  x - the result vectors

8504:    Notes:
8505:    The vectors b and x cannot be the same.  I.e., one cannot
8506:    call MatSolves(A,x,x).

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

8513:    Level: developer

8515: .seealso: MatSolveAdd(), MatSolveTranspose(), MatSolveTransposeAdd(), MatSolve()
8516: @*/
8517: PetscErrorCode MatSolves(Mat mat,Vecs b,Vecs x)
8518: {

8524:   if (x == b) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_IDN,"x and b must be different vectors");
8525:   if (!mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Unfactored matrix");
8526:   if (!mat->rmap->N && !mat->cmap->N) return(0);

8528:   if (!mat->ops->solves) SETERRQ1(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Mat type %s",((PetscObject)mat)->type_name);
8529:   MatCheckPreallocated(mat,1);
8530:   PetscLogEventBegin(MAT_Solves,mat,0,0,0);
8531:   (*mat->ops->solves)(mat,b,x);
8532:   PetscLogEventEnd(MAT_Solves,mat,0,0,0);
8533:   return(0);
8534: }

8536: /*@
8537:    MatIsSymmetric - Test whether a matrix is symmetric

8539:    Collective on Mat

8541:    Input Parameter:
8542: +  A - the matrix to test
8543: -  tol - difference between value and its transpose less than this amount counts as equal (use 0.0 for exact transpose)

8545:    Output Parameters:
8546: .  flg - the result

8548:    Notes:
8549:     For real numbers MatIsSymmetric() and MatIsHermitian() return identical results

8551:    Level: intermediate

8553: .seealso: MatTranspose(), MatIsTranspose(), MatIsHermitian(), MatIsStructurallySymmetric(), MatSetOption(), MatIsSymmetricKnown()
8554: @*/
8555: PetscErrorCode MatIsSymmetric(Mat A,PetscReal tol,PetscBool  *flg)
8556: {


8563:   if (!A->symmetric_set) {
8564:     if (!A->ops->issymmetric) {
8565:       MatType mattype;
8566:       MatGetType(A,&mattype);
8567:       SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Matrix of type %s does not support checking for symmetric",mattype);
8568:     }
8569:     (*A->ops->issymmetric)(A,tol,flg);
8570:     if (!tol) {
8571:       MatSetOption(A,MAT_SYMMETRIC,*flg);
8572:     }
8573:   } else if (A->symmetric) {
8574:     *flg = PETSC_TRUE;
8575:   } else if (!tol) {
8576:     *flg = PETSC_FALSE;
8577:   } else {
8578:     if (!A->ops->issymmetric) {
8579:       MatType mattype;
8580:       MatGetType(A,&mattype);
8581:       SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Matrix of type %s does not support checking for symmetric",mattype);
8582:     }
8583:     (*A->ops->issymmetric)(A,tol,flg);
8584:   }
8585:   return(0);
8586: }

8588: /*@
8589:    MatIsHermitian - Test whether a matrix is Hermitian

8591:    Collective on Mat

8593:    Input Parameter:
8594: +  A - the matrix to test
8595: -  tol - difference between value and its transpose less than this amount counts as equal (use 0.0 for exact Hermitian)

8597:    Output Parameters:
8598: .  flg - the result

8600:    Level: intermediate

8602: .seealso: MatTranspose(), MatIsTranspose(), MatIsHermitian(), MatIsStructurallySymmetric(), MatSetOption(),
8603:           MatIsSymmetricKnown(), MatIsSymmetric()
8604: @*/
8605: PetscErrorCode MatIsHermitian(Mat A,PetscReal tol,PetscBool  *flg)
8606: {


8613:   if (!A->hermitian_set) {
8614:     if (!A->ops->ishermitian) {
8615:       MatType mattype;
8616:       MatGetType(A,&mattype);
8617:       SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Matrix of type %s does not support checking for hermitian",mattype);
8618:     }
8619:     (*A->ops->ishermitian)(A,tol,flg);
8620:     if (!tol) {
8621:       MatSetOption(A,MAT_HERMITIAN,*flg);
8622:     }
8623:   } else if (A->hermitian) {
8624:     *flg = PETSC_TRUE;
8625:   } else if (!tol) {
8626:     *flg = PETSC_FALSE;
8627:   } else {
8628:     if (!A->ops->ishermitian) {
8629:       MatType mattype;
8630:       MatGetType(A,&mattype);
8631:       SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Matrix of type %s does not support checking for hermitian",mattype);
8632:     }
8633:     (*A->ops->ishermitian)(A,tol,flg);
8634:   }
8635:   return(0);
8636: }

8638: /*@
8639:    MatIsSymmetricKnown - Checks the flag on the matrix to see if it is symmetric.

8641:    Not Collective

8643:    Input Parameter:
8644: .  A - the matrix to check

8646:    Output Parameters:
8647: +  set - if the symmetric flag is set (this tells you if the next flag is valid)
8648: -  flg - the result

8650:    Level: advanced

8652:    Note: Does not check the matrix values directly, so this may return unknown (set = PETSC_FALSE). Use MatIsSymmetric()
8653:          if you want it explicitly checked

8655: .seealso: MatTranspose(), MatIsTranspose(), MatIsHermitian(), MatIsStructurallySymmetric(), MatSetOption(), MatIsSymmetric()
8656: @*/
8657: PetscErrorCode MatIsSymmetricKnown(Mat A,PetscBool *set,PetscBool *flg)
8658: {
8663:   if (A->symmetric_set) {
8664:     *set = PETSC_TRUE;
8665:     *flg = A->symmetric;
8666:   } else {
8667:     *set = PETSC_FALSE;
8668:   }
8669:   return(0);
8670: }

8672: /*@
8673:    MatIsHermitianKnown - Checks the flag on the matrix to see if it is hermitian.

8675:    Not Collective

8677:    Input Parameter:
8678: .  A - the matrix to check

8680:    Output Parameters:
8681: +  set - if the hermitian flag is set (this tells you if the next flag is valid)
8682: -  flg - the result

8684:    Level: advanced

8686:    Note: Does not check the matrix values directly, so this may return unknown (set = PETSC_FALSE). Use MatIsHermitian()
8687:          if you want it explicitly checked

8689: .seealso: MatTranspose(), MatIsTranspose(), MatIsHermitian(), MatIsStructurallySymmetric(), MatSetOption(), MatIsSymmetric()
8690: @*/
8691: PetscErrorCode MatIsHermitianKnown(Mat A,PetscBool *set,PetscBool *flg)
8692: {
8697:   if (A->hermitian_set) {
8698:     *set = PETSC_TRUE;
8699:     *flg = A->hermitian;
8700:   } else {
8701:     *set = PETSC_FALSE;
8702:   }
8703:   return(0);
8704: }

8706: /*@
8707:    MatIsStructurallySymmetric - Test whether a matrix is structurally symmetric

8709:    Collective on Mat

8711:    Input Parameter:
8712: .  A - the matrix to test

8714:    Output Parameters:
8715: .  flg - the result

8717:    Level: intermediate

8719: .seealso: MatTranspose(), MatIsTranspose(), MatIsHermitian(), MatIsSymmetric(), MatSetOption()
8720: @*/
8721: PetscErrorCode MatIsStructurallySymmetric(Mat A,PetscBool *flg)
8722: {

8728:   if (!A->structurally_symmetric_set) {
8729:     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);
8730:     (*A->ops->isstructurallysymmetric)(A,flg);
8731:     MatSetOption(A,MAT_STRUCTURALLY_SYMMETRIC,*flg);
8732:   } else *flg = A->structurally_symmetric;
8733:   return(0);
8734: }

8736: /*@
8737:    MatStashGetInfo - Gets how many values are currently in the matrix stash, i.e. need
8738:        to be communicated to other processors during the MatAssemblyBegin/End() process

8740:     Not collective

8742:    Input Parameter:
8743: .   vec - the vector

8745:    Output Parameters:
8746: +   nstash   - the size of the stash
8747: .   reallocs - the number of additional mallocs incurred.
8748: .   bnstash   - the size of the block stash
8749: -   breallocs - the number of additional mallocs incurred.in the block stash

8751:    Level: advanced

8753: .seealso: MatAssemblyBegin(), MatAssemblyEnd(), Mat, MatStashSetInitialSize()

8755: @*/
8756: PetscErrorCode MatStashGetInfo(Mat mat,PetscInt *nstash,PetscInt *reallocs,PetscInt *bnstash,PetscInt *breallocs)
8757: {

8761:   MatStashGetInfo_Private(&mat->stash,nstash,reallocs);
8762:   MatStashGetInfo_Private(&mat->bstash,bnstash,breallocs);
8763:   return(0);
8764: }

8766: /*@C
8767:    MatCreateVecs - Get vector(s) compatible with the matrix, i.e. with the same
8768:      parallel layout

8770:    Collective on Mat

8772:    Input Parameter:
8773: .  mat - the matrix

8775:    Output Parameter:
8776: +   right - (optional) vector that the matrix can be multiplied against
8777: -   left - (optional) vector that the matrix vector product can be stored in

8779:    Notes:
8780:     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().

8782:   Notes:
8783:     These are new vectors which are not owned by the Mat, they should be destroyed in VecDestroy() when no longer needed

8785:   Level: advanced

8787: .seealso: MatCreate(), VecDestroy()
8788: @*/
8789: PetscErrorCode MatCreateVecs(Mat mat,Vec *right,Vec *left)
8790: {

8796:   if (mat->ops->getvecs) {
8797:     (*mat->ops->getvecs)(mat,right,left);
8798:   } else {
8799:     PetscInt rbs,cbs;
8800:     MatGetBlockSizes(mat,&rbs,&cbs);
8801:     if (right) {
8802:       if (mat->cmap->n < 0) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"PetscLayout for columns not yet setup");
8803:       VecCreate(PetscObjectComm((PetscObject)mat),right);
8804:       VecSetSizes(*right,mat->cmap->n,PETSC_DETERMINE);
8805:       VecSetBlockSize(*right,cbs);
8806:       VecSetType(*right,mat->defaultvectype);
8807:       PetscLayoutReference(mat->cmap,&(*right)->map);
8808:     }
8809:     if (left) {
8810:       if (mat->rmap->n < 0) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"PetscLayout for rows not yet setup");
8811:       VecCreate(PetscObjectComm((PetscObject)mat),left);
8812:       VecSetSizes(*left,mat->rmap->n,PETSC_DETERMINE);
8813:       VecSetBlockSize(*left,rbs);
8814:       VecSetType(*left,mat->defaultvectype);
8815:       PetscLayoutReference(mat->rmap,&(*left)->map);
8816:     }
8817:   }
8818:   return(0);
8819: }

8821: /*@C
8822:    MatFactorInfoInitialize - Initializes a MatFactorInfo data structure
8823:      with default values.

8825:    Not Collective

8827:    Input Parameters:
8828: .    info - the MatFactorInfo data structure


8831:    Notes:
8832:     The solvers are generally used through the KSP and PC objects, for example
8833:           PCLU, PCILU, PCCHOLESKY, PCICC

8835:    Level: developer

8837: .seealso: MatFactorInfo

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

8842: @*/

8844: PetscErrorCode MatFactorInfoInitialize(MatFactorInfo *info)
8845: {

8849:   PetscMemzero(info,sizeof(MatFactorInfo));
8850:   return(0);
8851: }

8853: /*@
8854:    MatFactorSetSchurIS - Set indices corresponding to the Schur complement you wish to have computed

8856:    Collective on Mat

8858:    Input Parameters:
8859: +  mat - the factored matrix
8860: -  is - the index set defining the Schur indices (0-based)

8862:    Notes:
8863:     Call MatFactorSolveSchurComplement() or MatFactorSolveSchurComplementTranspose() after this call to solve a Schur complement system.

8865:    You can call MatFactorGetSchurComplement() or MatFactorCreateSchurComplement() after this call.

8867:    Level: developer

8869: .seealso: MatGetFactor(), MatFactorGetSchurComplement(), MatFactorRestoreSchurComplement(), MatFactorCreateSchurComplement(), MatFactorSolveSchurComplement(),
8870:           MatFactorSolveSchurComplementTranspose(), MatFactorSolveSchurComplement()

8872: @*/
8873: PetscErrorCode MatFactorSetSchurIS(Mat mat,IS is)
8874: {
8875:   PetscErrorCode ierr,(*f)(Mat,IS);

8883:   if (!mat->factortype) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Only for factored matrix");
8884:   PetscObjectQueryFunction((PetscObject)mat,"MatFactorSetSchurIS_C",&f);
8885:   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");
8886:   MatDestroy(&mat->schur);
8887:   (*f)(mat,is);
8888:   if (!mat->schur) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_PLIB,"Schur complement has not been created");
8889:   return(0);
8890: }

8892: /*@
8893:   MatFactorCreateSchurComplement - Create a Schur complement matrix object using Schur data computed during the factorization step

8895:    Logically Collective on Mat

8897:    Input Parameters:
8898: +  F - the factored matrix obtained by calling MatGetFactor() from PETSc-MUMPS interface
8899: .  S - location where to return the Schur complement, can be NULL
8900: -  status - the status of the Schur complement matrix, can be NULL

8902:    Notes:
8903:    You must call MatFactorSetSchurIS() before calling this routine.

8905:    The routine provides a copy of the Schur matrix stored within the solver data structures.
8906:    The caller must destroy the object when it is no longer needed.
8907:    If MatFactorInvertSchurComplement() has been called, the routine gets back the inverse.

8909:    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)

8911:    Developer Notes:
8912:     The reason this routine exists is because the representation of the Schur complement within the factor matrix may be different than a standard PETSc
8913:    matrix representation and we normally do not want to use the time or memory to make a copy as a regular PETSc matrix.

8915:    See MatCreateSchurComplement() or MatGetSchurComplement() for ways to create virtual or approximate Schur complements.

8917:    Level: advanced

8919:    References:

8921: .seealso: MatGetFactor(), MatFactorSetSchurIS(), MatFactorGetSchurComplement(), MatFactorSchurStatus
8922: @*/
8923: PetscErrorCode MatFactorCreateSchurComplement(Mat F,Mat* S,MatFactorSchurStatus* status)
8924: {

8931:   if (S) {
8932:     PetscErrorCode (*f)(Mat,Mat*);

8934:     PetscObjectQueryFunction((PetscObject)F,"MatFactorCreateSchurComplement_C",&f);
8935:     if (f) {
8936:       (*f)(F,S);
8937:     } else {
8938:       MatDuplicate(F->schur,MAT_COPY_VALUES,S);
8939:     }
8940:   }
8941:   if (status) *status = F->schur_status;
8942:   return(0);
8943: }

8945: /*@
8946:   MatFactorGetSchurComplement - Gets access to a Schur complement matrix using the current Schur data within a factored matrix

8948:    Logically Collective on Mat

8950:    Input Parameters:
8951: +  F - the factored matrix obtained by calling MatGetFactor()
8952: .  *S - location where to return the Schur complement, can be NULL
8953: -  status - the status of the Schur complement matrix, can be NULL

8955:    Notes:
8956:    You must call MatFactorSetSchurIS() before calling this routine.

8958:    Schur complement mode is currently implemented for sequential matrices.
8959:    The routine returns a the Schur Complement stored within the data strutures of the solver.
8960:    If MatFactorInvertSchurComplement() has previously been called, the returned matrix is actually the inverse of the Schur complement.
8961:    The returned matrix should not be destroyed; the caller should call MatFactorRestoreSchurComplement() when the object is no longer needed.

8963:    Use MatFactorCreateSchurComplement() to create a copy of the Schur complement matrix that is within a factored matrix

8965:    See MatCreateSchurComplement() or MatGetSchurComplement() for ways to create virtual or approximate Schur complements.

8967:    Level: advanced

8969:    References:

8971: .seealso: MatGetFactor(), MatFactorSetSchurIS(), MatFactorRestoreSchurComplement(), MatFactorCreateSchurComplement(), MatFactorSchurStatus
8972: @*/
8973: PetscErrorCode MatFactorGetSchurComplement(Mat F,Mat* S,MatFactorSchurStatus* status)
8974: {
8979:   if (S) *S = F->schur;
8980:   if (status) *status = F->schur_status;
8981:   return(0);
8982: }

8984: /*@
8985:   MatFactorRestoreSchurComplement - Restore the Schur complement matrix object obtained from a call to MatFactorGetSchurComplement

8987:    Logically Collective on Mat

8989:    Input Parameters:
8990: +  F - the factored matrix obtained by calling MatGetFactor()
8991: .  *S - location where the Schur complement is stored
8992: -  status - the status of the Schur complement matrix (see MatFactorSchurStatus)

8994:    Notes:

8996:    Level: advanced

8998:    References:

9000: .seealso: MatGetFactor(), MatFactorSetSchurIS(), MatFactorRestoreSchurComplement(), MatFactorCreateSchurComplement(), MatFactorSchurStatus
9001: @*/
9002: PetscErrorCode MatFactorRestoreSchurComplement(Mat F,Mat* S,MatFactorSchurStatus status)
9003: {

9008:   if (S) {
9010:     *S = NULL;
9011:   }
9012:   F->schur_status = status;
9013:   MatFactorUpdateSchurStatus_Private(F);
9014:   return(0);
9015: }

9017: /*@
9018:   MatFactorSolveSchurComplementTranspose - Solve the transpose of the Schur complement system computed during the factorization step

9020:    Logically Collective on Mat

9022:    Input Parameters:
9023: +  F - the factored matrix obtained by calling MatGetFactor()
9024: .  rhs - location where the right hand side of the Schur complement system is stored
9025: -  sol - location where the solution of the Schur complement system has to be returned

9027:    Notes:
9028:    The sizes of the vectors should match the size of the Schur complement

9030:    Must be called after MatFactorSetSchurIS()

9032:    Level: advanced

9034:    References:

9036: .seealso: MatGetFactor(), MatFactorSetSchurIS(), MatFactorSolveSchurComplement()
9037: @*/
9038: PetscErrorCode MatFactorSolveSchurComplementTranspose(Mat F, Vec rhs, Vec sol)
9039: {

9051:   MatFactorFactorizeSchurComplement(F);
9052:   switch (F->schur_status) {
9053:   case MAT_FACTOR_SCHUR_FACTORED:
9054:     MatSolveTranspose(F->schur,rhs,sol);
9055:     break;
9056:   case MAT_FACTOR_SCHUR_INVERTED:
9057:     MatMultTranspose(F->schur,rhs,sol);
9058:     break;
9059:   default:
9060:     SETERRQ1(PetscObjectComm((PetscObject)F),PETSC_ERR_SUP,"Unhandled MatFactorSchurStatus %D",F->schur_status);
9061:     break;
9062:   }
9063:   return(0);
9064: }

9066: /*@
9067:   MatFactorSolveSchurComplement - Solve the Schur complement system computed during the factorization step

9069:    Logically Collective on Mat

9071:    Input Parameters:
9072: +  F - the factored matrix obtained by calling MatGetFactor()
9073: .  rhs - location where the right hand side of the Schur complement system is stored
9074: -  sol - location where the solution of the Schur complement system has to be returned

9076:    Notes:
9077:    The sizes of the vectors should match the size of the Schur complement

9079:    Must be called after MatFactorSetSchurIS()

9081:    Level: advanced

9083:    References:

9085: .seealso: MatGetFactor(), MatFactorSetSchurIS(), MatFactorSolveSchurComplementTranspose()
9086: @*/
9087: PetscErrorCode MatFactorSolveSchurComplement(Mat F, Vec rhs, Vec sol)
9088: {

9100:   MatFactorFactorizeSchurComplement(F);
9101:   switch (F->schur_status) {
9102:   case MAT_FACTOR_SCHUR_FACTORED:
9103:     MatSolve(F->schur,rhs,sol);
9104:     break;
9105:   case MAT_FACTOR_SCHUR_INVERTED:
9106:     MatMult(F->schur,rhs,sol);
9107:     break;
9108:   default:
9109:     SETERRQ1(PetscObjectComm((PetscObject)F),PETSC_ERR_SUP,"Unhandled MatFactorSchurStatus %D",F->schur_status);
9110:     break;
9111:   }
9112:   return(0);
9113: }

9115: /*@
9116:   MatFactorInvertSchurComplement - Invert the Schur complement matrix computed during the factorization step

9118:    Logically Collective on Mat

9120:    Input Parameters:
9121: .  F - the factored matrix obtained by calling MatGetFactor()

9123:    Notes:
9124:     Must be called after MatFactorSetSchurIS().

9126:    Call MatFactorGetSchurComplement() or  MatFactorCreateSchurComplement() AFTER this call to actually compute the inverse and get access to it.

9128:    Level: advanced

9130:    References:

9132: .seealso: MatGetFactor(), MatFactorSetSchurIS(), MatFactorGetSchurComplement(), MatFactorCreateSchurComplement()
9133: @*/
9134: PetscErrorCode MatFactorInvertSchurComplement(Mat F)
9135: {

9141:   if (F->schur_status == MAT_FACTOR_SCHUR_INVERTED) return(0);
9142:   MatFactorFactorizeSchurComplement(F);
9143:   MatFactorInvertSchurComplement_Private(F);
9144:   F->schur_status = MAT_FACTOR_SCHUR_INVERTED;
9145:   return(0);
9146: }

9148: /*@
9149:   MatFactorFactorizeSchurComplement - Factorize the Schur complement matrix computed during the factorization step

9151:    Logically Collective on Mat

9153:    Input Parameters:
9154: .  F - the factored matrix obtained by calling MatGetFactor()

9156:    Notes:
9157:     Must be called after MatFactorSetSchurIS().

9159:    Level: advanced

9161:    References:

9163: .seealso: MatGetFactor(), MatFactorSetSchurIS(), MatFactorInvertSchurComplement()
9164: @*/
9165: PetscErrorCode MatFactorFactorizeSchurComplement(Mat F)
9166: {

9172:   if (F->schur_status == MAT_FACTOR_SCHUR_INVERTED || F->schur_status == MAT_FACTOR_SCHUR_FACTORED) return(0);
9173:   MatFactorFactorizeSchurComplement_Private(F);
9174:   F->schur_status = MAT_FACTOR_SCHUR_FACTORED;
9175:   return(0);
9176: }

9178: /*@
9179:    MatPtAP - Creates the matrix product C = P^T * A * P

9181:    Neighbor-wise Collective on Mat

9183:    Input Parameters:
9184: +  A - the matrix
9185: .  P - the projection matrix
9186: .  scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
9187: -  fill - expected fill as ratio of nnz(C)/(nnz(A) + nnz(P)), use PETSC_DEFAULT if you do not have a good estimate
9188:           if the result is a dense matrix this is irrelevent

9190:    Output Parameters:
9191: .  C - the product matrix

9193:    Notes:
9194:    C will be created and must be destroyed by the user with MatDestroy().

9196:    For matrix types without special implementation the function fallbacks to MatMatMult() followed by MatTransposeMatMult().

9198:    Level: intermediate

9200: .seealso: MatMatMult(), MatRARt()
9201: @*/
9202: PetscErrorCode MatPtAP(Mat A,Mat P,MatReuse scall,PetscReal fill,Mat *C)
9203: {

9207:   if (scall == MAT_REUSE_MATRIX) MatCheckProduct(*C,5);
9208:   if (scall == MAT_INPLACE_MATRIX) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Inplace product not supported");

9210:   if (scall == MAT_INITIAL_MATRIX) {
9211:     MatProductCreate(A,P,NULL,C);
9212:     MatProductSetType(*C,MATPRODUCT_PtAP);
9213:     MatProductSetAlgorithm(*C,"default");
9214:     MatProductSetFill(*C,fill);

9216:     (*C)->product->api_user = PETSC_TRUE;
9217:     MatProductSetFromOptions(*C);
9218:     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);
9219:     MatProductSymbolic(*C);
9220:   } else { /* scall == MAT_REUSE_MATRIX */
9221:     MatProductReplaceMats(A,P,NULL,*C);
9222:   }

9224:   MatProductNumeric(*C);
9225:   if (A->symmetric_set && A->symmetric) {
9226:     MatSetOption(*C,MAT_SYMMETRIC,PETSC_TRUE);
9227:   }
9228:   return(0);
9229: }

9231: /*@
9232:    MatRARt - Creates the matrix product C = R * A * R^T

9234:    Neighbor-wise Collective on Mat

9236:    Input Parameters:
9237: +  A - the matrix
9238: .  R - the projection matrix
9239: .  scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
9240: -  fill - expected fill as ratio of nnz(C)/nnz(A), use PETSC_DEFAULT if you do not have a good estimate
9241:           if the result is a dense matrix this is irrelevent

9243:    Output Parameters:
9244: .  C - the product matrix

9246:    Notes:
9247:    C will be created and must be destroyed by the user with MatDestroy().

9249:    This routine is currently only implemented for pairs of AIJ matrices and classes
9250:    which inherit from AIJ. Due to PETSc sparse matrix block row distribution among processes,
9251:    parallel MatRARt is implemented via explicit transpose of R, which could be very expensive.
9252:    We recommend using MatPtAP().

9254:    Level: intermediate

9256: .seealso: MatMatMult(), MatPtAP()
9257: @*/
9258: PetscErrorCode MatRARt(Mat A,Mat R,MatReuse scall,PetscReal fill,Mat *C)
9259: {

9263:   if (scall == MAT_REUSE_MATRIX) MatCheckProduct(*C,5);
9264:   if (scall == MAT_INPLACE_MATRIX) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Inplace product not supported");

9266:   if (scall == MAT_INITIAL_MATRIX) {
9267:     MatProductCreate(A,R,NULL,C);
9268:     MatProductSetType(*C,MATPRODUCT_RARt);
9269:     MatProductSetAlgorithm(*C,"default");
9270:     MatProductSetFill(*C,fill);

9272:     (*C)->product->api_user = PETSC_TRUE;
9273:     MatProductSetFromOptions(*C);
9274:     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);
9275:     MatProductSymbolic(*C);
9276:   } else { /* scall == MAT_REUSE_MATRIX */
9277:     MatProductReplaceMats(A,R,NULL,*C);
9278:   }

9280:   MatProductNumeric(*C);
9281:   if (A->symmetric_set && A->symmetric) {
9282:     MatSetOption(*C,MAT_SYMMETRIC,PETSC_TRUE);
9283:   }
9284:   return(0);
9285: }


9288: static PetscErrorCode MatProduct_Private(Mat A,Mat B,MatReuse scall,PetscReal fill,MatProductType ptype, Mat *C)
9289: {

9293:   if (scall == MAT_INPLACE_MATRIX) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_E